]> git.wh0rd.org - tt-rss.git/blame - include/rssfuncs.php
do not generate warning on csrf_token being unassigned
[tt-rss.git] / include / rssfuncs.php
CommitLineData
2c08214a 1<?php
09e8bdfd
AD
2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
4 define('DAEMON_SLEEP_INTERVAL', 120);
5
79178062
AD
6 function update_feedbrowser_cache($link) {
7
8 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
9 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
10 WHERE tf.feed_url = ttrss_feeds.feed_url
11 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
12 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
13
14 db_query($link, "BEGIN");
15
16 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
17
18 $count = 0;
19
20 while ($line = db_fetch_assoc($result)) {
21 $subscribers = db_escape_string($line["subscribers"]);
22 $feed_url = db_escape_string($line["feed_url"]);
23 $title = db_escape_string($line["title"]);
24 $site_url = db_escape_string($line["site_url"]);
25
26 $tmp_result = db_query($link, "SELECT subscribers FROM
27 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
28
29 if (db_num_rows($tmp_result) == 0) {
30
31 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
32 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
33 '$site_url', '$title', '$subscribers')");
34
35 ++$count;
36
37 }
38
39 }
40
41 db_query($link, "COMMIT");
42
43 return $count;
44
45 }
46
47
2c08214a
AD
48 /**
49 * Update a feed batch.
50 * Used by daemons to update n feeds by run.
51 * Only update feed needing a update, and not being processed
52 * by another process.
53 *
54 * @param mixed $link Database link
55 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
56 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
57 * @param boolean $debug Set to false to disable debug output. Default to true.
58 * @return void
59 */
60 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
61 // Process all other feeds using last_updated and interval parameters
62
63 // Test if the user has loggued in recently. If not, it does not update its feeds.
09e8bdfd 64 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
2c08214a
AD
65 if (DB_TYPE == "pgsql") {
66 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
67 } else {
68 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
69 }
70 } else {
71 $login_thresh_qpart = "";
72 }
73
74 // Test if the feed need a update (update interval exceded).
75 if (DB_TYPE == "pgsql") {
76 $update_limit_qpart = "AND ((
77 ttrss_feeds.update_interval = 0
78 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
79 ) OR (
80 ttrss_feeds.update_interval > 0
81 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
82 ) OR ttrss_feeds.last_updated IS NULL)";
83 } else {
84 $update_limit_qpart = "AND ((
85 ttrss_feeds.update_interval = 0
86 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
87 ) OR (
88 ttrss_feeds.update_interval > 0
89 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
90 ) OR ttrss_feeds.last_updated IS NULL)";
91 }
92
93 // Test if feed is currently being updated by another process.
94 if (DB_TYPE == "pgsql") {
95 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
96 } else {
97 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
98 }
99
100 // Test if there is a limit to number of updated feeds
101 $query_limit = "";
102 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
103
104 $random_qpart = sql_random_function();
105
106 // We search for feed needing update.
107 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
108 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
109 ttrss_feeds.update_interval
110 FROM
111 ttrss_feeds, ttrss_users, ttrss_user_prefs
112 WHERE
113 ttrss_feeds.owner_uid = ttrss_users.id
114 AND ttrss_users.id = ttrss_user_prefs.owner_uid
115 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
116 $login_thresh_qpart $update_limit_qpart
117 $updstart_thresh_qpart
118 ORDER BY $random_qpart $query_limit");
119
120 $user_prefs_cache = array();
121
122 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
123
124 // Here is a little cache magic in order to minimize risk of double feed updates.
125 $feeds_to_update = array();
126 while ($line = db_fetch_assoc($result)) {
127 $feeds_to_update[$line['id']] = $line;
128 }
129
130 // We update the feed last update started date before anything else.
131 // There is no lag due to feed contents downloads
132 // It prevent an other process to update the same feed.
133 $feed_ids = array_keys($feeds_to_update);
134 if($feed_ids) {
135 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
136 WHERE id IN (%s)", implode(',', $feed_ids)));
137 }
138
3c696512
AD
139 expire_cached_files($debug);
140
2c08214a
AD
141 // For each feed, we call the feed update function.
142 while ($line = array_pop($feeds_to_update)) {
143
144 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
145
146 update_rss_feed($link, $line["id"], true);
147
148 sleep(1); // prevent flood (FIXME make this an option?)
149 }
150
151 // Send feed digests by email if needed.
036cd3a4 152 send_headlines_digests($link, 100, $debug);
2c08214a
AD
153
154 } // function update_daemon_common
155
156 function fetch_twitter_rss($link, $url, $owner_uid) {
157
158 require_once 'lib/tmhoauth/tmhOAuth.php';
159
160 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
161 WHERE id = $owner_uid");
162
163 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
164 $url_escaped = db_escape_string($url);
165
166 if ($access_token) {
167
168 $tmhOAuth = new tmhOAuth(array(
169 'consumer_key' => CONSUMER_KEY,
170 'consumer_secret' => CONSUMER_SECRET,
171 'user_token' => $access_token['oauth_token'],
172 'user_secret' => $access_token['oauth_token_secret'],
173 ));
174
175 $code = $tmhOAuth->request('GET', $url);
176
177 if ($code == 200) {
178
179 $content = $tmhOAuth->response['response'];
180
181 define('MAGPIE_CACHE_ON', false);
182
183 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING,
184 MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
185
186 return $rss;
187
188 } else {
189
190 db_query($link, "UPDATE ttrss_feeds
191 SET last_error = 'OAuth authorization failed ($code).'
192 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
193 }
194
195 } else {
196
197 db_query($link, "UPDATE ttrss_feeds
198 SET last_error = 'OAuth information not found.'
199 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
200
201 return false;
202 }
203 }
204
205 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
206
207 global $memcache;
208
209 /* Update all feeds with the same URL to utilize memcache */
210
211 if ($memcache) {
212 $result = db_query($link, "SELECT f1.id
213 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
214 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
215
216 while ($line = db_fetch_assoc($result)) {
217 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
218 }
219 } else {
220 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
221 }
222 }
223
224 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
225 $override_url = false) {
226
227 require_once "lib/simplepie/simplepie.inc";
228 require_once "lib/magpierss/rss_fetch.inc";
229 require_once 'lib/magpierss/rss_utils.inc';
230
231 global $memcache;
232
233 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
234
235 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
236 return false;
237 }
238
239 if ($debug_enabled) {
240 _debug("update_rss_feed: start");
241 }
242
243 if (!$ignore_daemon) {
244
245 if (DB_TYPE == "pgsql") {
246 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
247 } else {
248 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
249 }
250
251 $result = db_query($link, "SELECT id,update_interval,auth_login,
252 auth_pass,cache_images,update_method
253 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
254
255 } else {
256
257 $result = db_query($link, "SELECT id,update_interval,auth_login,
258 feed_url,auth_pass,cache_images,update_method,last_updated,
259 mark_unread_on_update, owner_uid, update_on_checksum_change,
260 pubsub_state
261 FROM ttrss_feeds WHERE id = '$feed'");
262
263 }
264
265 if (db_num_rows($result) == 0) {
266 if ($debug_enabled) {
267 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
268 }
269 return false;
270 }
271
272 $update_method = db_fetch_result($result, 0, "update_method");
273 $last_updated = db_fetch_result($result, 0, "last_updated");
274 $owner_uid = db_fetch_result($result, 0, "owner_uid");
275 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
276 0, "mark_unread_on_update"));
277 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
278 0, "update_on_checksum_change"));
279 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
280
281 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
282 WHERE id = '$feed'");
283
284 $auth_login = db_fetch_result($result, 0, "auth_login");
285 $auth_pass = db_fetch_result($result, 0, "auth_pass");
286
287 if ($update_method == 0)
288 $update_method = DEFAULT_UPDATE_METHOD + 1;
289
290 // 1 - Magpie
291 // 2 - SimplePie
292 // 3 - Twitter OAuth
293
294 if ($update_method == 2)
295 $use_simplepie = true;
296 else
297 $use_simplepie = false;
298
299 if ($debug_enabled) {
300 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
301 }
302
303 if ($update_method == 1) {
304 $auth_login = urlencode($auth_login);
305 $auth_pass = urlencode($auth_pass);
306 }
307
308 $update_interval = db_fetch_result($result, 0, "update_interval");
309 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
310 $fetch_url = db_fetch_result($result, 0, "feed_url");
311
312 if ($update_interval < 0) { return false; }
313
314 $feed = db_escape_string($feed);
315
316 if ($auth_login && $auth_pass ){
317 $url_parts = array();
318 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
319
320 if ($url_parts[1] && $url_parts[2]) {
321 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
322 }
323
324 }
325
326 if ($override_url)
327 $fetch_url = $override_url;
328
329 if ($debug_enabled) {
330 _debug("update_rss_feed: fetching [$fetch_url]...");
331 }
332
333 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
334
335 if ($memcache && $obj = $memcache->get($obj_id)) {
336
337 if ($debug_enabled) {
338 _debug("update_rss_feed: data found in memcache.");
339 }
340
341 $rss = $obj;
342
343 } else {
344
345 if ($update_method == 3) {
346 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
347 } else if ($update_method == 1) {
348
349 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
350 define('MAGPIE_CACHE_ON', !$no_cache);
351 define('MAGPIE_FETCH_TIME_OUT', 60);
352 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
353
354 $rss = @fetch_rss($fetch_url);
355 } else {
356 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
357
358 if (!is_dir($simplepie_cache_dir)) {
359 mkdir($simplepie_cache_dir);
360 }
361
362 $rss = new SimplePie();
363 $rss->set_useragent(SELF_USER_AGENT);
364 # $rss->set_timeout(10);
365 $rss->set_feed_url($fetch_url);
366 $rss->set_output_encoding('UTF-8');
f1e511c8 367 //$rss->force_feed(true);
2c08214a 368
2c08214a
AD
369 if ($debug_enabled) {
370 _debug("feed update interval (sec): " .
371 get_feed_update_interval($link, $feed)*60);
372 }
373
374 $rss->enable_cache(!$no_cache);
375
376 if (!$no_cache) {
377 $rss->set_cache_location($simplepie_cache_dir);
378 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
379 }
380
381 $rss->init();
382 }
383
384 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
385 }
386
387// print_r($rss);
388
389 if ($debug_enabled) {
390 _debug("update_rss_feed: fetch done, parsing...");
391 }
392
393 $feed = db_escape_string($feed);
394
395 if ($update_method == 2) {
396 $fetch_ok = !$rss->error();
397 } else {
398 $fetch_ok = !!$rss;
399 }
400
401 if ($fetch_ok) {
402
403 if ($debug_enabled) {
404 _debug("update_rss_feed: processing feed data...");
405 }
406
407// db_query($link, "BEGIN");
408
409 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
410 FROM ttrss_feeds WHERE id = '$feed'");
411
412 $registered_title = db_fetch_result($result, 0, "title");
413 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
414 $orig_site_url = db_fetch_result($result, 0, "site_url");
415
416 $owner_uid = db_fetch_result($result, 0, "owner_uid");
417
418 if ($use_simplepie) {
419 $site_url = $rss->get_link();
420 } else {
421 $site_url = $rss->channel["link"];
422 }
423
424 $site_url = rewrite_relative_url($fetch_url, $site_url);
425
426 if ($debug_enabled) {
427 _debug("update_rss_feed: checking favicon...");
428 }
429
430 check_feed_favicon($site_url, $feed, $link);
431
432 if (!$registered_title || $registered_title == "[Unknown]") {
433
434 if ($use_simplepie) {
435 $feed_title = db_escape_string($rss->get_title());
436 } else {
437 $feed_title = db_escape_string($rss->channel["title"]);
438 }
439
440 if ($debug_enabled) {
441 _debug("update_rss_feed: registering title: $feed_title");
442 }
443
444 db_query($link, "UPDATE ttrss_feeds SET
445 title = '$feed_title' WHERE id = '$feed'");
446 }
447
448 // weird, weird Magpie
449 if (!$use_simplepie) {
450 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
451 }
452
453 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
454 db_query($link, "UPDATE ttrss_feeds SET
455 site_url = '$site_url' WHERE id = '$feed'");
456 }
457
458// print "I: " . $rss->channel["image"]["url"];
459
460 if (!$use_simplepie) {
461 $icon_url = db_escape_string($rss->image["url"]);
462 } else {
463 $icon_url = db_escape_string($rss->get_image_url());
464 }
465
466 $icon_url = substr($icon_url, 0, 250);
467
468 if ($icon_url && $orig_icon_url != $icon_url) {
469 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
470 }
471
472 if ($debug_enabled) {
473 _debug("update_rss_feed: loading filters...");
474 }
475
476 $filters = load_filters($link, $feed, $owner_uid);
477
478// if ($debug_enabled) {
479// print_r($filters);
480// }
481
482 if ($use_simplepie) {
483 $iterator = $rss->get_items();
484 } else {
485 $iterator = $rss->items;
486 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
487 if (!$iterator || !is_array($iterator)) $iterator = $rss;
488 }
489
490 if (!is_array($iterator)) {
491 /* db_query($link, "UPDATE ttrss_feeds
492 SET last_error = 'Parse error: can\'t find any articles.'
493 WHERE id = '$feed'"); */
494
495 // clear any errors and mark feed as updated if fetched okay
496 // even if it's blank
497
498 if ($debug_enabled) {
499 _debug("update_rss_feed: entry iterator is not an array, no articles?");
500 }
501
502 db_query($link, "UPDATE ttrss_feeds
503 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
504
505 return; // no articles
506 }
507
508 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
509
510 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
511
512 $feed_hub_url = false;
513 if ($use_simplepie) {
514 $links = $rss->get_links('hub');
515
516 if ($links && is_array($links)) {
517 foreach ($links as $l) {
518 $feed_hub_url = $l;
519 break;
520 }
521 }
522
523 } else {
524 $atom = $rss->channel['atom'];
525
526 if ($atom) {
527 if ($atom['link@rel'] == 'hub') {
528 $feed_hub_url = $atom['link@href'];
529 }
530
531 if (!$feed_hub_url && $atom['link#'] > 1) {
532 for ($i = 2; $i <= $atom['link#']; $i++) {
533 if ($atom["link#$i@rel"] == 'hub') {
534 $feed_hub_url = $atom["link#$i@href"];
535 break;
536 }
537 }
538 }
539 } else {
540 $feed_hub_url = $rss->channel['link_hub'];
541 }
542 }
543
544 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
545
546 if ($feed_hub_url && function_exists('curl_init') &&
547 !ini_get("open_basedir")) {
548
549 require_once 'lib/pubsubhubbub/subscriber.php';
550
551 $callback_url = get_self_url_prefix() .
552 "/public.php?op=pubsub&id=$feed";
553
554 $s = new Subscriber($feed_hub_url, $callback_url);
555
556 $rc = $s->subscribe($fetch_url);
557
558 if ($debug_enabled)
559 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
560
561 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
562 WHERE id = '$feed'");
563 }
564 }
565
566 if ($debug_enabled) {
567 _debug("update_rss_feed: processing articles...");
568 }
569
570 foreach ($iterator as $item) {
571
572 if ($_REQUEST['xdebug'] == 2) {
573 print_r($item);
574 }
575
576 if ($use_simplepie) {
577 $entry_guid = $item->get_id();
578 if (!$entry_guid) $entry_guid = $item->get_link();
579 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
580
581 } else {
582
583 $entry_guid = $item["id"];
584
585 if (!$entry_guid) $entry_guid = $item["guid"];
586 if (!$entry_guid) $entry_guid = $item["about"];
587 if (!$entry_guid) $entry_guid = $item["link"];
588 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
589 }
590
591 if ($debug_enabled) {
592 _debug("update_rss_feed: guid $entry_guid");
593 }
594
595 if (!$entry_guid) continue;
596
597 $entry_timestamp = "";
598
599 if ($use_simplepie) {
600 $entry_timestamp = strtotime($item->get_date());
601 } else {
602 $rss_2_date = $item['pubdate'];
603 $rss_1_date = $item['dc']['date'];
604 $atom_date = $item['issued'];
605 if (!$atom_date) $atom_date = $item['updated'];
606
607 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
608 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
609 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
610
611 }
612
613 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
614 $entry_timestamp = time();
615 $no_orig_date = 'true';
616 } else {
617 $no_orig_date = 'false';
618 }
619
620 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
621
622 if ($debug_enabled) {
623 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
624 }
625
626 if ($use_simplepie) {
627 $entry_title = $item->get_title();
628 } else {
629 $entry_title = trim(strip_tags($item["title"]));
630 }
631
632 if ($use_simplepie) {
633 $entry_link = $item->get_link();
634 } else {
635 // strange Magpie workaround
636 $entry_link = $item["link_"];
637 if (!$entry_link) $entry_link = $item["link"];
638 }
639
640 $entry_link = rewrite_relative_url($site_url, $entry_link);
641
642 if ($debug_enabled) {
643 _debug("update_rss_feed: title $entry_title");
644 _debug("update_rss_feed: link $entry_link");
645 }
646
647 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
648
649 $entry_link = strip_tags($entry_link);
650
651 if ($use_simplepie) {
652 $entry_content = $item->get_content();
653 if (!$entry_content) $entry_content = $item->get_description();
654 } else {
655 $entry_content = $item["content:escaped"];
656
657 if (!$entry_content) $entry_content = $item["content:encoded"];
658 if (!$entry_content) $entry_content = $item["content"]["encoded"];
659 if (!$entry_content) $entry_content = $item["content"];
660
661 if (is_array($entry_content)) $entry_content = $entry_content[0];
662
663 // Magpie bugs are getting ridiculous
664 if (trim($entry_content) == "Array") $entry_content = false;
665
666 if (!$entry_content) $entry_content = $item["atom_content"];
667 if (!$entry_content) $entry_content = $item["summary"];
668
669 if (!$entry_content ||
670 strlen($entry_content) < strlen($item["description"])) {
671 $entry_content = $item["description"];
672 };
673
674 // WTF
675 if (is_array($entry_content)) {
676 $entry_content = $entry_content["encoded"];
677 if (!$entry_content) $entry_content = $entry_content["escaped"];
678 }
679 }
680
c5867798 681 if ($cache_images && is_writable(CACHE_DIR . '/images'))
3c696512
AD
682 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
683
2c08214a
AD
684 if ($_REQUEST["xdebug"] == 2) {
685 print "update_rss_feed: content: ";
487f0750 686 print $entry_content;
3c696512 687 print "\n";
2c08214a
AD
688 }
689
690 $entry_content_unescaped = $entry_content;
691
692 if ($use_simplepie) {
693 $entry_comments = strip_tags($item->data["comments"]);
694 if ($item->get_author()) {
695 $entry_author_item = $item->get_author();
696 $entry_author = $entry_author_item->get_name();
697 if (!$entry_author) $entry_author = $entry_author_item->get_email();
698
699 $entry_author = db_escape_string($entry_author);
700 }
701 } else {
702 $entry_comments = strip_tags($item["comments"]);
703
704 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
705
706 if ($item['author']) {
707
708 if (is_array($item['author'])) {
709
710 if (!$entry_author) {
711 $entry_author = db_escape_string(strip_tags($item['author']['name']));
712 }
713
714 if (!$entry_author) {
715 $entry_author = db_escape_string(strip_tags($item['author']['email']));
716 }
717 }
718
719 if (!$entry_author) {
720 $entry_author = db_escape_string(strip_tags($item['author']));
721 }
722 }
723 }
724
725 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
726
727 $entry_guid = db_escape_string(strip_tags($entry_guid));
728 $entry_guid = mb_substr($entry_guid, 0, 250);
729
730 $result = db_query($link, "SELECT id FROM ttrss_entries
731 WHERE guid = '$entry_guid'");
732
733 $entry_content = db_escape_string($entry_content, false);
734
487f0750 735 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
2c08214a
AD
736
737 $entry_title = db_escape_string($entry_title);
738 $entry_link = db_escape_string($entry_link);
739 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
740 $entry_author = mb_substr($entry_author, 0, 250);
741
742 if ($use_simplepie) {
743 $num_comments = 0; #FIXME#
744 } else {
745 $num_comments = db_escape_string($item["slash"]["comments"]);
746 }
747
748 if (!$num_comments) $num_comments = 0;
749
750 if ($debug_enabled) {
751 _debug("update_rss_feed: looking for tags [1]...");
752 }
753
754 // parse <category> entries into tags
755
756 $additional_tags = array();
757
758 if ($use_simplepie) {
759
760 $additional_tags_src = $item->get_categories();
761
762 if (is_array($additional_tags_src)) {
763 foreach ($additional_tags_src as $tobj) {
764 array_push($additional_tags, $tobj->get_term());
765 }
766 }
767
768 if ($debug_enabled) {
769 _debug("update_rss_feed: category tags:");
770 print_r($additional_tags);
771 }
772
773 } else {
774
775 $t_ctr = $item['category#'];
776
777 if ($t_ctr == 0) {
778 $additional_tags = array();
779 } else if ($t_ctr > 0) {
780 $additional_tags = array($item['category']);
781
782 if ($item['category@term']) {
783 array_push($additional_tags, $item['category@term']);
784 }
785
786 for ($i = 0; $i <= $t_ctr; $i++ ) {
787 if ($item["category#$i"]) {
788 array_push($additional_tags, $item["category#$i"]);
789 }
790
791 if ($item["category#$i@term"]) {
792 array_push($additional_tags, $item["category#$i@term"]);
793 }
794 }
795 }
796
797 // parse <dc:subject> elements
798
799 $t_ctr = $item['dc']['subject#'];
800
801 if ($t_ctr > 0) {
802 array_push($additional_tags, $item['dc']['subject']);
803
804 for ($i = 0; $i <= $t_ctr; $i++ ) {
805 if ($item['dc']["subject#$i"]) {
806 array_push($additional_tags, $item['dc']["subject#$i"]);
807 }
808 }
809 }
810 }
811
812 if ($debug_enabled) {
813 _debug("update_rss_feed: looking for tags [2]...");
814 }
815
816 /* taaaags */
817 // <a href="..." rel="tag">Xorg</a>, //
818
819 $entry_tags = null;
820
821 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
822 $entry_content_unescaped, $entry_tags);
823
824 $entry_tags = $entry_tags[1];
825
826 $entry_tags = array_merge($entry_tags, $additional_tags);
827 $entry_tags = array_unique($entry_tags);
828
829 for ($i = 0; $i < count($entry_tags); $i++)
830 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
831
832 if ($debug_enabled) {
833 _debug("update_rss_feed: unfiltered tags found:");
834 print_r($entry_tags);
835 }
836
837 # sanitize content
838
839 $entry_content = sanitize_article_content($entry_content);
840 $entry_title = sanitize_article_content($entry_title);
841
842 if ($debug_enabled) {
843 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
844 }
845
846 db_query($link, "BEGIN");
847
848 if (db_num_rows($result) == 0) {
849
850 if ($debug_enabled) {
851 _debug("update_rss_feed: base guid not found");
852 }
853
854 // base post entry does not exist, create it
855
856 $result = db_query($link,
857 "INSERT INTO ttrss_entries
858 (title,
859 guid,
860 link,
861 updated,
862 content,
863 content_hash,
864 no_orig_date,
865 date_updated,
866 date_entered,
867 comments,
868 num_comments,
869 author)
870 VALUES
871 ('$entry_title',
872 '$entry_guid',
873 '$entry_link',
874 '$entry_timestamp_fmt',
875 '$entry_content',
876 '$content_hash',
877 $no_orig_date,
878 NOW(),
879 NOW(),
880 '$entry_comments',
881 '$num_comments',
882 '$entry_author')");
883 } else {
884 // we keep encountering the entry in feeds, so we need to
885 // update date_updated column so that we don't get horrible
886 // dupes when the entry gets purged and reinserted again e.g.
887 // in the case of SLOW SLOW OMG SLOW updating feeds
888
889 $base_entry_id = db_fetch_result($result, 0, "id");
890
891 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
892 WHERE id = '$base_entry_id'");
893 }
894
895 // now it should exist, if not - bad luck then
896
897 $result = db_query($link, "SELECT
898 id,content_hash,no_orig_date,title,
899 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
900 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
901 num_comments
902 FROM
903 ttrss_entries
904 WHERE guid = '$entry_guid'");
905
906 $entry_ref_id = 0;
907 $entry_int_id = 0;
908
909 if (db_num_rows($result) == 1) {
910
911 if ($debug_enabled) {
912 _debug("update_rss_feed: base guid found, checking for user record");
913 }
914
915 // this will be used below in update handler
916 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
917 $orig_title = db_fetch_result($result, 0, "title");
918 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
919 $orig_date_updated = strtotime(db_fetch_result($result,
920 0, "date_updated"));
921
922 $ref_id = db_fetch_result($result, 0, "id");
923 $entry_ref_id = $ref_id;
924
925 // check for user post link to main table
926
927 // do we allow duplicate posts with same GUID in different feeds?
928 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
929 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
930 } else {
931 $dupcheck_qpart = "";
932 }
933
934 /* Collect article tags here so we could filter by them: */
935
936 $article_filters = get_article_filters($filters, $entry_title,
937 $entry_content, $entry_link, $entry_timestamp, $entry_author,
938 $entry_tags);
939
940 if ($debug_enabled) {
941 _debug("update_rss_feed: article filters: ");
942 if (count($article_filters) != 0) {
943 print_r($article_filters);
944 }
945 }
946
947 if (find_article_filter($article_filters, "filter")) {
948 db_query($link, "COMMIT"); // close transaction in progress
949 continue;
950 }
951
952 $score = calculate_article_score($article_filters);
953
954 if ($debug_enabled) {
955 _debug("update_rss_feed: initial score: $score");
956 }
957
958 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
959 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
960 $dupcheck_qpart";
961
962// if ($_REQUEST["xdebug"]) print "$query\n";
963
964 $result = db_query($link, $query);
965
966 // okay it doesn't exist - create user entry
967 if (db_num_rows($result) == 0) {
968
969 if ($debug_enabled) {
970 _debug("update_rss_feed: user record not found, creating...");
971 }
972
973 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
974 $unread = 'true';
975 $last_read_qpart = 'NULL';
976 } else {
977 $unread = 'false';
978 $last_read_qpart = 'NOW()';
979 }
980
981 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
982 $marked = 'true';
983 } else {
984 $marked = 'false';
985 }
986
987 if (find_article_filter($article_filters, 'publish')) {
988 $published = 'true';
989 } else {
990 $published = 'false';
991 }
992
993 $result = db_query($link,
994 "INSERT INTO ttrss_user_entries
995 (ref_id, owner_uid, feed_id, unread, last_read, marked,
996 published, score, tag_cache, label_cache, uuid)
997 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
998 $last_read_qpart, $marked, $published, '$score', '', '', '')");
999
1000 if (PUBSUBHUBBUB_HUB && $published == 'true') {
1001 $rss_link = get_self_url_prefix() .
1002 "/public.php?op=rss&id=-2&key=" .
1003 get_feed_access_key($link, -2, false, $owner_uid);
1004
1005 $p = new Publisher(PUBSUBHUBBUB_HUB);
1006
1007 $pubsub_result = $p->publish_update($rss_link);
1008 }
1009
1010 $result = db_query($link,
1011 "SELECT int_id FROM ttrss_user_entries WHERE
1012 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1013 feed_id = '$feed' LIMIT 1");
1014
1015 if (db_num_rows($result) == 1) {
1016 $entry_int_id = db_fetch_result($result, 0, "int_id");
1017 }
1018 } else {
1019 if ($debug_enabled) {
1020 _debug("update_rss_feed: user record FOUND");
1021 }
1022
1023 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1024 $entry_int_id = db_fetch_result($result, 0, "int_id");
1025 }
1026
1027 if ($debug_enabled) {
1028 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1029 }
1030
1031 $post_needs_update = false;
1032 $update_insignificant = false;
1033
1034 if ($orig_num_comments != $num_comments) {
1035 $post_needs_update = true;
1036 $update_insignificant = true;
1037 }
1038
1039 if ($content_hash != $orig_content_hash) {
1040 $post_needs_update = true;
1041 $update_insignificant = false;
1042 }
1043
1044 if (db_escape_string($orig_title) != $entry_title) {
1045 $post_needs_update = true;
1046 $update_insignificant = false;
1047 }
1048
1049 // if post needs update, update it and mark all user entries
1050 // linking to this post as updated
1051 if ($post_needs_update) {
1052
1053 if (defined('DAEMON_EXTENDED_DEBUG')) {
1054 _debug("update_rss_feed: post $entry_guid needs update...");
1055 }
1056
1057// print "<!-- post $orig_title needs update : $post_needs_update -->";
1058
1059 db_query($link, "UPDATE ttrss_entries
1060 SET title = '$entry_title', content = '$entry_content',
1061 content_hash = '$content_hash',
1062 updated = '$entry_timestamp_fmt',
1063 num_comments = '$num_comments'
1064 WHERE id = '$ref_id'");
1065
1066 if (!$update_insignificant) {
1067 if ($mark_unread_on_update) {
1068 db_query($link, "UPDATE ttrss_user_entries
1069 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1070 } else if ($update_on_checksum_change) {
1071 db_query($link, "UPDATE ttrss_user_entries
1072 SET last_read = null WHERE ref_id = '$ref_id'
1073 AND unread = false");
1074 }
1075 }
1076 }
1077 }
1078
1079 db_query($link, "COMMIT");
1080
1081 if ($debug_enabled) {
1082 _debug("update_rss_feed: assigning labels...");
1083 }
1084
1085 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1086 $owner_uid);
1087
1088 if ($debug_enabled) {
1089 _debug("update_rss_feed: looking for enclosures...");
1090 }
1091
1092 // enclosures
1093
1094 $enclosures = array();
1095
1096 if ($use_simplepie) {
1097 $encs = $item->get_enclosures();
1098
1099 if (is_array($encs)) {
1100 foreach ($encs as $e) {
1101 $e_item = array(
1102 $e->link, $e->type, $e->length);
1103
1104 array_push($enclosures, $e_item);
1105 }
1106 }
1107
1108 } else {
1109 // <enclosure>
1110
1111 $e_ctr = $item['enclosure#'];
1112
1113 if ($e_ctr > 0) {
1114 $e_item = array($item['enclosure@url'],
1115 $item['enclosure@type'],
1116 $item['enclosure@length']);
1117
1118 array_push($enclosures, $e_item);
1119
1120 for ($i = 0; $i <= $e_ctr; $i++ ) {
1121
1122 if ($item["enclosure#$i@url"]) {
1123 $e_item = array($item["enclosure#$i@url"],
1124 $item["enclosure#$i@type"],
1125 $item["enclosure#$i@length"]);
1126 array_push($enclosures, $e_item);
1127 }
1128 }
1129 }
1130
1131 // <media:content>
1132 // can there be many of those? yes -fox
1133
1134 $m_ctr = $item['media']['content#'];
1135
1136 if ($m_ctr > 0) {
1137 $e_item = array($item['media']['content@url'],
1138 $item['media']['content@medium'],
1139 $item['media']['content@length']);
1140
1141 array_push($enclosures, $e_item);
1142
1143 for ($i = 0; $i <= $m_ctr; $i++ ) {
1144
1145 if ($item["media"]["content#$i@url"]) {
1146 $e_item = array($item["media"]["content#$i@url"],
1147 $item["media"]["content#$i@medium"],
1148 $item["media"]["content#$i@length"]);
1149 array_push($enclosures, $e_item);
1150 }
1151 }
1152
1153 }
1154 }
1155
1156
1157 if ($debug_enabled) {
1158 _debug("update_rss_feed: article enclosures:");
1159 print_r($enclosures);
1160 }
1161
1162 db_query($link, "BEGIN");
1163
1164 foreach ($enclosures as $enc) {
1165 $enc_url = db_escape_string($enc[0]);
1166 $enc_type = db_escape_string($enc[1]);
1167 $enc_dur = db_escape_string($enc[2]);
1168
1169 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1170 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1171
1172 if (db_num_rows($result) == 0) {
1173 db_query($link, "INSERT INTO ttrss_enclosures
1174 (content_url, content_type, title, duration, post_id) VALUES
1175 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1176 }
1177 }
1178
1179 db_query($link, "COMMIT");
1180
1181 // check for manual tags (we have to do it here since they're loaded from filters)
1182
1183 foreach ($article_filters as $f) {
1184 if ($f[0] == "tag") {
1185
1186 $manual_tags = trim_array(explode(",", $f[1]));
1187
1188 foreach ($manual_tags as $tag) {
1189 if (tag_is_valid($tag)) {
1190 array_push($entry_tags, $tag);
1191 }
1192 }
1193 }
1194 }
1195
1196 // Skip boring tags
1197
1198 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1199 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1200
1201 $filtered_tags = array();
1202 $tags_to_cache = array();
1203
1204 if ($entry_tags && is_array($entry_tags)) {
1205 foreach ($entry_tags as $tag) {
1206 if (array_search($tag, $boring_tags) === false) {
1207 array_push($filtered_tags, $tag);
1208 }
1209 }
1210 }
1211
1212 $filtered_tags = array_unique($filtered_tags);
1213
1214 if ($debug_enabled) {
1215 _debug("update_rss_feed: filtered article tags:");
1216 print_r($filtered_tags);
1217 }
1218
1219 // Save article tags in the database
1220
1221 if (count($filtered_tags) > 0) {
1222
1223 db_query($link, "BEGIN");
1224
1225 foreach ($filtered_tags as $tag) {
1226
1227 $tag = sanitize_tag($tag);
1228 $tag = db_escape_string($tag);
1229
1230 if (!tag_is_valid($tag)) continue;
1231
1232 $result = db_query($link, "SELECT id FROM ttrss_tags
1233 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1234 owner_uid = '$owner_uid' LIMIT 1");
1235
1236 if ($result && db_num_rows($result) == 0) {
1237
1238 db_query($link, "INSERT INTO ttrss_tags
1239 (owner_uid,tag_name,post_int_id)
1240 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1241 }
1242
1243 array_push($tags_to_cache, $tag);
1244 }
1245
1246 /* update the cache */
1247
1248 $tags_to_cache = array_unique($tags_to_cache);
1249
1250 $tags_str = db_escape_string(join(",", $tags_to_cache));
1251
1252 db_query($link, "UPDATE ttrss_user_entries
1253 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1254 AND owner_uid = $owner_uid");
1255
1256 db_query($link, "COMMIT");
1257 }
1258
1259 if ($debug_enabled) {
1260 _debug("update_rss_feed: article processed");
1261 }
1262 }
1263
1264 if (!$last_updated) {
1265 if ($debug_enabled) {
1266 _debug("update_rss_feed: new feed, catching it up...");
1267 }
1268 catchup_feed($link, $feed, false, $owner_uid);
1269 }
1270
1271 if ($debug_enabled) {
1272 _debug("purging feed...");
1273 }
1274
1275 purge_feed($link, $feed, 0, $debug_enabled);
1276
1277 db_query($link, "UPDATE ttrss_feeds
1278 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1279
1280// db_query($link, "COMMIT");
1281
1282 } else {
1283
1284 if ($use_simplepie) {
1285 $error_msg = mb_substr($rss->error(), 0, 250);
1286 } else {
1287 $error_msg = mb_substr(magpie_error(), 0, 250);
1288 }
1289
1290 if ($debug_enabled) {
1291 _debug("update_rss_feed: error fetching feed: $error_msg");
1292 }
1293
1294 $error_msg = db_escape_string($error_msg);
1295
1296 db_query($link,
1297 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1298 last_updated = NOW() WHERE id = '$feed'");
1299 }
1300
1301 if ($use_simplepie) {
1302 unset($rss);
1303 }
1304
1305 if ($debug_enabled) {
1306 _debug("update_rss_feed: done");
1307 }
1308
1309 }
1310
3c696512
AD
1311 function cache_images($html, $site_url, $debug) {
1312 $cache_dir = CACHE_DIR . "/images";
1313
1314 libxml_use_internal_errors(true);
1315
1316 $charset_hack = '<head>
1317 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1318 </head>';
1319
1320 $doc = new DOMDocument();
1321 $doc->loadHTML($charset_hack . $html);
1322 $xpath = new DOMXPath($doc);
1323
1324 $entries = $xpath->query('(//img[@src])');
1325
1326 foreach ($entries as $entry) {
1327 if ($entry->hasAttribute('src')) {
1328 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1329
1330 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1331
1332 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1333
1334 if (!file_exists($local_filename)) {
1335 $file_content = fetch_file_contents($src);
1336
1337 if ($file_content) {
1338 file_put_contents($local_filename, $file_content);
1339 }
1340 }
1341
1342 if (file_exists($local_filename)) {
1343 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
487f0750 1344 base64_encode($src));
3c696512
AD
1345 }
1346 }
1347 }
1348
1349 $node = $doc->getElementsByTagName('body')->item(0);
1350
1351 return $doc->saveXML($node);
1352 }
1353
1354 function expire_cached_files($debug) {
1355 foreach (array("magpie", "simplepie", "images") as $dir) {
1356 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1357
3c696512 1358 if ($debug) _debug("Expiring $cache_dir");
2c08214a 1359
3c696512
AD
1360 $num_deleted = 0;
1361
1362 if (is_writable($cache_dir)) {
1363 $files = glob("$cache_dir/*");
1364
1365 foreach ($files as $file) {
1366 if (time() - filemtime($file) > 86400*7) {
1367 unlink($file);
1368
1369 ++$num_deleted;
1370 }
1371 }
1372 }
1373
1374 if ($debug) _debug("Removed $num_deleted files.");
1375 }
1376 }
2c08214a
AD
1377
1378?>