4 * Used by daemons to update n feeds by run.
5 * Only update feed needing a update, and not being processed
8 * @param mixed $link Database link
9 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
10 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
11 * @param boolean $debug Set to false to disable debug output. Default to true.
14 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
15 // Process all other feeds using last_updated and interval parameters
17 // Test if the user has loggued in recently. If not, it does not update its feeds.
18 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
19 if (DB_TYPE
== "pgsql") {
20 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
22 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
25 $login_thresh_qpart = "";
28 // Test if the feed need a update (update interval exceded).
29 if (DB_TYPE
== "pgsql") {
30 $update_limit_qpart = "AND ((
31 ttrss_feeds.update_interval = 0
32 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
34 ttrss_feeds.update_interval > 0
35 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
36 ) OR ttrss_feeds.last_updated IS NULL)";
38 $update_limit_qpart = "AND ((
39 ttrss_feeds.update_interval = 0
40 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
42 ttrss_feeds.update_interval > 0
43 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
44 ) OR ttrss_feeds.last_updated IS NULL)";
47 // Test if feed is currently being updated by another process.
48 if (DB_TYPE
== "pgsql") {
49 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
51 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
54 // Test if there is a limit to number of updated feeds
56 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
58 $random_qpart = sql_random_function();
60 // We search for feed needing update.
61 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
62 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
63 ttrss_feeds.update_interval
65 ttrss_feeds, ttrss_users, ttrss_user_prefs
67 ttrss_feeds.owner_uid = ttrss_users.id
68 AND ttrss_users.id = ttrss_user_prefs.owner_uid
69 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
70 $login_thresh_qpart $update_limit_qpart
71 $updstart_thresh_qpart
72 ORDER BY $random_qpart $query_limit");
74 $user_prefs_cache = array();
76 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
78 // Here is a little cache magic in order to minimize risk of double feed updates.
79 $feeds_to_update = array();
80 while ($line = db_fetch_assoc($result)) {
81 $feeds_to_update[$line['id']] = $line;
84 // We update the feed last update started date before anything else.
85 // There is no lag due to feed contents downloads
86 // It prevent an other process to update the same feed.
87 $feed_ids = array_keys($feeds_to_update);
89 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
90 WHERE id IN (%s)", implode(',', $feed_ids)));
93 // For each feed, we call the feed update function.
94 while ($line = array_pop($feeds_to_update)) {
96 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
98 update_rss_feed($link, $line["id"], true);
100 sleep(1); // prevent flood (FIXME make this an option?)
103 // Send feed digests by email if needed.
104 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
106 } // function update_daemon_common
108 function fetch_twitter_rss($link, $url, $owner_uid) {
110 require_once 'lib/tmhoauth/tmhOAuth.php';
112 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
113 WHERE id = $owner_uid");
115 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
116 $url_escaped = db_escape_string($url);
120 $tmhOAuth = new tmhOAuth(array(
121 'consumer_key' => CONSUMER_KEY
,
122 'consumer_secret' => CONSUMER_SECRET
,
123 'user_token' => $access_token['oauth_token'],
124 'user_secret' => $access_token['oauth_token_secret'],
127 $code = $tmhOAuth->request('GET', $url);
131 $content = $tmhOAuth->response
['response'];
133 define('MAGPIE_CACHE_ON', false);
135 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
136 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
142 db_query($link, "UPDATE ttrss_feeds
143 SET last_error = 'OAuth authorization failed ($code).'
144 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
149 db_query($link, "UPDATE ttrss_feeds
150 SET last_error = 'OAuth information not found.'
151 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
157 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
161 /* Update all feeds with the same URL to utilize memcache */
164 $result = db_query($link, "SELECT f1.id
165 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
166 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
168 while ($line = db_fetch_assoc($result)) {
169 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
172 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
176 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
177 $override_url = false) {
179 require_once "lib/simplepie/simplepie.inc";
180 require_once "lib/magpierss/rss_fetch.inc";
181 require_once 'lib/magpierss/rss_utils.inc';
185 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
187 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
191 if ($debug_enabled) {
192 _debug("update_rss_feed: start");
195 if (!$ignore_daemon) {
197 if (DB_TYPE
== "pgsql") {
198 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
200 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
203 $result = db_query($link, "SELECT id,update_interval,auth_login,
204 auth_pass,cache_images,update_method
205 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
209 $result = db_query($link, "SELECT id,update_interval,auth_login,
210 feed_url,auth_pass,cache_images,update_method,last_updated,
211 mark_unread_on_update, owner_uid, update_on_checksum_change,
213 FROM ttrss_feeds WHERE id = '$feed'");
217 if (db_num_rows($result) == 0) {
218 if ($debug_enabled) {
219 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
224 $update_method = db_fetch_result($result, 0, "update_method");
225 $last_updated = db_fetch_result($result, 0, "last_updated");
226 $owner_uid = db_fetch_result($result, 0, "owner_uid");
227 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
228 0, "mark_unread_on_update"));
229 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
230 0, "update_on_checksum_change"));
231 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
233 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
234 WHERE id = '$feed'");
236 $auth_login = db_fetch_result($result, 0, "auth_login");
237 $auth_pass = db_fetch_result($result, 0, "auth_pass");
239 if ($update_method == 0)
240 $update_method = DEFAULT_UPDATE_METHOD +
1;
246 if ($update_method == 2)
247 $use_simplepie = true;
249 $use_simplepie = false;
251 if ($debug_enabled) {
252 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
255 if ($update_method == 1) {
256 $auth_login = urlencode($auth_login);
257 $auth_pass = urlencode($auth_pass);
260 $update_interval = db_fetch_result($result, 0, "update_interval");
261 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
262 $fetch_url = db_fetch_result($result, 0, "feed_url");
264 if ($update_interval < 0) { return false; }
266 $feed = db_escape_string($feed);
268 if ($auth_login && $auth_pass ){
269 $url_parts = array();
270 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
272 if ($url_parts[1] && $url_parts[2]) {
273 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
279 $fetch_url = $override_url;
281 if ($debug_enabled) {
282 _debug("update_rss_feed: fetching [$fetch_url]...");
285 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
287 if ($memcache && $obj = $memcache->get($obj_id)) {
289 if ($debug_enabled) {
290 _debug("update_rss_feed: data found in memcache.");
297 if ($update_method == 3) {
298 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
299 } else if ($update_method == 1) {
301 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
302 define('MAGPIE_CACHE_ON', !$no_cache);
303 define('MAGPIE_FETCH_TIME_OUT', 60);
304 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
306 $rss = @fetch_rss
($fetch_url);
308 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
310 if (!is_dir($simplepie_cache_dir)) {
311 mkdir($simplepie_cache_dir);
314 $rss = new SimplePie();
315 $rss->set_useragent(SELF_USER_AGENT
);
316 # $rss->set_timeout(10);
317 $rss->set_feed_url($fetch_url);
318 $rss->set_output_encoding('UTF-8');
319 $rss->force_feed(true);
321 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
323 if ($debug_enabled) {
324 _debug("enabling image cache");
327 $rss->set_image_handler("image.php", 'i');
330 if ($debug_enabled) {
331 _debug("feed update interval (sec): " .
332 get_feed_update_interval($link, $feed)*60);
335 $rss->enable_cache(!$no_cache);
338 $rss->set_cache_location($simplepie_cache_dir);
339 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
345 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
350 if ($debug_enabled) {
351 _debug("update_rss_feed: fetch done, parsing...");
354 $feed = db_escape_string($feed);
356 if ($update_method == 2) {
357 $fetch_ok = !$rss->error();
364 if ($debug_enabled) {
365 _debug("update_rss_feed: processing feed data...");
368 // db_query($link, "BEGIN");
370 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
371 FROM ttrss_feeds WHERE id = '$feed'");
373 $registered_title = db_fetch_result($result, 0, "title");
374 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
375 $orig_site_url = db_fetch_result($result, 0, "site_url");
377 $owner_uid = db_fetch_result($result, 0, "owner_uid");
379 if ($use_simplepie) {
380 $site_url = $rss->get_link();
382 $site_url = $rss->channel
["link"];
385 $site_url = rewrite_relative_url($fetch_url, $site_url);
387 if ($debug_enabled) {
388 _debug("update_rss_feed: checking favicon...");
391 check_feed_favicon($site_url, $feed, $link);
393 if (!$registered_title ||
$registered_title == "[Unknown]") {
395 if ($use_simplepie) {
396 $feed_title = db_escape_string($rss->get_title());
398 $feed_title = db_escape_string($rss->channel
["title"]);
401 if ($debug_enabled) {
402 _debug("update_rss_feed: registering title: $feed_title");
405 db_query($link, "UPDATE ttrss_feeds SET
406 title = '$feed_title' WHERE id = '$feed'");
409 // weird, weird Magpie
410 if (!$use_simplepie) {
411 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
414 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
415 db_query($link, "UPDATE ttrss_feeds SET
416 site_url = '$site_url' WHERE id = '$feed'");
419 // print "I: " . $rss->channel["image"]["url"];
421 if (!$use_simplepie) {
422 $icon_url = db_escape_string($rss->image
["url"]);
424 $icon_url = db_escape_string($rss->get_image_url());
427 $icon_url = substr($icon_url, 0, 250);
429 if ($icon_url && $orig_icon_url != $icon_url) {
430 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
433 if ($debug_enabled) {
434 _debug("update_rss_feed: loading filters...");
437 $filters = load_filters($link, $feed, $owner_uid);
439 // if ($debug_enabled) {
440 // print_r($filters);
443 if ($use_simplepie) {
444 $iterator = $rss->get_items();
446 $iterator = $rss->items
;
447 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
448 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
451 if (!is_array($iterator)) {
452 /* db_query($link, "UPDATE ttrss_feeds
453 SET last_error = 'Parse error: can\'t find any articles.'
454 WHERE id = '$feed'"); */
456 // clear any errors and mark feed as updated if fetched okay
457 // even if it's blank
459 if ($debug_enabled) {
460 _debug("update_rss_feed: entry iterator is not an array, no articles?");
463 db_query($link, "UPDATE ttrss_feeds
464 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
466 return; // no articles
469 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
471 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
473 $feed_hub_url = false;
474 if ($use_simplepie) {
475 $links = $rss->get_links('hub');
477 if ($links && is_array($links)) {
478 foreach ($links as $l) {
485 $atom = $rss->channel
['atom'];
488 if ($atom['link@rel'] == 'hub') {
489 $feed_hub_url = $atom['link@href'];
492 if (!$feed_hub_url && $atom['link#'] > 1) {
493 for ($i = 2; $i <= $atom['link#']; $i++
) {
494 if ($atom["link#$i@rel"] == 'hub') {
495 $feed_hub_url = $atom["link#$i@href"];
501 $feed_hub_url = $rss->channel
['link_hub'];
505 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
507 if ($feed_hub_url && function_exists('curl_init') &&
508 !ini_get("open_basedir")) {
510 require_once 'lib/pubsubhubbub/subscriber.php';
512 $callback_url = get_self_url_prefix() .
513 "/public.php?op=pubsub&id=$feed";
515 $s = new Subscriber($feed_hub_url, $callback_url);
517 $rc = $s->subscribe($fetch_url);
520 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
522 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
523 WHERE id = '$feed'");
527 if ($debug_enabled) {
528 _debug("update_rss_feed: processing articles...");
531 foreach ($iterator as $item) {
533 if ($_REQUEST['xdebug'] == 2) {
537 if ($use_simplepie) {
538 $entry_guid = $item->get_id();
539 if (!$entry_guid) $entry_guid = $item->get_link();
540 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
544 $entry_guid = $item["id"];
546 if (!$entry_guid) $entry_guid = $item["guid"];
547 if (!$entry_guid) $entry_guid = $item["about"];
548 if (!$entry_guid) $entry_guid = $item["link"];
549 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
552 if ($debug_enabled) {
553 _debug("update_rss_feed: guid $entry_guid");
556 if (!$entry_guid) continue;
558 $entry_timestamp = "";
560 if ($use_simplepie) {
561 $entry_timestamp = strtotime($item->get_date());
563 $rss_2_date = $item['pubdate'];
564 $rss_1_date = $item['dc']['date'];
565 $atom_date = $item['issued'];
566 if (!$atom_date) $atom_date = $item['updated'];
568 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
569 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
570 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
574 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
575 $entry_timestamp = time();
576 $no_orig_date = 'true';
578 $no_orig_date = 'false';
581 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
583 if ($debug_enabled) {
584 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
587 if ($use_simplepie) {
588 $entry_title = $item->get_title();
590 $entry_title = trim(strip_tags($item["title"]));
593 if ($use_simplepie) {
594 $entry_link = $item->get_link();
596 // strange Magpie workaround
597 $entry_link = $item["link_"];
598 if (!$entry_link) $entry_link = $item["link"];
601 $entry_link = rewrite_relative_url($site_url, $entry_link);
603 if ($debug_enabled) {
604 _debug("update_rss_feed: title $entry_title");
605 _debug("update_rss_feed: link $entry_link");
608 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
610 $entry_link = strip_tags($entry_link);
612 if ($use_simplepie) {
613 $entry_content = $item->get_content();
614 if (!$entry_content) $entry_content = $item->get_description();
616 $entry_content = $item["content:escaped"];
618 if (!$entry_content) $entry_content = $item["content:encoded"];
619 if (!$entry_content) $entry_content = $item["content"]["encoded"];
620 if (!$entry_content) $entry_content = $item["content"];
622 if (is_array($entry_content)) $entry_content = $entry_content[0];
624 // Magpie bugs are getting ridiculous
625 if (trim($entry_content) == "Array") $entry_content = false;
627 if (!$entry_content) $entry_content = $item["atom_content"];
628 if (!$entry_content) $entry_content = $item["summary"];
630 if (!$entry_content ||
631 strlen($entry_content) < strlen($item["description"])) {
632 $entry_content = $item["description"];
636 if (is_array($entry_content)) {
637 $entry_content = $entry_content["encoded"];
638 if (!$entry_content) $entry_content = $entry_content["escaped"];
642 if ($_REQUEST["xdebug"] == 2) {
643 print "update_rss_feed: content: ";
644 print_r(htmlspecialchars($entry_content));
647 $entry_content_unescaped = $entry_content;
649 if ($use_simplepie) {
650 $entry_comments = strip_tags($item->data
["comments"]);
651 if ($item->get_author()) {
652 $entry_author_item = $item->get_author();
653 $entry_author = $entry_author_item->get_name();
654 if (!$entry_author) $entry_author = $entry_author_item->get_email();
656 $entry_author = db_escape_string($entry_author);
659 $entry_comments = strip_tags($item["comments"]);
661 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
663 if ($item['author']) {
665 if (is_array($item['author'])) {
667 if (!$entry_author) {
668 $entry_author = db_escape_string(strip_tags($item['author']['name']));
671 if (!$entry_author) {
672 $entry_author = db_escape_string(strip_tags($item['author']['email']));
676 if (!$entry_author) {
677 $entry_author = db_escape_string(strip_tags($item['author']));
682 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
684 $entry_guid = db_escape_string(strip_tags($entry_guid));
685 $entry_guid = mb_substr($entry_guid, 0, 250);
687 $result = db_query($link, "SELECT id FROM ttrss_entries
688 WHERE guid = '$entry_guid'");
690 $entry_content = db_escape_string($entry_content, false);
692 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
694 $entry_title = db_escape_string($entry_title);
695 $entry_link = db_escape_string($entry_link);
696 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
697 $entry_author = mb_substr($entry_author, 0, 250);
699 if ($use_simplepie) {
700 $num_comments = 0; #FIXME#
702 $num_comments = db_escape_string($item["slash"]["comments"]);
705 if (!$num_comments) $num_comments = 0;
707 if ($debug_enabled) {
708 _debug("update_rss_feed: looking for tags [1]...");
711 // parse <category> entries into tags
713 $additional_tags = array();
715 if ($use_simplepie) {
717 $additional_tags_src = $item->get_categories();
719 if (is_array($additional_tags_src)) {
720 foreach ($additional_tags_src as $tobj) {
721 array_push($additional_tags, $tobj->get_term());
725 if ($debug_enabled) {
726 _debug("update_rss_feed: category tags:");
727 print_r($additional_tags);
732 $t_ctr = $item['category#'];
735 $additional_tags = array();
736 } else if ($t_ctr > 0) {
737 $additional_tags = array($item['category']);
739 if ($item['category@term']) {
740 array_push($additional_tags, $item['category@term']);
743 for ($i = 0; $i <= $t_ctr; $i++
) {
744 if ($item["category#$i"]) {
745 array_push($additional_tags, $item["category#$i"]);
748 if ($item["category#$i@term"]) {
749 array_push($additional_tags, $item["category#$i@term"]);
754 // parse <dc:subject> elements
756 $t_ctr = $item['dc']['subject#'];
759 array_push($additional_tags, $item['dc']['subject']);
761 for ($i = 0; $i <= $t_ctr; $i++
) {
762 if ($item['dc']["subject#$i"]) {
763 array_push($additional_tags, $item['dc']["subject#$i"]);
769 if ($debug_enabled) {
770 _debug("update_rss_feed: looking for tags [2]...");
774 // <a href="..." rel="tag">Xorg</a>, //
778 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
779 $entry_content_unescaped, $entry_tags);
781 $entry_tags = $entry_tags[1];
783 $entry_tags = array_merge($entry_tags, $additional_tags);
784 $entry_tags = array_unique($entry_tags);
786 for ($i = 0; $i < count($entry_tags); $i++
)
787 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
789 if ($debug_enabled) {
790 _debug("update_rss_feed: unfiltered tags found:");
791 print_r($entry_tags);
796 $entry_content = sanitize_article_content($entry_content);
797 $entry_title = sanitize_article_content($entry_title);
799 if ($debug_enabled) {
800 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
803 db_query($link, "BEGIN");
805 if (db_num_rows($result) == 0) {
807 if ($debug_enabled) {
808 _debug("update_rss_feed: base guid not found");
811 // base post entry does not exist, create it
813 $result = db_query($link,
814 "INSERT INTO ttrss_entries
831 '$entry_timestamp_fmt',
841 // we keep encountering the entry in feeds, so we need to
842 // update date_updated column so that we don't get horrible
843 // dupes when the entry gets purged and reinserted again e.g.
844 // in the case of SLOW SLOW OMG SLOW updating feeds
846 $base_entry_id = db_fetch_result($result, 0, "id");
848 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
849 WHERE id = '$base_entry_id'");
852 // now it should exist, if not - bad luck then
854 $result = db_query($link, "SELECT
855 id,content_hash,no_orig_date,title,
856 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
857 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
861 WHERE guid = '$entry_guid'");
866 if (db_num_rows($result) == 1) {
868 if ($debug_enabled) {
869 _debug("update_rss_feed: base guid found, checking for user record");
872 // this will be used below in update handler
873 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
874 $orig_title = db_fetch_result($result, 0, "title");
875 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
876 $orig_date_updated = strtotime(db_fetch_result($result,
879 $ref_id = db_fetch_result($result, 0, "id");
880 $entry_ref_id = $ref_id;
882 // check for user post link to main table
884 // do we allow duplicate posts with same GUID in different feeds?
885 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
886 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
888 $dupcheck_qpart = "";
891 /* Collect article tags here so we could filter by them: */
893 $article_filters = get_article_filters($filters, $entry_title,
894 $entry_content, $entry_link, $entry_timestamp, $entry_author,
897 if ($debug_enabled) {
898 _debug("update_rss_feed: article filters: ");
899 if (count($article_filters) != 0) {
900 print_r($article_filters);
904 if (find_article_filter($article_filters, "filter")) {
905 db_query($link, "COMMIT"); // close transaction in progress
909 $score = calculate_article_score($article_filters);
911 if ($debug_enabled) {
912 _debug("update_rss_feed: initial score: $score");
915 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
916 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
919 // if ($_REQUEST["xdebug"]) print "$query\n";
921 $result = db_query($link, $query);
923 // okay it doesn't exist - create user entry
924 if (db_num_rows($result) == 0) {
926 if ($debug_enabled) {
927 _debug("update_rss_feed: user record not found, creating...");
930 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
932 $last_read_qpart = 'NULL';
935 $last_read_qpart = 'NOW()';
938 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
944 if (find_article_filter($article_filters, 'publish')) {
947 $published = 'false';
950 $result = db_query($link,
951 "INSERT INTO ttrss_user_entries
952 (ref_id, owner_uid, feed_id, unread, last_read, marked,
953 published, score, tag_cache, label_cache, uuid)
954 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
955 $last_read_qpart, $marked, $published, '$score', '', '', '')");
957 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
958 $rss_link = get_self_url_prefix() .
959 "/public.php?op=rss&id=-2&key=" .
960 get_feed_access_key($link, -2, false, $owner_uid);
962 $p = new Publisher(PUBSUBHUBBUB_HUB
);
964 $pubsub_result = $p->publish_update($rss_link);
967 $result = db_query($link,
968 "SELECT int_id FROM ttrss_user_entries WHERE
969 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
970 feed_id = '$feed' LIMIT 1");
972 if (db_num_rows($result) == 1) {
973 $entry_int_id = db_fetch_result($result, 0, "int_id");
976 if ($debug_enabled) {
977 _debug("update_rss_feed: user record FOUND");
980 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
981 $entry_int_id = db_fetch_result($result, 0, "int_id");
984 if ($debug_enabled) {
985 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
988 $post_needs_update = false;
989 $update_insignificant = false;
991 if ($orig_num_comments != $num_comments) {
992 $post_needs_update = true;
993 $update_insignificant = true;
996 if ($content_hash != $orig_content_hash) {
997 $post_needs_update = true;
998 $update_insignificant = false;
1001 if (db_escape_string($orig_title) != $entry_title) {
1002 $post_needs_update = true;
1003 $update_insignificant = false;
1006 // if post needs update, update it and mark all user entries
1007 // linking to this post as updated
1008 if ($post_needs_update) {
1010 if (defined('DAEMON_EXTENDED_DEBUG')) {
1011 _debug("update_rss_feed: post $entry_guid needs update...");
1014 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1016 db_query($link, "UPDATE ttrss_entries
1017 SET title = '$entry_title', content = '$entry_content',
1018 content_hash = '$content_hash',
1019 updated = '$entry_timestamp_fmt',
1020 num_comments = '$num_comments'
1021 WHERE id = '$ref_id'");
1023 if (!$update_insignificant) {
1024 if ($mark_unread_on_update) {
1025 db_query($link, "UPDATE ttrss_user_entries
1026 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1027 } else if ($update_on_checksum_change) {
1028 db_query($link, "UPDATE ttrss_user_entries
1029 SET last_read = null WHERE ref_id = '$ref_id'
1030 AND unread = false");
1036 db_query($link, "COMMIT");
1038 if ($debug_enabled) {
1039 _debug("update_rss_feed: assigning labels...");
1042 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1045 if ($debug_enabled) {
1046 _debug("update_rss_feed: looking for enclosures...");
1051 $enclosures = array();
1053 if ($use_simplepie) {
1054 $encs = $item->get_enclosures();
1056 if (is_array($encs)) {
1057 foreach ($encs as $e) {
1059 $e->link
, $e->type
, $e->length
);
1061 array_push($enclosures, $e_item);
1068 $e_ctr = $item['enclosure#'];
1071 $e_item = array($item['enclosure@url'],
1072 $item['enclosure@type'],
1073 $item['enclosure@length']);
1075 array_push($enclosures, $e_item);
1077 for ($i = 0; $i <= $e_ctr; $i++
) {
1079 if ($item["enclosure#$i@url"]) {
1080 $e_item = array($item["enclosure#$i@url"],
1081 $item["enclosure#$i@type"],
1082 $item["enclosure#$i@length"]);
1083 array_push($enclosures, $e_item);
1089 // can there be many of those? yes -fox
1091 $m_ctr = $item['media']['content#'];
1094 $e_item = array($item['media']['content@url'],
1095 $item['media']['content@medium'],
1096 $item['media']['content@length']);
1098 array_push($enclosures, $e_item);
1100 for ($i = 0; $i <= $m_ctr; $i++
) {
1102 if ($item["media"]["content#$i@url"]) {
1103 $e_item = array($item["media"]["content#$i@url"],
1104 $item["media"]["content#$i@medium"],
1105 $item["media"]["content#$i@length"]);
1106 array_push($enclosures, $e_item);
1114 if ($debug_enabled) {
1115 _debug("update_rss_feed: article enclosures:");
1116 print_r($enclosures);
1119 db_query($link, "BEGIN");
1121 foreach ($enclosures as $enc) {
1122 $enc_url = db_escape_string($enc[0]);
1123 $enc_type = db_escape_string($enc[1]);
1124 $enc_dur = db_escape_string($enc[2]);
1126 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1127 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1129 if (db_num_rows($result) == 0) {
1130 db_query($link, "INSERT INTO ttrss_enclosures
1131 (content_url, content_type, title, duration, post_id) VALUES
1132 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1136 db_query($link, "COMMIT");
1138 // check for manual tags (we have to do it here since they're loaded from filters)
1140 foreach ($article_filters as $f) {
1141 if ($f[0] == "tag") {
1143 $manual_tags = trim_array(explode(",", $f[1]));
1145 foreach ($manual_tags as $tag) {
1146 if (tag_is_valid($tag)) {
1147 array_push($entry_tags, $tag);
1155 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1156 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1158 $filtered_tags = array();
1159 $tags_to_cache = array();
1161 if ($entry_tags && is_array($entry_tags)) {
1162 foreach ($entry_tags as $tag) {
1163 if (array_search($tag, $boring_tags) === false) {
1164 array_push($filtered_tags, $tag);
1169 $filtered_tags = array_unique($filtered_tags);
1171 if ($debug_enabled) {
1172 _debug("update_rss_feed: filtered article tags:");
1173 print_r($filtered_tags);
1176 // Save article tags in the database
1178 if (count($filtered_tags) > 0) {
1180 db_query($link, "BEGIN");
1182 foreach ($filtered_tags as $tag) {
1184 $tag = sanitize_tag($tag);
1185 $tag = db_escape_string($tag);
1187 if (!tag_is_valid($tag)) continue;
1189 $result = db_query($link, "SELECT id FROM ttrss_tags
1190 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1191 owner_uid = '$owner_uid' LIMIT 1");
1193 if ($result && db_num_rows($result) == 0) {
1195 db_query($link, "INSERT INTO ttrss_tags
1196 (owner_uid,tag_name,post_int_id)
1197 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1200 array_push($tags_to_cache, $tag);
1203 /* update the cache */
1205 $tags_to_cache = array_unique($tags_to_cache);
1207 $tags_str = db_escape_string(join(",", $tags_to_cache));
1209 db_query($link, "UPDATE ttrss_user_entries
1210 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1211 AND owner_uid = $owner_uid");
1213 db_query($link, "COMMIT");
1216 if ($debug_enabled) {
1217 _debug("update_rss_feed: article processed");
1221 if (!$last_updated) {
1222 if ($debug_enabled) {
1223 _debug("update_rss_feed: new feed, catching it up...");
1225 catchup_feed($link, $feed, false, $owner_uid);
1228 if ($debug_enabled) {
1229 _debug("purging feed...");
1232 purge_feed($link, $feed, 0, $debug_enabled);
1234 db_query($link, "UPDATE ttrss_feeds
1235 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1237 // db_query($link, "COMMIT");
1241 if ($use_simplepie) {
1242 $error_msg = mb_substr($rss->error(), 0, 250);
1244 $error_msg = mb_substr(magpie_error(), 0, 250);
1247 if ($debug_enabled) {
1248 _debug("update_rss_feed: error fetching feed: $error_msg");
1251 $error_msg = db_escape_string($error_msg);
1254 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1255 last_updated = NOW() WHERE id = '$feed'");
1258 if ($use_simplepie) {
1262 if ($debug_enabled) {
1263 _debug("update_rss_feed: done");