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_IMAGE_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 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
27 WHERE tf.feed_url = ttrss_feeds.feed_url
28 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
29 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
33 db_query("DELETE FROM ttrss_feedbrowser_cache");
37 while ($line = db_fetch_assoc($result)) {
38 $subscribers = db_escape_string($line["subscribers"]);
39 $feed_url = db_escape_string($line["feed_url"]);
40 $title = db_escape_string($line["title"]);
41 $site_url = db_escape_string($line["site_url"]);
43 $tmp_result = db_query("SELECT subscribers FROM
44 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
46 if (db_num_rows($tmp_result) == 0) {
48 db_query("INSERT INTO ttrss_feedbrowser_cache
49 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
50 '$site_url', '$title', '$subscribers')");
66 * Update a feed batch.
67 * Used by daemons to update n feeds by run.
68 * Only update feed needing a update, and not being processed
71 * @param mixed $link Database link
72 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
73 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
74 * @param boolean $debug Set to false to disable debug output. Default to true.
77 function update_daemon_common($limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
78 // Process all other feeds using last_updated and interval parameters
80 $schema_version = get_schema_version();
82 if ($schema_version != SCHEMA_VERSION
) {
83 die("Schema version is wrong, please upgrade the database.\n");
86 define('PREFS_NO_CACHE', true);
88 // Test if the user has loggued in recently. If not, it does not update its feeds.
89 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
90 if (DB_TYPE
== "pgsql") {
91 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
93 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
96 $login_thresh_qpart = "";
99 // Test if the feed need a update (update interval exceeded).
100 if (DB_TYPE
== "pgsql") {
101 $update_limit_qpart = "AND ((
102 ttrss_feeds.update_interval = 0
103 AND ttrss_user_prefs.value != '-1'
104 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
106 ttrss_feeds.update_interval > 0
107 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
108 ) OR (ttrss_feeds.last_updated IS NULL
109 AND ttrss_user_prefs.value != '-1')
110 OR (last_updated = '1970-01-01 00:00:00'
111 AND ttrss_user_prefs.value != '-1'))";
113 $update_limit_qpart = "AND ((
114 ttrss_feeds.update_interval = 0
115 AND ttrss_user_prefs.value != '-1'
116 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
118 ttrss_feeds.update_interval > 0
119 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
120 ) OR (ttrss_feeds.last_updated IS NULL
121 AND ttrss_user_prefs.value != '-1')
122 OR (last_updated = '1970-01-01 00:00:00'
123 AND ttrss_user_prefs.value != '-1'))";
126 // Test if feed is currently being updated by another process.
127 if (DB_TYPE
== "pgsql") {
128 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
130 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
133 // Test if there is a limit to number of updated feeds
135 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
137 // Update the least recently updated feeds first
138 $query_order = "ORDER BY last_updated";
139 if (DB_TYPE
== "pgsql") $query_order .= " NULLS FIRST";
141 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
143 ttrss_feeds, ttrss_users, ttrss_user_prefs
145 ttrss_feeds.owner_uid = ttrss_users.id
146 AND ttrss_user_prefs.profile IS NULL
147 AND ttrss_users.id = ttrss_user_prefs.owner_uid
148 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
149 $login_thresh_qpart $update_limit_qpart
150 $updstart_thresh_qpart
151 $query_order $query_limit";
153 // We search for feed needing update.
154 $result = db_query($query);
156 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
158 // Here is a little cache magic in order to minimize risk of double feed updates.
159 $feeds_to_update = array();
160 while ($line = db_fetch_assoc($result)) {
161 array_push($feeds_to_update, db_escape_string($line['feed_url']));
164 // We update the feed last update started date before anything else.
165 // There is no lag due to feed contents downloads
166 // It prevent an other process to update the same feed.
168 if(count($feeds_to_update) > 0) {
169 $feeds_quoted = array();
171 foreach ($feeds_to_update as $feed) {
172 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
175 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
176 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
180 $bstarted = microtime(true);
182 $batch_owners = array();
184 // For each feed, we call the feed update function.
185 foreach ($feeds_to_update as $feed) {
186 if($debug) _debug("Base feed: $feed");
188 //update_rss_feed($line["id"], true);
190 // since we have the data cached, we can deal with other feeds with the same url
192 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
193 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
194 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
195 ttrss_users.id = ttrss_user_prefs.owner_uid AND
196 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
197 ttrss_user_prefs.profile IS NULL AND
198 feed_url = '".db_escape_string($feed)."'
201 ORDER BY ttrss_feeds.id $query_limit");
203 if (db_num_rows($tmp_result) > 0) {
206 while ($tline = db_fetch_assoc($tmp_result)) {
207 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
209 if (array_search($tline["owner_uid"], $batch_owners) === FALSE)
210 array_push($batch_owners, $tline["owner_uid"]);
212 $fstarted = microtime(true);
213 $rss = update_rss_feed($tline["id"], true, false);
214 _debug_suppress(false);
216 _debug(sprintf(" %.4f (sec)", microtime(true) - $fstarted));
224 _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
225 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
228 foreach ($batch_owners as $owner_uid) {
229 _debug("Running housekeeping tasks for user $owner_uid...");
231 housekeeping_user($owner_uid);
234 require_once "digest.php";
236 // Send feed digests by email if needed.
237 send_headlines_digests($debug);
241 } // function update_daemon_common
243 // this is used when subscribing
244 function set_basic_feed_info($feed) {
246 $feed = db_escape_string($feed);
248 $result = db_query("SELECT feed_url,auth_pass,auth_login,auth_pass_encrypted
249 FROM ttrss_feeds WHERE id = '$feed'");
251 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
252 0, "auth_pass_encrypted"));
254 $auth_login = db_fetch_result($result, 0, "auth_login");
255 $auth_pass = db_fetch_result($result, 0, "auth_pass");
257 if ($auth_pass_encrypted) {
258 require_once "crypt.php";
259 $auth_pass = decrypt_string($auth_pass);
262 $fetch_url = db_fetch_result($result, 0, "feed_url");
264 $feed_data = fetch_file_contents($fetch_url, false,
265 $auth_login, $auth_pass, false,
266 FEED_FETCH_TIMEOUT_TIMEOUT
,
269 global $fetch_curl_used;
271 if (!$fetch_curl_used) {
272 $tmp = @gzdecode
($feed_data);
274 if ($tmp) $feed_data = $tmp;
277 $feed_data = trim($feed_data);
279 $rss = new FeedParser($feed_data);
282 if (!$rss->error()) {
284 $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
286 $registered_title = db_fetch_result($result, 0, "title");
287 $orig_site_url = db_fetch_result($result, 0, "site_url");
289 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
290 $feed_title = db_escape_string(mb_substr($rss->get_title(), 0, 199));
292 if ($feed_title && (!$registered_title ||
$registered_title == "[Unknown]")) {
293 db_query("UPDATE ttrss_feeds SET
294 title = '$feed_title' WHERE id = '$feed'");
297 if ($site_url && $orig_site_url != $site_url) {
298 db_query("UPDATE ttrss_feeds SET
299 site_url = '$site_url' WHERE id = '$feed'");
304 // ignore_daemon is not used
305 function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false) {
307 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
309 _debug_suppress(!$debug_enabled);
310 _debug("start", $debug_enabled);
312 $result = db_query("SELECT title FROM ttrss_feeds
313 WHERE id = '$feed'");
314 $title = db_fetch_result($result, 0, "title");
316 // feed was batch-subscribed or something, we need to get basic info
317 // this is not optimal currently as it fetches stuff separately TODO: optimize
318 if ($title == "[Unknown]") {
319 _debug("setting basic feed info for $feed...");
320 set_basic_feed_info($feed);
323 $result = db_query("SELECT id,update_interval,auth_login,
324 feed_url,auth_pass,cache_images,
325 mark_unread_on_update, owner_uid,
326 pubsub_state, auth_pass_encrypted,
328 FROM ttrss_feeds WHERE id = '$feed'");
330 if (db_num_rows($result) == 0) {
331 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
332 user_error("Attempt to update unknown/invalid feed $feed", E_USER_WARNING
);
336 $owner_uid = db_fetch_result($result, 0, "owner_uid");
337 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
338 0, "mark_unread_on_update"));
339 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
340 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
341 0, "auth_pass_encrypted"));
343 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
344 WHERE id = '$feed'");
346 $auth_login = db_fetch_result($result, 0, "auth_login");
347 $auth_pass = db_fetch_result($result, 0, "auth_pass");
349 if ($auth_pass_encrypted) {
350 require_once "crypt.php";
351 $auth_pass = decrypt_string($auth_pass);
354 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
355 $fetch_url = db_fetch_result($result, 0, "feed_url");
356 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
357 if (!$feed_language) $feed_language = 'english';
359 $feed = db_escape_string($feed);
361 $date_feed_processed = date('Y-m-d H:i');
363 $cache_filename = CACHE_DIR
. "/simplepie/" . sha1($fetch_url) . ".xml";
365 $pluginhost = new PluginHost();
366 $pluginhost->set_debug($debug_enabled);
367 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
369 $pluginhost->load(PLUGINS
, PluginHost
::KIND_ALL
);
370 $pluginhost->load($user_plugins, PluginHost
::KIND_USER
, $owner_uid);
371 $pluginhost->load_data();
373 if ($rss && is_object($rss) && get_class($rss) == "FeedParser") {
374 _debug("using previously initialized parser object");
378 $force_refetch = isset($_REQUEST["force_refetch"]);
381 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FETCH_FEED
) as $plugin) {
382 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, 0, $auth_login, $auth_pass);
387 file_exists($cache_filename) &&
388 is_readable($cache_filename) &&
389 !$auth_login && !$auth_pass &&
390 filemtime($cache_filename) > time() - 30) {
392 _debug("using local cache [$cache_filename].", $debug_enabled);
394 @$feed_data = file_get_contents($cache_filename);
397 $rss_hash = sha1($feed_data);
401 _debug("local cache will not be used for this feed", $debug_enabled);
404 // fetch feed from source
406 _debug("fetching [$fetch_url]...", $debug_enabled);
408 if (ini_get("open_basedir") && function_exists("curl_init")) {
409 _debug("not using CURL due to open_basedir restrictions");
412 $feed_data = fetch_file_contents($fetch_url, false,
413 $auth_login, $auth_pass, false,
414 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT
: FEED_FETCH_TIMEOUT
,
417 global $fetch_curl_used;
419 if (!$fetch_curl_used) {
420 $tmp = @gzdecode
($feed_data);
422 if ($tmp) $feed_data = $tmp;
425 $feed_data = trim($feed_data);
427 _debug("fetch done.", $debug_enabled);
429 // cache vanilla feed data for re-use
430 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR
. "/simplepie")) {
431 $new_rss_hash = sha1($feed_data);
433 if ($new_rss_hash != $rss_hash) {
434 _debug("saving $cache_filename", $debug_enabled);
435 @file_put_contents
($cache_filename, $feed_data);
441 global $fetch_last_error;
442 global $fetch_last_error_code;
444 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
449 if ($fetch_last_error_code != 304) {
450 $error_escaped = db_escape_string($fetch_last_error);
452 _debug("source claims data not modified, nothing to do.", $debug_enabled);
456 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
457 last_updated = NOW() WHERE id = '$feed'");
463 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FEED_FETCHED
) as $plugin) {
464 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
467 // set last update to now so if anything *simplepie* crashes later we won't be
468 // continuously failing on the same feed
469 //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
472 $rss = new FeedParser($feed_data);
478 $feed = db_escape_string($feed);
480 if (!$rss->error()) {
482 // We use local pluginhost here because we need to load different per-user feed plugins
483 $pluginhost->run_hooks(PluginHost
::HOOK_FEED_PARSED
, "hook_feed_parsed", $rss);
485 _debug("language: $feed_language", $debug_enabled);
486 _debug("processing feed data...", $debug_enabled);
488 // db_query("BEGIN");
490 if (DB_TYPE
== "pgsql") {
491 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
493 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
496 $result = db_query("SELECT owner_uid,favicon_avg_color,
497 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
499 FROM ttrss_feeds WHERE id = '$feed'");
501 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
502 "favicon_needs_check"));
503 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
505 $owner_uid = db_fetch_result($result, 0, "owner_uid");
507 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
509 _debug("site_url: $site_url", $debug_enabled);
510 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
512 if ($favicon_needs_check ||
$force_refetch) {
514 /* terrible hack: if we crash on floicon shit here, we won't check
515 * the icon avgcolor again (unless the icon got updated) */
517 $favicon_file = ICONS_DIR
. "/$feed.ico";
518 $favicon_modified = @filemtime
($favicon_file);
520 _debug("checking favicon...", $debug_enabled);
522 check_feed_favicon($site_url, $feed);
523 $favicon_modified_new = @filemtime
($favicon_file);
525 if ($favicon_modified_new > $favicon_modified)
526 $favicon_avg_color = '';
528 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
529 require_once "colors.php";
531 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
534 $favicon_color = db_escape_string(
535 calculate_avg_color($favicon_file));
537 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
538 } else if ($favicon_avg_color == 'fail') {
539 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
542 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
544 WHERE id = '$feed'");
547 _debug("loading filters & labels...", $debug_enabled);
549 $filters = load_filters($feed, $owner_uid);
551 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
553 $items = $rss->get_items();
555 if (!is_array($items)) {
556 _debug("no articles found.", $debug_enabled);
558 db_query("UPDATE ttrss_feeds
559 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
561 return; // no articles
564 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
566 _debug("checking for PUSH hub...", $debug_enabled);
568 $feed_hub_url = false;
570 $links = $rss->get_links('hub');
572 if ($links && is_array($links)) {
573 foreach ($links as $l) {
579 _debug("feed hub url: $feed_hub_url", $debug_enabled);
581 $feed_self_url = $fetch_url;
583 $links = $rss->get_links('self');
585 if ($links && is_array($links)) {
586 foreach ($links as $l) {
592 _debug("feed self url = $feed_self_url");
594 if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
595 !ini_get("open_basedir")) {
597 require_once 'lib/pubsubhubbub/subscriber.php';
599 $callback_url = get_self_url_prefix() .
600 "/public.php?op=pubsub&id=$feed";
602 $s = new Subscriber($feed_hub_url, $callback_url);
604 $rc = $s->subscribe($feed_self_url);
606 _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
608 db_query("UPDATE ttrss_feeds SET pubsub_state = 1
609 WHERE id = '$feed'");
613 _debug("processing articles...", $debug_enabled);
617 foreach ($items as $item) {
618 if ($_REQUEST['xdebug'] == 3) {
622 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
623 _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
627 $entry_guid = $item->get_id();
628 if (!$entry_guid) $entry_guid = $item->get_link();
629 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
630 if (!$entry_guid) continue;
632 $entry_guid = "$owner_uid,$entry_guid";
634 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
636 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
638 $entry_timestamp = "";
640 $entry_timestamp = $item->get_date();
642 _debug("orig date: " . $item->get_date(), $debug_enabled);
644 if ($entry_timestamp == -1 ||
!$entry_timestamp ||
$entry_timestamp > time()) {
645 $entry_timestamp = time();
648 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
650 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
652 // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
653 // $entry_title = decode_numeric_entities($entry_title);
654 $entry_title = $item->get_title();
656 $entry_link = rewrite_relative_url($site_url, $item->get_link());
658 _debug("title $entry_title", $debug_enabled);
659 _debug("link $entry_link", $debug_enabled);
661 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
663 $entry_content = $item->get_content();
664 if (!$entry_content) $entry_content = $item->get_description();
666 if ($_REQUEST["xdebug"] == 2) {
668 print htmlspecialchars($entry_content);
672 $entry_comments = $item->get_comments_url();
673 $entry_author = $item->get_author();
675 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
677 $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
678 $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
680 $num_comments = (int) $item->get_comments_count();
682 _debug("author $entry_author", $debug_enabled);
683 _debug("num_comments: $num_comments", $debug_enabled);
684 _debug("looking for tags...", $debug_enabled);
686 // parse <category> entries into tags
688 $additional_tags = array();
690 $additional_tags_src = $item->get_categories();
692 if (is_array($additional_tags_src)) {
693 foreach ($additional_tags_src as $tobj) {
694 array_push($additional_tags, $tobj);
698 $entry_tags = array_unique($additional_tags);
700 for ($i = 0; $i < count($entry_tags); $i++
)
701 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
703 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
705 _debug("done collecting data.", $debug_enabled);
707 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
708 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
710 if (db_num_rows($result) != 0) {
711 $base_entry_id = db_fetch_result($result, 0, "id");
712 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
713 $article_labels = get_article_labels($base_entry_id, $owner_uid);
714 $entry_language = db_fetch_result($result, 0, "lang");
716 $existing_tags = get_article_tags($base_entry_id, $owner_uid);
717 $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
720 $base_entry_id = false;
721 $entry_stored_hash = "";
722 $article_labels = array();
723 $entry_language = "";
726 $article = array("owner_uid" => $owner_uid, // read only
727 "guid" => $entry_guid, // read only
728 "guid_hashed" => $entry_guid_hashed, // read only
729 "title" => $entry_title,
730 "content" => $entry_content,
731 "link" => $entry_link,
732 "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
733 "tags" => $entry_tags,
734 "author" => $entry_author,
735 "force_catchup" => false, // ugly hack for the time being
736 "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
737 "language" => $entry_language,
738 "feed" => array("id" => $feed,
739 "fetch_url" => $fetch_url,
740 "site_url" => $site_url,
741 "cache_images" => $cache_images)
744 $entry_plugin_data = "";
745 $entry_current_hash = calculate_article_hash($article, $pluginhost);
747 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
749 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
750 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
752 // we keep encountering the entry in feeds, so we need to
753 // update date_updated column so that we don't get horrible
754 // dupes when the entry gets purged and reinserted again e.g.
755 // in the case of SLOW SLOW OMG SLOW updating feeds
757 $base_entry_id = db_fetch_result($result, 0, "id");
759 db_query("UPDATE ttrss_entries SET date_updated = NOW()
760 WHERE id = '$base_entry_id'");
765 _debug("hash differs, applying plugin filters:", $debug_enabled);
767 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_ARTICLE_FILTER
) as $plugin) {
768 _debug("... " . get_class($plugin), $debug_enabled);
770 $start = microtime(true);
771 $article = $plugin->hook_article_filter($article);
773 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
775 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
778 if ($_REQUEST["xdebug"] == 2) {
779 print "processed content: ";
780 print htmlspecialchars($article["content"]);
784 $entry_plugin_data = db_escape_string($entry_plugin_data);
786 _debug("plugin data: $entry_plugin_data", $debug_enabled);
788 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
789 if (DB_TYPE
== "mysql") {
790 foreach ($article as $k => $v) {
792 // i guess we'll have to take the risk of 4byte unicode labels & tags here
793 if (is_string($article[$k])) {
794 $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
799 /* Collect article tags here so we could filter by them: */
801 $matched_rules = array();
803 $article_filters = get_article_filters($filters, $article["title"],
804 $article["content"], $article["link"], 0, $article["author"],
805 $article["tags"], $matched_rules);
807 if ($debug_enabled) {
808 _debug("matched filter rules: ", $debug_enabled);
810 if (count($matched_rules) != 0) {
811 print_r($matched_rules);
814 _debug("filter actions: ", $debug_enabled);
816 if (count($article_filters) != 0) {
817 print_r($article_filters);
821 $plugin_filter_names = find_article_filters($article_filters, "plugin");
822 $plugin_filter_actions = $pluginhost->get_filter_actions();
824 if (count($plugin_filter_names) > 0) {
825 _debug("applying plugin filter actions...", $debug_enabled);
827 foreach ($plugin_filter_names as $pfn) {
828 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
830 if (isset($plugin_filter_actions[$pfclass])) {
831 $plugin = $pluginhost->get_plugin($pfclass);
833 _debug("... $pfclass: $pfaction", $debug_enabled);
836 $start = microtime(true);
837 $article = $plugin->hook_article_filter_action($article, $pfaction);
839 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
841 _debug("??? $pfclass: plugin object not found.");
844 _debug("??? $pfclass: filter plugin not registered.");
849 $entry_tags = $article["tags"];
850 $entry_guid = db_escape_string($entry_guid);
851 $entry_title = db_escape_string($article["title"]);
852 $entry_author = db_escape_string($article["author"]);
853 $entry_link = db_escape_string($article["link"]);
854 $entry_content = $article["content"]; // escaped below
855 $entry_force_catchup = $article["force_catchup"];
856 $article_labels = $article["labels"];
857 $entry_score_modifier = (int) $article["score_modifier"];
858 $entry_language = db_escape_string($article["language"]);
860 if ($debug_enabled) {
861 _debug("article labels:", $debug_enabled);
863 if (count($article_labels) != 0) {
864 print_r($article_labels);
868 _debug("force catchup: $entry_force_catchup");
870 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
871 cache_images($entry_content, $site_url, $debug_enabled);
873 $entry_content = db_escape_string($entry_content, false);
877 $result = db_query("SELECT id FROM ttrss_entries
878 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
880 if (db_num_rows($result) == 0) {
882 _debug("base guid [$entry_guid] not found", $debug_enabled);
884 // base post entry does not exist, create it
887 "INSERT INTO ttrss_entries
904 '$entry_guid_hashed',
906 '$entry_timestamp_fmt',
908 '$entry_current_hash',
911 '$date_feed_processed',
914 '$entry_plugin_data',
919 $base_entry_id = db_fetch_result($result, 0, "id");
922 // now it should exist, if not - bad luck then
924 $result = db_query("SELECT id FROM ttrss_entries
925 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
930 if (db_num_rows($result) == 1) {
932 _debug("base guid found, checking for user record", $debug_enabled);
934 $ref_id = db_fetch_result($result, 0, "id");
935 $entry_ref_id = $ref_id;
937 /* $stored_guid = db_fetch_result($result, 0, "guid");
938 if ($stored_guid != $entry_guid_hashed) {
939 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
941 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
945 if (find_article_filter($article_filters, "filter")) {
946 //db_query("COMMIT"); // close transaction in progress
950 $score = calculate_article_score($article_filters) +
$entry_score_modifier;
952 _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
954 // check for user post link to main table
956 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
957 ref_id = '$ref_id' AND owner_uid = '$owner_uid'";
959 // if ($_REQUEST["xdebug"]) print "$query\n";
961 $result = db_query($query);
963 // okay it doesn't exist - create user entry
964 if (db_num_rows($result) == 0) {
966 _debug("user record not found, creating...", $debug_enabled);
968 if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
970 $last_read_qpart = 'NULL';
973 $last_read_qpart = 'NOW()';
976 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
982 if (find_article_filter($article_filters, 'publish')) {
985 $published = 'false';
990 /* if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
992 $result = db_query("SELECT COUNT(*) AS similar FROM
993 ttrss_entries,ttrss_user_entries
994 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
995 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
996 AND owner_uid = $owner_uid");
998 $ngram_similar = db_fetch_result($result, 0, "similar");
1000 _debug("N-gram similar results: $ngram_similar", $debug_enabled);
1002 if ($ngram_similar > 0) {
1007 $last_marked = ($marked == 'true') ?
'NOW()' : 'NULL';
1008 $last_published = ($published == 'true') ?
'NOW()' : 'NULL';
1011 "INSERT INTO ttrss_user_entries
1012 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1013 published, score, tag_cache, label_cache, uuid,
1014 last_marked, last_published)
1015 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1016 $last_read_qpart, $marked, $published, '$score', '', '',
1017 '', $last_marked, $last_published)");
1019 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1020 $rss_link = get_self_url_prefix() .
1021 "/public.php?op=rss&id=-2&key=" .
1022 get_feed_access_key(-2, false, $owner_uid);
1024 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1026 /* $pubsub_result = */ $p->publish_update($rss_link);
1030 "SELECT int_id FROM ttrss_user_entries WHERE
1031 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1032 feed_id = '$feed' LIMIT 1");
1034 if (db_num_rows($result) == 1) {
1035 $entry_int_id = db_fetch_result($result, 0, "int_id");
1038 _debug("user record FOUND", $debug_enabled);
1040 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1041 $entry_int_id = db_fetch_result($result, 0, "int_id");
1044 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
1046 if (DB_TYPE
== "pgsql") {
1047 $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
1050 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
1053 $tsvector_qpart = "";
1056 db_query("UPDATE ttrss_entries
1057 SET title = '$entry_title',
1058 content = '$entry_content',
1059 content_hash = '$entry_current_hash',
1060 updated = '$entry_timestamp_fmt',
1062 num_comments = '$num_comments',
1063 plugin_data = '$entry_plugin_data',
1064 author = '$entry_author',
1065 lang = '$entry_language'
1066 WHERE id = '$ref_id'");
1069 db_query("UPDATE ttrss_user_entries
1070 SET score = '$score' WHERE ref_id = '$ref_id'");
1072 if ($mark_unread_on_update) {
1073 _debug("article updated, marking unread as requested.", $debug_enabled);
1075 db_query("UPDATE ttrss_user_entries
1076 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1080 //db_query("COMMIT");
1082 _debug("assigning labels [other]...", $debug_enabled);
1084 foreach ($article_labels as $label) {
1085 label_add_article($entry_ref_id, $label[1], $owner_uid);
1088 _debug("assigning labels [filters]...", $debug_enabled);
1090 assign_article_to_label_filters($entry_ref_id, $article_filters,
1091 $owner_uid, $article_labels);
1093 _debug("looking for enclosures...", $debug_enabled);
1097 $enclosures = array();
1099 $encs = $item->get_enclosures();
1101 if (is_array($encs)) {
1102 foreach ($encs as $e) {
1104 $e->link
, $e->type
, $e->length
, $e->title
, $e->width
, $e->height
);
1105 array_push($enclosures, $e_item);
1109 if ($debug_enabled) {
1110 _debug("article enclosures:", $debug_enabled);
1111 print_r($enclosures);
1114 //db_query("BEGIN");
1117 // db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1119 foreach ($enclosures as $enc) {
1120 $enc_url = db_escape_string($enc[0]);
1121 $enc_type = db_escape_string($enc[1]);
1122 $enc_dur = db_escape_string($enc[2]);
1123 $enc_title = db_escape_string($enc[3]);
1124 $enc_width = intval($enc[4]);
1125 $enc_height = intval($enc[5]);
1127 $result = db_query("SELECT id FROM ttrss_enclosures
1128 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1130 if (db_num_rows($result) == 0) {
1131 db_query("INSERT INTO ttrss_enclosures
1132 (content_url, content_type, title, duration, post_id, width, height) VALUES
1133 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
1137 //db_query("COMMIT");
1139 // check for manual tags (we have to do it here since they're loaded from filters)
1141 foreach ($article_filters as $f) {
1142 if ($f["type"] == "tag") {
1144 $manual_tags = trim_array(explode(",", $f["param"]));
1146 foreach ($manual_tags as $tag) {
1147 if (tag_is_valid($tag)) {
1148 array_push($entry_tags, $tag);
1156 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
1157 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1159 $filtered_tags = array();
1160 $tags_to_cache = array();
1162 if ($entry_tags && is_array($entry_tags)) {
1163 foreach ($entry_tags as $tag) {
1164 if (array_search($tag, $boring_tags) === false) {
1165 array_push($filtered_tags, $tag);
1170 $filtered_tags = array_unique($filtered_tags);
1172 if ($debug_enabled) {
1173 _debug("filtered article tags:", $debug_enabled);
1174 print_r($filtered_tags);
1177 // Save article tags in the database
1179 if (count($filtered_tags) > 0) {
1181 //db_query("BEGIN");
1183 foreach ($filtered_tags as $tag) {
1185 $tag = sanitize_tag($tag);
1186 $tag = db_escape_string($tag);
1188 if (!tag_is_valid($tag)) continue;
1190 $result = db_query("SELECT id FROM ttrss_tags
1191 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1192 owner_uid = '$owner_uid' LIMIT 1");
1194 if ($result && db_num_rows($result) == 0) {
1196 db_query("INSERT INTO ttrss_tags
1197 (owner_uid,tag_name,post_int_id)
1198 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1201 array_push($tags_to_cache, $tag);
1204 /* update the cache */
1206 $tags_to_cache = array_unique($tags_to_cache);
1208 $tags_str = db_escape_string(join(",", $tags_to_cache));
1210 db_query("UPDATE ttrss_user_entries
1211 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1212 AND owner_uid = $owner_uid");
1214 //db_query("COMMIT");
1217 _debug("article processed", $debug_enabled);
1220 _debug("purging feed...", $debug_enabled);
1222 purge_feed($feed, 0, $debug_enabled);
1224 db_query("UPDATE ttrss_feeds
1225 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1227 // db_query("COMMIT");
1231 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
1233 _debug("fetch error: $error_msg", $debug_enabled);
1235 if (count($rss->errors()) > 1) {
1236 foreach ($rss->errors() as $error) {
1242 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1243 last_updated = NOW() WHERE id = '$feed'");
1248 _debug("done", $debug_enabled);
1253 function cache_images($html, $site_url, $debug) {
1254 libxml_use_internal_errors(true);
1256 $charset_hack = '<head>
1257 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1260 $doc = new DOMDocument();
1261 $doc->loadHTML($charset_hack . $html);
1262 $xpath = new DOMXPath($doc);
1264 $entries = $xpath->query('(//img[@src])');
1266 foreach ($entries as $entry) {
1267 if ($entry->hasAttribute('src')) {
1268 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1270 $local_filename = CACHE_DIR
. "/images/" . sha1($src) . ".png";
1272 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1274 if (!file_exists($local_filename)) {
1275 $file_content = fetch_file_contents($src);
1277 if ($file_content && strlen($file_content) > _MIN_CACHE_IMAGE_SIZE
) {
1278 file_put_contents($local_filename, $file_content);
1281 touch($local_filename);
1287 function expire_error_log($debug) {
1288 if ($debug) _debug("Removing old error log entries...");
1290 if (DB_TYPE
== "pgsql") {
1291 db_query("DELETE FROM ttrss_error_log
1292 WHERE created_at < NOW() - INTERVAL '7 days'");
1294 db_query("DELETE FROM ttrss_error_log
1295 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1300 function expire_lock_files($debug) {
1301 //if ($debug) _debug("Removing old lock files...");
1305 if (is_writable(LOCK_DIRECTORY
)) {
1306 $files = glob(LOCK_DIRECTORY
. "/*.lock");
1309 foreach ($files as $file) {
1310 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
1318 if ($debug) _debug("Removed $num_deleted old lock files.");
1321 function expire_cached_files($debug) {
1322 foreach (array("simplepie", "images", "export", "upload") as $dir) {
1323 $cache_dir = CACHE_DIR
. "/$dir";
1325 // if ($debug) _debug("Expiring $cache_dir");
1329 if (is_writable($cache_dir)) {
1330 $files = glob("$cache_dir/*");
1333 foreach ($files as $file) {
1334 if (time() - filemtime($file) > 86400*7) {
1343 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
1348 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1349 * Returns the url query as associative array
1351 * @param string query
1352 * @return array params
1354 function convertUrlQuery($query) {
1355 $queryParts = explode('&', $query);
1359 foreach ($queryParts as $param) {
1360 $item = explode('=', $param);
1361 $params[$item[0]] = $item[1];
1367 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags, &$matched_rules = false) {
1370 foreach ($filters as $filter) {
1371 $match_any_rule = $filter["match_any_rule"];
1372 $inverse = $filter["inverse"];
1373 $filter_match = false;
1375 foreach ($filter["rules"] as $rule) {
1377 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
1378 $rule_inverse = $rule["inverse"];
1383 switch ($rule["type"]) {
1385 $match = @preg_match
("/$reg_exp/i", $title);
1388 // we don't need to deal with multiline regexps
1389 $content = preg_replace("/[\r\n\t]/", "", $content);
1391 $match = @preg_match
("/$reg_exp/i", $content);
1394 // we don't need to deal with multiline regexps
1395 $content = preg_replace("/[\r\n\t]/", "", $content);
1397 $match = (@preg_match
("/$reg_exp/i", $title) || @preg_match
("/$reg_exp/i", $content));
1400 $match = @preg_match
("/$reg_exp/i", $link);
1403 $match = @preg_match
("/$reg_exp/i", $author);
1406 foreach ($tags as $tag) {
1407 if (@preg_match
("/$reg_exp/i", $tag)) {
1415 if ($rule_inverse) $match = !$match;
1417 if ($match_any_rule) {
1419 $filter_match = true;
1423 $filter_match = $match;
1430 if ($inverse) $filter_match = !$filter_match;
1432 if ($filter_match) {
1433 if (is_array($matched_rules)) array_push($matched_rules, $rule);
1435 foreach ($filter["actions"] AS $action) {
1436 array_push($matches, $action);
1438 // if Stop action encountered, perform no further processing
1439 if (isset($action["type"]) && $action["type"] == "stop") return $matches;
1447 function find_article_filter($filters, $filter_name) {
1448 foreach ($filters as $f) {
1449 if ($f["type"] == $filter_name) {
1456 function find_article_filters($filters, $filter_name) {
1459 foreach ($filters as $f) {
1460 if ($f["type"] == $filter_name) {
1461 array_push($results, $f);
1467 function calculate_article_score($filters) {
1470 foreach ($filters as $f) {
1471 if ($f["type"] == "score") {
1472 $score +
= $f["param"];
1478 function labels_contains_caption($labels, $caption) {
1479 foreach ($labels as $label) {
1480 if ($label[1] == $caption) {
1488 function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
1489 foreach ($filters as $f) {
1490 if ($f["type"] == "label") {
1491 if (!labels_contains_caption($article_labels, $f["param"])) {
1492 label_add_article($id, $f["param"], $owner_uid);
1498 function make_guid_from_title($title) {
1499 return preg_replace("/[ \"\',.:;]/", "-",
1500 mb_strtolower(strip_tags($title), 'utf-8'));
1503 /* function verify_feed_xml($feed_data) {
1504 libxml_use_internal_errors(true);
1505 $doc = new DOMDocument();
1506 $doc->loadXML($feed_data);
1507 $error = libxml_get_last_error();
1508 libxml_clear_errors();
1512 function cleanup_counters_cache($debug) {
1513 $result = db_query("DELETE FROM ttrss_counters_cache
1514 WHERE feed_id > 0 AND
1515 (SELECT COUNT(id) FROM ttrss_feeds WHERE
1517 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1518 $frows = db_affected_rows($result);
1520 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1521 WHERE feed_id > 0 AND
1522 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1524 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1525 $crows = db_affected_rows($result);
1527 _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
1530 function housekeeping_user($owner_uid) {
1531 $tmph = new PluginHost();
1533 load_user_plugins($owner_uid, $tmph);
1535 $tmph->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");
1538 function housekeeping_common($debug) {
1539 expire_cached_files($debug);
1540 expire_lock_files($debug);
1541 expire_error_log($debug);
1543 $count = update_feedbrowser_cache();
1544 _debug("Feedbrowser updated, $count feeds processed.");
1546 purge_orphans( true);
1547 cleanup_counters_cache($debug);
1549 //$rc = cleanup_tags( 14, 50000);
1550 //_debug("Cleaned $rc cached tags.");
1552 PluginHost
::getInstance()->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");