2 define_default('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define_default('DAEMON_FEED_LIMIT', 500);
4 define_default('DAEMON_SLEEP_INTERVAL', 120);
5 define_default('_MIN_CACHE_FILE_SIZE', 1024);
7 function calculate_article_hash($article, $pluginhost) {
10 foreach ($article as $k => $v) {
11 if ($k != "feed" && isset($v)) {
12 $x = strip_tags(is_array($v) ?
implode(",", $v) : $v);
14 //_debug("$k:" . sha1($x) . ":" . htmlspecialchars($x), true);
16 $tmp .= sha1("$k:" . sha1($x));
20 return sha1(implode(",", $pluginhost->get_plugin_names()) . $tmp);
23 function update_feedbrowser_cache() {
25 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
26 FROM ttrss_feeds WHERE feed_url NOT IN (SELECT feed_url FROM ttrss_feeds
27 WHERE private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%')
28 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
32 db_query("DELETE FROM ttrss_feedbrowser_cache");
36 while ($line = db_fetch_assoc($result)) {
37 $subscribers = db_escape_string($line["subscribers"]);
38 $feed_url = db_escape_string($line["feed_url"]);
39 $title = db_escape_string($line["title"]);
40 $site_url = db_escape_string($line["site_url"]);
42 $tmp_result = db_query("SELECT subscribers FROM
43 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
45 if (db_num_rows($tmp_result) == 0) {
47 db_query("INSERT INTO ttrss_feedbrowser_cache
48 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
49 '$site_url', '$title', '$subscribers')");
63 function update_daemon_common($limit = DAEMON_FEED_LIMIT
, $debug = true) {
64 // Process all other feeds using last_updated and interval parameters
66 $schema_version = get_schema_version();
68 if ($schema_version != SCHEMA_VERSION
) {
69 die("Schema version is wrong, please upgrade the database.\n");
72 define('PREFS_NO_CACHE', true);
74 // Test if the user has loggued in recently. If not, it does not update its feeds.
75 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
76 if (DB_TYPE
== "pgsql") {
77 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
79 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
82 $login_thresh_qpart = "";
85 // Test if the feed need a update (update interval exceeded).
86 if (DB_TYPE
== "pgsql") {
87 $update_limit_qpart = "AND ((
88 ttrss_feeds.update_interval = 0
89 AND ttrss_user_prefs.value != '-1'
90 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
92 ttrss_feeds.update_interval > 0
93 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
94 ) OR (ttrss_feeds.last_updated IS NULL
95 AND ttrss_user_prefs.value != '-1')
96 OR (last_updated = '1970-01-01 00:00:00'
97 AND ttrss_user_prefs.value != '-1'))";
99 $update_limit_qpart = "AND ((
100 ttrss_feeds.update_interval = 0
101 AND ttrss_user_prefs.value != '-1'
102 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
104 ttrss_feeds.update_interval > 0
105 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
106 ) OR (ttrss_feeds.last_updated IS NULL
107 AND ttrss_user_prefs.value != '-1')
108 OR (last_updated = '1970-01-01 00:00:00'
109 AND ttrss_user_prefs.value != '-1'))";
112 // Test if feed is currently being updated by another process.
113 if (DB_TYPE
== "pgsql") {
114 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
116 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
119 // Test if there is a limit to number of updated feeds
121 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
123 // Update the least recently updated feeds first
124 $query_order = "ORDER BY last_updated";
125 if (DB_TYPE
== "pgsql") $query_order .= " NULLS FIRST";
127 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
129 ttrss_feeds, ttrss_users, ttrss_user_prefs
131 ttrss_feeds.owner_uid = ttrss_users.id
132 AND ttrss_user_prefs.profile IS NULL
133 AND ttrss_users.id = ttrss_user_prefs.owner_uid
134 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
135 $login_thresh_qpart $update_limit_qpart
136 $updstart_thresh_qpart
137 $query_order $query_limit";
139 // We search for feed needing update.
140 $result = db_query($query);
142 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
144 // Here is a little cache magic in order to minimize risk of double feed updates.
145 $feeds_to_update = array();
146 while ($line = db_fetch_assoc($result)) {
147 array_push($feeds_to_update, db_escape_string($line['feed_url']));
150 // We update the feed last update started date before anything else.
151 // There is no lag due to feed contents downloads
152 // It prevent an other process to update the same feed.
154 if(count($feeds_to_update) > 0) {
155 $feeds_quoted = array();
157 foreach ($feeds_to_update as $feed) {
158 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
161 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
162 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
166 $bstarted = microtime(true);
168 $batch_owners = array();
170 // For each feed, we call the feed update function.
171 foreach ($feeds_to_update as $feed) {
172 if($debug) _debug("Base feed: $feed");
174 //update_rss_feed($line["id"], true);
176 // since we have the data cached, we can deal with other feeds with the same url
178 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
179 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
180 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
181 ttrss_users.id = ttrss_user_prefs.owner_uid AND
182 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
183 ttrss_user_prefs.profile IS NULL AND
184 feed_url = '".db_escape_string($feed)."'
187 ORDER BY ttrss_feeds.id $query_limit");
189 if (db_num_rows($tmp_result) > 0) {
190 while ($tline = db_fetch_assoc($tmp_result)) {
191 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
193 if (array_search($tline["owner_uid"], $batch_owners) === FALSE)
194 array_push($batch_owners, $tline["owner_uid"]);
196 $fstarted = microtime(true);
197 update_rss_feed($tline["id"], true, false);
198 _debug_suppress(false);
200 _debug(sprintf(" %.4f (sec)", microtime(true) - $fstarted));
208 _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
209 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
212 foreach ($batch_owners as $owner_uid) {
213 _debug("Running housekeeping tasks for user $owner_uid...");
215 housekeeping_user($owner_uid);
218 require_once "digest.php";
220 // Send feed digests by email if needed.
221 send_headlines_digests($debug);
227 // this is used when subscribing
228 function set_basic_feed_info($feed) {
230 $feed = db_escape_string($feed);
232 $result = db_query("SELECT feed_url,auth_pass,auth_login,auth_pass_encrypted
233 FROM ttrss_feeds WHERE id = '$feed'");
235 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
236 0, "auth_pass_encrypted"));
238 $auth_login = db_fetch_result($result, 0, "auth_login");
239 $auth_pass = db_fetch_result($result, 0, "auth_pass");
241 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
242 require_once "crypt.php";
243 $auth_pass = decrypt_string($auth_pass);
246 $fetch_url = db_fetch_result($result, 0, "feed_url");
248 $feed_data = fetch_file_contents($fetch_url, false,
249 $auth_login, $auth_pass, false,
253 global $fetch_curl_used;
255 if (!$fetch_curl_used) {
256 $tmp = @gzdecode
($feed_data);
258 if ($tmp) $feed_data = $tmp;
261 $feed_data = trim($feed_data);
263 $rss = new FeedParser($feed_data);
266 if (!$rss->error()) {
268 $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
270 $registered_title = db_fetch_result($result, 0, "title");
271 $orig_site_url = db_fetch_result($result, 0, "site_url");
273 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
274 $feed_title = db_escape_string(mb_substr($rss->get_title(), 0, 199));
276 if ($feed_title && (!$registered_title ||
$registered_title == "[Unknown]")) {
277 db_query("UPDATE ttrss_feeds SET
278 title = '$feed_title' WHERE id = '$feed'");
281 if ($site_url && $orig_site_url != $site_url) {
282 db_query("UPDATE ttrss_feeds SET
283 site_url = '$site_url' WHERE id = '$feed'");
289 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
291 function update_rss_feed($feed, $no_cache = false) {
293 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
295 _debug_suppress(!$debug_enabled);
296 _debug("start", $debug_enabled);
298 $result = db_query("SELECT title FROM ttrss_feeds
299 WHERE id = '$feed'");
301 if (db_num_rows($result) == 0) {
302 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
303 user_error("Attempt to update unknown/invalid feed $feed", E_USER_WARNING
);
307 $title = db_fetch_result($result, 0, "title");
309 // feed was batch-subscribed or something, we need to get basic info
310 // this is not optimal currently as it fetches stuff separately TODO: optimize
311 if ($title == "[Unknown]") {
312 _debug("setting basic feed info for $feed...");
313 set_basic_feed_info($feed);
316 $result = db_query("SELECT id,update_interval,auth_login,
317 feed_url,auth_pass,cache_images,
318 mark_unread_on_update, owner_uid,
319 pubsub_state, auth_pass_encrypted,
321 FROM ttrss_feeds WHERE id = '$feed'");
323 $owner_uid = db_fetch_result($result, 0, "owner_uid");
324 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
325 0, "mark_unread_on_update"));
326 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
327 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
328 0, "auth_pass_encrypted"));
330 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
331 WHERE id = '$feed'");
333 $auth_login = db_fetch_result($result, 0, "auth_login");
334 $auth_pass = db_fetch_result($result, 0, "auth_pass");
336 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
337 require_once "crypt.php";
338 $auth_pass = decrypt_string($auth_pass);
341 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
342 $fetch_url = db_fetch_result($result, 0, "feed_url");
343 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
344 if (!$feed_language) $feed_language = 'english';
346 $feed = db_escape_string($feed);
348 $date_feed_processed = date('Y-m-d H:i');
350 $cache_filename = CACHE_DIR
. "/simplepie/" . sha1($fetch_url) . ".xml";
352 $pluginhost = new PluginHost();
353 $pluginhost->set_debug($debug_enabled);
354 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
356 $pluginhost->load(PLUGINS
, PluginHost
::KIND_ALL
);
357 $pluginhost->load($user_plugins, PluginHost
::KIND_USER
, $owner_uid);
358 $pluginhost->load_data();
362 $force_refetch = isset($_REQUEST["force_refetch"]);
365 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FETCH_FEED
) as $plugin) {
366 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, 0, $auth_login, $auth_pass);
371 file_exists($cache_filename) &&
372 is_readable($cache_filename) &&
373 !$auth_login && !$auth_pass &&
374 filemtime($cache_filename) > time() - 30) {
376 _debug("using local cache [$cache_filename].", $debug_enabled);
378 @$feed_data = file_get_contents($cache_filename);
381 $rss_hash = sha1($feed_data);
385 _debug("local cache will not be used for this feed", $debug_enabled);
388 // fetch feed from source
390 _debug("fetching [$fetch_url]...", $debug_enabled);
392 if (ini_get("open_basedir") && function_exists("curl_init")) {
393 _debug("not using CURL due to open_basedir restrictions");
396 $feed_data = fetch_file_contents($fetch_url, false,
397 $auth_login, $auth_pass, false,
398 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT
: FEED_FETCH_TIMEOUT
,
401 global $fetch_curl_used;
403 if (!$fetch_curl_used) {
404 $tmp = @gzdecode
($feed_data);
406 if ($tmp) $feed_data = $tmp;
409 $feed_data = trim($feed_data);
411 _debug("fetch done.", $debug_enabled);
413 // cache vanilla feed data for re-use
414 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR
. "/simplepie")) {
415 $new_rss_hash = sha1($feed_data);
417 if ($new_rss_hash != $rss_hash) {
418 _debug("saving $cache_filename", $debug_enabled);
419 @file_put_contents
($cache_filename, $feed_data);
425 global $fetch_last_error;
426 global $fetch_last_error_code;
428 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
433 if ($fetch_last_error_code != 304) {
434 $error_escaped = db_escape_string($fetch_last_error);
436 _debug("source claims data not modified, nothing to do.", $debug_enabled);
440 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
441 last_updated = NOW() WHERE id = '$feed'");
446 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FEED_FETCHED
) as $plugin) {
447 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
450 $rss = new FeedParser($feed_data);
453 $feed = db_escape_string($feed);
455 if (!$rss->error()) {
457 // We use local pluginhost here because we need to load different per-user feed plugins
458 $pluginhost->run_hooks(PluginHost
::HOOK_FEED_PARSED
, "hook_feed_parsed", $rss);
460 _debug("language: $feed_language", $debug_enabled);
461 _debug("processing feed data...", $debug_enabled);
463 // db_query("BEGIN");
465 if (DB_TYPE
== "pgsql") {
466 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
468 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
471 $result = db_query("SELECT owner_uid,favicon_avg_color,
472 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
474 FROM ttrss_feeds WHERE id = '$feed'");
476 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
477 "favicon_needs_check"));
478 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
480 $owner_uid = db_fetch_result($result, 0, "owner_uid");
482 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
484 _debug("site_url: $site_url", $debug_enabled);
485 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
487 if ($favicon_needs_check ||
$force_refetch) {
489 /* terrible hack: if we crash on floicon shit here, we won't check
490 * the icon avgcolor again (unless the icon got updated) */
492 $favicon_file = ICONS_DIR
. "/$feed.ico";
493 $favicon_modified = @filemtime
($favicon_file);
495 _debug("checking favicon...", $debug_enabled);
497 check_feed_favicon($site_url, $feed);
498 $favicon_modified_new = @filemtime
($favicon_file);
500 if ($favicon_modified_new > $favicon_modified)
501 $favicon_avg_color = '';
503 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
504 require_once "colors.php";
506 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
509 $favicon_color = db_escape_string(
510 calculate_avg_color($favicon_file));
512 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
513 } else if ($favicon_avg_color == 'fail') {
514 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
517 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
519 WHERE id = '$feed'");
522 _debug("loading filters & labels...", $debug_enabled);
524 $filters = load_filters($feed, $owner_uid);
526 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
528 $items = $rss->get_items();
530 if (!is_array($items)) {
531 _debug("no articles found.", $debug_enabled);
533 db_query("UPDATE ttrss_feeds
534 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
536 return; // no articles
539 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
541 _debug("checking for PUSH hub...", $debug_enabled);
543 $feed_hub_url = false;
545 $links = $rss->get_links('hub');
547 if ($links && is_array($links)) {
548 foreach ($links as $l) {
554 _debug("feed hub url: $feed_hub_url", $debug_enabled);
556 $feed_self_url = $fetch_url;
558 $links = $rss->get_links('self');
560 if ($links && is_array($links)) {
561 foreach ($links as $l) {
567 _debug("feed self url = $feed_self_url");
569 if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
570 !ini_get("open_basedir")) {
572 require_once 'lib/pubsubhubbub/Subscriber.php';
574 $callback_url = get_self_url_prefix() .
575 "/public.php?op=pubsub&id=$feed";
577 $s = new Pubsubhubbub\Subscriber\
Subscriber($feed_hub_url, $callback_url);
579 $rc = $s->subscribe($feed_self_url);
581 _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
583 db_query("UPDATE ttrss_feeds SET pubsub_state = 1
584 WHERE id = '$feed'");
588 _debug("processing articles...", $debug_enabled);
592 foreach ($items as $item) {
593 if ($_REQUEST['xdebug'] == 3) {
597 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
598 _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
602 $entry_guid = $item->get_id();
603 if (!$entry_guid) $entry_guid = $item->get_link();
604 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
605 if (!$entry_guid) continue;
607 $entry_guid = "$owner_uid,$entry_guid";
609 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
611 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
613 $entry_timestamp = "";
615 $entry_timestamp = $item->get_date();
617 _debug("orig date: " . $item->get_date(), $debug_enabled);
619 if ($entry_timestamp == -1 ||
!$entry_timestamp ||
$entry_timestamp > time()) {
620 $entry_timestamp = time();
623 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
625 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
627 // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
628 // $entry_title = decode_numeric_entities($entry_title);
629 $entry_title = $item->get_title();
631 $entry_link = rewrite_relative_url($site_url, $item->get_link());
633 _debug("title $entry_title", $debug_enabled);
634 _debug("link $entry_link", $debug_enabled);
636 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
638 $entry_content = $item->get_content();
639 if (!$entry_content) $entry_content = $item->get_description();
641 if ($_REQUEST["xdebug"] == 2) {
643 print htmlspecialchars($entry_content);
647 $entry_comments = db_escape_string(mb_substr($item->get_comments_url(), 0, 245));
648 $num_comments = (int) $item->get_comments_count();
650 $entry_author = $item->get_author(); // escaped later
651 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
653 _debug("author $entry_author", $debug_enabled);
654 _debug("num_comments: $num_comments", $debug_enabled);
655 _debug("looking for tags...", $debug_enabled);
657 // parse <category> entries into tags
659 $additional_tags = array();
661 $additional_tags_src = $item->get_categories();
663 if (is_array($additional_tags_src)) {
664 foreach ($additional_tags_src as $tobj) {
665 array_push($additional_tags, $tobj);
669 $entry_tags = array_unique($additional_tags);
671 for ($i = 0; $i < count($entry_tags); $i++
)
672 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
674 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
676 _debug("done collecting data.", $debug_enabled);
678 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
679 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
681 if (db_num_rows($result) != 0) {
682 $base_entry_id = db_fetch_result($result, 0, "id");
683 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
684 $article_labels = get_article_labels($base_entry_id, $owner_uid);
685 $entry_language = db_fetch_result($result, 0, "lang");
687 $existing_tags = get_article_tags($base_entry_id, $owner_uid);
688 $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
691 $base_entry_id = false;
692 $entry_stored_hash = "";
693 $article_labels = array();
694 $entry_language = "";
697 $article = array("owner_uid" => $owner_uid, // read only
698 "guid" => $entry_guid, // read only
699 "guid_hashed" => $entry_guid_hashed, // read only
700 "title" => $entry_title,
701 "content" => $entry_content,
702 "link" => $entry_link,
703 "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
704 "tags" => $entry_tags,
705 "author" => $entry_author,
706 "force_catchup" => false, // ugly hack for the time being
707 "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
708 "language" => $entry_language,
709 "feed" => array("id" => $feed,
710 "fetch_url" => $fetch_url,
711 "site_url" => $site_url,
712 "cache_images" => $cache_images)
715 $entry_plugin_data = "";
716 $entry_current_hash = calculate_article_hash($article, $pluginhost);
718 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
720 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
721 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
723 // we keep encountering the entry in feeds, so we need to
724 // update date_updated column so that we don't get horrible
725 // dupes when the entry gets purged and reinserted again e.g.
726 // in the case of SLOW SLOW OMG SLOW updating feeds
728 $base_entry_id = db_fetch_result($result, 0, "id");
730 db_query("UPDATE ttrss_entries SET date_updated = NOW()
731 WHERE id = '$base_entry_id'");
736 _debug("hash differs, applying plugin filters:", $debug_enabled);
738 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_ARTICLE_FILTER
) as $plugin) {
739 _debug("... " . get_class($plugin), $debug_enabled);
741 $start = microtime(true);
742 $article = $plugin->hook_article_filter($article);
744 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
746 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
749 if ($_REQUEST["xdebug"] == 2) {
750 print "processed content: ";
751 print htmlspecialchars($article["content"]);
755 $entry_plugin_data = db_escape_string($entry_plugin_data);
757 _debug("plugin data: $entry_plugin_data", $debug_enabled);
759 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
760 if (DB_TYPE
== "mysql") {
761 foreach ($article as $k => $v) {
763 // i guess we'll have to take the risk of 4byte unicode labels & tags here
764 if (is_string($article[$k])) {
765 $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
770 /* Collect article tags here so we could filter by them: */
772 $matched_rules = array();
774 $article_filters = get_article_filters($filters, $article["title"],
775 $article["content"], $article["link"], $article["author"],
776 $article["tags"], $matched_rules);
778 if ($debug_enabled) {
779 _debug("matched filter rules: ", $debug_enabled);
781 if (count($matched_rules) != 0) {
782 print_r($matched_rules);
785 _debug("filter actions: ", $debug_enabled);
787 if (count($article_filters) != 0) {
788 print_r($article_filters);
792 $plugin_filter_names = find_article_filters($article_filters, "plugin");
793 $plugin_filter_actions = $pluginhost->get_filter_actions();
795 if (count($plugin_filter_names) > 0) {
796 _debug("applying plugin filter actions...", $debug_enabled);
798 foreach ($plugin_filter_names as $pfn) {
799 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
801 if (isset($plugin_filter_actions[$pfclass])) {
802 $plugin = $pluginhost->get_plugin($pfclass);
804 _debug("... $pfclass: $pfaction", $debug_enabled);
807 $start = microtime(true);
808 $article = $plugin->hook_article_filter_action($article, $pfaction);
810 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
812 _debug("??? $pfclass: plugin object not found.");
815 _debug("??? $pfclass: filter plugin not registered.");
820 $entry_tags = $article["tags"];
821 $entry_guid = db_escape_string($entry_guid);
822 $entry_title = db_escape_string($article["title"]);
823 $entry_author = db_escape_string(mb_substr($article["author"], 0, 245));
824 $entry_link = db_escape_string($article["link"]);
825 $entry_content = $article["content"]; // escaped below
826 $entry_force_catchup = $article["force_catchup"];
827 $article_labels = $article["labels"];
828 $entry_score_modifier = (int) $article["score_modifier"];
829 $entry_language = db_escape_string($article["language"]);
831 if ($debug_enabled) {
832 _debug("article labels:", $debug_enabled);
834 if (count($article_labels) != 0) {
835 print_r($article_labels);
839 _debug("force catchup: $entry_force_catchup");
841 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
842 cache_media($entry_content, $site_url, $debug_enabled);
844 $entry_content = db_escape_string($entry_content, false);
848 $result = db_query("SELECT id FROM ttrss_entries
849 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
851 if (db_num_rows($result) == 0) {
853 _debug("base guid [$entry_guid or $entry_guid_hashed] not found, creating...", $debug_enabled);
855 // base post entry does not exist, create it
858 "INSERT INTO ttrss_entries
875 '$entry_guid_hashed',
877 '$entry_timestamp_fmt',
879 '$entry_current_hash',
882 '$date_feed_processed',
885 '$entry_plugin_data',
891 // now it should exist, if not - bad luck then
893 $result = db_query("SELECT id FROM ttrss_entries
894 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
899 if (db_num_rows($result) == 1) {
901 _debug("base guid found, checking for user record", $debug_enabled);
903 $ref_id = db_fetch_result($result, 0, "id");
904 $entry_ref_id = $ref_id;
906 /* $stored_guid = db_fetch_result($result, 0, "guid");
907 if ($stored_guid != $entry_guid_hashed) {
908 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
910 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
914 if (find_article_filter($article_filters, "filter")) {
915 //db_query("COMMIT"); // close transaction in progress
919 $score = calculate_article_score($article_filters) +
$entry_score_modifier;
921 _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
923 // check for user post link to main table
925 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
926 ref_id = '$ref_id' AND owner_uid = '$owner_uid'";
928 // if ($_REQUEST["xdebug"]) print "$query\n";
930 $result = db_query($query);
932 // okay it doesn't exist - create user entry
933 if (db_num_rows($result) == 0) {
935 _debug("user record not found, creating...", $debug_enabled);
937 if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
939 $last_read_qpart = 'NULL';
942 $last_read_qpart = 'NOW()';
945 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
951 if (find_article_filter($article_filters, 'publish')) {
954 $published = 'false';
957 $last_marked = ($marked == 'true') ?
'NOW()' : 'NULL';
958 $last_published = ($published == 'true') ?
'NOW()' : 'NULL';
961 "INSERT INTO ttrss_user_entries
962 (ref_id, owner_uid, feed_id, unread, last_read, marked,
963 published, score, tag_cache, label_cache, uuid,
964 last_marked, last_published)
965 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
966 $last_read_qpart, $marked, $published, '$score', '', '',
967 '', $last_marked, $last_published)");
969 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
970 $rss_link = get_self_url_prefix() .
971 "/public.php?op=rss&id=-2&key=" .
972 get_feed_access_key(-2, false, $owner_uid);
974 $p = new pubsubhubbub\publisher\
Publisher(PUBSUBHUBBUB_HUB
);
976 /* $pubsub_result = */ $p->publish_update($rss_link);
980 "SELECT int_id FROM ttrss_user_entries WHERE
981 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
982 feed_id = '$feed' LIMIT 1");
984 if (db_num_rows($result) == 1) {
985 $entry_int_id = db_fetch_result($result, 0, "int_id");
988 _debug("user record FOUND", $debug_enabled);
990 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
991 $entry_int_id = db_fetch_result($result, 0, "int_id");
994 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
996 if (DB_TYPE
== "pgsql") {
997 $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
1000 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
1003 $tsvector_qpart = "";
1006 db_query("UPDATE ttrss_entries
1007 SET title = '$entry_title',
1008 content = '$entry_content',
1009 content_hash = '$entry_current_hash',
1010 updated = '$entry_timestamp_fmt',
1012 num_comments = '$num_comments',
1013 plugin_data = '$entry_plugin_data',
1014 author = '$entry_author',
1015 lang = '$entry_language'
1016 WHERE id = '$ref_id'");
1019 db_query("UPDATE ttrss_user_entries
1020 SET score = '$score' WHERE ref_id = '$ref_id'");
1022 if ($mark_unread_on_update) {
1023 _debug("article updated, marking unread as requested.", $debug_enabled);
1025 db_query("UPDATE ttrss_user_entries
1026 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1030 //db_query("COMMIT");
1032 _debug("assigning labels [other]...", $debug_enabled);
1034 foreach ($article_labels as $label) {
1035 label_add_article($entry_ref_id, $label[1], $owner_uid);
1038 _debug("assigning labels [filters]...", $debug_enabled);
1040 assign_article_to_label_filters($entry_ref_id, $article_filters,
1041 $owner_uid, $article_labels);
1043 _debug("looking for enclosures...", $debug_enabled);
1047 $enclosures = array();
1049 $encs = $item->get_enclosures();
1051 if (is_array($encs)) {
1052 foreach ($encs as $e) {
1054 rewrite_relative_url($site_url, $e->link
),
1055 $e->type
, $e->length
, $e->title
, $e->width
, $e->height
);
1056 array_push($enclosures, $e_item);
1060 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
1061 cache_enclosures($enclosures, $site_url, $debug_enabled);
1063 if ($debug_enabled) {
1064 _debug("article enclosures:", $debug_enabled);
1065 print_r($enclosures);
1068 //db_query("BEGIN");
1071 // db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1073 foreach ($enclosures as $enc) {
1074 $enc_url = db_escape_string($enc[0]);
1075 $enc_type = db_escape_string($enc[1]);
1076 $enc_dur = db_escape_string($enc[2]);
1077 $enc_title = db_escape_string($enc[3]);
1078 $enc_width = intval($enc[4]);
1079 $enc_height = intval($enc[5]);
1081 $result = db_query("SELECT id FROM ttrss_enclosures
1082 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1084 if (db_num_rows($result) == 0) {
1085 db_query("INSERT INTO ttrss_enclosures
1086 (content_url, content_type, title, duration, post_id, width, height) VALUES
1087 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
1091 //db_query("COMMIT");
1093 // check for manual tags (we have to do it here since they're loaded from filters)
1095 foreach ($article_filters as $f) {
1096 if ($f["type"] == "tag") {
1098 $manual_tags = trim_array(explode(",", $f["param"]));
1100 foreach ($manual_tags as $tag) {
1101 if (tag_is_valid($tag)) {
1102 array_push($entry_tags, $tag);
1110 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
1111 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1113 $filtered_tags = array();
1114 $tags_to_cache = array();
1116 if ($entry_tags && is_array($entry_tags)) {
1117 foreach ($entry_tags as $tag) {
1118 if (array_search($tag, $boring_tags) === false) {
1119 array_push($filtered_tags, $tag);
1124 $filtered_tags = array_unique($filtered_tags);
1126 if ($debug_enabled) {
1127 _debug("filtered article tags:", $debug_enabled);
1128 print_r($filtered_tags);
1131 // Save article tags in the database
1133 if (count($filtered_tags) > 0) {
1135 //db_query("BEGIN");
1137 foreach ($filtered_tags as $tag) {
1139 $tag = sanitize_tag($tag);
1140 $tag = db_escape_string($tag);
1142 if (!tag_is_valid($tag)) continue;
1144 $result = db_query("SELECT id FROM ttrss_tags
1145 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1146 owner_uid = '$owner_uid' LIMIT 1");
1148 if ($result && db_num_rows($result) == 0) {
1150 db_query("INSERT INTO ttrss_tags
1151 (owner_uid,tag_name,post_int_id)
1152 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1155 array_push($tags_to_cache, $tag);
1158 /* update the cache */
1160 $tags_to_cache = array_unique($tags_to_cache);
1162 $tags_str = db_escape_string(join(",", $tags_to_cache));
1164 db_query("UPDATE ttrss_user_entries
1165 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1166 AND owner_uid = $owner_uid");
1168 //db_query("COMMIT");
1171 _debug("article processed", $debug_enabled);
1174 _debug("purging feed...", $debug_enabled);
1176 purge_feed($feed, 0, $debug_enabled);
1178 db_query("UPDATE ttrss_feeds
1179 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1181 // db_query("COMMIT");
1185 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
1187 _debug("fetch error: $error_msg", $debug_enabled);
1189 if (count($rss->errors()) > 1) {
1190 foreach ($rss->errors() as $error) {
1196 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1197 last_updated = NOW() WHERE id = '$feed'");
1203 _debug("done", $debug_enabled);
1208 function cache_enclosures($enclosures, $site_url, $debug) {
1209 foreach ($enclosures as $enc) {
1211 if (preg_match("/(image|audio|video)/", $enc[1])) {
1213 $src = rewrite_relative_url($site_url, $enc[0]);
1215 $local_filename = CACHE_DIR
. "/images/" . sha1($src);
1217 if ($debug) _debug("cache_enclosures: downloading: $src to $local_filename");
1219 if (!file_exists($local_filename)) {
1220 $file_content = fetch_file_contents($src);
1222 if ($file_content && strlen($file_content) > _MIN_CACHE_FILE_SIZE
) {
1223 file_put_contents($local_filename, $file_content);
1226 touch($local_filename);
1232 function cache_media($html, $site_url, $debug) {
1233 libxml_use_internal_errors(true);
1235 $charset_hack = '<head>
1236 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1239 $doc = new DOMDocument();
1240 $doc->loadHTML($charset_hack . $html);
1241 $xpath = new DOMXPath($doc);
1243 $entries = $xpath->query('(//img[@src])|(//video/source[@src])|(//audio/source[@src])');
1245 foreach ($entries as $entry) {
1246 if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
1247 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1249 $local_filename = CACHE_DIR
. "/images/" . sha1($src);
1251 if ($debug) _debug("cache_media: downloading: $src to $local_filename");
1253 if (!file_exists($local_filename)) {
1254 $file_content = fetch_file_contents($src);
1256 if ($file_content && strlen($file_content) > _MIN_CACHE_FILE_SIZE
) {
1257 file_put_contents($local_filename, $file_content);
1260 touch($local_filename);
1266 function expire_error_log($debug) {
1267 if ($debug) _debug("Removing old error log entries...");
1269 if (DB_TYPE
== "pgsql") {
1270 db_query("DELETE FROM ttrss_error_log
1271 WHERE created_at < NOW() - INTERVAL '7 days'");
1273 db_query("DELETE FROM ttrss_error_log
1274 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1279 function expire_lock_files($debug) {
1280 //if ($debug) _debug("Removing old lock files...");
1284 if (is_writable(LOCK_DIRECTORY
)) {
1285 $files = glob(LOCK_DIRECTORY
. "/*.lock");
1288 foreach ($files as $file) {
1289 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
1297 if ($debug) _debug("Removed $num_deleted old lock files.");
1300 function expire_cached_files($debug) {
1301 foreach (array("simplepie", "images", "export", "upload") as $dir) {
1302 $cache_dir = CACHE_DIR
. "/$dir";
1304 // if ($debug) _debug("Expiring $cache_dir");
1308 if (is_writable($cache_dir)) {
1309 $files = glob("$cache_dir/*");
1312 foreach ($files as $file) {
1313 if (time() - filemtime($file) > 86400*7) {
1322 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
1327 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1328 * Returns the url query as associative array
1330 * @param string query
1331 * @return array params
1333 function convertUrlQuery($query) {
1334 $queryParts = explode('&', $query);
1338 foreach ($queryParts as $param) {
1339 $item = explode('=', $param);
1340 $params[$item[0]] = $item[1];
1346 function get_article_filters($filters, $title, $content, $link, $author, $tags, &$matched_rules = false) {
1349 foreach ($filters as $filter) {
1350 $match_any_rule = $filter["match_any_rule"];
1351 $inverse = $filter["inverse"];
1352 $filter_match = false;
1354 foreach ($filter["rules"] as $rule) {
1356 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
1357 $rule_inverse = $rule["inverse"];
1362 switch ($rule["type"]) {
1364 $match = @preg_match
("/$reg_exp/iu", $title);
1367 // we don't need to deal with multiline regexps
1368 $content = preg_replace("/[\r\n\t]/", "", $content);
1370 $match = @preg_match
("/$reg_exp/iu", $content);
1373 // we don't need to deal with multiline regexps
1374 $content = preg_replace("/[\r\n\t]/", "", $content);
1376 $match = (@preg_match
("/$reg_exp/iu", $title) || @preg_match
("/$reg_exp/iu", $content));
1379 $match = @preg_match
("/$reg_exp/iu", $link);
1382 $match = @preg_match
("/$reg_exp/iu", $author);
1385 foreach ($tags as $tag) {
1386 if (@preg_match
("/$reg_exp/iu", $tag)) {
1394 if ($rule_inverse) $match = !$match;
1396 if ($match_any_rule) {
1398 $filter_match = true;
1402 $filter_match = $match;
1409 if ($inverse) $filter_match = !$filter_match;
1411 if ($filter_match) {
1412 if (is_array($matched_rules)) array_push($matched_rules, $rule);
1414 foreach ($filter["actions"] AS $action) {
1415 array_push($matches, $action);
1417 // if Stop action encountered, perform no further processing
1418 if (isset($action["type"]) && $action["type"] == "stop") return $matches;
1426 function find_article_filter($filters, $filter_name) {
1427 foreach ($filters as $f) {
1428 if ($f["type"] == $filter_name) {
1435 function find_article_filters($filters, $filter_name) {
1438 foreach ($filters as $f) {
1439 if ($f["type"] == $filter_name) {
1440 array_push($results, $f);
1446 function calculate_article_score($filters) {
1449 foreach ($filters as $f) {
1450 if ($f["type"] == "score") {
1451 $score +
= $f["param"];
1457 function labels_contains_caption($labels, $caption) {
1458 foreach ($labels as $label) {
1459 if ($label[1] == $caption) {
1467 function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
1468 foreach ($filters as $f) {
1469 if ($f["type"] == "label") {
1470 if (!labels_contains_caption($article_labels, $f["param"])) {
1471 label_add_article($id, $f["param"], $owner_uid);
1477 function make_guid_from_title($title) {
1478 return preg_replace("/[ \"\',.:;]/", "-",
1479 mb_strtolower(strip_tags($title), 'utf-8'));
1482 function cleanup_counters_cache($debug) {
1483 $result = db_query("DELETE FROM ttrss_counters_cache
1484 WHERE feed_id > 0 AND
1485 (SELECT COUNT(id) FROM ttrss_feeds WHERE
1487 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1488 $frows = db_affected_rows($result);
1490 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1491 WHERE feed_id > 0 AND
1492 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1494 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1495 $crows = db_affected_rows($result);
1497 if ($debug) _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
1500 function housekeeping_user($owner_uid) {
1501 $tmph = new PluginHost();
1503 load_user_plugins($owner_uid, $tmph);
1505 $tmph->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");
1508 function housekeeping_common($debug) {
1509 expire_cached_files($debug);
1510 expire_lock_files($debug);
1511 expire_error_log($debug);
1513 $count = update_feedbrowser_cache();
1514 _debug("Feedbrowser updated, $count feeds processed.");
1516 purge_orphans( true);
1517 cleanup_counters_cache($debug);
1519 //$rc = cleanup_tags( 14, 50000);
1520 //_debug("Cleaned $rc cached tags.");
1522 PluginHost
::getInstance()->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");