2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
4 define('DAEMON_SLEEP_INTERVAL', 60);
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 define('PREFS_NO_CACHE', true);
65 // Test if the user has loggued in recently. If not, it does not update its feeds.
66 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
67 if (DB_TYPE == "pgsql") {
68 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
70 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
73 $login_thresh_qpart = "";
76 // Test if the feed need a update (update interval exceded).
77 if (DB_TYPE == "pgsql") {
78 $update_limit_qpart = "AND ((
79 ttrss_feeds.update_interval = 0
80 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
82 ttrss_feeds.update_interval > 0
83 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
84 ) OR ttrss_feeds.last_updated IS NULL
85 OR last_updated = '1970-01-01 00:00:00')";
87 $update_limit_qpart = "AND ((
88 ttrss_feeds.update_interval = 0
89 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
91 ttrss_feeds.update_interval > 0
92 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
93 ) OR ttrss_feeds.last_updated IS NULL
94 OR last_updated = '1970-01-01 00:00:00')";
97 // Test if feed is currently being updated by another process.
98 if (DB_TYPE == "pgsql") {
99 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
101 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
104 // Test if there is a limit to number of updated feeds
106 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
108 $random_qpart = sql_random_function();
110 // We search for feed needing update.
111 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
112 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
113 ttrss_feeds.update_interval
115 ttrss_feeds, ttrss_users, ttrss_user_prefs
117 ttrss_feeds.owner_uid = ttrss_users.id
118 AND ttrss_users.id = ttrss_user_prefs.owner_uid
119 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
120 $login_thresh_qpart $update_limit_qpart
121 $updstart_thresh_qpart
122 ORDER BY $random_qpart $query_limit");
124 $user_prefs_cache = array();
126 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
128 // Here is a little cache magic in order to minimize risk of double feed updates.
129 $feeds_to_update = array();
130 while ($line = db_fetch_assoc($result)) {
131 $feeds_to_update[$line['id']] = $line;
134 // We update the feed last update started date before anything else.
135 // There is no lag due to feed contents downloads
136 // It prevent an other process to update the same feed.
137 $feed_ids = array_keys($feeds_to_update);
139 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
140 WHERE id IN (%s)", implode(',', $feed_ids)));
143 expire_cached_files($debug);
145 // For each feed, we call the feed update function.
146 while ($line = array_pop($feeds_to_update)) {
148 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
150 update_rss_feed($link, $line["id"], true);
152 sleep(1); // prevent flood (FIXME make this an option?)
155 // Send feed digests by email if needed.
156 send_headlines_digests($link, $debug);
158 } // function update_daemon_common
160 // ignore_daemon is not used
161 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
162 $override_url = false) {
164 require_once "lib/simplepie/simplepie.inc";
165 require_once "lib/magpierss/rss_fetch.inc";
166 require_once 'lib/magpierss/rss_utils.inc';
168 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
170 if ($debug_enabled) {
171 _debug("update_rss_feed: start");
174 $result = db_query($link, "SELECT id,update_interval,auth_login,
175 feed_url,auth_pass,cache_images,update_method,last_updated,cache_content,
176 mark_unread_on_update, owner_uid, update_on_checksum_change,
178 FROM ttrss_feeds WHERE id = '$feed'");
180 if (db_num_rows($result) == 0) {
181 if ($debug_enabled) {
182 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
187 $update_method = db_fetch_result($result, 0, "update_method");
188 $last_updated = db_fetch_result($result, 0, "last_updated");
189 $owner_uid = db_fetch_result($result, 0, "owner_uid");
190 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
191 0, "mark_unread_on_update"));
192 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
193 0, "update_on_checksum_change"));
194 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
196 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
197 WHERE id = '$feed'");
199 $auth_login = db_fetch_result($result, 0, "auth_login");
200 $auth_pass = db_fetch_result($result, 0, "auth_pass");
202 if ($update_method == 0)
203 $update_method = DEFAULT_UPDATE_METHOD + 1;
209 if ($update_method == 2)
210 $use_simplepie = true;
212 $use_simplepie = false;
214 if ($debug_enabled) {
215 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
218 if ($update_method == 1) {
219 $auth_login = urlencode($auth_login);
220 $auth_pass = urlencode($auth_pass);
223 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
224 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
225 $fetch_url = db_fetch_result($result, 0, "feed_url");
227 $feed = db_escape_string($feed);
229 if ($auth_login && $auth_pass ){
230 $url_parts = array();
231 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
233 if ($url_parts[1] && $url_parts[2]) {
234 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
240 $fetch_url = $override_url;
242 if ($debug_enabled) {
243 _debug("update_rss_feed: fetching [$fetch_url]...");
246 // Ignore cache if new feed or manual update.
247 $cache_age = (is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
248 -1 : get_feed_update_interval($link, $feed) * 60;
250 if ($update_method == 1) {
252 define('MAGPIE_CACHE_AGE', $cache_age);
253 define('MAGPIE_CACHE_ON', !$no_cache);
254 define('MAGPIE_FETCH_TIME_OUT', $no_cache ? 15 : 60);
255 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
257 $rss = @fetch_rss($fetch_url);
259 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
261 if (!is_dir($simplepie_cache_dir)) {
262 mkdir($simplepie_cache_dir);
265 $rss = new SimplePie();
266 $rss->set_useragent(SELF_USER_AGENT);
267 $rss->set_timeout($no_cache ? 15 : 60);
268 $rss->set_feed_url($fetch_url);
269 $rss->set_output_encoding('UTF-8');
270 //$rss->force_feed(true);
272 if ($debug_enabled) {
273 _debug("feed update interval (sec): " .
274 get_feed_update_interval($link, $feed)*60);
277 $rss->enable_cache(!$no_cache);
280 $rss->set_cache_location($simplepie_cache_dir);
281 $rss->set_cache_duration($cache_age);
289 if ($debug_enabled) {
290 _debug("update_rss_feed: fetch done, parsing...");
293 $feed = db_escape_string($feed);
295 if ($update_method == 2) {
296 $fetch_ok = !$rss->error();
303 if ($debug_enabled) {
304 _debug("update_rss_feed: processing feed data...");
307 // db_query($link, "BEGIN");
309 if (DB_TYPE == "pgsql") {
310 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
312 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
315 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid,
316 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
318 FROM ttrss_feeds WHERE id = '$feed'");
320 $registered_title = db_fetch_result($result, 0, "title");
321 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
322 $orig_site_url = db_fetch_result($result, 0, "site_url");
323 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
324 "favicon_needs_check"));
326 $owner_uid = db_fetch_result($result, 0, "owner_uid");
328 if ($use_simplepie) {
329 $site_url = db_escape_string(trim($rss->get_link()));
331 $site_url = db_escape_string(trim($rss->channel["link"]));
334 // weird, weird Magpie
335 if (!$use_simplepie) {
336 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
339 $site_url = rewrite_relative_url($fetch_url, $site_url);
340 $site_url = substr($site_url, 0, 250);
342 if ($debug_enabled) {
343 _debug("update_rss_feed: checking favicon...");
346 if ($favicon_needs_check) {
347 check_feed_favicon($site_url, $feed, $link);
349 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
350 WHERE id = '$feed'");
353 if (!$registered_title || $registered_title == "[Unknown]") {
355 if ($use_simplepie) {
356 $feed_title = db_escape_string($rss->get_title());
358 $feed_title = db_escape_string($rss->channel["title"]);
361 if ($debug_enabled) {
362 _debug("update_rss_feed: registering title: $feed_title");
365 db_query($link, "UPDATE ttrss_feeds SET
366 title = '$feed_title' WHERE id = '$feed'");
369 if ($site_url && $orig_site_url != $site_url) {
370 db_query($link, "UPDATE ttrss_feeds SET
371 site_url = '$site_url' WHERE id = '$feed'");
374 // print "I: " . $rss->channel["image"]["url"];
376 if (!$use_simplepie) {
377 $icon_url = db_escape_string(trim($rss->image["url"]));
379 $icon_url = db_escape_string(trim($rss->get_image_url()));
382 $icon_url = rewrite_relative_url($fetch_url, $icon_url);
383 $icon_url = substr($icon_url, 0, 250);
385 if ($icon_url && $orig_icon_url != $icon_url) {
386 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
389 if ($debug_enabled) {
390 _debug("update_rss_feed: loading filters & labels...");
393 $filters = load_filters($link, $feed, $owner_uid);
394 $labels = get_all_labels($link, $owner_uid);
396 if ($debug_enabled) {
398 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
401 if ($use_simplepie) {
402 $iterator = $rss->get_items();
404 $iterator = $rss->items;
405 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
406 if (!$iterator || !is_array($iterator)) $iterator = $rss;
409 if (!is_array($iterator)) {
410 /* db_query($link, "UPDATE ttrss_feeds
411 SET last_error = 'Parse error: can\'t find any articles.'
412 WHERE id = '$feed'"); */
414 // clear any errors and mark feed as updated if fetched okay
415 // even if it's blank
417 if ($debug_enabled) {
418 _debug("update_rss_feed: entry iterator is not an array, no articles?");
421 db_query($link, "UPDATE ttrss_feeds
422 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
424 return; // no articles
427 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
429 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
431 $feed_hub_url = false;
432 if ($use_simplepie) {
433 $links = $rss->get_links('hub');
435 if ($links && is_array($links)) {
436 foreach ($links as $l) {
443 $atom = $rss->channel['atom'];
446 if ($atom['link@rel'] == 'hub') {
447 $feed_hub_url = $atom['link@href'];
450 if (!$feed_hub_url && $atom['link#'] > 1) {
451 for ($i = 2; $i <= $atom['link#']; $i++) {
452 if ($atom["link#$i@rel"] == 'hub') {
453 $feed_hub_url = $atom["link#$i@href"];
459 $feed_hub_url = $rss->channel['link_hub'];
463 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
465 if ($feed_hub_url && function_exists('curl_init') &&
466 !ini_get("open_basedir")) {
468 require_once 'lib/pubsubhubbub/subscriber.php';
470 $callback_url = get_self_url_prefix() .
471 "/public.php?op=pubsub&id=$feed";
473 $s = new Subscriber($feed_hub_url, $callback_url);
475 $rc = $s->subscribe($fetch_url);
478 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
480 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
481 WHERE id = '$feed'");
485 if ($debug_enabled) {
486 _debug("update_rss_feed: processing articles...");
489 foreach ($iterator as $item) {
490 if ($_REQUEST['xdebug'] == 2) {
494 if ($use_simplepie) {
495 $entry_guid = $item->get_id();
496 if (!$entry_guid) $entry_guid = $item->get_link();
497 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
501 $entry_guid = $item["id"];
503 if (!$entry_guid) $entry_guid = $item["guid"];
504 if (!$entry_guid) $entry_guid = $item["about"];
505 if (!$entry_guid) $entry_guid = $item["link"];
506 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
509 if ($debug_enabled) {
510 _debug("update_rss_feed: guid $entry_guid");
513 if (!$entry_guid) continue;
515 $entry_timestamp = "";
517 if ($use_simplepie) {
518 $entry_timestamp = strtotime($item->get_date());
520 $rss_2_date = $item['pubdate'];
521 $rss_1_date = $item['dc']['date'];
522 $atom_date = $item['issued'];
523 if (!$atom_date) $atom_date = $item['updated'];
525 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
526 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
527 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
531 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
532 $entry_timestamp = time();
533 $no_orig_date = 'true';
535 $no_orig_date = 'false';
538 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
540 if ($debug_enabled) {
541 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
544 if ($use_simplepie) {
545 $entry_title = $item->get_title();
547 $entry_title = trim(strip_tags($item["title"]));
550 if ($use_simplepie) {
551 $entry_link = $item->get_link();
553 // strange Magpie workaround
554 $entry_link = $item["link_"];
555 if (!$entry_link) $entry_link = $item["link"];
558 $entry_link = rewrite_relative_url($site_url, $entry_link);
560 if ($debug_enabled) {
561 _debug("update_rss_feed: title $entry_title");
562 _debug("update_rss_feed: link $entry_link");
565 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
567 $entry_link = strip_tags($entry_link);
569 if ($use_simplepie) {
570 $entry_content = $item->get_content();
571 if (!$entry_content) $entry_content = $item->get_description();
573 $entry_content = $item["content:escaped"];
575 if (!$entry_content) $entry_content = $item["content:encoded"];
576 if (!$entry_content && is_array($entry_content)) $entry_content = $item["content"]["encoded"];
577 if (!$entry_content) $entry_content = $item["content"];
579 if (is_array($entry_content)) $entry_content = $entry_content[0];
581 // Magpie bugs are getting ridiculous
582 if (trim($entry_content) == "Array") $entry_content = false;
584 if (!$entry_content) $entry_content = $item["atom_content"];
585 if (!$entry_content) $entry_content = $item["summary"];
587 if (!$entry_content ||
588 strlen($entry_content) < strlen($item["description"])) {
589 $entry_content = $item["description"];
593 if (is_array($entry_content)) {
594 $entry_content = $entry_content["encoded"];
595 if (!$entry_content) $entry_content = $entry_content["escaped"];
599 if ($cache_images && is_writable(CACHE_DIR . '/images'))
600 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
602 if ($_REQUEST["xdebug"] == 2) {
603 print "update_rss_feed: content: ";
604 print $entry_content;
608 $entry_content_unescaped = $entry_content;
609 $entry_cached_content = "";
611 if ($use_simplepie) {
612 $entry_comments = strip_tags($item->data["comments"]);
613 if ($item->get_author()) {
614 $entry_author_item = $item->get_author();
615 $entry_author = $entry_author_item->get_name();
616 if (!$entry_author) $entry_author = $entry_author_item->get_email();
618 $entry_author = db_escape_string($entry_author);
621 $entry_comments = strip_tags($item["comments"]);
623 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
625 if ($item['author']) {
627 if (is_array($item['author'])) {
629 if (!$entry_author) {
630 $entry_author = db_escape_string(strip_tags($item['author']['name']));
633 if (!$entry_author) {
634 $entry_author = db_escape_string(strip_tags($item['author']['email']));
638 if (!$entry_author) {
639 $entry_author = db_escape_string(strip_tags($item['author']));
644 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
646 $entry_guid = db_escape_string(strip_tags($entry_guid));
647 $entry_guid = mb_substr($entry_guid, 0, 250);
649 $result = db_query($link, "SELECT id FROM ttrss_entries
650 WHERE guid = '$entry_guid'");
652 $entry_content = db_escape_string($entry_content, false);
654 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
656 $entry_title = db_escape_string($entry_title);
657 $entry_link = db_escape_string($entry_link);
658 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
659 $entry_author = mb_substr($entry_author, 0, 250);
661 if ($use_simplepie) {
662 $num_comments = 0; #FIXME#
664 $num_comments = db_escape_string($item["slash"]["comments"]);
667 if (!$num_comments) $num_comments = 0;
669 if ($debug_enabled) {
670 _debug("update_rss_feed: looking for tags [1]...");
673 // parse <category> entries into tags
675 $additional_tags = array();
677 if ($use_simplepie) {
679 $additional_tags_src = $item->get_categories();
681 if (is_array($additional_tags_src)) {
682 foreach ($additional_tags_src as $tobj) {
683 array_push($additional_tags, $tobj->get_term());
687 if ($debug_enabled) {
688 _debug("update_rss_feed: category tags:");
689 print_r($additional_tags);
694 $t_ctr = $item['category#'];
697 $additional_tags = array();
698 } else if ($t_ctr > 0) {
699 $additional_tags = array($item['category']);
701 if ($item['category@term']) {
702 array_push($additional_tags, $item['category@term']);
705 for ($i = 0; $i <= $t_ctr; $i++ ) {
706 if ($item["category#$i"]) {
707 array_push($additional_tags, $item["category#$i"]);
710 if ($item["category#$i@term"]) {
711 array_push($additional_tags, $item["category#$i@term"]);
716 // parse <dc:subject> elements
718 $t_ctr = $item['dc']['subject#'];
721 array_push($additional_tags, $item['dc']['subject']);
723 for ($i = 0; $i <= $t_ctr; $i++ ) {
724 if ($item['dc']["subject#$i"]) {
725 array_push($additional_tags, $item['dc']["subject#$i"]);
731 if ($debug_enabled) {
732 _debug("update_rss_feed: looking for tags [2]...");
736 // <a href="..." rel="tag">Xorg</a>, //
740 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
741 $entry_content_unescaped, $entry_tags);
743 $entry_tags = $entry_tags[1];
745 $entry_tags = array_merge($entry_tags, $additional_tags);
746 $entry_tags = array_unique($entry_tags);
748 for ($i = 0; $i < count($entry_tags); $i++)
749 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
751 if ($debug_enabled) {
752 //_debug("update_rss_feed: unfiltered tags found:");
753 //print_r($entry_tags);
756 if ($debug_enabled) {
757 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
760 db_query($link, "BEGIN");
762 if (db_num_rows($result) == 0) {
764 if ($debug_enabled) {
765 _debug("update_rss_feed: base guid not found");
768 if ($cache_content) {
769 if ($debug_enabled) {
770 _debug("update_rss_feed: caching content...");
773 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
775 if ($cache_images && is_writable(CACHE_DIR . '/images'))
776 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
778 $entry_cached_content = db_escape_string($entry_cached_content, false);
782 // base post entry does not exist, create it
784 $result = db_query($link,
785 "INSERT INTO ttrss_entries
803 '$entry_timestamp_fmt',
806 '$entry_cached_content',
814 $article_labels = array();
817 // we keep encountering the entry in feeds, so we need to
818 // update date_updated column so that we don't get horrible
819 // dupes when the entry gets purged and reinserted again e.g.
820 // in the case of SLOW SLOW OMG SLOW updating feeds
822 $base_entry_id = db_fetch_result($result, 0, "id");
824 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
825 WHERE id = '$base_entry_id'");
827 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
830 // now it should exist, if not - bad luck then
832 $result = db_query($link, "SELECT
833 id,content_hash,no_orig_date,title,
834 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
835 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
839 WHERE guid = '$entry_guid'");
844 if (db_num_rows($result) == 1) {
846 if ($debug_enabled) {
847 _debug("update_rss_feed: base guid found, checking for user record");
850 // this will be used below in update handler
851 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
852 $orig_title = db_fetch_result($result, 0, "title");
853 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
854 $orig_date_updated = strtotime(db_fetch_result($result,
857 $ref_id = db_fetch_result($result, 0, "id");
858 $entry_ref_id = $ref_id;
860 // check for user post link to main table
862 // do we allow duplicate posts with same GUID in different feeds?
863 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
864 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
866 $dupcheck_qpart = "";
869 /* Collect article tags here so we could filter by them: */
871 $article_filters = get_article_filters($filters, $entry_title,
872 $entry_content, $entry_link, $entry_timestamp, $entry_author,
875 if ($debug_enabled) {
876 _debug("update_rss_feed: article filters: ");
877 if (count($article_filters) != 0) {
878 print_r($article_filters);
882 if (find_article_filter($article_filters, "filter")) {
883 db_query($link, "COMMIT"); // close transaction in progress
887 $score = calculate_article_score($article_filters);
889 if ($debug_enabled) {
890 _debug("update_rss_feed: initial score: $score");
893 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
894 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
897 // if ($_REQUEST["xdebug"]) print "$query\n";
899 $result = db_query($link, $query);
901 // okay it doesn't exist - create user entry
902 if (db_num_rows($result) == 0) {
904 if ($debug_enabled) {
905 _debug("update_rss_feed: user record not found, creating...");
908 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
910 $last_read_qpart = 'NULL';
913 $last_read_qpart = 'NOW()';
916 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
922 if (find_article_filter($article_filters, 'publish')) {
925 $published = 'false';
930 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
932 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
933 ttrss_entries,ttrss_user_entries
934 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
935 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
936 AND owner_uid = $owner_uid");
938 $ngram_similar = db_fetch_result($result, 0, "similar");
940 if ($debug_enabled) {
941 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
944 if ($ngram_similar > 0) {
949 $result = db_query($link,
950 "INSERT INTO ttrss_user_entries
951 (ref_id, owner_uid, feed_id, unread, last_read, marked,
952 published, score, tag_cache, label_cache, uuid)
953 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
954 $last_read_qpart, $marked, $published, '$score', '', '', '')");
956 if (PUBSUBHUBBUB_HUB && $published == 'true') {
957 $rss_link = get_self_url_prefix() .
958 "/public.php?op=rss&id=-2&key=" .
959 get_feed_access_key($link, -2, false, $owner_uid);
961 $p = new Publisher(PUBSUBHUBBUB_HUB);
963 $pubsub_result = $p->publish_update($rss_link);
966 $result = db_query($link,
967 "SELECT int_id FROM ttrss_user_entries WHERE
968 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
969 feed_id = '$feed' LIMIT 1");
971 if (db_num_rows($result) == 1) {
972 $entry_int_id = db_fetch_result($result, 0, "int_id");
975 if ($debug_enabled) {
976 _debug("update_rss_feed: user record FOUND");
979 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
980 $entry_int_id = db_fetch_result($result, 0, "int_id");
983 if ($debug_enabled) {
984 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
987 $post_needs_update = false;
988 $update_insignificant = false;
990 if ($orig_num_comments != $num_comments) {
991 $post_needs_update = true;
992 $update_insignificant = true;
995 if ($content_hash != $orig_content_hash) {
996 $post_needs_update = true;
997 $update_insignificant = false;
999 if ($cache_content) {
1000 if ($debug_enabled) {
1001 _debug("update_rss_feed: caching content because original checksum changed...");
1004 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
1006 if ($cache_images && is_writable(CACHE_DIR . '/images'))
1007 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
1009 $entry_cached_content = db_escape_string($entry_cached_content, false);
1013 if (db_escape_string($orig_title) != $entry_title) {
1014 $post_needs_update = true;
1015 $update_insignificant = false;
1018 // if post needs update, update it and mark all user entries
1019 // linking to this post as updated
1020 if ($post_needs_update) {
1022 if (defined('DAEMON_EXTENDED_DEBUG')) {
1023 _debug("update_rss_feed: post $entry_guid needs update...");
1026 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1028 db_query($link, "UPDATE ttrss_entries
1029 SET title = '$entry_title', content = '$entry_content',
1030 content_hash = '$content_hash',
1031 cached_content = '$entry_cached_content',
1032 updated = '$entry_timestamp_fmt',
1033 num_comments = '$num_comments'
1034 WHERE id = '$ref_id'");
1036 if (!$update_insignificant) {
1037 if ($mark_unread_on_update) {
1038 db_query($link, "UPDATE ttrss_user_entries
1039 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1040 } else if ($update_on_checksum_change) {
1041 db_query($link, "UPDATE ttrss_user_entries
1042 SET last_read = null WHERE ref_id = '$ref_id'
1043 AND unread = false");
1049 db_query($link, "COMMIT");
1051 if ($debug_enabled) {
1052 _debug("update_rss_feed: assigning labels...");
1055 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
1056 $owner_uid, $article_labels);
1058 if ($debug_enabled) {
1059 _debug("update_rss_feed: looking for enclosures...");
1064 $enclosures = array();
1066 if ($use_simplepie) {
1067 $encs = $item->get_enclosures();
1069 if (is_array($encs)) {
1070 foreach ($encs as $e) {
1072 $e->link, $e->type, $e->length);
1074 array_push($enclosures, $e_item);
1081 $e_ctr = $item['enclosure#'];
1084 $e_item = array($item['enclosure@url'],
1085 $item['enclosure@type'],
1086 $item['enclosure@length']);
1088 array_push($enclosures, $e_item);
1090 for ($i = 0; $i <= $e_ctr; $i++ ) {
1092 if ($item["enclosure#$i@url"]) {
1093 $e_item = array($item["enclosure#$i@url"],
1094 $item["enclosure#$i@type"],
1095 $item["enclosure#$i@length"]);
1096 array_push($enclosures, $e_item);
1102 // can there be many of those? yes -fox
1104 $m_ctr = $item['media']['content#'];
1107 $e_item = array($item['media']['content@url'],
1108 $item['media']['content@medium'],
1109 $item['media']['content@length']);
1111 array_push($enclosures, $e_item);
1113 for ($i = 0; $i <= $m_ctr; $i++ ) {
1115 if ($item["media"]["content#$i@url"]) {
1116 $e_item = array($item["media"]["content#$i@url"],
1117 $item["media"]["content#$i@medium"],
1118 $item["media"]["content#$i@length"]);
1119 array_push($enclosures, $e_item);
1127 if ($debug_enabled) {
1128 _debug("update_rss_feed: article enclosures:");
1129 print_r($enclosures);
1132 db_query($link, "BEGIN");
1134 foreach ($enclosures as $enc) {
1135 $enc_url = db_escape_string($enc[0]);
1136 $enc_type = db_escape_string($enc[1]);
1137 $enc_dur = db_escape_string($enc[2]);
1139 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1140 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1142 if (db_num_rows($result) == 0) {
1143 db_query($link, "INSERT INTO ttrss_enclosures
1144 (content_url, content_type, title, duration, post_id) VALUES
1145 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1149 db_query($link, "COMMIT");
1151 // check for manual tags (we have to do it here since they're loaded from filters)
1153 foreach ($article_filters as $f) {
1154 if ($f["type"] == "tag") {
1156 $manual_tags = trim_array(explode(",", $f["param"]));
1158 foreach ($manual_tags as $tag) {
1159 if (tag_is_valid($tag)) {
1160 array_push($entry_tags, $tag);
1168 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1169 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1171 $filtered_tags = array();
1172 $tags_to_cache = array();
1174 if ($entry_tags && is_array($entry_tags)) {
1175 foreach ($entry_tags as $tag) {
1176 if (array_search($tag, $boring_tags) === false) {
1177 array_push($filtered_tags, $tag);
1182 $filtered_tags = array_unique($filtered_tags);
1184 if ($debug_enabled) {
1185 _debug("update_rss_feed: filtered article tags:");
1186 print_r($filtered_tags);
1189 // Save article tags in the database
1191 if (count($filtered_tags) > 0) {
1193 db_query($link, "BEGIN");
1195 foreach ($filtered_tags as $tag) {
1197 $tag = sanitize_tag($tag);
1198 $tag = db_escape_string($tag);
1200 if (!tag_is_valid($tag)) continue;
1202 $result = db_query($link, "SELECT id FROM ttrss_tags
1203 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1204 owner_uid = '$owner_uid' LIMIT 1");
1206 if ($result && db_num_rows($result) == 0) {
1208 db_query($link, "INSERT INTO ttrss_tags
1209 (owner_uid,tag_name,post_int_id)
1210 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1213 array_push($tags_to_cache, $tag);
1216 /* update the cache */
1218 $tags_to_cache = array_unique($tags_to_cache);
1220 $tags_str = db_escape_string(join(",", $tags_to_cache));
1222 db_query($link, "UPDATE ttrss_user_entries
1223 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1224 AND owner_uid = $owner_uid");
1226 db_query($link, "COMMIT");
1229 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1230 if ($debug_enabled) {
1231 _debug("update_rss_feed: auto-assigning labels...");
1234 foreach ($labels as $label) {
1235 $caption = $label["caption"];
1237 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
1238 if (!labels_contains_caption($article_labels, $caption)) {
1239 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1245 if ($debug_enabled) {
1246 _debug("update_rss_feed: article processed");
1250 if (!$last_updated) {
1251 if ($debug_enabled) {
1252 _debug("update_rss_feed: new feed, catching it up...");
1254 catchup_feed($link, $feed, false, $owner_uid);
1257 if ($debug_enabled) {
1258 _debug("purging feed...");
1261 purge_feed($link, $feed, 0, $debug_enabled);
1263 db_query($link, "UPDATE ttrss_feeds
1264 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1266 // db_query($link, "COMMIT");
1270 if ($use_simplepie) {
1271 $error_msg = mb_substr($rss->error(), 0, 250);
1273 $error_msg = mb_substr(magpie_error(), 0, 250);
1276 if ($debug_enabled) {
1277 _debug("update_rss_feed: error fetching feed: $error_msg");
1280 $error_msg = db_escape_string($error_msg);
1283 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1284 last_updated = NOW() WHERE id = '$feed'");
1287 if ($use_simplepie) {
1291 if ($debug_enabled) {
1292 _debug("update_rss_feed: done");
1297 function cache_images($html, $site_url, $debug) {
1298 $cache_dir = CACHE_DIR . "/images";
1300 libxml_use_internal_errors(true);
1302 $charset_hack = '<head>
1303 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1306 $doc = new DOMDocument();
1307 $doc->loadHTML($charset_hack . $html);
1308 $xpath = new DOMXPath($doc);
1310 $entries = $xpath->query('(//img[@src])');
1312 foreach ($entries as $entry) {
1313 if ($entry->hasAttribute('src')) {
1314 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1316 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1318 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1320 if (!file_exists($local_filename)) {
1321 $file_content = fetch_file_contents($src);
1323 if ($file_content && strlen($file_content) > 1024) {
1324 file_put_contents($local_filename, $file_content);
1328 if (file_exists($local_filename)) {
1329 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
1330 base64_encode($src));
1335 $node = $doc->getElementsByTagName('body')->item(0);
1337 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1340 function expire_cached_files($debug) {
1341 foreach (array("magpie", "simplepie", "images", "export") as $dir) {
1342 $cache_dir = CACHE_DIR . "/$dir";
1344 if ($debug) _debug("Expiring $cache_dir");
1348 if (is_writable($cache_dir)) {
1349 $files = glob("$cache_dir/*");
1352 foreach ($files as $file) {
1353 if (time() - filemtime($file) > 86400*7) {
1361 if ($debug) _debug("Removed $num_deleted files.");
1366 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1367 * Returns the url query as associative array
1369 * @param string query
1370 * @return array params
1372 function convertUrlQuery($query) {
1373 $queryParts = explode('&', $query);
1377 foreach ($queryParts as $param) {
1378 $item = explode('=', $param);
1379 $params[$item[0]] = $item[1];
1385 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1388 foreach ($filters as $filter) {
1389 $match_any_rule = $filter["match_any_rule"];
1390 $filter_match = false;
1392 foreach ($filter["rules"] as $rule) {
1394 $reg_exp = $rule["reg_exp"];
1399 switch ($rule["type"]) {
1401 $match = @preg_match("/$reg_exp/i", $title);
1404 // we don't need to deal with multiline regexps
1405 $content = preg_replace("/[\r\n\t]/", "", $content);
1407 $match = @preg_match("/$reg_exp/i", $content);
1410 // we don't need to deal with multiline regexps
1411 $content = preg_replace("/[\r\n\t]/", "", $content);
1413 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
1416 $match = @preg_match("/$reg_exp/i", $link);
1419 $match = @preg_match("/$reg_exp/i", $author);
1422 $tag_string = join(",", $tags);
1423 $match = @preg_match("/$reg_exp/i", $tag_string);
1427 if ($match_any_rule) {
1429 $filter_match = true;
1433 $filter_match = $match;
1440 if ($filter_match) {
1441 foreach ($filter["actions"] AS $action) {
1442 array_push($matches, $action);
1450 function find_article_filter($filters, $filter_name) {
1451 foreach ($filters as $f) {
1452 if ($f["type"] == $filter_name) {
1459 function find_article_filters($filters, $filter_name) {
1462 foreach ($filters as $f) {
1463 if ($f["type"] == $filter_name) {
1464 array_push($results, $f);
1470 function calculate_article_score($filters) {
1473 foreach ($filters as $f) {
1474 if ($f["type"] == "score") {
1475 $score += $f["param"];
1481 function labels_contains_caption($labels, $caption) {
1482 foreach ($labels as $label) {
1483 if ($label[1] == $caption) {
1491 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1492 foreach ($filters as $f) {
1493 if ($f["type"] == "label") {
1494 if (!labels_contains_caption($article_labels, $f["param"])) {
1495 label_add_article($link, $id, $f["param"], $owner_uid);
1501 function cache_content($link, $url, $login, $pass) {
1503 $content = fetch_file_contents($url, $login, $pass);
1506 $doc = new DOMDocument();
1507 @$doc->loadHTML($content);
1508 $xpath = new DOMXPath($doc);
1510 $node = $doc->getElementsByTagName('body')->item(0);
1513 $content = $doc->saveXML($node, LIBXML_NOEMPTYTAG);