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($link, $line["subscribers"]);
22 $feed_url = db_escape_string($link, $line["feed_url"]);
23 $title = db_escape_string($link, $line["title"]);
24 $site_url = db_escape_string($link, $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 $schema_version = get_schema_version($link);
65 if ($schema_version != SCHEMA_VERSION
) {
66 die("Schema version is wrong, please upgrade the database.\n");
69 define('PREFS_NO_CACHE', true);
71 // Test if the user has loggued in recently. If not, it does not update its feeds.
72 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
73 if (DB_TYPE
== "pgsql") {
74 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
76 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
79 $login_thresh_qpart = "";
82 // Test if the feed need a update (update interval exceded).
83 if (DB_TYPE
== "pgsql") {
84 $update_limit_qpart = "AND ((
85 ttrss_feeds.update_interval = 0
86 AND ttrss_user_prefs.value != '-1'
87 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
89 ttrss_feeds.update_interval > 0
90 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
91 ) OR ttrss_feeds.last_updated IS NULL
92 OR last_updated = '1970-01-01 00:00:00')";
94 $update_limit_qpart = "AND ((
95 ttrss_feeds.update_interval = 0
96 AND ttrss_user_prefs.value != '-1'
97 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
99 ttrss_feeds.update_interval > 0
100 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
101 ) OR ttrss_feeds.last_updated IS NULL
102 OR last_updated = '1970-01-01 00:00:00')";
105 // Test if feed is currently being updated by another process.
106 if (DB_TYPE
== "pgsql") {
107 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
109 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
112 // Test if there is a limit to number of updated feeds
114 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
116 $random_qpart = sql_random_function();
118 // We search for feed needing update.
119 $result = db_query($link, "SELECT DISTINCT ttrss_feeds.feed_url,$random_qpart
121 ttrss_feeds, ttrss_users, ttrss_user_prefs
123 ttrss_feeds.owner_uid = ttrss_users.id
124 AND ttrss_users.id = ttrss_user_prefs.owner_uid
125 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
126 $login_thresh_qpart $update_limit_qpart
127 $updstart_thresh_qpart
128 ORDER BY $random_qpart $query_limit");
130 $user_prefs_cache = array();
132 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
134 // Here is a little cache magic in order to minimize risk of double feed updates.
135 $feeds_to_update = array();
136 while ($line = db_fetch_assoc($result)) {
137 array_push($feeds_to_update, db_escape_string($link, $line['feed_url']));
140 // We update the feed last update started date before anything else.
141 // There is no lag due to feed contents downloads
142 // It prevent an other process to update the same feed.
144 if(count($feeds_to_update) > 0) {
145 $feeds_quoted = array();
147 foreach ($feeds_to_update as $feed) {
148 array_push($feeds_quoted, "'" . db_escape_string($link, $feed) . "'");
151 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
152 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
155 expire_cached_files($debug);
156 expire_lock_files($debug);
157 expire_error_log($link, $debug);
161 // For each feed, we call the feed update function.
162 foreach ($feeds_to_update as $feed) {
163 if($debug) _debug("Base feed: $feed");
165 //update_rss_feed($link, $line["id"], true);
167 // since we have the data cached, we can deal with other feeds with the same url
169 $tmp_result = db_query($link, "SELECT DISTINCT ttrss_feeds.id,last_updated
170 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
171 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
172 ttrss_users.id = ttrss_user_prefs.owner_uid AND
173 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
174 feed_url = '".db_escape_string($link, $feed)."' AND
175 (ttrss_feeds.update_interval > 0 OR
176 ttrss_user_prefs.value != '-1')
178 ORDER BY ttrss_feeds.id $query_limit");
180 if (db_num_rows($tmp_result) > 0) {
181 while ($tline = db_fetch_assoc($tmp_result)) {
182 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"]);
183 update_rss_feed($link, $tline["id"], true);
189 require_once "digest.php";
191 // Send feed digests by email if needed.
192 send_headlines_digests($link, $debug);
196 } // function update_daemon_common
198 // ignore_daemon is not used
199 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
200 $override_url = false) {
202 require_once "lib/simplepie/simplepie.inc";
204 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
206 if ($debug_enabled) {
207 _debug("update_rss_feed: start");
210 $result = db_query($link, "SELECT id,update_interval,auth_login,
211 feed_url,auth_pass,cache_images,last_updated,
212 mark_unread_on_update, owner_uid,
213 pubsub_state, auth_pass_encrypted
214 FROM ttrss_feeds WHERE id = '$feed'");
216 if (db_num_rows($result) == 0) {
217 if ($debug_enabled) {
218 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
223 $last_updated = db_fetch_result($result, 0, "last_updated");
224 $owner_uid = db_fetch_result($result, 0, "owner_uid");
225 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
226 0, "mark_unread_on_update"));
227 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
228 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
229 0, "auth_pass_encrypted"));
231 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
232 WHERE id = '$feed'");
234 $auth_login = db_fetch_result($result, 0, "auth_login");
235 $auth_pass = db_fetch_result($result, 0, "auth_pass");
237 if ($auth_pass_encrypted) {
238 require_once "crypt.php";
239 $auth_pass = decrypt_string($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($link, $feed);
247 if ($override_url) $fetch_url = $override_url;
249 $date_feed_processed = date('Y-m-d H:i');
251 $cache_filename = CACHE_DIR
. "/simplepie/" . sha1($fetch_url) . ".feed";
253 // Ignore cache if new feed or manual update.
254 $cache_age = ($no_cache ||
is_null($last_updated) ||
$last_updated == '1970-01-01 00:00:00') ?
255 30 : get_feed_update_interval($link, $feed) * 60;
257 if ($debug_enabled) {
258 _debug("update_rss_feed: cache filename: $cache_filename exists: " . file_exists($cache_filename));
259 _debug("update_rss_feed: cache age: $cache_age; no cache: $no_cache");
262 $cached_feed_data_hash = false;
266 $cache_timestamp = file_exists($cache_filename) ?
filemtime($cache_filename) : 0;
267 $last_updated_timestamp = strtotime($last_updated);
269 $force_refetch = isset($_REQUEST["force_refetch"]);
271 if (file_exists($cache_filename) &&
272 is_readable($cache_filename) &&
273 !$auth_login && !$auth_pass &&
274 filemtime($cache_filename) > time() - $cache_age) {
276 if ($debug_enabled) {
277 _debug("update_rss_feed: using local cache.");
280 if ($cache_timestamp > $last_updated_timestamp) {
281 @$rss_data = file_get_contents($cache_filename);
284 $rss_hash = sha1($rss_data);
285 @$rss = unserialize($rss_data);
287 } else if (!$force_refetch) {
288 if ($debug_enabled) {
289 _debug("update_rss_feed: local cache valid and older than last_updated, nothing to do.");
298 if ($debug_enabled) {
299 _debug("update_rss_feed: fetching [$fetch_url] (ts: $cache_timestamp/$last_updated_timestamp)");
302 $feed_data = fetch_file_contents($fetch_url, false,
303 $auth_login, $auth_pass, false,
304 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT
: FEED_FETCH_TIMEOUT
,
305 $force_refetch ?
0 : max($last_updated_timestamp, $cache_timestamp));
307 if ($debug_enabled) {
308 _debug("update_rss_feed: fetch done.");
314 global $fetch_last_error;
315 global $fetch_last_error_code;
317 if ($debug_enabled) {
318 _debug("update_rss_feed: unable to fetch: $fetch_last_error [$fetch_last_error_code]");
324 if ($fetch_last_error_code != 304) {
325 $error_escaped = db_escape_string($link, $fetch_last_error);
327 if ($debug_enabled) {
328 _debug("update_rss_feed: source claims data not modified, nothing to do.");
333 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
334 last_updated = NOW() WHERE id = '$feed'");
340 $pluginhost = new PluginHost($link);
341 $pluginhost->set_debug($debug_enabled);
342 $user_plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
344 $pluginhost->load(PLUGINS
, $pluginhost::KIND_ALL
);
345 $pluginhost->load($user_plugins, $pluginhost::KIND_USER
, $owner_uid);
346 $pluginhost->load_data();
348 foreach ($pluginhost->get_hooks($pluginhost::HOOK_FEED_FETCHED
) as $plugin) {
349 $feed_data = $plugin->hook_feed_fetched($feed_data);
353 $rss = new SimplePie();
354 $rss->set_sanitize_class("SanitizeDummy");
355 // simplepie ignores the above and creates default sanitizer anyway,
356 // so let's override it...
357 $rss->sanitize
= new SanitizeDummy();
358 $rss->set_output_encoding('UTF-8');
359 $rss->set_raw_data($feed_data);
360 $rss->enable_cache(false);
367 $feed = db_escape_string($link, $feed);
369 if (!$rss->error()) {
371 // cache data for later
372 if (!$auth_pass && !$auth_login && is_writable(CACHE_DIR
. "/simplepie")) {
373 $rss_data = serialize($rss);
374 $new_rss_hash = sha1($rss_data);
376 if ($new_rss_hash != $rss_hash) {
377 if ($debug_enabled) {
378 _debug("update_rss_feed: saving $cache_filename");
380 @file_put_contents
($cache_filename, serialize($rss));
384 // We use local pluginhost here because we need to load different per-user feed plugins
385 $pluginhost->run_hooks($pluginhost::HOOK_FEED_PARSED
, "hook_feed_parsed", $rss);
387 if ($debug_enabled) {
388 _debug("update_rss_feed: processing feed data...");
391 // db_query($link, "BEGIN");
393 if (DB_TYPE
== "pgsql") {
394 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
396 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
399 $result = db_query($link, "SELECT title,site_url,owner_uid,
400 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
402 FROM ttrss_feeds WHERE id = '$feed'");
404 $registered_title = db_fetch_result($result, 0, "title");
405 $orig_site_url = db_fetch_result($result, 0, "site_url");
406 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
407 "favicon_needs_check"));
409 $owner_uid = db_fetch_result($result, 0, "owner_uid");
411 $site_url = db_escape_string($link, mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
413 if ($favicon_needs_check ||
$force_refetch) {
414 if ($debug_enabled) {
415 _debug("update_rss_feed: checking favicon...");
418 check_feed_favicon($site_url, $feed, $link);
419 $favicon_file = ICONS_DIR
. "/$feed.ico";
421 if (file_exists($favicon_file)) {
422 require_once "colors.php";
424 $favicon_color = db_escape_string($link,
425 calculate_avg_color($favicon_file));
427 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
430 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
432 WHERE id = '$feed'");
435 if (!$registered_title ||
$registered_title == "[Unknown]") {
437 $feed_title = db_escape_string($link, $rss->get_title());
439 if ($debug_enabled) {
440 _debug("update_rss_feed: registering title: $feed_title");
443 db_query($link, "UPDATE ttrss_feeds SET
444 title = '$feed_title' WHERE id = '$feed'");
447 if ($site_url && $orig_site_url != $site_url) {
448 db_query($link, "UPDATE ttrss_feeds SET
449 site_url = '$site_url' WHERE id = '$feed'");
452 if ($debug_enabled) {
453 _debug("update_rss_feed: loading filters & labels...");
456 $filters = load_filters($link, $feed, $owner_uid);
457 $labels = get_all_labels($link, $owner_uid);
459 if ($debug_enabled) {
461 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
464 $items = $rss->get_items();
466 if (!is_array($items)) {
467 if ($debug_enabled) {
468 _debug("update_rss_feed: no articles found.");
471 db_query($link, "UPDATE ttrss_feeds
472 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
474 return; // no articles
477 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
479 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
481 $feed_hub_url = false;
483 $links = $rss->get_links('hub');
485 if ($links && is_array($links)) {
486 foreach ($links as $l) {
492 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
494 if ($feed_hub_url && function_exists('curl_init') &&
495 !ini_get("open_basedir")) {
497 require_once 'lib/pubsubhubbub/subscriber.php';
499 $callback_url = get_self_url_prefix() .
500 "/public.php?op=pubsub&id=$feed";
502 $s = new Subscriber($feed_hub_url, $callback_url);
504 $rc = $s->subscribe($fetch_url);
507 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
509 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
510 WHERE id = '$feed'");
514 if ($debug_enabled) {
515 _debug("update_rss_feed: processing articles...");
518 foreach ($items as $item) {
519 if ($_REQUEST['xdebug'] == 3) {
523 $entry_guid = $item->get_id();
524 if (!$entry_guid) $entry_guid = $item->get_link();
525 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
527 if (!$entry_guid) continue;
529 $entry_guid = "$owner_uid,$entry_guid";
531 $entry_guid_hashed = db_escape_string($link, 'SHA1:' . sha1($entry_guid));
533 if ($debug_enabled) {
534 _debug("update_rss_feed: guid $entry_guid / $entry_guid_hashed");
537 $entry_timestamp = "";
539 $entry_timestamp = strtotime($item->get_date());
541 if ($entry_timestamp == -1 ||
!$entry_timestamp ||
$entry_timestamp > time()) {
542 $entry_timestamp = time();
543 $no_orig_date = 'true';
545 $no_orig_date = 'false';
548 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
550 if ($debug_enabled) {
551 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
554 $entry_title = html_entity_decode($item->get_title());
556 $entry_link = rewrite_relative_url($site_url, $item->get_link());
558 if ($debug_enabled) {
559 _debug("update_rss_feed: title $entry_title");
560 _debug("update_rss_feed: link $entry_link");
563 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
565 $entry_content = $item->get_content();
566 if (!$entry_content) $entry_content = $item->get_description();
568 if ($_REQUEST["xdebug"] == 2) {
569 print "update_rss_feed: content: ";
570 print $entry_content;
574 $entry_comments = $item->data
["comments"];
576 if ($item->get_author()) {
577 $entry_author_item = $item->get_author();
578 $entry_author = $entry_author_item->get_name();
579 if (!$entry_author) $entry_author = $entry_author_item->get_email();
581 $entry_author = db_escape_string($link, $entry_author);
584 $entry_guid = db_escape_string($link, mb_substr($entry_guid, 0, 245));
586 $entry_comments = db_escape_string($link, mb_substr($entry_comments, 0, 245));
587 $entry_author = db_escape_string($link, mb_substr($entry_author, 0, 245));
589 $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
591 if (is_array($num_comments) && is_array($num_comments[0])) {
592 $num_comments = (int) $num_comments[0]["data"];
597 if ($debug_enabled) {
598 _debug("update_rss_feed: num_comments: $num_comments");
599 _debug("update_rss_feed: looking for tags [1]...");
602 // parse <category> entries into tags
604 $additional_tags = array();
606 $additional_tags_src = $item->get_categories();
608 if (is_array($additional_tags_src)) {
609 foreach ($additional_tags_src as $tobj) {
610 array_push($additional_tags, $tobj->get_term());
614 if ($debug_enabled) {
615 _debug("update_rss_feed: category tags:");
616 print_r($additional_tags);
619 if ($debug_enabled) {
620 _debug("update_rss_feed: looking for tags [2]...");
623 $entry_tags = array_unique($additional_tags);
625 for ($i = 0; $i < count($entry_tags); $i++
)
626 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
628 if ($debug_enabled) {
629 //_debug("update_rss_feed: unfiltered tags found:");
630 //print_r($entry_tags);
633 if ($debug_enabled) {
634 _debug("update_rss_feed: done collecting data.");
637 // TODO: less memory-hungry implementation
639 if ($debug_enabled) {
640 _debug("update_rss_feed: applying plugin filters..");
643 // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
644 $result = db_query($link, "SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries
645 WHERE ref_id = id AND (guid = '".db_escape_string($link, $entry_guid)."' OR guid = '$entry_guid_hashed') AND owner_uid = $owner_uid");
647 if (db_num_rows($result) != 0) {
648 $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
649 $stored_article = array("title" => db_fetch_result($result, 0, "title"),
650 "content" => db_fetch_result($result, 0, "content"),
651 "link" => db_fetch_result($result, 0, "link"),
652 "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")),
653 "author" => db_fetch_result($result, 0, "author"));
655 $entry_plugin_data = "";
656 $stored_article = array();
659 $article = array("owner_uid" => $owner_uid, // read only
660 "guid" => $entry_guid, // read only
661 "title" => $entry_title,
662 "content" => $entry_content,
663 "link" => $entry_link,
664 "tags" => $entry_tags,
665 "plugin_data" => $entry_plugin_data,
666 "author" => $entry_author,
667 "stored" => $stored_article);
669 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER
) as $plugin) {
670 $article = $plugin->hook_article_filter($article);
673 $entry_tags = $article["tags"];
674 $entry_guid = db_escape_string($link, $entry_guid);
675 $entry_title = db_escape_string($link, $article["title"]);
676 $entry_author = db_escape_string($link, $article["author"]);
677 $entry_link = db_escape_string($link, $article["link"]);
678 $entry_plugin_data = db_escape_string($link, $article["plugin_data"]);
679 $entry_content = $article["content"]; // escaped below
682 if ($debug_enabled) {
683 _debug("update_rss_feed: plugin data: $entry_plugin_data");
686 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
687 cache_images($entry_content, $site_url, $debug_enabled);
689 $entry_content = db_escape_string($link, $entry_content, false);
691 $content_hash = "SHA1:" . sha1($entry_content);
693 db_query($link, "BEGIN");
695 $result = db_query($link, "SELECT id FROM ttrss_entries
696 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
698 if (db_num_rows($result) == 0) {
700 if ($debug_enabled) {
701 _debug("update_rss_feed: base guid [$entry_guid] not found");
704 // base post entry does not exist, create it
706 $result = db_query($link,
707 "INSERT INTO ttrss_entries
724 '$entry_guid_hashed',
726 '$entry_timestamp_fmt',
732 '$date_feed_processed',
735 '$entry_plugin_data',
738 $article_labels = array();
741 // we keep encountering the entry in feeds, so we need to
742 // update date_updated column so that we don't get horrible
743 // dupes when the entry gets purged and reinserted again e.g.
744 // in the case of SLOW SLOW OMG SLOW updating feeds
746 $base_entry_id = db_fetch_result($result, 0, "id");
748 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
749 WHERE id = '$base_entry_id'");
751 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
754 // now it should exist, if not - bad luck then
756 $result = db_query($link, "SELECT
757 id,content_hash,no_orig_date,title,plugin_data,guid,
758 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
759 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
763 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
768 if (db_num_rows($result) == 1) {
770 if ($debug_enabled) {
771 _debug("update_rss_feed: base guid found, checking for user record");
774 // this will be used below in update handler
775 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
776 $orig_title = db_fetch_result($result, 0, "title");
777 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
778 $orig_date_updated = strtotime(db_fetch_result($result,
780 $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
782 $ref_id = db_fetch_result($result, 0, "id");
783 $entry_ref_id = $ref_id;
785 /* $stored_guid = db_fetch_result($result, 0, "guid");
786 if ($stored_guid != $entry_guid_hashed) {
787 if ($debug_enabled) _debug("upgrading compat guid to hashed one");
789 db_query($link, "UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
793 // check for user post link to main table
795 // do we allow duplicate posts with same GUID in different feeds?
796 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
797 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
799 $dupcheck_qpart = "";
802 /* Collect article tags here so we could filter by them: */
804 $article_filters = get_article_filters($filters, $entry_title,
805 $entry_content, $entry_link, $entry_timestamp, $entry_author,
808 if ($debug_enabled) {
809 _debug("update_rss_feed: article filters: ");
810 if (count($article_filters) != 0) {
811 print_r($article_filters);
815 if (find_article_filter($article_filters, "filter")) {
816 db_query($link, "COMMIT"); // close transaction in progress
820 $score = calculate_article_score($article_filters);
822 if ($debug_enabled) {
823 _debug("update_rss_feed: initial score: $score");
826 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
827 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
830 // if ($_REQUEST["xdebug"]) print "$query\n";
832 $result = db_query($link, $query);
834 // okay it doesn't exist - create user entry
835 if (db_num_rows($result) == 0) {
837 if ($debug_enabled) {
838 _debug("update_rss_feed: user record not found, creating...");
841 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
843 $last_read_qpart = 'NULL';
846 $last_read_qpart = 'NOW()';
849 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
855 if (find_article_filter($article_filters, 'publish')) {
858 $published = 'false';
863 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
865 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
866 ttrss_entries,ttrss_user_entries
867 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
868 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD
."
869 AND owner_uid = $owner_uid");
871 $ngram_similar = db_fetch_result($result, 0, "similar");
873 if ($debug_enabled) {
874 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
877 if ($ngram_similar > 0) {
882 $last_marked = ($marked == 'true') ?
'NOW()' : 'NULL';
883 $last_published = ($published == 'true') ?
'NOW()' : 'NULL';
885 $result = db_query($link,
886 "INSERT INTO ttrss_user_entries
887 (ref_id, owner_uid, feed_id, unread, last_read, marked,
888 published, score, tag_cache, label_cache, uuid,
889 last_marked, last_published)
890 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
891 $last_read_qpart, $marked, $published, '$score', '', '',
892 '', $last_marked, $last_published)");
894 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
895 $rss_link = get_self_url_prefix() .
896 "/public.php?op=rss&id=-2&key=" .
897 get_feed_access_key($link, -2, false, $owner_uid);
899 $p = new Publisher(PUBSUBHUBBUB_HUB
);
901 $pubsub_result = $p->publish_update($rss_link);
904 $result = db_query($link,
905 "SELECT int_id FROM ttrss_user_entries WHERE
906 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
907 feed_id = '$feed' LIMIT 1");
909 if (db_num_rows($result) == 1) {
910 $entry_int_id = db_fetch_result($result, 0, "int_id");
913 if ($debug_enabled) {
914 _debug("update_rss_feed: user record FOUND");
917 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
918 $entry_int_id = db_fetch_result($result, 0, "int_id");
921 if ($debug_enabled) {
922 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
925 $post_needs_update = false;
926 $update_insignificant = false;
928 if ($orig_num_comments != $num_comments) {
929 $post_needs_update = true;
930 $update_insignificant = true;
933 if ($entry_plugin_data != $orig_plugin_data) {
934 $post_needs_update = true;
935 $update_insignificant = true;
938 if ($content_hash != $orig_content_hash) {
939 $post_needs_update = true;
940 $update_insignificant = false;
943 if (db_escape_string($link, $orig_title) != $entry_title) {
944 $post_needs_update = true;
945 $update_insignificant = false;
948 // if post needs update, update it and mark all user entries
949 // linking to this post as updated
950 if ($post_needs_update) {
952 if (defined('DAEMON_EXTENDED_DEBUG')) {
953 _debug("update_rss_feed: post $entry_guid_hashed needs update...");
956 // print "<!-- post $orig_title needs update : $post_needs_update -->";
958 db_query($link, "UPDATE ttrss_entries
959 SET title = '$entry_title', content = '$entry_content',
960 content_hash = '$content_hash',
961 updated = '$entry_timestamp_fmt',
962 num_comments = '$num_comments',
963 plugin_data = '$entry_plugin_data'
964 WHERE id = '$ref_id'");
966 if (!$update_insignificant) {
967 if ($mark_unread_on_update) {
968 db_query($link, "UPDATE ttrss_user_entries
969 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
975 db_query($link, "COMMIT");
977 if ($debug_enabled) {
978 _debug("update_rss_feed: assigning labels...");
981 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
982 $owner_uid, $article_labels);
984 if ($debug_enabled) {
985 _debug("update_rss_feed: looking for enclosures...");
990 $enclosures = array();
992 $encs = $item->get_enclosures();
994 if (is_array($encs)) {
995 foreach ($encs as $e) {
997 $e->link
, $e->type
, $e->length
);
998 array_push($enclosures, $e_item);
1002 if ($debug_enabled) {
1003 _debug("update_rss_feed: article enclosures:");
1004 print_r($enclosures);
1007 db_query($link, "BEGIN");
1009 foreach ($enclosures as $enc) {
1010 $enc_url = db_escape_string($link, $enc[0]);
1011 $enc_type = db_escape_string($link, $enc[1]);
1012 $enc_dur = db_escape_string($link, $enc[2]);
1014 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1015 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1017 if (db_num_rows($result) == 0) {
1018 db_query($link, "INSERT INTO ttrss_enclosures
1019 (content_url, content_type, title, duration, post_id) VALUES
1020 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1024 db_query($link, "COMMIT");
1026 // check for manual tags (we have to do it here since they're loaded from filters)
1028 foreach ($article_filters as $f) {
1029 if ($f["type"] == "tag") {
1031 $manual_tags = trim_array(explode(",", $f["param"]));
1033 foreach ($manual_tags as $tag) {
1034 if (tag_is_valid($tag)) {
1035 array_push($entry_tags, $tag);
1043 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1044 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1046 $filtered_tags = array();
1047 $tags_to_cache = array();
1049 if ($entry_tags && is_array($entry_tags)) {
1050 foreach ($entry_tags as $tag) {
1051 if (array_search($tag, $boring_tags) === false) {
1052 array_push($filtered_tags, $tag);
1057 $filtered_tags = array_unique($filtered_tags);
1059 if ($debug_enabled) {
1060 _debug("update_rss_feed: filtered article tags:");
1061 print_r($filtered_tags);
1064 // Save article tags in the database
1066 if (count($filtered_tags) > 0) {
1068 db_query($link, "BEGIN");
1070 foreach ($filtered_tags as $tag) {
1072 $tag = sanitize_tag($tag);
1073 $tag = db_escape_string($link, $tag);
1075 if (!tag_is_valid($tag)) continue;
1077 $result = db_query($link, "SELECT id FROM ttrss_tags
1078 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1079 owner_uid = '$owner_uid' LIMIT 1");
1081 if ($result && db_num_rows($result) == 0) {
1083 db_query($link, "INSERT INTO ttrss_tags
1084 (owner_uid,tag_name,post_int_id)
1085 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1088 array_push($tags_to_cache, $tag);
1091 /* update the cache */
1093 $tags_to_cache = array_unique($tags_to_cache);
1095 $tags_str = db_escape_string($link, join(",", $tags_to_cache));
1097 db_query($link, "UPDATE ttrss_user_entries
1098 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1099 AND owner_uid = $owner_uid");
1101 db_query($link, "COMMIT");
1104 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1105 if ($debug_enabled) {
1106 _debug("update_rss_feed: auto-assigning labels...");
1109 foreach ($labels as $label) {
1110 $caption = preg_quote($label["caption"]);
1112 if ($caption && preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
1113 if (!labels_contains_caption($article_labels, $caption)) {
1114 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1120 if ($debug_enabled) {
1121 _debug("update_rss_feed: article processed");
1125 if (!$last_updated) {
1126 if ($debug_enabled) {
1127 _debug("update_rss_feed: new feed, catching it up...");
1129 catchup_feed($link, $feed, false, $owner_uid);
1132 if ($debug_enabled) {
1133 _debug("purging feed...");
1136 purge_feed($link, $feed, 0, $debug_enabled);
1138 db_query($link, "UPDATE ttrss_feeds
1139 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1141 // db_query($link, "COMMIT");
1145 $error_msg = db_escape_string($link, mb_substr($rss->error(), 0, 245));
1147 if ($debug_enabled) {
1148 _debug("update_rss_feed: error fetching feed: $error_msg");
1152 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1153 last_updated = NOW() WHERE id = '$feed'");
1158 if ($debug_enabled) {
1159 _debug("update_rss_feed: done");
1164 function cache_images($html, $site_url, $debug) {
1165 $cache_dir = CACHE_DIR
. "/images";
1167 libxml_use_internal_errors(true);
1169 $charset_hack = '<head>
1170 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1173 $doc = new DOMDocument();
1174 $doc->loadHTML($charset_hack . $html);
1175 $xpath = new DOMXPath($doc);
1177 $entries = $xpath->query('(//img[@src])');
1179 foreach ($entries as $entry) {
1180 if ($entry->hasAttribute('src')) {
1181 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1183 $local_filename = CACHE_DIR
. "/images/" . sha1($src) . ".png";
1185 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1187 if (!file_exists($local_filename)) {
1188 $file_content = fetch_file_contents($src);
1190 if ($file_content && strlen($file_content) > 1024) {
1191 file_put_contents($local_filename, $file_content);
1195 if (file_exists($local_filename)) {
1196 $entry->setAttribute('src', SELF_URL_PATH
. '/image.php?url=' .
1197 base64_encode($src));
1202 $node = $doc->getElementsByTagName('body')->item(0);
1204 return $doc->saveXML($node);
1207 function expire_error_log($link, $debug) {
1208 if ($debug) _debug("Removing old error log entries...");
1210 if (DB_TYPE
== "pgsql") {
1211 db_query($link, "DELETE FROM ttrss_error_log
1212 WHERE created_at < NOW() - INTERVAL '7 days'");
1214 db_query($link, "DELETE FROM ttrss_error_log
1215 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1220 function expire_lock_files($debug) {
1221 if ($debug) _debug("Removing old lock files...");
1225 if (is_writable(LOCK_DIRECTORY
)) {
1226 $files = glob(LOCK_DIRECTORY
. "/*.lock");
1229 foreach ($files as $file) {
1230 if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
1238 if ($debug) _debug("Removed $num_deleted files.");
1241 function expire_cached_files($debug) {
1242 foreach (array("simplepie", "images", "export", "upload") as $dir) {
1243 $cache_dir = CACHE_DIR
. "/$dir";
1245 if ($debug) _debug("Expiring $cache_dir");
1249 if (is_writable($cache_dir)) {
1250 $files = glob("$cache_dir/*");
1253 foreach ($files as $file) {
1254 if (time() - filemtime($file) > 86400*7) {
1263 if ($debug) _debug("Removed $num_deleted files.");
1268 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1269 * Returns the url query as associative array
1271 * @param string query
1272 * @return array params
1274 function convertUrlQuery($query) {
1275 $queryParts = explode('&', $query);
1279 foreach ($queryParts as $param) {
1280 $item = explode('=', $param);
1281 $params[$item[0]] = $item[1];
1287 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1290 foreach ($filters as $filter) {
1291 $match_any_rule = $filter["match_any_rule"];
1292 $inverse = $filter["inverse"];
1293 $filter_match = false;
1295 foreach ($filter["rules"] as $rule) {
1297 $reg_exp = $rule["reg_exp"];
1298 $rule_inverse = $rule["inverse"];
1303 switch ($rule["type"]) {
1305 $match = @preg_match
("/$reg_exp/i", $title);
1308 // we don't need to deal with multiline regexps
1309 $content = preg_replace("/[\r\n\t]/", "", $content);
1311 $match = @preg_match
("/$reg_exp/i", $content);
1314 // we don't need to deal with multiline regexps
1315 $content = preg_replace("/[\r\n\t]/", "", $content);
1317 $match = (@preg_match
("/$reg_exp/i", $title) || @preg_match
("/$reg_exp/i", $content));
1320 $match = @preg_match
("/$reg_exp/i", $link);
1323 $match = @preg_match
("/$reg_exp/i", $author);
1326 $tag_string = join(",", $tags);
1327 $match = @preg_match
("/$reg_exp/i", $tag_string);
1331 if ($rule_inverse) $match = !$match;
1333 if ($match_any_rule) {
1335 $filter_match = true;
1339 $filter_match = $match;
1346 if ($inverse) $filter_match = !$filter_match;
1348 if ($filter_match) {
1349 foreach ($filter["actions"] AS $action) {
1350 array_push($matches, $action);
1352 // if Stop action encountered, perform no further processing
1353 if ($action["type"] == "stop") return $matches;
1361 function find_article_filter($filters, $filter_name) {
1362 foreach ($filters as $f) {
1363 if ($f["type"] == $filter_name) {
1370 function find_article_filters($filters, $filter_name) {
1373 foreach ($filters as $f) {
1374 if ($f["type"] == $filter_name) {
1375 array_push($results, $f);
1381 function calculate_article_score($filters) {
1384 foreach ($filters as $f) {
1385 if ($f["type"] == "score") {
1386 $score +
= $f["param"];
1392 function labels_contains_caption($labels, $caption) {
1393 foreach ($labels as $label) {
1394 if ($label[1] == $caption) {
1402 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1403 foreach ($filters as $f) {
1404 if ($f["type"] == "label") {
1405 if (!labels_contains_caption($article_labels, $f["param"])) {
1406 label_add_article($link, $id, $f["param"], $owner_uid);
1412 function make_guid_from_title($title) {
1413 return preg_replace("/[ \"\',.:;]/", "-",
1414 mb_strtolower(strip_tags($title), 'utf-8'));