2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
4 define('DAEMON_SLEEP_INTERVAL', 120);
6 function update_feedbrowser_cache($link) {
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");
14 db_query($link, "BEGIN");
16 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
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"]);
26 $tmp_result = db_query($link, "SELECT subscribers FROM
27 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
29 if (db_num_rows($tmp_result) == 0) {
31 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
32 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
33 '$site_url', '$title', '$subscribers')");
41 db_query($link, "COMMIT");
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
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.
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
63 // Test if the user has loggued in recently. If not, it does not update its feeds.
64 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
65 if (DB_TYPE
== "pgsql") {
66 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
68 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
71 $login_thresh_qpart = "";
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)
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)";
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)
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)";
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')";
97 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
100 // Test if there is a limit to number of updated feeds
102 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
104 $random_qpart = sql_random_function();
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
111 ttrss_feeds, ttrss_users, ttrss_user_prefs
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");
120 $user_prefs_cache = array();
122 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
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;
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);
135 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
136 WHERE id IN (%s)", implode(',', $feed_ids)));
139 expire_cached_files($debug);
141 // For each feed, we call the feed update function.
142 while ($line = array_pop($feeds_to_update)) {
144 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
146 update_rss_feed($link, $line["id"], true);
148 sleep(1); // prevent flood (FIXME make this an option?)
151 // Send feed digests by email if needed.
152 send_headlines_digests($link, 100, $debug);
154 } // function update_daemon_common
156 function fetch_twitter_rss($link, $url, $owner_uid) {
158 require_once 'lib/tmhoauth/tmhOAuth.php';
160 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
161 WHERE id = $owner_uid");
163 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
164 $url_escaped = db_escape_string($url);
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'],
175 $code = $tmhOAuth->request('GET', $url);
179 $content = $tmhOAuth->response
['response'];
181 define('MAGPIE_CACHE_ON', false);
183 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
184 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
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");
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");
205 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
209 /* Update all feeds with the same URL to utilize 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'");
216 while ($line = db_fetch_assoc($result)) {
217 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
220 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
224 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
225 $override_url = false) {
227 require_once "lib/simplepie/simplepie.inc";
228 require_once "lib/magpierss/rss_fetch.inc";
229 require_once 'lib/magpierss/rss_utils.inc';
233 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
235 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
239 if ($debug_enabled) {
240 _debug("update_rss_feed: start");
243 if (!$ignore_daemon) {
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')";
248 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
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");
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,
261 FROM ttrss_feeds WHERE id = '$feed'");
265 if (db_num_rows($result) == 0) {
266 if ($debug_enabled) {
267 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
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");
281 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
282 WHERE id = '$feed'");
284 $auth_login = db_fetch_result($result, 0, "auth_login");
285 $auth_pass = db_fetch_result($result, 0, "auth_pass");
287 if ($update_method == 0)
288 $update_method = DEFAULT_UPDATE_METHOD +
1;
294 if ($update_method == 2)
295 $use_simplepie = true;
297 $use_simplepie = false;
299 if ($debug_enabled) {
300 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
303 if ($update_method == 1) {
304 $auth_login = urlencode($auth_login);
305 $auth_pass = urlencode($auth_pass);
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");
312 if ($update_interval < 0) { return false; }
314 $feed = db_escape_string($feed);
316 if ($auth_login && $auth_pass ){
317 $url_parts = array();
318 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
320 if ($url_parts[1] && $url_parts[2]) {
321 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
327 $fetch_url = $override_url;
329 if ($debug_enabled) {
330 _debug("update_rss_feed: fetching [$fetch_url]...");
333 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
335 if ($memcache && $obj = $memcache->get($obj_id)) {
337 if ($debug_enabled) {
338 _debug("update_rss_feed: data found in memcache.");
345 if ($update_method == 3) {
346 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
347 } else if ($update_method == 1) {
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");
354 $rss = @fetch_rss
($fetch_url);
356 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
358 if (!is_dir($simplepie_cache_dir)) {
359 mkdir($simplepie_cache_dir);
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');
367 $rss->force_feed(true);
369 if ($debug_enabled) {
370 _debug("feed update interval (sec): " .
371 get_feed_update_interval($link, $feed)*60);
374 $rss->enable_cache(!$no_cache);
377 $rss->set_cache_location($simplepie_cache_dir);
378 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
384 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
389 if ($debug_enabled) {
390 _debug("update_rss_feed: fetch done, parsing...");
393 $feed = db_escape_string($feed);
395 if ($update_method == 2) {
396 $fetch_ok = !$rss->error();
403 if ($debug_enabled) {
404 _debug("update_rss_feed: processing feed data...");
407 // db_query($link, "BEGIN");
409 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
410 FROM ttrss_feeds WHERE id = '$feed'");
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");
416 $owner_uid = db_fetch_result($result, 0, "owner_uid");
418 if ($use_simplepie) {
419 $site_url = $rss->get_link();
421 $site_url = $rss->channel
["link"];
424 $site_url = rewrite_relative_url($fetch_url, $site_url);
426 if ($debug_enabled) {
427 _debug("update_rss_feed: checking favicon...");
430 check_feed_favicon($site_url, $feed, $link);
432 if (!$registered_title ||
$registered_title == "[Unknown]") {
434 if ($use_simplepie) {
435 $feed_title = db_escape_string($rss->get_title());
437 $feed_title = db_escape_string($rss->channel
["title"]);
440 if ($debug_enabled) {
441 _debug("update_rss_feed: registering title: $feed_title");
444 db_query($link, "UPDATE ttrss_feeds SET
445 title = '$feed_title' WHERE id = '$feed'");
448 // weird, weird Magpie
449 if (!$use_simplepie) {
450 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
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'");
458 // print "I: " . $rss->channel["image"]["url"];
460 if (!$use_simplepie) {
461 $icon_url = db_escape_string($rss->image
["url"]);
463 $icon_url = db_escape_string($rss->get_image_url());
466 $icon_url = substr($icon_url, 0, 250);
468 if ($icon_url && $orig_icon_url != $icon_url) {
469 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
472 if ($debug_enabled) {
473 _debug("update_rss_feed: loading filters...");
476 $filters = load_filters($link, $feed, $owner_uid);
478 // if ($debug_enabled) {
479 // print_r($filters);
482 if ($use_simplepie) {
483 $iterator = $rss->get_items();
485 $iterator = $rss->items
;
486 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
487 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
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'"); */
495 // clear any errors and mark feed as updated if fetched okay
496 // even if it's blank
498 if ($debug_enabled) {
499 _debug("update_rss_feed: entry iterator is not an array, no articles?");
502 db_query($link, "UPDATE ttrss_feeds
503 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
505 return; // no articles
508 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
510 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
512 $feed_hub_url = false;
513 if ($use_simplepie) {
514 $links = $rss->get_links('hub');
516 if ($links && is_array($links)) {
517 foreach ($links as $l) {
524 $atom = $rss->channel
['atom'];
527 if ($atom['link@rel'] == 'hub') {
528 $feed_hub_url = $atom['link@href'];
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"];
540 $feed_hub_url = $rss->channel
['link_hub'];
544 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
546 if ($feed_hub_url && function_exists('curl_init') &&
547 !ini_get("open_basedir")) {
549 require_once 'lib/pubsubhubbub/subscriber.php';
551 $callback_url = get_self_url_prefix() .
552 "/public.php?op=pubsub&id=$feed";
554 $s = new Subscriber($feed_hub_url, $callback_url);
556 $rc = $s->subscribe($fetch_url);
559 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
561 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
562 WHERE id = '$feed'");
566 if ($debug_enabled) {
567 _debug("update_rss_feed: processing articles...");
570 foreach ($iterator as $item) {
572 if ($_REQUEST['xdebug'] == 2) {
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());
583 $entry_guid = $item["id"];
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"]);
591 if ($debug_enabled) {
592 _debug("update_rss_feed: guid $entry_guid");
595 if (!$entry_guid) continue;
597 $entry_timestamp = "";
599 if ($use_simplepie) {
600 $entry_timestamp = strtotime($item->get_date());
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'];
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);
613 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
614 $entry_timestamp = time();
615 $no_orig_date = 'true';
617 $no_orig_date = 'false';
620 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
622 if ($debug_enabled) {
623 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
626 if ($use_simplepie) {
627 $entry_title = $item->get_title();
629 $entry_title = trim(strip_tags($item["title"]));
632 if ($use_simplepie) {
633 $entry_link = $item->get_link();
635 // strange Magpie workaround
636 $entry_link = $item["link_"];
637 if (!$entry_link) $entry_link = $item["link"];
640 $entry_link = rewrite_relative_url($site_url, $entry_link);
642 if ($debug_enabled) {
643 _debug("update_rss_feed: title $entry_title");
644 _debug("update_rss_feed: link $entry_link");
647 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
649 $entry_link = strip_tags($entry_link);
651 if ($use_simplepie) {
652 $entry_content = $item->get_content();
653 if (!$entry_content) $entry_content = $item->get_description();
655 $entry_content = $item["content:escaped"];
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"];
661 if (is_array($entry_content)) $entry_content = $entry_content[0];
663 // Magpie bugs are getting ridiculous
664 if (trim($entry_content) == "Array") $entry_content = false;
666 if (!$entry_content) $entry_content = $item["atom_content"];
667 if (!$entry_content) $entry_content = $item["summary"];
669 if (!$entry_content ||
670 strlen($entry_content) < strlen($item["description"])) {
671 $entry_content = $item["description"];
675 if (is_array($entry_content)) {
676 $entry_content = $entry_content["encoded"];
677 if (!$entry_content) $entry_content = $entry_content["escaped"];
681 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
682 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
684 if ($_REQUEST["xdebug"] == 2) {
685 print "update_rss_feed: content: ";
686 print $entry_content;
690 $entry_content_unescaped = $entry_content;
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();
699 $entry_author = db_escape_string($entry_author);
702 $entry_comments = strip_tags($item["comments"]);
704 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
706 if ($item['author']) {
708 if (is_array($item['author'])) {
710 if (!$entry_author) {
711 $entry_author = db_escape_string(strip_tags($item['author']['name']));
714 if (!$entry_author) {
715 $entry_author = db_escape_string(strip_tags($item['author']['email']));
719 if (!$entry_author) {
720 $entry_author = db_escape_string(strip_tags($item['author']));
725 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
727 $entry_guid = db_escape_string(strip_tags($entry_guid));
728 $entry_guid = mb_substr($entry_guid, 0, 250);
730 $result = db_query($link, "SELECT id FROM ttrss_entries
731 WHERE guid = '$entry_guid'");
733 $entry_content = db_escape_string($entry_content, false);
735 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
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);
742 if ($use_simplepie) {
743 $num_comments = 0; #FIXME#
745 $num_comments = db_escape_string($item["slash"]["comments"]);
748 if (!$num_comments) $num_comments = 0;
750 if ($debug_enabled) {
751 _debug("update_rss_feed: looking for tags [1]...");
754 // parse <category> entries into tags
756 $additional_tags = array();
758 if ($use_simplepie) {
760 $additional_tags_src = $item->get_categories();
762 if (is_array($additional_tags_src)) {
763 foreach ($additional_tags_src as $tobj) {
764 array_push($additional_tags, $tobj->get_term());
768 if ($debug_enabled) {
769 _debug("update_rss_feed: category tags:");
770 print_r($additional_tags);
775 $t_ctr = $item['category#'];
778 $additional_tags = array();
779 } else if ($t_ctr > 0) {
780 $additional_tags = array($item['category']);
782 if ($item['category@term']) {
783 array_push($additional_tags, $item['category@term']);
786 for ($i = 0; $i <= $t_ctr; $i++
) {
787 if ($item["category#$i"]) {
788 array_push($additional_tags, $item["category#$i"]);
791 if ($item["category#$i@term"]) {
792 array_push($additional_tags, $item["category#$i@term"]);
797 // parse <dc:subject> elements
799 $t_ctr = $item['dc']['subject#'];
802 array_push($additional_tags, $item['dc']['subject']);
804 for ($i = 0; $i <= $t_ctr; $i++
) {
805 if ($item['dc']["subject#$i"]) {
806 array_push($additional_tags, $item['dc']["subject#$i"]);
812 if ($debug_enabled) {
813 _debug("update_rss_feed: looking for tags [2]...");
817 // <a href="..." rel="tag">Xorg</a>, //
821 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
822 $entry_content_unescaped, $entry_tags);
824 $entry_tags = $entry_tags[1];
826 $entry_tags = array_merge($entry_tags, $additional_tags);
827 $entry_tags = array_unique($entry_tags);
829 for ($i = 0; $i < count($entry_tags); $i++
)
830 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
832 if ($debug_enabled) {
833 _debug("update_rss_feed: unfiltered tags found:");
834 print_r($entry_tags);
839 $entry_content = sanitize_article_content($entry_content);
840 $entry_title = sanitize_article_content($entry_title);
842 if ($debug_enabled) {
843 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
846 db_query($link, "BEGIN");
848 if (db_num_rows($result) == 0) {
850 if ($debug_enabled) {
851 _debug("update_rss_feed: base guid not found");
854 // base post entry does not exist, create it
856 $result = db_query($link,
857 "INSERT INTO ttrss_entries
874 '$entry_timestamp_fmt',
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
889 $base_entry_id = db_fetch_result($result, 0, "id");
891 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
892 WHERE id = '$base_entry_id'");
895 // now it should exist, if not - bad luck then
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,
904 WHERE guid = '$entry_guid'");
909 if (db_num_rows($result) == 1) {
911 if ($debug_enabled) {
912 _debug("update_rss_feed: base guid found, checking for user record");
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,
922 $ref_id = db_fetch_result($result, 0, "id");
923 $entry_ref_id = $ref_id;
925 // check for user post link to main table
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)";
931 $dupcheck_qpart = "";
934 /* Collect article tags here so we could filter by them: */
936 $article_filters = get_article_filters($filters, $entry_title,
937 $entry_content, $entry_link, $entry_timestamp, $entry_author,
940 if ($debug_enabled) {
941 _debug("update_rss_feed: article filters: ");
942 if (count($article_filters) != 0) {
943 print_r($article_filters);
947 if (find_article_filter($article_filters, "filter")) {
948 db_query($link, "COMMIT"); // close transaction in progress
952 $score = calculate_article_score($article_filters);
954 if ($debug_enabled) {
955 _debug("update_rss_feed: initial score: $score");
958 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
959 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
962 // if ($_REQUEST["xdebug"]) print "$query\n";
964 $result = db_query($link, $query);
966 // okay it doesn't exist - create user entry
967 if (db_num_rows($result) == 0) {
969 if ($debug_enabled) {
970 _debug("update_rss_feed: user record not found, creating...");
973 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
975 $last_read_qpart = 'NULL';
978 $last_read_qpart = 'NOW()';
981 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
987 if (find_article_filter($article_filters, 'publish')) {
990 $published = 'false';
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', '', '', '')");
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);
1005 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1007 $pubsub_result = $p->publish_update($rss_link);
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");
1015 if (db_num_rows($result) == 1) {
1016 $entry_int_id = db_fetch_result($result, 0, "int_id");
1019 if ($debug_enabled) {
1020 _debug("update_rss_feed: user record FOUND");
1023 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1024 $entry_int_id = db_fetch_result($result, 0, "int_id");
1027 if ($debug_enabled) {
1028 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1031 $post_needs_update = false;
1032 $update_insignificant = false;
1034 if ($orig_num_comments != $num_comments) {
1035 $post_needs_update = true;
1036 $update_insignificant = true;
1039 if ($content_hash != $orig_content_hash) {
1040 $post_needs_update = true;
1041 $update_insignificant = false;
1044 if (db_escape_string($orig_title) != $entry_title) {
1045 $post_needs_update = true;
1046 $update_insignificant = false;
1049 // if post needs update, update it and mark all user entries
1050 // linking to this post as updated
1051 if ($post_needs_update) {
1053 if (defined('DAEMON_EXTENDED_DEBUG')) {
1054 _debug("update_rss_feed: post $entry_guid needs update...");
1057 // print "<!-- post $orig_title needs update : $post_needs_update -->";
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'");
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");
1079 db_query($link, "COMMIT");
1081 if ($debug_enabled) {
1082 _debug("update_rss_feed: assigning labels...");
1085 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1088 if ($debug_enabled) {
1089 _debug("update_rss_feed: looking for enclosures...");
1094 $enclosures = array();
1096 if ($use_simplepie) {
1097 $encs = $item->get_enclosures();
1099 if (is_array($encs)) {
1100 foreach ($encs as $e) {
1102 $e->link
, $e->type
, $e->length
);
1104 array_push($enclosures, $e_item);
1111 $e_ctr = $item['enclosure#'];
1114 $e_item = array($item['enclosure@url'],
1115 $item['enclosure@type'],
1116 $item['enclosure@length']);
1118 array_push($enclosures, $e_item);
1120 for ($i = 0; $i <= $e_ctr; $i++
) {
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);
1132 // can there be many of those? yes -fox
1134 $m_ctr = $item['media']['content#'];
1137 $e_item = array($item['media']['content@url'],
1138 $item['media']['content@medium'],
1139 $item['media']['content@length']);
1141 array_push($enclosures, $e_item);
1143 for ($i = 0; $i <= $m_ctr; $i++
) {
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);
1157 if ($debug_enabled) {
1158 _debug("update_rss_feed: article enclosures:");
1159 print_r($enclosures);
1162 db_query($link, "BEGIN");
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]);
1169 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1170 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
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')");
1179 db_query($link, "COMMIT");
1181 // check for manual tags (we have to do it here since they're loaded from filters)
1183 foreach ($article_filters as $f) {
1184 if ($f[0] == "tag") {
1186 $manual_tags = trim_array(explode(",", $f[1]));
1188 foreach ($manual_tags as $tag) {
1189 if (tag_is_valid($tag)) {
1190 array_push($entry_tags, $tag);
1198 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1199 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1201 $filtered_tags = array();
1202 $tags_to_cache = array();
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);
1212 $filtered_tags = array_unique($filtered_tags);
1214 if ($debug_enabled) {
1215 _debug("update_rss_feed: filtered article tags:");
1216 print_r($filtered_tags);
1219 // Save article tags in the database
1221 if (count($filtered_tags) > 0) {
1223 db_query($link, "BEGIN");
1225 foreach ($filtered_tags as $tag) {
1227 $tag = sanitize_tag($tag);
1228 $tag = db_escape_string($tag);
1230 if (!tag_is_valid($tag)) continue;
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");
1236 if ($result && db_num_rows($result) == 0) {
1238 db_query($link, "INSERT INTO ttrss_tags
1239 (owner_uid,tag_name,post_int_id)
1240 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1243 array_push($tags_to_cache, $tag);
1246 /* update the cache */
1248 $tags_to_cache = array_unique($tags_to_cache);
1250 $tags_str = db_escape_string(join(",", $tags_to_cache));
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");
1256 db_query($link, "COMMIT");
1259 if ($debug_enabled) {
1260 _debug("update_rss_feed: article processed");
1264 if (!$last_updated) {
1265 if ($debug_enabled) {
1266 _debug("update_rss_feed: new feed, catching it up...");
1268 catchup_feed($link, $feed, false, $owner_uid);
1271 if ($debug_enabled) {
1272 _debug("purging feed...");
1275 purge_feed($link, $feed, 0, $debug_enabled);
1277 db_query($link, "UPDATE ttrss_feeds
1278 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1280 // db_query($link, "COMMIT");
1284 if ($use_simplepie) {
1285 $error_msg = mb_substr($rss->error(), 0, 250);
1287 $error_msg = mb_substr(magpie_error(), 0, 250);
1290 if ($debug_enabled) {
1291 _debug("update_rss_feed: error fetching feed: $error_msg");
1294 $error_msg = db_escape_string($error_msg);
1297 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1298 last_updated = NOW() WHERE id = '$feed'");
1301 if ($use_simplepie) {
1305 if ($debug_enabled) {
1306 _debug("update_rss_feed: done");
1311 function cache_images($html, $site_url, $debug) {
1312 $cache_dir = CACHE_DIR
. "/images";
1314 libxml_use_internal_errors(true);
1316 $charset_hack = '<head>
1317 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1320 $doc = new DOMDocument();
1321 $doc->loadHTML($charset_hack . $html);
1322 $xpath = new DOMXPath($doc);
1324 $entries = $xpath->query('(//img[@src])');
1326 foreach ($entries as $entry) {
1327 if ($entry->hasAttribute('src')) {
1328 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1330 $local_filename = CACHE_DIR
. "/images/" . sha1($src) . ".png";
1332 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1334 if (!file_exists($local_filename)) {
1335 $file_content = fetch_file_contents($src);
1337 if ($file_content) {
1338 file_put_contents($local_filename, $file_content);
1342 if (file_exists($local_filename)) {
1343 $entry->setAttribute('src', SELF_URL_PATH
. '/image.php?url=' .
1344 base64_encode($src));
1349 $node = $doc->getElementsByTagName('body')->item(0);
1351 return $doc->saveXML($node);
1354 function expire_cached_files($debug) {
1355 foreach (array("magpie", "simplepie", "images") as $dir) {
1356 $cache_dir = CACHE_DIR
. "/$dir";
1358 if ($debug) _debug("Expiring $cache_dir");
1362 if (is_writable($cache_dir)) {
1363 $files = glob("$cache_dir/*");
1365 foreach ($files as $file) {
1366 if (time() - filemtime($file) > 86400*7) {
1374 if ($debug) _debug("Removed $num_deleted files.");