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 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
161 $override_url = false) {
163 require_once "lib/simplepie/simplepie.inc";
164 require_once "lib/magpierss/rss_fetch.inc";
165 require_once 'lib/magpierss/rss_utils.inc';
167 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
169 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
173 if ($debug_enabled) {
174 _debug("update_rss_feed: start");
177 if (!$ignore_daemon) {
179 if (DB_TYPE == "pgsql") {
180 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
182 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
185 $result = db_query($link, "SELECT id,update_interval,auth_login,
186 auth_pass,cache_images,update_method,last_updated
187 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
191 $result = db_query($link, "SELECT id,update_interval,auth_login,
192 feed_url,auth_pass,cache_images,update_method,last_updated,
193 mark_unread_on_update, owner_uid, update_on_checksum_change,
195 FROM ttrss_feeds WHERE id = '$feed'");
199 if (db_num_rows($result) == 0) {
200 if ($debug_enabled) {
201 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
206 $update_method = db_fetch_result($result, 0, "update_method");
207 $last_updated = db_fetch_result($result, 0, "last_updated");
208 $owner_uid = db_fetch_result($result, 0, "owner_uid");
209 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
210 0, "mark_unread_on_update"));
211 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
212 0, "update_on_checksum_change"));
213 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
215 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
216 WHERE id = '$feed'");
218 $auth_login = db_fetch_result($result, 0, "auth_login");
219 $auth_pass = db_fetch_result($result, 0, "auth_pass");
221 if ($update_method == 0)
222 $update_method = DEFAULT_UPDATE_METHOD + 1;
228 if ($update_method == 2)
229 $use_simplepie = true;
231 $use_simplepie = false;
233 if ($debug_enabled) {
234 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
237 if ($update_method == 1) {
238 $auth_login = urlencode($auth_login);
239 $auth_pass = urlencode($auth_pass);
242 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
243 $fetch_url = db_fetch_result($result, 0, "feed_url");
245 $feed = db_escape_string($feed);
247 if ($auth_login && $auth_pass ){
248 $url_parts = array();
249 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
251 if ($url_parts[1] && $url_parts[2]) {
252 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
258 $fetch_url = $override_url;
260 if ($debug_enabled) {
261 _debug("update_rss_feed: fetching [$fetch_url]...");
264 // Ignore cache if new feed or manual update.
265 $cache_age = (is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
266 -1 : get_feed_update_interval($link, $feed) * 60;
268 if ($update_method == 1) {
270 define('MAGPIE_CACHE_AGE', $cache_age);
271 define('MAGPIE_CACHE_ON', !$no_cache);
272 define('MAGPIE_FETCH_TIME_OUT', $no_cache ? 15 : 60);
273 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
275 $rss = @fetch_rss($fetch_url);
277 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
279 if (!is_dir($simplepie_cache_dir)) {
280 mkdir($simplepie_cache_dir);
283 $rss = new SimplePie();
284 $rss->set_useragent(SELF_USER_AGENT);
285 $rss->set_timeout($no_cache ? 15 : 60);
286 $rss->set_feed_url($fetch_url);
287 $rss->set_output_encoding('UTF-8');
288 //$rss->force_feed(true);
290 if ($debug_enabled) {
291 _debug("feed update interval (sec): " .
292 get_feed_update_interval($link, $feed)*60);
295 $rss->enable_cache(!$no_cache);
298 $rss->set_cache_location($simplepie_cache_dir);
299 $rss->set_cache_duration($cache_age);
307 if ($debug_enabled) {
308 _debug("update_rss_feed: fetch done, parsing...");
311 $feed = db_escape_string($feed);
313 if ($update_method == 2) {
314 $fetch_ok = !$rss->error();
321 if ($debug_enabled) {
322 _debug("update_rss_feed: processing feed data...");
325 // db_query($link, "BEGIN");
327 if (DB_TYPE == "pgsql") {
328 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
330 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
333 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid,
334 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
336 FROM ttrss_feeds WHERE id = '$feed'");
338 $registered_title = db_fetch_result($result, 0, "title");
339 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
340 $orig_site_url = db_fetch_result($result, 0, "site_url");
341 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
342 "favicon_needs_check"));
344 $owner_uid = db_fetch_result($result, 0, "owner_uid");
346 if ($use_simplepie) {
347 $site_url = db_escape_string(trim($rss->get_link()));
349 $site_url = db_escape_string(trim($rss->channel["link"]));
352 // weird, weird Magpie
353 if (!$use_simplepie) {
354 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
357 $site_url = rewrite_relative_url($fetch_url, $site_url);
358 $site_url = substr($site_url, 0, 250);
360 if ($debug_enabled) {
361 _debug("update_rss_feed: checking favicon...");
364 if ($favicon_needs_check) {
365 check_feed_favicon($site_url, $feed, $link);
367 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
368 WHERE id = '$feed'");
371 if (!$registered_title || $registered_title == "[Unknown]") {
373 if ($use_simplepie) {
374 $feed_title = db_escape_string($rss->get_title());
376 $feed_title = db_escape_string($rss->channel["title"]);
379 if ($debug_enabled) {
380 _debug("update_rss_feed: registering title: $feed_title");
383 db_query($link, "UPDATE ttrss_feeds SET
384 title = '$feed_title' WHERE id = '$feed'");
387 if ($site_url && $orig_site_url != $site_url) {
388 db_query($link, "UPDATE ttrss_feeds SET
389 site_url = '$site_url' WHERE id = '$feed'");
392 // print "I: " . $rss->channel["image"]["url"];
394 if (!$use_simplepie) {
395 $icon_url = db_escape_string(trim($rss->image["url"]));
397 $icon_url = db_escape_string(trim($rss->get_image_url()));
400 $icon_url = rewrite_relative_url($fetch_url, $icon_url);
401 $icon_url = substr($icon_url, 0, 250);
403 if ($icon_url && $orig_icon_url != $icon_url) {
404 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
407 if ($debug_enabled) {
408 _debug("update_rss_feed: loading filters & labels...");
411 $filters = load_filters($link, $feed, $owner_uid);
412 $labels = get_all_labels($link, $owner_uid);
414 if ($debug_enabled) {
416 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
419 if ($use_simplepie) {
420 $iterator = $rss->get_items();
422 $iterator = $rss->items;
423 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
424 if (!$iterator || !is_array($iterator)) $iterator = $rss;
427 if (!is_array($iterator)) {
428 /* db_query($link, "UPDATE ttrss_feeds
429 SET last_error = 'Parse error: can\'t find any articles.'
430 WHERE id = '$feed'"); */
432 // clear any errors and mark feed as updated if fetched okay
433 // even if it's blank
435 if ($debug_enabled) {
436 _debug("update_rss_feed: entry iterator is not an array, no articles?");
439 db_query($link, "UPDATE ttrss_feeds
440 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
442 return; // no articles
445 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
447 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
449 $feed_hub_url = false;
450 if ($use_simplepie) {
451 $links = $rss->get_links('hub');
453 if ($links && is_array($links)) {
454 foreach ($links as $l) {
461 $atom = $rss->channel['atom'];
464 if ($atom['link@rel'] == 'hub') {
465 $feed_hub_url = $atom['link@href'];
468 if (!$feed_hub_url && $atom['link#'] > 1) {
469 for ($i = 2; $i <= $atom['link#']; $i++) {
470 if ($atom["link#$i@rel"] == 'hub') {
471 $feed_hub_url = $atom["link#$i@href"];
477 $feed_hub_url = $rss->channel['link_hub'];
481 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
483 if ($feed_hub_url && function_exists('curl_init') &&
484 !ini_get("open_basedir")) {
486 require_once 'lib/pubsubhubbub/subscriber.php';
488 $callback_url = get_self_url_prefix() .
489 "/public.php?op=pubsub&id=$feed";
491 $s = new Subscriber($feed_hub_url, $callback_url);
493 $rc = $s->subscribe($fetch_url);
496 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
498 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
499 WHERE id = '$feed'");
503 if ($debug_enabled) {
504 _debug("update_rss_feed: processing articles...");
507 foreach ($iterator as $item) {
508 if ($_REQUEST['xdebug'] == 2) {
512 if ($use_simplepie) {
513 $entry_guid = $item->get_id();
514 if (!$entry_guid) $entry_guid = $item->get_link();
515 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
519 $entry_guid = $item["id"];
521 if (!$entry_guid) $entry_guid = $item["guid"];
522 if (!$entry_guid) $entry_guid = $item["about"];
523 if (!$entry_guid) $entry_guid = $item["link"];
524 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
527 if ($debug_enabled) {
528 _debug("update_rss_feed: guid $entry_guid");
531 if (!$entry_guid) continue;
533 $entry_timestamp = "";
535 if ($use_simplepie) {
536 $entry_timestamp = strtotime($item->get_date());
538 $rss_2_date = $item['pubdate'];
539 $rss_1_date = $item['dc']['date'];
540 $atom_date = $item['issued'];
541 if (!$atom_date) $atom_date = $item['updated'];
543 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
544 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
545 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
549 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
550 $entry_timestamp = time();
551 $no_orig_date = 'true';
553 $no_orig_date = 'false';
556 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
558 if ($debug_enabled) {
559 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
562 if ($use_simplepie) {
563 $entry_title = $item->get_title();
565 $entry_title = trim(strip_tags($item["title"]));
568 if ($use_simplepie) {
569 $entry_link = $item->get_link();
571 // strange Magpie workaround
572 $entry_link = $item["link_"];
573 if (!$entry_link) $entry_link = $item["link"];
576 $entry_link = rewrite_relative_url($site_url, $entry_link);
578 if ($debug_enabled) {
579 _debug("update_rss_feed: title $entry_title");
580 _debug("update_rss_feed: link $entry_link");
583 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
585 $entry_link = strip_tags($entry_link);
587 if ($use_simplepie) {
588 $entry_content = $item->get_content();
589 if (!$entry_content) $entry_content = $item->get_description();
591 $entry_content = $item["content:escaped"];
593 if (!$entry_content) $entry_content = $item["content:encoded"];
594 if (!$entry_content && is_array($entry_content)) $entry_content = $item["content"]["encoded"];
595 if (!$entry_content) $entry_content = $item["content"];
597 if (is_array($entry_content)) $entry_content = $entry_content[0];
599 // Magpie bugs are getting ridiculous
600 if (trim($entry_content) == "Array") $entry_content = false;
602 if (!$entry_content) $entry_content = $item["atom_content"];
603 if (!$entry_content) $entry_content = $item["summary"];
605 if (!$entry_content ||
606 strlen($entry_content) < strlen($item["description"])) {
607 $entry_content = $item["description"];
611 if (is_array($entry_content)) {
612 $entry_content = $entry_content["encoded"];
613 if (!$entry_content) $entry_content = $entry_content["escaped"];
617 if ($cache_images && is_writable(CACHE_DIR . '/images'))
618 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
620 if ($_REQUEST["xdebug"] == 2) {
621 print "update_rss_feed: content: ";
622 print $entry_content;
626 $entry_content_unescaped = $entry_content;
628 if ($use_simplepie) {
629 $entry_comments = strip_tags($item->data["comments"]);
630 if ($item->get_author()) {
631 $entry_author_item = $item->get_author();
632 $entry_author = $entry_author_item->get_name();
633 if (!$entry_author) $entry_author = $entry_author_item->get_email();
635 $entry_author = db_escape_string($entry_author);
638 $entry_comments = strip_tags($item["comments"]);
640 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
642 if ($item['author']) {
644 if (is_array($item['author'])) {
646 if (!$entry_author) {
647 $entry_author = db_escape_string(strip_tags($item['author']['name']));
650 if (!$entry_author) {
651 $entry_author = db_escape_string(strip_tags($item['author']['email']));
655 if (!$entry_author) {
656 $entry_author = db_escape_string(strip_tags($item['author']));
661 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
663 $entry_guid = db_escape_string(strip_tags($entry_guid));
664 $entry_guid = mb_substr($entry_guid, 0, 250);
666 $result = db_query($link, "SELECT id FROM ttrss_entries
667 WHERE guid = '$entry_guid'");
669 $entry_content = db_escape_string($entry_content, false);
671 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
673 $entry_title = db_escape_string($entry_title);
674 $entry_link = db_escape_string($entry_link);
675 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
676 $entry_author = mb_substr($entry_author, 0, 250);
678 if ($use_simplepie) {
679 $num_comments = 0; #FIXME#
681 $num_comments = db_escape_string($item["slash"]["comments"]);
684 if (!$num_comments) $num_comments = 0;
686 if ($debug_enabled) {
687 _debug("update_rss_feed: looking for tags [1]...");
690 // parse <category> entries into tags
692 $additional_tags = array();
694 if ($use_simplepie) {
696 $additional_tags_src = $item->get_categories();
698 if (is_array($additional_tags_src)) {
699 foreach ($additional_tags_src as $tobj) {
700 array_push($additional_tags, $tobj->get_term());
704 if ($debug_enabled) {
705 _debug("update_rss_feed: category tags:");
706 print_r($additional_tags);
711 $t_ctr = $item['category#'];
714 $additional_tags = array();
715 } else if ($t_ctr > 0) {
716 $additional_tags = array($item['category']);
718 if ($item['category@term']) {
719 array_push($additional_tags, $item['category@term']);
722 for ($i = 0; $i <= $t_ctr; $i++ ) {
723 if ($item["category#$i"]) {
724 array_push($additional_tags, $item["category#$i"]);
727 if ($item["category#$i@term"]) {
728 array_push($additional_tags, $item["category#$i@term"]);
733 // parse <dc:subject> elements
735 $t_ctr = $item['dc']['subject#'];
738 array_push($additional_tags, $item['dc']['subject']);
740 for ($i = 0; $i <= $t_ctr; $i++ ) {
741 if ($item['dc']["subject#$i"]) {
742 array_push($additional_tags, $item['dc']["subject#$i"]);
748 if ($debug_enabled) {
749 _debug("update_rss_feed: looking for tags [2]...");
753 // <a href="..." rel="tag">Xorg</a>, //
757 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
758 $entry_content_unescaped, $entry_tags);
760 $entry_tags = $entry_tags[1];
762 $entry_tags = array_merge($entry_tags, $additional_tags);
763 $entry_tags = array_unique($entry_tags);
765 for ($i = 0; $i < count($entry_tags); $i++)
766 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
768 if ($debug_enabled) {
769 //_debug("update_rss_feed: unfiltered tags found:");
770 //print_r($entry_tags);
773 if ($debug_enabled) {
774 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
777 db_query($link, "BEGIN");
779 if (db_num_rows($result) == 0) {
781 if ($debug_enabled) {
782 _debug("update_rss_feed: base guid not found");
785 // base post entry does not exist, create it
787 $result = db_query($link,
788 "INSERT INTO ttrss_entries
805 '$entry_timestamp_fmt',
815 $article_labels = array();
818 // we keep encountering the entry in feeds, so we need to
819 // update date_updated column so that we don't get horrible
820 // dupes when the entry gets purged and reinserted again e.g.
821 // in the case of SLOW SLOW OMG SLOW updating feeds
823 $base_entry_id = db_fetch_result($result, 0, "id");
825 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
826 WHERE id = '$base_entry_id'");
828 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
831 // now it should exist, if not - bad luck then
833 $result = db_query($link, "SELECT
834 id,content_hash,no_orig_date,title,
835 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
836 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
840 WHERE guid = '$entry_guid'");
845 if (db_num_rows($result) == 1) {
847 if ($debug_enabled) {
848 _debug("update_rss_feed: base guid found, checking for user record");
851 // this will be used below in update handler
852 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
853 $orig_title = db_fetch_result($result, 0, "title");
854 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
855 $orig_date_updated = strtotime(db_fetch_result($result,
858 $ref_id = db_fetch_result($result, 0, "id");
859 $entry_ref_id = $ref_id;
861 // check for user post link to main table
863 // do we allow duplicate posts with same GUID in different feeds?
864 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
865 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
867 $dupcheck_qpart = "";
870 /* Collect article tags here so we could filter by them: */
872 $article_filters = get_article_filters($filters, $entry_title,
873 strip_tags($entry_content), $entry_link, $entry_timestamp, $entry_author,
876 if ($debug_enabled) {
877 _debug("update_rss_feed: article filters: ");
878 if (count($article_filters) != 0) {
879 print_r($article_filters);
883 if (find_article_filter($article_filters, "filter")) {
884 db_query($link, "COMMIT"); // close transaction in progress
888 $score = calculate_article_score($article_filters);
890 if ($debug_enabled) {
891 _debug("update_rss_feed: initial score: $score");
894 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
895 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
898 // if ($_REQUEST["xdebug"]) print "$query\n";
900 $result = db_query($link, $query);
902 // okay it doesn't exist - create user entry
903 if (db_num_rows($result) == 0) {
905 if ($debug_enabled) {
906 _debug("update_rss_feed: user record not found, creating...");
909 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
911 $last_read_qpart = 'NULL';
914 $last_read_qpart = 'NOW()';
917 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
923 if (find_article_filter($article_filters, 'publish')) {
926 $published = 'false';
931 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
933 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
934 ttrss_entries,ttrss_user_entries
935 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
936 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
937 AND owner_uid = $owner_uid");
939 $ngram_similar = db_fetch_result($result, 0, "similar");
941 if ($debug_enabled) {
942 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
945 if ($ngram_similar > 0) {
950 $result = db_query($link,
951 "INSERT INTO ttrss_user_entries
952 (ref_id, owner_uid, feed_id, unread, last_read, marked,
953 published, score, tag_cache, label_cache, uuid)
954 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
955 $last_read_qpart, $marked, $published, '$score', '', '', '')");
957 if (PUBSUBHUBBUB_HUB && $published == 'true') {
958 $rss_link = get_self_url_prefix() .
959 "/public.php?op=rss&id=-2&key=" .
960 get_feed_access_key($link, -2, false, $owner_uid);
962 $p = new Publisher(PUBSUBHUBBUB_HUB);
964 $pubsub_result = $p->publish_update($rss_link);
967 $result = db_query($link,
968 "SELECT int_id FROM ttrss_user_entries WHERE
969 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
970 feed_id = '$feed' LIMIT 1");
972 if (db_num_rows($result) == 1) {
973 $entry_int_id = db_fetch_result($result, 0, "int_id");
976 if ($debug_enabled) {
977 _debug("update_rss_feed: user record FOUND");
980 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
981 $entry_int_id = db_fetch_result($result, 0, "int_id");
984 if ($debug_enabled) {
985 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
988 $post_needs_update = false;
989 $update_insignificant = false;
991 if ($orig_num_comments != $num_comments) {
992 $post_needs_update = true;
993 $update_insignificant = true;
996 if ($content_hash != $orig_content_hash) {
997 $post_needs_update = true;
998 $update_insignificant = false;
1001 if (db_escape_string($orig_title) != $entry_title) {
1002 $post_needs_update = true;
1003 $update_insignificant = false;
1006 // if post needs update, update it and mark all user entries
1007 // linking to this post as updated
1008 if ($post_needs_update) {
1010 if (defined('DAEMON_EXTENDED_DEBUG')) {
1011 _debug("update_rss_feed: post $entry_guid needs update...");
1014 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1016 db_query($link, "UPDATE ttrss_entries
1017 SET title = '$entry_title', content = '$entry_content',
1018 content_hash = '$content_hash',
1019 updated = '$entry_timestamp_fmt',
1020 num_comments = '$num_comments'
1021 WHERE id = '$ref_id'");
1023 if (!$update_insignificant) {
1024 if ($mark_unread_on_update) {
1025 db_query($link, "UPDATE ttrss_user_entries
1026 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1027 } else if ($update_on_checksum_change) {
1028 db_query($link, "UPDATE ttrss_user_entries
1029 SET last_read = null WHERE ref_id = '$ref_id'
1030 AND unread = false");
1036 db_query($link, "COMMIT");
1038 if ($debug_enabled) {
1039 _debug("update_rss_feed: assigning labels...");
1042 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
1043 $owner_uid, $article_labels);
1045 if ($debug_enabled) {
1046 _debug("update_rss_feed: looking for enclosures...");
1051 $enclosures = array();
1053 if ($use_simplepie) {
1054 $encs = $item->get_enclosures();
1056 if (is_array($encs)) {
1057 foreach ($encs as $e) {
1059 $e->link, $e->type, $e->length);
1061 array_push($enclosures, $e_item);
1068 $e_ctr = $item['enclosure#'];
1071 $e_item = array($item['enclosure@url'],
1072 $item['enclosure@type'],
1073 $item['enclosure@length']);
1075 array_push($enclosures, $e_item);
1077 for ($i = 0; $i <= $e_ctr; $i++ ) {
1079 if ($item["enclosure#$i@url"]) {
1080 $e_item = array($item["enclosure#$i@url"],
1081 $item["enclosure#$i@type"],
1082 $item["enclosure#$i@length"]);
1083 array_push($enclosures, $e_item);
1089 // can there be many of those? yes -fox
1091 $m_ctr = $item['media']['content#'];
1094 $e_item = array($item['media']['content@url'],
1095 $item['media']['content@medium'],
1096 $item['media']['content@length']);
1098 array_push($enclosures, $e_item);
1100 for ($i = 0; $i <= $m_ctr; $i++ ) {
1102 if ($item["media"]["content#$i@url"]) {
1103 $e_item = array($item["media"]["content#$i@url"],
1104 $item["media"]["content#$i@medium"],
1105 $item["media"]["content#$i@length"]);
1106 array_push($enclosures, $e_item);
1114 if ($debug_enabled) {
1115 _debug("update_rss_feed: article enclosures:");
1116 print_r($enclosures);
1119 db_query($link, "BEGIN");
1121 foreach ($enclosures as $enc) {
1122 $enc_url = db_escape_string($enc[0]);
1123 $enc_type = db_escape_string($enc[1]);
1124 $enc_dur = db_escape_string($enc[2]);
1126 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1127 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1129 if (db_num_rows($result) == 0) {
1130 db_query($link, "INSERT INTO ttrss_enclosures
1131 (content_url, content_type, title, duration, post_id) VALUES
1132 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1136 db_query($link, "COMMIT");
1138 // check for manual tags (we have to do it here since they're loaded from filters)
1140 foreach ($article_filters as $f) {
1141 if ($f["type"] == "tag") {
1143 $manual_tags = trim_array(explode(",", $f["param"]));
1145 foreach ($manual_tags as $tag) {
1146 if (tag_is_valid($tag)) {
1147 array_push($entry_tags, $tag);
1155 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1156 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1158 $filtered_tags = array();
1159 $tags_to_cache = array();
1161 if ($entry_tags && is_array($entry_tags)) {
1162 foreach ($entry_tags as $tag) {
1163 if (array_search($tag, $boring_tags) === false) {
1164 array_push($filtered_tags, $tag);
1169 $filtered_tags = array_unique($filtered_tags);
1171 if ($debug_enabled) {
1172 _debug("update_rss_feed: filtered article tags:");
1173 print_r($filtered_tags);
1176 // Save article tags in the database
1178 if (count($filtered_tags) > 0) {
1180 db_query($link, "BEGIN");
1182 foreach ($filtered_tags as $tag) {
1184 $tag = sanitize_tag($tag);
1185 $tag = db_escape_string($tag);
1187 if (!tag_is_valid($tag)) continue;
1189 $result = db_query($link, "SELECT id FROM ttrss_tags
1190 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1191 owner_uid = '$owner_uid' LIMIT 1");
1193 if ($result && db_num_rows($result) == 0) {
1195 db_query($link, "INSERT INTO ttrss_tags
1196 (owner_uid,tag_name,post_int_id)
1197 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1200 array_push($tags_to_cache, $tag);
1203 /* update the cache */
1205 $tags_to_cache = array_unique($tags_to_cache);
1207 $tags_str = db_escape_string(join(",", $tags_to_cache));
1209 db_query($link, "UPDATE ttrss_user_entries
1210 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1211 AND owner_uid = $owner_uid");
1213 db_query($link, "COMMIT");
1216 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1217 if ($debug_enabled) {
1218 _debug("update_rss_feed: auto-assigning labels...");
1221 foreach ($labels as $label) {
1222 $caption = $label["caption"];
1224 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
1225 if (!labels_contains_caption($article_labels, $caption)) {
1226 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1232 if ($debug_enabled) {
1233 _debug("update_rss_feed: article processed");
1237 if (!$last_updated) {
1238 if ($debug_enabled) {
1239 _debug("update_rss_feed: new feed, catching it up...");
1241 catchup_feed($link, $feed, false, $owner_uid);
1244 if ($debug_enabled) {
1245 _debug("purging feed...");
1248 purge_feed($link, $feed, 0, $debug_enabled);
1250 db_query($link, "UPDATE ttrss_feeds
1251 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1253 // db_query($link, "COMMIT");
1257 if ($use_simplepie) {
1258 $error_msg = mb_substr($rss->error(), 0, 250);
1260 $error_msg = mb_substr(magpie_error(), 0, 250);
1263 if ($debug_enabled) {
1264 _debug("update_rss_feed: error fetching feed: $error_msg");
1267 $error_msg = db_escape_string($error_msg);
1270 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1271 last_updated = NOW() WHERE id = '$feed'");
1274 if ($use_simplepie) {
1278 if ($debug_enabled) {
1279 _debug("update_rss_feed: done");
1284 function cache_images($html, $site_url, $debug) {
1285 $cache_dir = CACHE_DIR . "/images";
1287 libxml_use_internal_errors(true);
1289 $charset_hack = '<head>
1290 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1293 $doc = new DOMDocument();
1294 $doc->loadHTML($charset_hack . $html);
1295 $xpath = new DOMXPath($doc);
1297 $entries = $xpath->query('(//img[@src])');
1299 foreach ($entries as $entry) {
1300 if ($entry->hasAttribute('src')) {
1301 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1303 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1305 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1307 if (!file_exists($local_filename)) {
1308 $file_content = fetch_file_contents($src);
1310 if ($file_content && strlen($file_content) > 1024) {
1311 file_put_contents($local_filename, $file_content);
1315 if (file_exists($local_filename)) {
1316 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
1317 base64_encode($src));
1322 $node = $doc->getElementsByTagName('body')->item(0);
1324 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1327 function expire_cached_files($debug) {
1328 foreach (array("magpie", "simplepie", "images", "export") as $dir) {
1329 $cache_dir = CACHE_DIR . "/$dir";
1331 if ($debug) _debug("Expiring $cache_dir");
1335 if (is_writable($cache_dir)) {
1336 $files = glob("$cache_dir/*");
1339 foreach ($files as $file) {
1340 if (time() - filemtime($file) > 86400*7) {
1348 if ($debug) _debug("Removed $num_deleted files.");
1353 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1354 * Returns the url query as associative array
1356 * @param string query
1357 * @return array params
1359 function convertUrlQuery($query) {
1360 $queryParts = explode('&', $query);
1364 foreach ($queryParts as $param) {
1365 $item = explode('=', $param);
1366 $params[$item[0]] = $item[1];
1372 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1375 foreach ($filters as $filter) {
1376 $match_any_rule = $filter["match_any_rule"];
1377 $filter_match = false;
1379 foreach ($filter["rules"] as $rule) {
1381 $reg_exp = $rule["reg_exp"];
1386 switch ($rule["type"]) {
1388 $match = @preg_match("/$reg_exp/i", $title);
1391 $match = @preg_match("/$reg_exp/i", $content);
1394 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $title));
1397 $match = @preg_match("/$reg_exp/i", $link);
1400 $match = @preg_match("/$reg_exp/i", $author);
1403 $tag_string = join(",", $tags);
1404 $match = @preg_match("/$reg_exp/i", $tag_string);
1408 if ($match_any_rule) {
1410 $filter_match = true;
1414 $filter_match = $match;
1421 if ($filter_match) {
1422 foreach ($filter["actions"] AS $action) {
1423 array_push($matches, $action);
1431 function find_article_filter($filters, $filter_name) {
1432 foreach ($filters as $f) {
1433 if ($f["type"] == $filter_name) {
1440 function find_article_filters($filters, $filter_name) {
1443 foreach ($filters as $f) {
1444 if ($f["type"] == $filter_name) {
1445 array_push($results, $f);
1451 function calculate_article_score($filters) {
1454 foreach ($filters as $f) {
1455 if ($f["type"] == "score") {
1456 $score += $f["param"];
1462 function labels_contains_caption($labels, $caption) {
1463 foreach ($labels as $label) {
1464 if ($label[1] == $caption) {
1472 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1473 foreach ($filters as $f) {
1474 if ($f["type"] == "label") {
1475 if (!labels_contains_caption($article_labels, $f["param"])) {
1476 label_add_article($link, $id, $f["param"], $owner_uid);