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);
144 expire_lock_files($debug);
146 // For each feed, we call the feed update function.
147 while ($line = array_pop($feeds_to_update)) {
149 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
151 update_rss_feed($link, $line["id"], true);
153 sleep(1); // prevent flood (FIXME make this an option?)
156 // Send feed digests by email if needed.
157 send_headlines_digests($link, $debug);
159 } // function update_daemon_common
161 // ignore_daemon is not used
162 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
163 $override_url = false) {
165 require_once "lib/simplepie/simplepie.inc";
166 require_once "lib/magpierss/rss_fetch.inc";
167 require_once 'lib/magpierss/rss_utils.inc';
169 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
171 if ($debug_enabled) {
172 _debug("update_rss_feed: start");
175 $result = db_query($link, "SELECT id,update_interval,auth_login,
176 feed_url,auth_pass,cache_images,update_method,last_updated,cache_content,
177 mark_unread_on_update, owner_uid, update_on_checksum_change,
179 FROM ttrss_feeds WHERE id = '$feed'");
181 if (db_num_rows($result) == 0) {
182 if ($debug_enabled) {
183 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
188 $update_method = db_fetch_result($result, 0, "update_method");
189 $last_updated = db_fetch_result($result, 0, "last_updated");
190 $owner_uid = db_fetch_result($result, 0, "owner_uid");
191 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
192 0, "mark_unread_on_update"));
193 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
194 0, "update_on_checksum_change"));
195 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
197 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
198 WHERE id = '$feed'");
200 $auth_login = db_fetch_result($result, 0, "auth_login");
201 $auth_pass = db_fetch_result($result, 0, "auth_pass");
203 if ($update_method == 0)
204 $update_method = DEFAULT_UPDATE_METHOD +
1;
210 if ($update_method == 2)
211 $use_simplepie = true;
213 $use_simplepie = false;
215 if ($debug_enabled) {
216 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
219 if ($update_method == 1) {
220 $auth_login = urlencode($auth_login);
221 $auth_pass = urlencode($auth_pass);
224 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
225 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
226 $fetch_url = db_fetch_result($result, 0, "feed_url");
228 $feed = db_escape_string($feed);
230 if ($auth_login && $auth_pass ){
231 $url_parts = array();
232 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
234 if ($url_parts[1] && $url_parts[2]) {
235 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
241 $fetch_url = $override_url;
243 if ($debug_enabled) {
244 _debug("update_rss_feed: fetching [$fetch_url]...");
247 // Ignore cache if new feed or manual update.
248 $cache_age = (is_null($last_updated) ||
$last_updated == '1970-01-01 00:00:00') ?
249 -1 : get_feed_update_interval($link, $feed) * 60;
251 if ($update_method == 1) {
253 define('MAGPIE_CACHE_AGE', $cache_age);
254 define('MAGPIE_CACHE_ON', !$no_cache);
255 define('MAGPIE_FETCH_TIME_OUT', $no_cache ?
15 : 60);
256 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
258 $rss = @fetch_rss
($fetch_url);
260 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
262 if (!is_dir($simplepie_cache_dir)) {
263 mkdir($simplepie_cache_dir);
266 $rss = new SimplePie();
267 $rss->set_useragent(SELF_USER_AGENT
);
268 $rss->set_timeout($no_cache ?
15 : 60);
269 $rss->set_feed_url($fetch_url);
270 $rss->set_output_encoding('UTF-8');
271 //$rss->force_feed(true);
273 if ($debug_enabled) {
274 _debug("feed update interval (sec): " .
275 get_feed_update_interval($link, $feed)*60);
278 $rss->enable_cache(!$no_cache);
281 $rss->set_cache_location($simplepie_cache_dir);
282 $rss->set_cache_duration($cache_age);
290 if ($debug_enabled) {
291 _debug("update_rss_feed: fetch done, parsing...");
294 $feed = db_escape_string($feed);
296 if ($update_method == 2) {
297 $fetch_ok = !$rss->error();
304 if ($debug_enabled) {
305 _debug("update_rss_feed: processing feed data...");
308 // db_query($link, "BEGIN");
310 if (DB_TYPE
== "pgsql") {
311 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
313 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
316 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid,
317 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
319 FROM ttrss_feeds WHERE id = '$feed'");
321 $registered_title = db_fetch_result($result, 0, "title");
322 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
323 $orig_site_url = db_fetch_result($result, 0, "site_url");
324 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
325 "favicon_needs_check"));
327 $owner_uid = db_fetch_result($result, 0, "owner_uid");
329 if ($use_simplepie) {
330 $site_url = db_escape_string(trim($rss->get_link()));
332 $site_url = db_escape_string(trim($rss->channel
["link"]));
335 // weird, weird Magpie
336 if (!$use_simplepie) {
337 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
340 $site_url = rewrite_relative_url($fetch_url, $site_url);
341 $site_url = substr($site_url, 0, 250);
343 if ($debug_enabled) {
344 _debug("update_rss_feed: checking favicon...");
347 if ($favicon_needs_check) {
348 check_feed_favicon($site_url, $feed, $link);
350 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
351 WHERE id = '$feed'");
354 if (!$registered_title ||
$registered_title == "[Unknown]") {
356 if ($use_simplepie) {
357 $feed_title = db_escape_string($rss->get_title());
359 $feed_title = db_escape_string($rss->channel
["title"]);
362 if ($debug_enabled) {
363 _debug("update_rss_feed: registering title: $feed_title");
366 db_query($link, "UPDATE ttrss_feeds SET
367 title = '$feed_title' WHERE id = '$feed'");
370 if ($site_url && $orig_site_url != $site_url) {
371 db_query($link, "UPDATE ttrss_feeds SET
372 site_url = '$site_url' WHERE id = '$feed'");
375 // print "I: " . $rss->channel["image"]["url"];
377 if (!$use_simplepie) {
378 $icon_url = db_escape_string(trim($rss->image
["url"]));
380 $icon_url = db_escape_string(trim($rss->get_image_url()));
383 $icon_url = rewrite_relative_url($fetch_url, $icon_url);
384 $icon_url = substr($icon_url, 0, 250);
386 if ($icon_url && $orig_icon_url != $icon_url) {
387 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
390 if ($debug_enabled) {
391 _debug("update_rss_feed: loading filters & labels...");
394 $filters = load_filters($link, $feed, $owner_uid);
395 $labels = get_all_labels($link, $owner_uid);
397 if ($debug_enabled) {
399 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
402 $filter_plugins = array();
404 if (defined('_ARTICLE_FILTER_PLUGINS')) {
405 foreach (explode(",", _ARTICLE_FILTER_PLUGINS
) as $p) {
406 $pclass = "filter_" . trim($p);
408 if (class_exists($pclass)) {
409 $plugin = new $pclass($link);
410 array_push($filter_plugins, $plugin);
415 if ($debug_enabled) {
416 _debug("update_rss_feed: " . count($filter_plugins) . " filter plugins 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 ($cache_content) {
528 $entry_guid = "ccache:$entry_guid";
531 if ($auth_login ||
$auth_pass) {
532 $entry_guid = "auth,$owner_uid:$entry_guid";
535 if ($debug_enabled) {
536 _debug("update_rss_feed: guid $entry_guid");
539 if (!$entry_guid) continue;
541 $entry_timestamp = "";
543 if ($use_simplepie) {
544 $entry_timestamp = strtotime($item->get_date());
546 $rss_2_date = $item['pubdate'];
547 $rss_1_date = $item['dc']['date'];
548 $atom_date = $item['issued'];
549 if (!$atom_date) $atom_date = $item['updated'];
551 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
552 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
553 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
557 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
558 $entry_timestamp = time();
559 $no_orig_date = 'true';
561 $no_orig_date = 'false';
564 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
566 if ($debug_enabled) {
567 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
570 if ($use_simplepie) {
571 $entry_title = $item->get_title();
573 $entry_title = trim(strip_tags($item["title"]));
576 if ($use_simplepie) {
577 $entry_link = $item->get_link();
579 // strange Magpie workaround
580 $entry_link = $item["link_"];
581 if (!$entry_link) $entry_link = $item["link"];
584 $entry_link = rewrite_relative_url($site_url, $entry_link);
586 if ($debug_enabled) {
587 _debug("update_rss_feed: title $entry_title");
588 _debug("update_rss_feed: link $entry_link");
591 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
593 $entry_link = strip_tags($entry_link);
595 if ($use_simplepie) {
596 $entry_content = $item->get_content();
597 if (!$entry_content) $entry_content = $item->get_description();
599 $entry_content = $item["content:escaped"];
601 if (!$entry_content) $entry_content = $item["content:encoded"];
602 if (!$entry_content && is_array($entry_content)) $entry_content = $item["content"]["encoded"];
603 if (!$entry_content) $entry_content = $item["content"];
605 if (is_array($entry_content)) $entry_content = $entry_content[0];
607 // Magpie bugs are getting ridiculous
608 if (trim($entry_content) == "Array") $entry_content = false;
610 if (!$entry_content) $entry_content = $item["atom_content"];
611 if (!$entry_content) $entry_content = $item["summary"];
613 if (!$entry_content ||
614 strlen($entry_content) < strlen($item["description"])) {
615 $entry_content = $item["description"];
619 if (is_array($entry_content)) {
620 $entry_content = $entry_content["encoded"];
621 if (!$entry_content) $entry_content = $entry_content["escaped"];
625 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
626 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
628 if ($_REQUEST["xdebug"] == 2) {
629 print "update_rss_feed: content: ";
630 print $entry_content;
634 $entry_cached_content = "";
636 if ($use_simplepie) {
637 $entry_comments = strip_tags($item->data
["comments"]);
638 if ($item->get_author()) {
639 $entry_author_item = $item->get_author();
640 $entry_author = $entry_author_item->get_name();
641 if (!$entry_author) $entry_author = $entry_author_item->get_email();
643 $entry_author = db_escape_string($entry_author);
646 $entry_comments = strip_tags($item["comments"]);
648 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
650 if ($item['author']) {
652 if (is_array($item['author'])) {
654 if (!$entry_author) {
655 $entry_author = db_escape_string(strip_tags($item['author']['name']));
658 if (!$entry_author) {
659 $entry_author = db_escape_string(strip_tags($item['author']['email']));
663 if (!$entry_author) {
664 $entry_author = db_escape_string(strip_tags($item['author']));
669 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
671 $entry_guid = db_escape_string(strip_tags($entry_guid));
672 $entry_guid = mb_substr($entry_guid, 0, 250);
674 $result = db_query($link, "SELECT id FROM ttrss_entries
675 WHERE guid = '$entry_guid'");
677 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
678 $entry_author = mb_substr($entry_author, 0, 250);
680 if ($use_simplepie) {
681 $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
683 if (is_array($num_comments) && is_array($num_comments[0])) {
684 $num_comments = (int) $num_comments[0]["data"];
689 $num_comments = (int) $item["slash"]["comments"];
692 if ($debug_enabled) {
693 _debug("update_rss_feed: num_comments: $num_comments");
694 _debug("update_rss_feed: looking for tags [1]...");
697 // parse <category> entries into tags
699 $additional_tags = array();
701 if ($use_simplepie) {
703 $additional_tags_src = $item->get_categories();
705 if (is_array($additional_tags_src)) {
706 foreach ($additional_tags_src as $tobj) {
707 array_push($additional_tags, $tobj->get_term());
711 if ($debug_enabled) {
712 _debug("update_rss_feed: category tags:");
713 print_r($additional_tags);
718 $t_ctr = $item['category#'];
721 $additional_tags = array();
722 } else if ($t_ctr > 0) {
723 $additional_tags = array($item['category']);
725 if ($item['category@term']) {
726 array_push($additional_tags, $item['category@term']);
729 for ($i = 0; $i <= $t_ctr; $i++
) {
730 if ($item["category#$i"]) {
731 array_push($additional_tags, $item["category#$i"]);
734 if ($item["category#$i@term"]) {
735 array_push($additional_tags, $item["category#$i@term"]);
740 // parse <dc:subject> elements
742 $t_ctr = $item['dc']['subject#'];
745 array_push($additional_tags, $item['dc']['subject']);
747 for ($i = 0; $i <= $t_ctr; $i++
) {
748 if ($item['dc']["subject#$i"]) {
749 array_push($additional_tags, $item['dc']["subject#$i"]);
755 if ($debug_enabled) {
756 _debug("update_rss_feed: looking for tags [2]...");
760 // <a href="..." rel="tag">Xorg</a>, //
764 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
765 $entry_content, $entry_tags);
767 $entry_tags = $entry_tags[1];
769 $entry_tags = array_merge($entry_tags, $additional_tags);
770 $entry_tags = array_unique($entry_tags);
772 for ($i = 0; $i < count($entry_tags); $i++
)
773 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
775 if ($debug_enabled) {
776 //_debug("update_rss_feed: unfiltered tags found:");
777 //print_r($entry_tags);
780 if ($debug_enabled) {
781 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
784 // TODO: less memory-hungry implementation
785 if (count($filter_plugins) > 0) {
786 if ($debug_enabled) {
787 _debug("update_rss_feed: applying plugin filters...");
790 $article = array("owner_uid" => $owner_uid,
791 "title" => $entry_title,
792 "content" => $entry_content,
793 "link" => $entry_link,
794 "tags" => $entry_tags,
795 "author" => $entry_author);
797 foreach ($filter_plugins as $plugin) {
798 $article = $plugin->filter_article($article);
801 $entry_title = $article["title"];
802 $entry_content = $article["content"];
803 $entry_tags = $article["tags"];
804 $entry_author = $article["author"];
807 $entry_content = db_escape_string($entry_content, false);
808 $entry_title = db_escape_string($entry_title);
809 $entry_author = db_escape_string($entry_author);
810 $entry_link = db_escape_string($entry_link);
812 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
814 db_query($link, "BEGIN");
816 if (db_num_rows($result) == 0) {
818 if ($debug_enabled) {
819 _debug("update_rss_feed: base guid not found");
822 if ($cache_content) {
823 if ($debug_enabled) {
824 _debug("update_rss_feed: caching content (initial)...");
827 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
829 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
830 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
832 $entry_cached_content = db_escape_string($entry_cached_content, false);
835 // base post entry does not exist, create it
837 $result = db_query($link,
838 "INSERT INTO ttrss_entries
856 '$entry_timestamp_fmt',
859 '$entry_cached_content',
867 $article_labels = array();
870 // we keep encountering the entry in feeds, so we need to
871 // update date_updated column so that we don't get horrible
872 // dupes when the entry gets purged and reinserted again e.g.
873 // in the case of SLOW SLOW OMG SLOW updating feeds
875 $base_entry_id = db_fetch_result($result, 0, "id");
877 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
878 WHERE id = '$base_entry_id'");
880 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
883 // now it should exist, if not - bad luck then
885 $result = db_query($link, "SELECT
886 id,content_hash,no_orig_date,title,
887 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
888 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
889 num_comments, cached_content
892 WHERE guid = '$entry_guid'");
897 if (db_num_rows($result) == 1) {
899 if ($debug_enabled) {
900 _debug("update_rss_feed: base guid found, checking for user record");
903 // this will be used below in update handler
904 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
905 $orig_title = db_fetch_result($result, 0, "title");
906 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
907 $orig_cached_content = trim(db_fetch_result($result, 0, "cached_content"));
908 $orig_date_updated = strtotime(db_fetch_result($result,
911 $ref_id = db_fetch_result($result, 0, "id");
912 $entry_ref_id = $ref_id;
914 // check for user post link to main table
916 // do we allow duplicate posts with same GUID in different feeds?
917 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
918 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
920 $dupcheck_qpart = "";
923 /* Collect article tags here so we could filter by them: */
925 $article_filters = get_article_filters($filters, $entry_title,
926 $entry_content, $entry_link, $entry_timestamp, $entry_author,
929 if ($debug_enabled) {
930 _debug("update_rss_feed: article filters: ");
931 if (count($article_filters) != 0) {
932 print_r($article_filters);
936 if (find_article_filter($article_filters, "filter")) {
937 db_query($link, "COMMIT"); // close transaction in progress
941 $score = calculate_article_score($article_filters);
943 if ($debug_enabled) {
944 _debug("update_rss_feed: initial score: $score");
947 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
948 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
951 // if ($_REQUEST["xdebug"]) print "$query\n";
953 $result = db_query($link, $query);
955 // okay it doesn't exist - create user entry
956 if (db_num_rows($result) == 0) {
958 if ($debug_enabled) {
959 _debug("update_rss_feed: user record not found, creating...");
962 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
964 $last_read_qpart = 'NULL';
967 $last_read_qpart = 'NOW()';
970 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
976 if (find_article_filter($article_filters, 'publish')) {
979 $published = 'false';
984 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
986 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
987 ttrss_entries,ttrss_user_entries
988 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
989 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD
."
990 AND owner_uid = $owner_uid");
992 $ngram_similar = db_fetch_result($result, 0, "similar");
994 if ($debug_enabled) {
995 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
998 if ($ngram_similar > 0) {
1003 $result = db_query($link,
1004 "INSERT INTO ttrss_user_entries
1005 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1006 published, score, tag_cache, label_cache, uuid)
1007 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1008 $last_read_qpart, $marked, $published, '$score', '', '', '')");
1010 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1011 $rss_link = get_self_url_prefix() .
1012 "/public.php?op=rss&id=-2&key=" .
1013 get_feed_access_key($link, -2, false, $owner_uid);
1015 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1017 $pubsub_result = $p->publish_update($rss_link);
1020 $result = db_query($link,
1021 "SELECT int_id FROM ttrss_user_entries WHERE
1022 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1023 feed_id = '$feed' LIMIT 1");
1025 if (db_num_rows($result) == 1) {
1026 $entry_int_id = db_fetch_result($result, 0, "int_id");
1029 if ($debug_enabled) {
1030 _debug("update_rss_feed: user record FOUND");
1033 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1034 $entry_int_id = db_fetch_result($result, 0, "int_id");
1037 if ($debug_enabled) {
1038 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1041 $post_needs_update = false;
1042 $update_insignificant = false;
1043 $cached_content_needs_update = false;
1045 if ($orig_num_comments != $num_comments) {
1046 $post_needs_update = true;
1047 $update_insignificant = true;
1050 if ($content_hash != $orig_content_hash) {
1051 $post_needs_update = true;
1052 $update_insignificant = false;
1053 $cached_content_needs_update = true;
1056 if ($cache_content) {
1057 if ($debug_enabled) {
1058 _debug("update_rss_feed: caching content because original checksum changed...");
1061 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
1063 if ($entry_cached_content) {
1064 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
1065 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
1067 $entry_cached_content = db_escape_string($entry_cached_content, false);
1068 $post_needs_update = true;
1070 $entry_cached_content = db_escape_string($orig_cached_content);
1073 $entry_cached_content = db_escape_string($orig_cached_content);
1076 if (db_escape_string($orig_title) != $entry_title) {
1077 $post_needs_update = true;
1078 $update_insignificant = false;
1081 // if post needs update, update it and mark all user entries
1082 // linking to this post as updated
1083 if ($post_needs_update) {
1085 if (defined('DAEMON_EXTENDED_DEBUG')) {
1086 _debug("update_rss_feed: post $entry_guid needs update...");
1089 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1091 db_query($link, "UPDATE ttrss_entries
1092 SET title = '$entry_title', content = '$entry_content',
1093 content_hash = '$content_hash',
1094 cached_content = '$entry_cached_content',
1095 updated = '$entry_timestamp_fmt',
1096 num_comments = '$num_comments'
1097 WHERE id = '$ref_id'");
1099 if (!$update_insignificant) {
1100 if ($mark_unread_on_update) {
1101 db_query($link, "UPDATE ttrss_user_entries
1102 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1103 } else if ($update_on_checksum_change) {
1104 db_query($link, "UPDATE ttrss_user_entries
1105 SET last_read = null WHERE ref_id = '$ref_id'
1106 AND unread = false");
1112 db_query($link, "COMMIT");
1114 if ($debug_enabled) {
1115 _debug("update_rss_feed: assigning labels...");
1118 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
1119 $owner_uid, $article_labels);
1121 if ($debug_enabled) {
1122 _debug("update_rss_feed: looking for enclosures...");
1127 $enclosures = array();
1129 if ($use_simplepie) {
1130 $encs = $item->get_enclosures();
1132 if (is_array($encs)) {
1133 foreach ($encs as $e) {
1135 $e->link
, $e->type
, $e->length
);
1137 array_push($enclosures, $e_item);
1144 $e_ctr = $item['enclosure#'];
1147 $e_item = array($item['enclosure@url'],
1148 $item['enclosure@type'],
1149 $item['enclosure@length']);
1151 array_push($enclosures, $e_item);
1153 for ($i = 0; $i <= $e_ctr; $i++
) {
1155 if ($item["enclosure#$i@url"]) {
1156 $e_item = array($item["enclosure#$i@url"],
1157 $item["enclosure#$i@type"],
1158 $item["enclosure#$i@length"]);
1159 array_push($enclosures, $e_item);
1165 // can there be many of those? yes -fox
1167 $m_ctr = $item['media']['content#'];
1170 $e_item = array($item['media']['content@url'],
1171 $item['media']['content@medium'],
1172 $item['media']['content@length']);
1174 array_push($enclosures, $e_item);
1176 for ($i = 0; $i <= $m_ctr; $i++
) {
1178 if ($item["media"]["content#$i@url"]) {
1179 $e_item = array($item["media"]["content#$i@url"],
1180 $item["media"]["content#$i@medium"],
1181 $item["media"]["content#$i@length"]);
1182 array_push($enclosures, $e_item);
1190 if ($debug_enabled) {
1191 _debug("update_rss_feed: article enclosures:");
1192 print_r($enclosures);
1195 db_query($link, "BEGIN");
1197 foreach ($enclosures as $enc) {
1198 $enc_url = db_escape_string($enc[0]);
1199 $enc_type = db_escape_string($enc[1]);
1200 $enc_dur = db_escape_string($enc[2]);
1202 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1203 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1205 if (db_num_rows($result) == 0) {
1206 db_query($link, "INSERT INTO ttrss_enclosures
1207 (content_url, content_type, title, duration, post_id) VALUES
1208 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1212 db_query($link, "COMMIT");
1214 // check for manual tags (we have to do it here since they're loaded from filters)
1216 foreach ($article_filters as $f) {
1217 if ($f["type"] == "tag") {
1219 $manual_tags = trim_array(explode(",", $f["param"]));
1221 foreach ($manual_tags as $tag) {
1222 if (tag_is_valid($tag)) {
1223 array_push($entry_tags, $tag);
1231 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1232 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1234 $filtered_tags = array();
1235 $tags_to_cache = array();
1237 if ($entry_tags && is_array($entry_tags)) {
1238 foreach ($entry_tags as $tag) {
1239 if (array_search($tag, $boring_tags) === false) {
1240 array_push($filtered_tags, $tag);
1245 $filtered_tags = array_unique($filtered_tags);
1247 if ($debug_enabled) {
1248 _debug("update_rss_feed: filtered article tags:");
1249 print_r($filtered_tags);
1252 // Save article tags in the database
1254 if (count($filtered_tags) > 0) {
1256 db_query($link, "BEGIN");
1258 foreach ($filtered_tags as $tag) {
1260 $tag = sanitize_tag($tag);
1261 $tag = db_escape_string($tag);
1263 if (!tag_is_valid($tag)) continue;
1265 $result = db_query($link, "SELECT id FROM ttrss_tags
1266 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1267 owner_uid = '$owner_uid' LIMIT 1");
1269 if ($result && db_num_rows($result) == 0) {
1271 db_query($link, "INSERT INTO ttrss_tags
1272 (owner_uid,tag_name,post_int_id)
1273 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1276 array_push($tags_to_cache, $tag);
1279 /* update the cache */
1281 $tags_to_cache = array_unique($tags_to_cache);
1283 $tags_str = db_escape_string(join(",", $tags_to_cache));
1285 db_query($link, "UPDATE ttrss_user_entries
1286 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1287 AND owner_uid = $owner_uid");
1289 db_query($link, "COMMIT");
1292 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1293 if ($debug_enabled) {
1294 _debug("update_rss_feed: auto-assigning labels...");
1297 foreach ($labels as $label) {
1298 $caption = $label["caption"];
1300 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
1301 if (!labels_contains_caption($article_labels, $caption)) {
1302 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1308 if ($debug_enabled) {
1309 _debug("update_rss_feed: article processed");
1313 if (!$last_updated) {
1314 if ($debug_enabled) {
1315 _debug("update_rss_feed: new feed, catching it up...");
1317 catchup_feed($link, $feed, false, $owner_uid);
1320 if ($debug_enabled) {
1321 _debug("purging feed...");
1324 purge_feed($link, $feed, 0, $debug_enabled);
1326 db_query($link, "UPDATE ttrss_feeds
1327 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1329 // db_query($link, "COMMIT");
1333 if ($use_simplepie) {
1334 $error_msg = mb_substr($rss->error(), 0, 250);
1336 $error_msg = mb_substr(magpie_error(), 0, 250);
1339 if ($debug_enabled) {
1340 _debug("update_rss_feed: error fetching feed: $error_msg");
1343 $error_msg = db_escape_string($error_msg);
1346 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1347 last_updated = NOW() WHERE id = '$feed'");
1350 if ($use_simplepie) {
1354 if ($debug_enabled) {
1355 _debug("update_rss_feed: done");
1360 function cache_images($html, $site_url, $debug) {
1361 $cache_dir = CACHE_DIR
. "/images";
1363 libxml_use_internal_errors(true);
1365 $charset_hack = '<head>
1366 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1369 $doc = new DOMDocument();
1370 $doc->loadHTML($charset_hack . $html);
1371 $xpath = new DOMXPath($doc);
1373 $entries = $xpath->query('(//img[@src])');
1375 foreach ($entries as $entry) {
1376 if ($entry->hasAttribute('src')) {
1377 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1379 $local_filename = CACHE_DIR
. "/images/" . sha1($src) . ".png";
1381 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1383 if (!file_exists($local_filename)) {
1384 $file_content = fetch_file_contents($src);
1386 if ($file_content && strlen($file_content) > 1024) {
1387 file_put_contents($local_filename, $file_content);
1391 if (file_exists($local_filename)) {
1392 $entry->setAttribute('src', SELF_URL_PATH
. '/image.php?url=' .
1393 base64_encode($src));
1398 $node = $doc->getElementsByTagName('body')->item(0);
1400 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
1403 function expire_lock_files($debug) {
1404 if ($debug) _debug("Removing old lock files...");
1408 if (is_writable(LOCK_DIRECTORY
)) {
1409 $files = glob(LOCK_DIRECTORY
. "/*.lock");
1412 foreach ($files as $file) {
1413 if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
1421 if ($debug) _debug("Removed $num_deleted files.");
1424 function expire_cached_files($debug) {
1425 foreach (array("magpie", "simplepie", "images", "export") as $dir) {
1426 $cache_dir = CACHE_DIR
. "/$dir";
1428 if ($debug) _debug("Expiring $cache_dir");
1432 if (is_writable($cache_dir)) {
1433 $files = glob("$cache_dir/*");
1436 foreach ($files as $file) {
1437 if (time() - filemtime($file) > 86400*7) {
1446 if ($debug) _debug("Removed $num_deleted files.");
1451 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1452 * Returns the url query as associative array
1454 * @param string query
1455 * @return array params
1457 function convertUrlQuery($query) {
1458 $queryParts = explode('&', $query);
1462 foreach ($queryParts as $param) {
1463 $item = explode('=', $param);
1464 $params[$item[0]] = $item[1];
1470 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1473 foreach ($filters as $filter) {
1474 $match_any_rule = $filter["match_any_rule"];
1475 $filter_match = false;
1477 foreach ($filter["rules"] as $rule) {
1479 $reg_exp = $rule["reg_exp"];
1484 switch ($rule["type"]) {
1486 $match = @preg_match
("/$reg_exp/i", $title);
1489 // we don't need to deal with multiline regexps
1490 $content = preg_replace("/[\r\n\t]/", "", $content);
1492 $match = @preg_match
("/$reg_exp/i", $content);
1495 // we don't need to deal with multiline regexps
1496 $content = preg_replace("/[\r\n\t]/", "", $content);
1498 $match = (@preg_match
("/$reg_exp/i", $title) || @preg_match
("/$reg_exp/i", $content));
1501 $match = @preg_match
("/$reg_exp/i", $link);
1504 $match = @preg_match
("/$reg_exp/i", $author);
1507 $tag_string = join(",", $tags);
1508 $match = @preg_match
("/$reg_exp/i", $tag_string);
1512 if ($match_any_rule) {
1514 $filter_match = true;
1518 $filter_match = $match;
1525 if ($filter_match) {
1526 foreach ($filter["actions"] AS $action) {
1527 array_push($matches, $action);
1535 function find_article_filter($filters, $filter_name) {
1536 foreach ($filters as $f) {
1537 if ($f["type"] == $filter_name) {
1544 function find_article_filters($filters, $filter_name) {
1547 foreach ($filters as $f) {
1548 if ($f["type"] == $filter_name) {
1549 array_push($results, $f);
1555 function calculate_article_score($filters) {
1558 foreach ($filters as $f) {
1559 if ($f["type"] == "score") {
1560 $score +
= $f["param"];
1566 function labels_contains_caption($labels, $caption) {
1567 foreach ($labels as $label) {
1568 if ($label[1] == $caption) {
1576 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1577 foreach ($filters as $f) {
1578 if ($f["type"] == "label") {
1579 if (!labels_contains_caption($article_labels, $f["param"])) {
1580 label_add_article($link, $id, $f["param"], $owner_uid);
1586 function cache_content($link, $url, $login, $pass) {
1588 $content = fetch_file_contents($url, $login, $pass);
1591 $doc = new DOMDocument();
1592 @$doc->loadHTML($content);
1593 $xpath = new DOMXPath($doc);
1595 $node = $doc->getElementsByTagName('body')->item(0);
1598 $content = $doc->saveXML($node, LIBXML_NOEMPTYTAG
);