3 static function calculate_article_hash($article, $pluginhost) {
6 foreach ($article as $k => $v) {
7 if ($k != "feed" && isset($v)) {
8 $x = strip_tags(is_array($v) ?
implode(",", $v) : $v);
10 //_debug("$k:" . sha1($x) . ":" . htmlspecialchars($x), true);
12 $tmp .= sha1("$k:" . sha1($x));
16 return sha1(implode(",", $pluginhost->get_plugin_names()) . $tmp);
19 static function update_feedbrowser_cache() {
21 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
22 FROM ttrss_feeds WHERE feed_url NOT IN (SELECT feed_url FROM ttrss_feeds
23 WHERE private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%')
24 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
28 db_query("DELETE FROM ttrss_feedbrowser_cache");
32 while ($line = db_fetch_assoc($result)) {
33 $subscribers = db_escape_string($line["subscribers"]);
34 $feed_url = db_escape_string($line["feed_url"]);
35 $title = db_escape_string($line["title"]);
36 $site_url = db_escape_string($line["site_url"]);
38 $tmp_result = db_query("SELECT subscribers FROM
39 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
41 if (db_num_rows($tmp_result) == 0) {
43 db_query("INSERT INTO ttrss_feedbrowser_cache
44 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
45 '$site_url', '$title', '$subscribers')");
59 static function update_daemon_common($limit = DAEMON_FEED_LIMIT
, $debug = true) {
60 // Process all other feeds using last_updated and interval parameters
62 $schema_version = get_schema_version();
64 if ($schema_version != SCHEMA_VERSION
) {
65 die("Schema version is wrong, please upgrade the database.\n");
68 define('PREFS_NO_CACHE', true);
70 // Test if the user has loggued in recently. If not, it does not update its feeds.
71 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
72 if (DB_TYPE
== "pgsql") {
73 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
75 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
78 $login_thresh_qpart = "";
81 // Test if the feed need a update (update interval exceeded).
82 if (DB_TYPE
== "pgsql") {
83 $update_limit_qpart = "AND ((
84 ttrss_feeds.update_interval = 0
85 AND ttrss_user_prefs.value != '-1'
86 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
88 ttrss_feeds.update_interval > 0
89 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
90 ) OR (ttrss_feeds.last_updated IS NULL
91 AND ttrss_user_prefs.value != '-1')
92 OR (last_updated = '1970-01-01 00:00:00'
93 AND ttrss_user_prefs.value != '-1'))";
95 $update_limit_qpart = "AND ((
96 ttrss_feeds.update_interval = 0
97 AND ttrss_user_prefs.value != '-1'
98 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
100 ttrss_feeds.update_interval > 0
101 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
102 ) OR (ttrss_feeds.last_updated IS NULL
103 AND ttrss_user_prefs.value != '-1')
104 OR (last_updated = '1970-01-01 00:00:00'
105 AND ttrss_user_prefs.value != '-1'))";
108 // Test if feed is currently being updated by another process.
109 if (DB_TYPE
== "pgsql") {
110 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
112 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
115 // Test if there is a limit to number of updated feeds
117 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
119 // Update the least recently updated feeds first
120 $query_order = "ORDER BY last_updated";
121 if (DB_TYPE
== "pgsql") $query_order .= " NULLS FIRST";
123 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
125 ttrss_feeds, ttrss_users, ttrss_user_prefs
127 ttrss_feeds.owner_uid = ttrss_users.id
128 AND ttrss_user_prefs.profile IS NULL
129 AND ttrss_users.id = ttrss_user_prefs.owner_uid
130 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
131 $login_thresh_qpart $update_limit_qpart
132 $updstart_thresh_qpart
133 $query_order $query_limit";
135 // We search for feed needing update.
136 $result = db_query($query);
138 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
140 // Here is a little cache magic in order to minimize risk of double feed updates.
141 $feeds_to_update = array();
142 while ($line = db_fetch_assoc($result)) {
143 array_push($feeds_to_update, db_escape_string($line['feed_url']));
146 // We update the feed last update started date before anything else.
147 // There is no lag due to feed contents downloads
148 // It prevent an other process to update the same feed.
150 if(count($feeds_to_update) > 0) {
151 $feeds_quoted = array();
153 foreach ($feeds_to_update as $feed) {
154 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
157 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
158 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
162 $bstarted = microtime(true);
164 $batch_owners = array();
166 // For each feed, we call the feed update function.
167 foreach ($feeds_to_update as $feed) {
168 if($debug) _debug("Base feed: $feed");
170 //update_rss_feed($line["id"], true);
172 // since we have the data cached, we can deal with other feeds with the same url
174 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
175 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
176 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
177 ttrss_users.id = ttrss_user_prefs.owner_uid AND
178 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
179 ttrss_user_prefs.profile IS NULL AND
180 feed_url = '".db_escape_string($feed)."'
183 ORDER BY ttrss_feeds.id $query_limit");
185 if (db_num_rows($tmp_result) > 0) {
186 while ($tline = db_fetch_assoc($tmp_result)) {
187 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
189 if (array_search($tline["owner_uid"], $batch_owners) === FALSE)
190 array_push($batch_owners, $tline["owner_uid"]);
192 $fstarted = microtime(true);
193 RSSUtils
::update_rss_feed($tline["id"], true, false);
194 _debug_suppress(false);
196 _debug(sprintf(" %.4f (sec)", microtime(true) - $fstarted));
204 _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
205 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
208 foreach ($batch_owners as $owner_uid) {
209 _debug("Running housekeeping tasks for user $owner_uid...");
211 RSSUtils
::housekeeping_user($owner_uid);
214 // Send feed digests by email if needed.
215 Digest
::send_headlines_digests($debug);
221 // this is used when subscribing
222 static function set_basic_feed_info($feed) {
224 $feed = db_escape_string($feed);
226 $result = db_query("SELECT feed_url,auth_pass,auth_login,auth_pass_encrypted
227 FROM ttrss_feeds WHERE id = '$feed'");
229 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
230 0, "auth_pass_encrypted"));
232 $auth_login = db_fetch_result($result, 0, "auth_login");
233 $auth_pass = db_fetch_result($result, 0, "auth_pass");
235 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
236 require_once "crypt.php";
237 $auth_pass = decrypt_string($auth_pass);
240 $fetch_url = db_fetch_result($result, 0, "feed_url");
242 $feed_data = fetch_file_contents($fetch_url, false,
243 $auth_login, $auth_pass, false,
247 global $fetch_curl_used;
249 if (!$fetch_curl_used) {
250 $tmp = @gzdecode
($feed_data);
252 if ($tmp) $feed_data = $tmp;
255 $feed_data = trim($feed_data);
257 $rss = new FeedParser($feed_data);
260 if (!$rss->error()) {
262 $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
264 $registered_title = db_fetch_result($result, 0, "title");
265 $orig_site_url = db_fetch_result($result, 0, "site_url");
267 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
268 $feed_title = db_escape_string(mb_substr($rss->get_title(), 0, 199));
270 if ($feed_title && (!$registered_title ||
$registered_title == "[Unknown]")) {
271 db_query("UPDATE ttrss_feeds SET
272 title = '$feed_title' WHERE id = '$feed'");
275 if ($site_url && $orig_site_url != $site_url) {
276 db_query("UPDATE ttrss_feeds SET
277 site_url = '$site_url' WHERE id = '$feed'");
283 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
285 static function update_rss_feed($feed, $no_cache = false) {
287 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
289 _debug_suppress(!$debug_enabled);
290 _debug("start", $debug_enabled);
292 $result = db_query("SELECT title FROM ttrss_feeds
293 WHERE id = '$feed'");
295 if (db_num_rows($result) == 0) {
296 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
297 user_error("Attempt to update unknown/invalid feed $feed", E_USER_WARNING
);
301 $title = db_fetch_result($result, 0, "title");
303 // feed was batch-subscribed or something, we need to get basic info
304 // this is not optimal currently as it fetches stuff separately TODO: optimize
305 if ($title == "[Unknown]") {
306 _debug("setting basic feed info for $feed...");
307 RSSUtils
::set_basic_feed_info($feed);
310 $result = db_query("SELECT id,update_interval,auth_login,
311 feed_url,auth_pass,cache_images,
312 mark_unread_on_update, owner_uid,
313 auth_pass_encrypted, feed_language
314 FROM ttrss_feeds WHERE id = '$feed'");
316 $owner_uid = db_fetch_result($result, 0, "owner_uid");
317 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
318 0, "mark_unread_on_update"));
319 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
320 0, "auth_pass_encrypted"));
322 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
323 WHERE id = '$feed'");
325 $auth_login = db_fetch_result($result, 0, "auth_login");
326 $auth_pass = db_fetch_result($result, 0, "auth_pass");
328 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
329 require_once "crypt.php";
330 $auth_pass = decrypt_string($auth_pass);
333 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
334 $fetch_url = db_fetch_result($result, 0, "feed_url");
335 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
336 if (!$feed_language) $feed_language = 'english';
338 $feed = db_escape_string($feed);
340 $date_feed_processed = date('Y-m-d H:i');
342 $cache_filename = CACHE_DIR
. "/simplepie/" . sha1($fetch_url) . ".xml";
344 $pluginhost = new PluginHost();
345 $pluginhost->set_debug($debug_enabled);
346 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
348 $pluginhost->load(PLUGINS
, PluginHost
::KIND_ALL
);
349 $pluginhost->load($user_plugins, PluginHost
::KIND_USER
, $owner_uid);
350 $pluginhost->load_data();
354 $force_refetch = isset($_REQUEST["force_refetch"]);
357 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FETCH_FEED
) as $plugin) {
358 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, 0, $auth_login, $auth_pass);
363 file_exists($cache_filename) &&
364 is_readable($cache_filename) &&
365 !$auth_login && !$auth_pass &&
366 filemtime($cache_filename) > time() - 30) {
368 _debug("using local cache [$cache_filename].", $debug_enabled);
370 @$feed_data = file_get_contents($cache_filename);
373 $rss_hash = sha1($feed_data);
377 _debug("local cache will not be used for this feed", $debug_enabled);
380 // fetch feed from source
382 _debug("fetching [$fetch_url]...", $debug_enabled);
384 if (ini_get("open_basedir") && function_exists("curl_init")) {
385 _debug("not using CURL due to open_basedir restrictions");
388 $feed_data = fetch_file_contents($fetch_url, false,
389 $auth_login, $auth_pass, false,
390 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT
: FEED_FETCH_TIMEOUT
,
393 global $fetch_curl_used;
395 if (!$fetch_curl_used) {
396 $tmp = @gzdecode
($feed_data);
398 if ($tmp) $feed_data = $tmp;
401 $feed_data = trim($feed_data);
403 _debug("fetch done.", $debug_enabled);
405 // cache vanilla feed data for re-use
406 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR
. "/simplepie")) {
407 $new_rss_hash = sha1($feed_data);
409 if ($new_rss_hash != $rss_hash) {
410 _debug("saving $cache_filename", $debug_enabled);
411 @file_put_contents
($cache_filename, $feed_data);
417 global $fetch_last_error;
418 global $fetch_last_error_code;
420 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
425 if ($fetch_last_error_code != 304) {
426 $error_escaped = db_escape_string($fetch_last_error);
428 _debug("source claims data not modified, nothing to do.", $debug_enabled);
432 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
433 last_updated = NOW() WHERE id = '$feed'");
438 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_FEED_FETCHED
) as $plugin) {
439 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
442 $rss = new FeedParser($feed_data);
445 $feed = db_escape_string($feed);
447 if (!$rss->error()) {
449 // We use local pluginhost here because we need to load different per-user feed plugins
450 $pluginhost->run_hooks(PluginHost
::HOOK_FEED_PARSED
, "hook_feed_parsed", $rss);
452 _debug("language: $feed_language", $debug_enabled);
453 _debug("processing feed data...", $debug_enabled);
455 // db_query("BEGIN");
457 if (DB_TYPE
== "pgsql") {
458 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
460 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
463 $result = db_query("SELECT owner_uid,favicon_avg_color,
464 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
466 FROM ttrss_feeds WHERE id = '$feed'");
468 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
469 "favicon_needs_check"));
470 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
472 $owner_uid = db_fetch_result($result, 0, "owner_uid");
474 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
476 _debug("site_url: $site_url", $debug_enabled);
477 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
479 if ($favicon_needs_check ||
$force_refetch) {
481 /* terrible hack: if we crash on floicon shit here, we won't check
482 * the icon avgcolor again (unless the icon got updated) */
484 $favicon_file = ICONS_DIR
. "/$feed.ico";
485 $favicon_modified = @filemtime
($favicon_file);
487 _debug("checking favicon...", $debug_enabled);
489 RSSUtils
::check_feed_favicon($site_url, $feed);
490 $favicon_modified_new = @filemtime
($favicon_file);
492 if ($favicon_modified_new > $favicon_modified)
493 $favicon_avg_color = '';
495 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
496 require_once "colors.php";
498 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
501 $favicon_color = db_escape_string(
502 calculate_avg_color($favicon_file));
504 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
505 } else if ($favicon_avg_color == 'fail') {
506 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
509 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
511 WHERE id = '$feed'");
514 _debug("loading filters & labels...", $debug_enabled);
516 $filters = load_filters($feed, $owner_uid);
518 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
520 $items = $rss->get_items();
522 if (!is_array($items)) {
523 _debug("no articles found.", $debug_enabled);
525 db_query("UPDATE ttrss_feeds
526 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
528 return; // no articles
531 _debug("processing articles...", $debug_enabled);
535 foreach ($items as $item) {
536 if ($_REQUEST['xdebug'] == 3) {
540 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
541 _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
545 $entry_guid = $item->get_id();
546 if (!$entry_guid) $entry_guid = $item->get_link();
547 if (!$entry_guid) $entry_guid = RSSUtils
::make_guid_from_title($item->get_title());
548 if (!$entry_guid) continue;
550 $entry_guid = "$owner_uid,$entry_guid";
552 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
554 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
556 $entry_timestamp = "";
558 $entry_timestamp = $item->get_date();
560 _debug("orig date: " . $item->get_date(), $debug_enabled);
562 if ($entry_timestamp == -1 ||
!$entry_timestamp ||
$entry_timestamp > time()) {
563 $entry_timestamp = time();
566 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
568 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
570 // $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
571 // $entry_title = decode_numeric_entities($entry_title);
572 $entry_title = $item->get_title();
574 $entry_link = rewrite_relative_url($site_url, $item->get_link());
576 _debug("title $entry_title", $debug_enabled);
577 _debug("link $entry_link", $debug_enabled);
579 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
581 $entry_content = $item->get_content();
582 if (!$entry_content) $entry_content = $item->get_description();
584 if ($_REQUEST["xdebug"] == 2) {
586 print htmlspecialchars($entry_content);
590 $entry_comments = db_escape_string(mb_substr($item->get_comments_url(), 0, 245));
591 $num_comments = (int) $item->get_comments_count();
593 $entry_author = $item->get_author(); // escaped later
594 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
596 _debug("author $entry_author", $debug_enabled);
597 _debug("num_comments: $num_comments", $debug_enabled);
598 _debug("looking for tags...", $debug_enabled);
600 // parse <category> entries into tags
602 $additional_tags = array();
604 $additional_tags_src = $item->get_categories();
606 if (is_array($additional_tags_src)) {
607 foreach ($additional_tags_src as $tobj) {
608 array_push($additional_tags, $tobj);
612 $entry_tags = array_unique($additional_tags);
614 for ($i = 0; $i < count($entry_tags); $i++
)
615 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
617 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
619 _debug("done collecting data.", $debug_enabled);
621 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
622 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
624 if (db_num_rows($result) != 0) {
625 $base_entry_id = db_fetch_result($result, 0, "id");
626 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
627 $article_labels = Article
::get_article_labels($base_entry_id, $owner_uid);
628 $entry_language = db_fetch_result($result, 0, "lang");
630 $existing_tags = Article
::get_article_tags($base_entry_id, $owner_uid);
631 $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
634 $base_entry_id = false;
635 $entry_stored_hash = "";
636 $article_labels = array();
637 $entry_language = "";
640 $article = array("owner_uid" => $owner_uid, // read only
641 "guid" => $entry_guid, // read only
642 "guid_hashed" => $entry_guid_hashed, // read only
643 "title" => $entry_title,
644 "content" => $entry_content,
645 "link" => $entry_link,
646 "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
647 "tags" => $entry_tags,
648 "author" => $entry_author,
649 "force_catchup" => false, // ugly hack for the time being
650 "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
651 "language" => $entry_language,
652 "feed" => array("id" => $feed,
653 "fetch_url" => $fetch_url,
654 "site_url" => $site_url,
655 "cache_images" => $cache_images)
658 $entry_plugin_data = "";
659 $entry_current_hash = RSSUtils
::calculate_article_hash($article, $pluginhost);
661 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
663 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
664 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
666 // we keep encountering the entry in feeds, so we need to
667 // update date_updated column so that we don't get horrible
668 // dupes when the entry gets purged and reinserted again e.g.
669 // in the case of SLOW SLOW OMG SLOW updating feeds
671 $base_entry_id = db_fetch_result($result, 0, "id");
673 db_query("UPDATE ttrss_entries SET date_updated = NOW()
674 WHERE id = '$base_entry_id'");
679 _debug("hash differs, applying plugin filters:", $debug_enabled);
681 foreach ($pluginhost->get_hooks(PluginHost
::HOOK_ARTICLE_FILTER
) as $plugin) {
682 _debug("... " . get_class($plugin), $debug_enabled);
684 $start = microtime(true);
685 $article = $plugin->hook_article_filter($article);
687 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
689 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
692 if ($_REQUEST["xdebug"] == 2) {
693 print "processed content: ";
694 print htmlspecialchars($article["content"]);
698 $entry_plugin_data = db_escape_string($entry_plugin_data);
700 _debug("plugin data: $entry_plugin_data", $debug_enabled);
702 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
703 if (DB_TYPE
== "mysql") {
704 foreach ($article as $k => $v) {
706 // i guess we'll have to take the risk of 4byte unicode labels & tags here
707 if (is_string($article[$k])) {
708 $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
713 /* Collect article tags here so we could filter by them: */
715 $matched_rules = array();
717 $article_filters = RSSUtils
::get_article_filters($filters, $article["title"],
718 $article["content"], $article["link"], $article["author"],
719 $article["tags"], $matched_rules);
721 if ($debug_enabled) {
722 _debug("matched filter rules: ", $debug_enabled);
724 if (count($matched_rules) != 0) {
725 print_r($matched_rules);
728 _debug("filter actions: ", $debug_enabled);
730 if (count($article_filters) != 0) {
731 print_r($article_filters);
735 $plugin_filter_names = RSSUtils
::find_article_filters($article_filters, "plugin");
736 $plugin_filter_actions = $pluginhost->get_filter_actions();
738 if (count($plugin_filter_names) > 0) {
739 _debug("applying plugin filter actions...", $debug_enabled);
741 foreach ($plugin_filter_names as $pfn) {
742 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
744 if (isset($plugin_filter_actions[$pfclass])) {
745 $plugin = $pluginhost->get_plugin($pfclass);
747 _debug("... $pfclass: $pfaction", $debug_enabled);
750 $start = microtime(true);
751 $article = $plugin->hook_article_filter_action($article, $pfaction);
753 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
755 _debug("??? $pfclass: plugin object not found.");
758 _debug("??? $pfclass: filter plugin not registered.");
763 $entry_tags = $article["tags"];
764 $entry_guid = db_escape_string($entry_guid);
765 $entry_title = db_escape_string($article["title"]);
766 $entry_author = db_escape_string(mb_substr($article["author"], 0, 245));
767 $entry_link = db_escape_string($article["link"]);
768 $entry_content = $article["content"]; // escaped below
769 $entry_force_catchup = $article["force_catchup"];
770 $article_labels = $article["labels"];
771 $entry_score_modifier = (int) $article["score_modifier"];
772 $entry_language = db_escape_string($article["language"]);
774 if ($debug_enabled) {
775 _debug("article labels:", $debug_enabled);
777 if (count($article_labels) != 0) {
778 print_r($article_labels);
782 _debug("force catchup: $entry_force_catchup");
784 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
785 RSSUtils
::cache_media($entry_content, $site_url, $debug_enabled);
787 $entry_content = db_escape_string($entry_content, false);
791 $result = db_query("SELECT id FROM ttrss_entries
792 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
794 if (db_num_rows($result) == 0) {
796 _debug("base guid [$entry_guid or $entry_guid_hashed] not found, creating...", $debug_enabled);
798 // base post entry does not exist, create it
801 "INSERT INTO ttrss_entries
818 '$entry_guid_hashed',
820 '$entry_timestamp_fmt',
822 '$entry_current_hash',
825 '$date_feed_processed',
828 '$entry_plugin_data',
834 // now it should exist, if not - bad luck then
836 $result = db_query("SELECT id FROM ttrss_entries
837 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
842 if (db_num_rows($result) == 1) {
844 _debug("base guid found, checking for user record", $debug_enabled);
846 $ref_id = db_fetch_result($result, 0, "id");
847 $entry_ref_id = $ref_id;
849 /* $stored_guid = db_fetch_result($result, 0, "guid");
850 if ($stored_guid != $entry_guid_hashed) {
851 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
853 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
857 if (RSSUtils
::find_article_filter($article_filters, "filter")) {
858 //db_query("COMMIT"); // close transaction in progress
862 $score = RSSUtils
::calculate_article_score($article_filters) +
$entry_score_modifier;
864 _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
866 // check for user post link to main table
868 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
869 ref_id = '$ref_id' AND owner_uid = '$owner_uid'";
871 // if ($_REQUEST["xdebug"]) print "$query\n";
873 $result = db_query($query);
875 // okay it doesn't exist - create user entry
876 if (db_num_rows($result) == 0) {
878 _debug("user record not found, creating...", $debug_enabled);
880 if ($score >= -500 && !RSSUtils
::find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
882 $last_read_qpart = 'NULL';
885 $last_read_qpart = 'NOW()';
888 if (RSSUtils
::find_article_filter($article_filters, 'mark') ||
$score > 1000) {
894 if (RSSUtils
::find_article_filter($article_filters, 'publish')) {
897 $published = 'false';
900 $last_marked = ($marked == 'true') ?
'NOW()' : 'NULL';
901 $last_published = ($published == 'true') ?
'NOW()' : 'NULL';
904 "INSERT INTO ttrss_user_entries
905 (ref_id, owner_uid, feed_id, unread, last_read, marked,
906 published, score, tag_cache, label_cache, uuid,
907 last_marked, last_published)
908 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
909 $last_read_qpart, $marked, $published, '$score', '', '',
910 '', $last_marked, $last_published)");
913 "SELECT int_id FROM ttrss_user_entries WHERE
914 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
915 feed_id = '$feed' LIMIT 1");
917 if (db_num_rows($result) == 1) {
918 $entry_int_id = db_fetch_result($result, 0, "int_id");
921 _debug("user record FOUND", $debug_enabled);
923 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
924 $entry_int_id = db_fetch_result($result, 0, "int_id");
927 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
929 if (DB_TYPE
== "pgsql") {
930 $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
933 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
936 $tsvector_qpart = "";
939 db_query("UPDATE ttrss_entries
940 SET title = '$entry_title',
941 content = '$entry_content',
942 content_hash = '$entry_current_hash',
943 updated = '$entry_timestamp_fmt',
945 num_comments = '$num_comments',
946 plugin_data = '$entry_plugin_data',
947 author = '$entry_author',
948 lang = '$entry_language'
949 WHERE id = '$ref_id'");
952 db_query("UPDATE ttrss_user_entries
953 SET score = '$score' WHERE ref_id = '$ref_id'");
955 if ($mark_unread_on_update) {
956 _debug("article updated, marking unread as requested.", $debug_enabled);
958 db_query("UPDATE ttrss_user_entries
959 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
963 //db_query("COMMIT");
965 _debug("assigning labels [other]...", $debug_enabled);
967 foreach ($article_labels as $label) {
968 Labels
::add_article($entry_ref_id, $label[1], $owner_uid);
971 _debug("assigning labels [filters]...", $debug_enabled);
973 RSSUtils
::assign_article_to_label_filters($entry_ref_id, $article_filters,
974 $owner_uid, $article_labels);
976 _debug("looking for enclosures...", $debug_enabled);
980 $enclosures = array();
982 $encs = $item->get_enclosures();
984 if (is_array($encs)) {
985 foreach ($encs as $e) {
987 rewrite_relative_url($site_url, $e->link
),
988 $e->type
, $e->length
, $e->title
, $e->width
, $e->height
);
989 array_push($enclosures, $e_item);
993 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
994 RSSUtils
::cache_enclosures($enclosures, $site_url, $debug_enabled);
996 if ($debug_enabled) {
997 _debug("article enclosures:", $debug_enabled);
998 print_r($enclosures);
1001 //db_query("BEGIN");
1004 // db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1006 foreach ($enclosures as $enc) {
1007 $enc_url = db_escape_string($enc[0]);
1008 $enc_type = db_escape_string($enc[1]);
1009 $enc_dur = db_escape_string($enc[2]);
1010 $enc_title = db_escape_string($enc[3]);
1011 $enc_width = intval($enc[4]);
1012 $enc_height = intval($enc[5]);
1014 $result = db_query("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("INSERT INTO ttrss_enclosures
1019 (content_url, content_type, title, duration, post_id, width, height) VALUES
1020 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
1024 //db_query("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(
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("filtered article tags:", $debug_enabled);
1061 print_r($filtered_tags);
1064 // Save article tags in the database
1066 if (count($filtered_tags) > 0) {
1068 //db_query("BEGIN");
1070 foreach ($filtered_tags as $tag) {
1072 $tag = sanitize_tag($tag);
1073 $tag = db_escape_string($tag);
1075 if (!tag_is_valid($tag)) continue;
1077 $result = db_query("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("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(join(",", $tags_to_cache));
1097 db_query("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("COMMIT");
1104 _debug("article processed", $debug_enabled);
1107 _debug("purging feed...", $debug_enabled);
1109 purge_feed($feed, 0, $debug_enabled);
1111 db_query("UPDATE ttrss_feeds
1112 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1114 // db_query("COMMIT");
1118 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
1120 _debug("fetch error: $error_msg", $debug_enabled);
1122 if (count($rss->errors()) > 1) {
1123 foreach ($rss->errors() as $error) {
1129 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1130 last_updated = NOW() WHERE id = '$feed'");
1136 _debug("done", $debug_enabled);
1141 static function cache_enclosures($enclosures, $site_url, $debug) {
1142 foreach ($enclosures as $enc) {
1144 if (preg_match("/(image|audio|video)/", $enc[1])) {
1146 $src = rewrite_relative_url($site_url, $enc[0]);
1148 $local_filename = CACHE_DIR
. "/images/" . sha1($src);
1150 if ($debug) _debug("cache_enclosures: downloading: $src to $local_filename");
1152 if (!file_exists($local_filename)) {
1153 $file_content = fetch_file_contents($src);
1155 if ($file_content && strlen($file_content) > _MIN_CACHE_FILE_SIZE
) {
1156 file_put_contents($local_filename, $file_content);
1159 touch($local_filename);
1165 static function cache_media($html, $site_url, $debug) {
1166 libxml_use_internal_errors(true);
1168 $charset_hack = '<head>
1169 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1172 $doc = new DOMDocument();
1173 $doc->loadHTML($charset_hack . $html);
1174 $xpath = new DOMXPath($doc);
1176 $entries = $xpath->query('(//img[@src])|(//video/source[@src])|(//audio/source[@src])');
1178 foreach ($entries as $entry) {
1179 if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
1180 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1182 $local_filename = CACHE_DIR
. "/images/" . sha1($src);
1184 if ($debug) _debug("cache_media: downloading: $src to $local_filename");
1186 if (!file_exists($local_filename)) {
1187 $file_content = fetch_file_contents($src);
1189 if ($file_content && strlen($file_content) > _MIN_CACHE_FILE_SIZE
) {
1190 file_put_contents($local_filename, $file_content);
1193 touch($local_filename);
1199 static function expire_error_log($debug) {
1200 if ($debug) _debug("Removing old error log entries...");
1202 if (DB_TYPE
== "pgsql") {
1203 db_query("DELETE FROM ttrss_error_log
1204 WHERE created_at < NOW() - INTERVAL '7 days'");
1206 db_query("DELETE FROM ttrss_error_log
1207 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1212 static function expire_lock_files($debug) {
1213 //if ($debug) _debug("Removing old lock files...");
1217 if (is_writable(LOCK_DIRECTORY
)) {
1218 $files = glob(LOCK_DIRECTORY
. "/*.lock");
1221 foreach ($files as $file) {
1222 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
1230 if ($debug) _debug("Removed $num_deleted old lock files.");
1233 static function expire_cached_files($debug) {
1234 foreach (array("simplepie", "images", "export", "upload") as $dir) {
1235 $cache_dir = CACHE_DIR
. "/$dir";
1237 // if ($debug) _debug("Expiring $cache_dir");
1241 if (is_writable($cache_dir)) {
1242 $files = glob("$cache_dir/*");
1245 foreach ($files as $file) {
1246 if (time() - filemtime($file) > 86400*7) {
1255 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
1260 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1261 * Returns the url query as associative array
1263 * @param string query
1264 * @return array params
1266 static function convertUrlQuery($query) {
1267 $queryParts = explode('&', $query);
1271 foreach ($queryParts as $param) {
1272 $item = explode('=', $param);
1273 $params[$item[0]] = $item[1];
1279 static function get_article_filters($filters, $title, $content, $link, $author, $tags, &$matched_rules = false) {
1282 foreach ($filters as $filter) {
1283 $match_any_rule = $filter["match_any_rule"];
1284 $inverse = $filter["inverse"];
1285 $filter_match = false;
1287 foreach ($filter["rules"] as $rule) {
1289 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
1290 $rule_inverse = $rule["inverse"];
1295 switch ($rule["type"]) {
1297 $match = @preg_match
("/$reg_exp/iu", $title);
1300 // we don't need to deal with multiline regexps
1301 $content = preg_replace("/[\r\n\t]/", "", $content);
1303 $match = @preg_match
("/$reg_exp/iu", $content);
1306 // we don't need to deal with multiline regexps
1307 $content = preg_replace("/[\r\n\t]/", "", $content);
1309 $match = (@preg_match
("/$reg_exp/iu", $title) || @preg_match
("/$reg_exp/iu", $content));
1312 $match = @preg_match
("/$reg_exp/iu", $link);
1315 $match = @preg_match
("/$reg_exp/iu", $author);
1318 foreach ($tags as $tag) {
1319 if (@preg_match
("/$reg_exp/iu", $tag)) {
1327 if ($rule_inverse) $match = !$match;
1329 if ($match_any_rule) {
1331 $filter_match = true;
1335 $filter_match = $match;
1342 if ($inverse) $filter_match = !$filter_match;
1344 if ($filter_match) {
1345 if (is_array($matched_rules)) array_push($matched_rules, $rule);
1347 foreach ($filter["actions"] AS $action) {
1348 array_push($matches, $action);
1350 // if Stop action encountered, perform no further processing
1351 if (isset($action["type"]) && $action["type"] == "stop") return $matches;
1359 static function find_article_filter($filters, $filter_name) {
1360 foreach ($filters as $f) {
1361 if ($f["type"] == $filter_name) {
1368 static function find_article_filters($filters, $filter_name) {
1371 foreach ($filters as $f) {
1372 if ($f["type"] == $filter_name) {
1373 array_push($results, $f);
1379 static function calculate_article_score($filters) {
1382 foreach ($filters as $f) {
1383 if ($f["type"] == "score") {
1384 $score +
= $f["param"];
1390 static function labels_contains_caption($labels, $caption) {
1391 foreach ($labels as $label) {
1392 if ($label[1] == $caption) {
1400 static function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
1401 foreach ($filters as $f) {
1402 if ($f["type"] == "label") {
1403 if (!RSSUtils
::labels_contains_caption($article_labels, $f["param"])) {
1404 Labels
::add_article($id, $f["param"], $owner_uid);
1410 static function make_guid_from_title($title) {
1411 return preg_replace("/[ \"\',.:;]/", "-",
1412 mb_strtolower(strip_tags($title), 'utf-8'));
1415 static function cleanup_counters_cache($debug) {
1416 $result = db_query("DELETE FROM ttrss_counters_cache
1417 WHERE feed_id > 0 AND
1418 (SELECT COUNT(id) FROM ttrss_feeds WHERE
1420 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1421 $frows = db_affected_rows($result);
1423 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1424 WHERE feed_id > 0 AND
1425 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1427 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1428 $crows = db_affected_rows($result);
1430 if ($debug) _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
1433 static function housekeeping_user($owner_uid) {
1434 $tmph = new PluginHost();
1436 load_user_plugins($owner_uid, $tmph);
1438 $tmph->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");
1441 static function housekeeping_common($debug) {
1442 RSSUtils
::expire_cached_files($debug);
1443 RSSUtils
::expire_lock_files($debug);
1444 RSSUtils
::expire_error_log($debug);
1446 $count = RSSUtils
::update_feedbrowser_cache();
1447 _debug("Feedbrowser updated, $count feeds processed.");
1449 Article
::purge_orphans( true);
1450 RSSUtils
::cleanup_counters_cache($debug);
1452 //$rc = cleanup_tags( 14, 50000);
1453 //_debug("Cleaned $rc cached tags.");
1455 PluginHost
::getInstance()->run_hooks(PluginHost
::HOOK_HOUSE_KEEPING
, "hook_house_keeping", "");
1458 static function check_feed_favicon($site_url, $feed) {
1459 # print "FAVICON [$site_url]: $favicon_url\n";
1461 $icon_file = ICONS_DIR
. "/$feed.ico";
1463 if (!file_exists($icon_file)) {
1464 $favicon_url = get_favicon_url($site_url);
1467 // Limiting to "image" type misses those served with text/plain
1468 $contents = fetch_file_contents($favicon_url); // , "image");
1471 // Crude image type matching.
1472 // Patterns gleaned from the file(1) source code.
1473 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
1474 // 0 string \000\000\001\000 MS Windows icon resource
1475 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
1477 elseif (preg_match('/^GIF8/', $contents)) {
1478 // 0 string GIF8 GIF image data
1479 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
1481 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
1482 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
1483 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
1485 elseif (preg_match('/^\xff\xd8/', $contents)) {
1486 // 0 beshort 0xffd8 JPEG image data
1487 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
1490 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
1496 $fp = @fopen
($icon_file, "w");
1499 fwrite($fp, $contents);
1501 chmod($icon_file, 0644);