2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
4 define('DAEMON_SLEEP_INTERVAL', 120);
6 function update_feedbrowser_cache($link) {
8 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
9 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
10 WHERE tf.feed_url = ttrss_feeds.feed_url
11 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
12 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
14 db_query($link, "BEGIN");
16 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
20 while ($line = db_fetch_assoc($result)) {
21 $subscribers = db_escape_string($line["subscribers"]);
22 $feed_url = db_escape_string($line["feed_url"]);
23 $title = db_escape_string($line["title"]);
24 $site_url = db_escape_string($line["site_url"]);
26 $tmp_result = db_query($link, "SELECT subscribers FROM
27 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
29 if (db_num_rows($tmp_result) == 0) {
31 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
32 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
33 '$site_url', '$title', '$subscribers')");
41 db_query($link, "COMMIT");
49 * Update a feed batch.
50 * Used by daemons to update n feeds by run.
51 * Only update feed needing a update, and not being processed
54 * @param mixed $link Database link
55 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
56 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
57 * @param boolean $debug Set to false to disable debug output. Default to true.
60 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
61 // Process all other feeds using last_updated and interval parameters
63 define('PREFS_NO_CACHE', true);
65 // Test if the user has loggued in recently. If not, it does not update its feeds.
66 if (!SINGLE_USER_MODE
&& DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
67 if (DB_TYPE
== "pgsql") {
68 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
70 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
73 $login_thresh_qpart = "";
76 // Test if the feed need a update (update interval exceded).
77 if (DB_TYPE
== "pgsql") {
78 $update_limit_qpart = "AND ((
79 ttrss_feeds.update_interval = 0
80 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
82 ttrss_feeds.update_interval > 0
83 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
84 ) OR ttrss_feeds.last_updated IS NULL
85 OR last_updated = '1970-01-01 00:00:00')";
87 $update_limit_qpart = "AND ((
88 ttrss_feeds.update_interval = 0
89 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
91 ttrss_feeds.update_interval > 0
92 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
93 ) OR ttrss_feeds.last_updated IS NULL
94 OR last_updated = '1970-01-01 00:00:00')";
97 // Test if feed is currently being updated by another process.
98 if (DB_TYPE
== "pgsql") {
99 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
101 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
104 // Test if there is a limit to number of updated feeds
106 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
108 $random_qpart = sql_random_function();
110 // We search for feed needing update.
111 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
112 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
113 ttrss_feeds.update_interval
115 ttrss_feeds, ttrss_users, ttrss_user_prefs
117 ttrss_feeds.owner_uid = ttrss_users.id
118 AND ttrss_users.id = ttrss_user_prefs.owner_uid
119 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
120 $login_thresh_qpart $update_limit_qpart
121 $updstart_thresh_qpart
122 ORDER BY $random_qpart $query_limit");
124 $user_prefs_cache = array();
126 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
128 // Here is a little cache magic in order to minimize risk of double feed updates.
129 $feeds_to_update = array();
130 while ($line = db_fetch_assoc($result)) {
131 $feeds_to_update[$line['id']] = $line;
134 // We update the feed last update started date before anything else.
135 // There is no lag due to feed contents downloads
136 // It prevent an other process to update the same feed.
137 $feed_ids = array_keys($feeds_to_update);
139 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
140 WHERE id IN (%s)", implode(',', $feed_ids)));
143 expire_cached_files($debug);
145 // For each feed, we call the feed update function.
146 while ($line = array_pop($feeds_to_update)) {
148 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
150 update_rss_feed($link, $line["id"], true);
152 sleep(1); // prevent flood (FIXME make this an option?)
155 // Send feed digests by email if needed.
156 send_headlines_digests($link, $debug);
158 } // function update_daemon_common
160 function fetch_twitter_rss($link, $url, $owner_uid) {
162 require_once 'lib/tmhoauth/tmhOAuth.php';
163 require_once "lib/magpierss/rss_fetch.inc";
164 require_once 'lib/magpierss/rss_utils.inc';
166 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
167 WHERE id = $owner_uid");
169 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
170 $url_escaped = db_escape_string($url);
174 $tmhOAuth = new tmhOAuth(array(
175 'consumer_key' => CONSUMER_KEY
,
176 'consumer_secret' => CONSUMER_SECRET
,
177 'user_token' => $access_token['oauth_token'],
178 'user_secret' => $access_token['oauth_token_secret'],
181 $code = $tmhOAuth->request('GET', $url,
182 convertUrlQuery(parse_url($url, PHP_URL_QUERY
)));
186 $content = $tmhOAuth->response
['response'];
188 define('MAGPIE_CACHE_ON', false);
190 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
191 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
197 db_query($link, "UPDATE ttrss_feeds
198 SET last_error = 'OAuth authorization failed ($code).'
199 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
204 db_query($link, "UPDATE ttrss_feeds
205 SET last_error = 'OAuth information not found.'
206 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
212 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
216 /* Update all feeds with the same URL to utilize memcache */
219 $result = db_query($link, "SELECT f1.id
220 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
221 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
223 while ($line = db_fetch_assoc($result)) {
224 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
227 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
231 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
232 $override_url = false) {
234 require_once "lib/simplepie/simplepie.inc";
235 require_once "lib/magpierss/rss_fetch.inc";
236 require_once 'lib/magpierss/rss_utils.inc';
240 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
242 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
246 if ($debug_enabled) {
247 _debug("update_rss_feed: start");
250 if (!$ignore_daemon) {
252 if (DB_TYPE
== "pgsql") {
253 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
255 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
258 $result = db_query($link, "SELECT id,update_interval,auth_login,
259 auth_pass,cache_images,update_method,last_updated
260 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
264 $result = db_query($link, "SELECT id,update_interval,auth_login,
265 feed_url,auth_pass,cache_images,update_method,last_updated,
266 mark_unread_on_update, owner_uid, update_on_checksum_change,
268 FROM ttrss_feeds WHERE id = '$feed'");
272 if (db_num_rows($result) == 0) {
273 if ($debug_enabled) {
274 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
279 $update_method = db_fetch_result($result, 0, "update_method");
280 $last_updated = db_fetch_result($result, 0, "last_updated");
281 $owner_uid = db_fetch_result($result, 0, "owner_uid");
282 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
283 0, "mark_unread_on_update"));
284 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
285 0, "update_on_checksum_change"));
286 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
288 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
289 WHERE id = '$feed'");
291 $auth_login = db_fetch_result($result, 0, "auth_login");
292 $auth_pass = db_fetch_result($result, 0, "auth_pass");
294 if ($update_method == 0)
295 $update_method = DEFAULT_UPDATE_METHOD +
1;
301 if ($update_method == 2)
302 $use_simplepie = true;
304 $use_simplepie = false;
306 if ($debug_enabled) {
307 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
310 if ($update_method == 1) {
311 $auth_login = urlencode($auth_login);
312 $auth_pass = urlencode($auth_pass);
315 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
316 $fetch_url = db_fetch_result($result, 0, "feed_url");
318 $feed = db_escape_string($feed);
320 if ($auth_login && $auth_pass ){
321 $url_parts = array();
322 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
324 if ($url_parts[1] && $url_parts[2]) {
325 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
331 $fetch_url = $override_url;
333 if ($debug_enabled) {
334 _debug("update_rss_feed: fetching [$fetch_url]...");
337 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
339 if ($memcache && $obj = $memcache->get($obj_id)) {
341 if ($debug_enabled) {
342 _debug("update_rss_feed: data found in memcache.");
349 // Ignore cache if new feed or manual update.
350 $cache_age = (is_null($last_updated) ||
$last_updated == '1970-01-01 00:00:00') ?
351 -1 : get_feed_update_interval($link, $feed) * 60;
353 if ($update_method == 3) {
354 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
355 } else if ($update_method == 1) {
357 define('MAGPIE_CACHE_AGE', $cache_age);
358 define('MAGPIE_CACHE_ON', !$no_cache);
359 define('MAGPIE_FETCH_TIME_OUT', 60);
360 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
362 $rss = @fetch_rss
($fetch_url);
364 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
366 if (!is_dir($simplepie_cache_dir)) {
367 mkdir($simplepie_cache_dir);
370 $rss = new SimplePie();
371 $rss->set_useragent(SELF_USER_AGENT
);
372 # $rss->set_timeout(10);
373 $rss->set_feed_url($fetch_url);
374 $rss->set_output_encoding('UTF-8');
375 //$rss->force_feed(true);
377 if ($debug_enabled) {
378 _debug("feed update interval (sec): " .
379 get_feed_update_interval($link, $feed)*60);
382 $rss->enable_cache(!$no_cache);
385 $rss->set_cache_location($simplepie_cache_dir);
386 $rss->set_cache_duration($cache_age);
392 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
397 if ($debug_enabled) {
398 _debug("update_rss_feed: fetch done, parsing...");
401 $feed = db_escape_string($feed);
403 if ($update_method == 2) {
404 $fetch_ok = !$rss->error();
411 if ($debug_enabled) {
412 _debug("update_rss_feed: processing feed data...");
415 // db_query($link, "BEGIN");
417 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
418 FROM ttrss_feeds WHERE id = '$feed'");
420 $registered_title = db_fetch_result($result, 0, "title");
421 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
422 $orig_site_url = db_fetch_result($result, 0, "site_url");
424 $owner_uid = db_fetch_result($result, 0, "owner_uid");
426 if ($use_simplepie) {
427 $site_url = db_escape_string(trim($rss->get_link()));
429 $site_url = db_escape_string(trim($rss->channel
["link"]));
432 // weird, weird Magpie
433 if (!$use_simplepie) {
434 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
437 $site_url = rewrite_relative_url($fetch_url, $site_url);
438 $site_url = substr($site_url, 0, 250);
440 if ($debug_enabled) {
441 _debug("update_rss_feed: checking favicon...");
444 if (!file_exists(ICONS_DIR
. "/$feed.ico")) {
445 if ($use_simplepie) {
446 $atom_icon = $rss->get_favicon();
448 $atom_icon = $rss->channel
["icon"];
450 check_feed_favicon($site_url, $feed, $link, $atom_icon);
453 if (!$registered_title ||
$registered_title == "[Unknown]") {
455 if ($use_simplepie) {
456 $feed_title = db_escape_string($rss->get_title());
458 $feed_title = db_escape_string($rss->channel
["title"]);
461 if ($debug_enabled) {
462 _debug("update_rss_feed: registering title: $feed_title");
465 db_query($link, "UPDATE ttrss_feeds SET
466 title = '$feed_title' WHERE id = '$feed'");
469 if ($site_url && $orig_site_url != $site_url) {
470 db_query($link, "UPDATE ttrss_feeds SET
471 site_url = '$site_url' WHERE id = '$feed'");
474 // print "I: " . $rss->channel["image"]["url"];
476 if (!$use_simplepie) {
477 $icon_url = db_escape_string(trim($rss->image
["url"]));
479 $icon_url = db_escape_string(trim($rss->get_image_url()));
482 $icon_url = rewrite_relative_url($fetch_url, $icon_url);
483 $icon_url = substr($icon_url, 0, 250);
485 if ($icon_url && $orig_icon_url != $icon_url) {
486 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
489 if ($debug_enabled) {
490 _debug("update_rss_feed: loading filters...");
493 $filters = load_filters($link, $feed, $owner_uid);
495 // if ($debug_enabled) {
496 // print_r($filters);
499 if ($use_simplepie) {
500 $iterator = $rss->get_items();
502 $iterator = $rss->items
;
503 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
504 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
507 if (!is_array($iterator)) {
508 /* db_query($link, "UPDATE ttrss_feeds
509 SET last_error = 'Parse error: can\'t find any articles.'
510 WHERE id = '$feed'"); */
512 // clear any errors and mark feed as updated if fetched okay
513 // even if it's blank
515 if ($debug_enabled) {
516 _debug("update_rss_feed: entry iterator is not an array, no articles?");
519 db_query($link, "UPDATE ttrss_feeds
520 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
522 return; // no articles
525 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
527 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
529 $feed_hub_url = false;
530 if ($use_simplepie) {
531 $links = $rss->get_links('hub');
533 if ($links && is_array($links)) {
534 foreach ($links as $l) {
541 $atom = $rss->channel
['atom'];
544 if ($atom['link@rel'] == 'hub') {
545 $feed_hub_url = $atom['link@href'];
548 if (!$feed_hub_url && $atom['link#'] > 1) {
549 for ($i = 2; $i <= $atom['link#']; $i++
) {
550 if ($atom["link#$i@rel"] == 'hub') {
551 $feed_hub_url = $atom["link#$i@href"];
557 $feed_hub_url = $rss->channel
['link_hub'];
561 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
563 if ($feed_hub_url && function_exists('curl_init') &&
564 !ini_get("open_basedir")) {
566 require_once 'lib/pubsubhubbub/subscriber.php';
568 $callback_url = get_self_url_prefix() .
569 "/public.php?op=pubsub&id=$feed";
571 $s = new Subscriber($feed_hub_url, $callback_url);
573 $rc = $s->subscribe($fetch_url);
576 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
578 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
579 WHERE id = '$feed'");
583 if ($debug_enabled) {
584 _debug("update_rss_feed: processing articles...");
587 foreach ($iterator as $item) {
589 if ($_REQUEST['xdebug'] == 2) {
593 if ($use_simplepie) {
594 $entry_guid = $item->get_id();
595 if (!$entry_guid) $entry_guid = $item->get_link();
596 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
600 $entry_guid = $item["id"];
602 if (!$entry_guid) $entry_guid = $item["guid"];
603 if (!$entry_guid) $entry_guid = $item["about"];
604 if (!$entry_guid) $entry_guid = $item["link"];
605 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
608 if ($debug_enabled) {
609 _debug("update_rss_feed: guid $entry_guid");
612 if (!$entry_guid) continue;
614 $entry_timestamp = "";
616 if ($use_simplepie) {
617 $entry_timestamp = strtotime($item->get_date());
619 $rss_2_date = $item['pubdate'];
620 $rss_1_date = $item['dc']['date'];
621 $atom_date = $item['issued'];
622 if (!$atom_date) $atom_date = $item['updated'];
624 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
625 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
626 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
630 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
631 $entry_timestamp = time();
632 $no_orig_date = 'true';
634 $no_orig_date = 'false';
637 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
639 if ($debug_enabled) {
640 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
643 if ($use_simplepie) {
644 $entry_title = $item->get_title();
646 $entry_title = trim(strip_tags($item["title"]));
649 if ($use_simplepie) {
650 $entry_link = $item->get_link();
652 // strange Magpie workaround
653 $entry_link = $item["link_"];
654 if (!$entry_link) $entry_link = $item["link"];
657 $entry_link = rewrite_relative_url($site_url, $entry_link);
659 if ($debug_enabled) {
660 _debug("update_rss_feed: title $entry_title");
661 _debug("update_rss_feed: link $entry_link");
664 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
666 $entry_link = strip_tags($entry_link);
668 if ($use_simplepie) {
669 $entry_content = $item->get_content();
670 if (!$entry_content) $entry_content = $item->get_description();
672 $entry_content = $item["content:escaped"];
674 if (!$entry_content) $entry_content = $item["content:encoded"];
675 if (!$entry_content) $entry_content = $item["content"]["encoded"];
676 if (!$entry_content) $entry_content = $item["content"];
678 if (is_array($entry_content)) $entry_content = $entry_content[0];
680 // Magpie bugs are getting ridiculous
681 if (trim($entry_content) == "Array") $entry_content = false;
683 if (!$entry_content) $entry_content = $item["atom_content"];
684 if (!$entry_content) $entry_content = $item["summary"];
686 if (!$entry_content ||
687 strlen($entry_content) < strlen($item["description"])) {
688 $entry_content = $item["description"];
692 if (is_array($entry_content)) {
693 $entry_content = $entry_content["encoded"];
694 if (!$entry_content) $entry_content = $entry_content["escaped"];
698 if ($cache_images && is_writable(CACHE_DIR
. '/images'))
699 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
701 if ($_REQUEST["xdebug"] == 2) {
702 print "update_rss_feed: content: ";
703 print $entry_content;
707 $entry_content_unescaped = $entry_content;
709 if ($use_simplepie) {
710 $entry_comments = strip_tags($item->data
["comments"]);
711 if ($item->get_author()) {
712 $entry_author_item = $item->get_author();
713 $entry_author = $entry_author_item->get_name();
714 if (!$entry_author) $entry_author = $entry_author_item->get_email();
716 $entry_author = db_escape_string($entry_author);
719 $entry_comments = strip_tags($item["comments"]);
721 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
723 if ($item['author']) {
725 if (is_array($item['author'])) {
727 if (!$entry_author) {
728 $entry_author = db_escape_string(strip_tags($item['author']['name']));
731 if (!$entry_author) {
732 $entry_author = db_escape_string(strip_tags($item['author']['email']));
736 if (!$entry_author) {
737 $entry_author = db_escape_string(strip_tags($item['author']));
742 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
744 $entry_guid = db_escape_string(strip_tags($entry_guid));
745 $entry_guid = mb_substr($entry_guid, 0, 250);
747 $result = db_query($link, "SELECT id FROM ttrss_entries
748 WHERE guid = '$entry_guid'");
750 $entry_content = db_escape_string($entry_content, false);
752 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
754 $entry_title = db_escape_string($entry_title);
755 $entry_link = db_escape_string($entry_link);
756 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
757 $entry_author = mb_substr($entry_author, 0, 250);
759 if ($use_simplepie) {
760 $num_comments = 0; #FIXME#
762 $num_comments = db_escape_string($item["slash"]["comments"]);
765 if (!$num_comments) $num_comments = 0;
767 if ($debug_enabled) {
768 _debug("update_rss_feed: looking for tags [1]...");
771 // parse <category> entries into tags
773 $additional_tags = array();
775 if ($use_simplepie) {
777 $additional_tags_src = $item->get_categories();
779 if (is_array($additional_tags_src)) {
780 foreach ($additional_tags_src as $tobj) {
781 array_push($additional_tags, $tobj->get_term());
785 if ($debug_enabled) {
786 _debug("update_rss_feed: category tags:");
787 print_r($additional_tags);
792 $t_ctr = $item['category#'];
795 $additional_tags = array();
796 } else if ($t_ctr > 0) {
797 $additional_tags = array($item['category']);
799 if ($item['category@term']) {
800 array_push($additional_tags, $item['category@term']);
803 for ($i = 0; $i <= $t_ctr; $i++
) {
804 if ($item["category#$i"]) {
805 array_push($additional_tags, $item["category#$i"]);
808 if ($item["category#$i@term"]) {
809 array_push($additional_tags, $item["category#$i@term"]);
814 // parse <dc:subject> elements
816 $t_ctr = $item['dc']['subject#'];
819 array_push($additional_tags, $item['dc']['subject']);
821 for ($i = 0; $i <= $t_ctr; $i++
) {
822 if ($item['dc']["subject#$i"]) {
823 array_push($additional_tags, $item['dc']["subject#$i"]);
829 if ($debug_enabled) {
830 _debug("update_rss_feed: looking for tags [2]...");
834 // <a href="..." rel="tag">Xorg</a>, //
838 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
839 $entry_content_unescaped, $entry_tags);
841 $entry_tags = $entry_tags[1];
843 $entry_tags = array_merge($entry_tags, $additional_tags);
844 $entry_tags = array_unique($entry_tags);
846 for ($i = 0; $i < count($entry_tags); $i++
)
847 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
849 if ($debug_enabled) {
850 _debug("update_rss_feed: unfiltered tags found:");
851 print_r($entry_tags);
856 $entry_content = sanitize_article_content($entry_content);
857 $entry_title = sanitize_article_content($entry_title);
859 if ($debug_enabled) {
860 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
863 db_query($link, "BEGIN");
865 if (db_num_rows($result) == 0) {
867 if ($debug_enabled) {
868 _debug("update_rss_feed: base guid not found");
871 // base post entry does not exist, create it
873 $result = db_query($link,
874 "INSERT INTO ttrss_entries
891 '$entry_timestamp_fmt',
901 // we keep encountering the entry in feeds, so we need to
902 // update date_updated column so that we don't get horrible
903 // dupes when the entry gets purged and reinserted again e.g.
904 // in the case of SLOW SLOW OMG SLOW updating feeds
906 $base_entry_id = db_fetch_result($result, 0, "id");
908 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
909 WHERE id = '$base_entry_id'");
912 // now it should exist, if not - bad luck then
914 $result = db_query($link, "SELECT
915 id,content_hash,no_orig_date,title,
916 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
917 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
921 WHERE guid = '$entry_guid'");
926 if (db_num_rows($result) == 1) {
928 if ($debug_enabled) {
929 _debug("update_rss_feed: base guid found, checking for user record");
932 // this will be used below in update handler
933 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
934 $orig_title = db_fetch_result($result, 0, "title");
935 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
936 $orig_date_updated = strtotime(db_fetch_result($result,
939 $ref_id = db_fetch_result($result, 0, "id");
940 $entry_ref_id = $ref_id;
942 // check for user post link to main table
944 // do we allow duplicate posts with same GUID in different feeds?
945 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
946 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
948 $dupcheck_qpart = "";
951 /* Collect article tags here so we could filter by them: */
953 $article_filters = get_article_filters($filters, $entry_title,
954 $entry_content, $entry_link, $entry_timestamp, $entry_author,
957 if ($debug_enabled) {
958 _debug("update_rss_feed: article filters: ");
959 if (count($article_filters) != 0) {
960 print_r($article_filters);
964 if (find_article_filter($article_filters, "filter")) {
965 db_query($link, "COMMIT"); // close transaction in progress
969 $score = calculate_article_score($article_filters);
971 if ($debug_enabled) {
972 _debug("update_rss_feed: initial score: $score");
975 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
976 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
979 // if ($_REQUEST["xdebug"]) print "$query\n";
981 $result = db_query($link, $query);
983 // okay it doesn't exist - create user entry
984 if (db_num_rows($result) == 0) {
986 if ($debug_enabled) {
987 _debug("update_rss_feed: user record not found, creating...");
990 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
992 $last_read_qpart = 'NULL';
995 $last_read_qpart = 'NOW()';
998 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1004 if (find_article_filter($article_filters, 'publish')) {
1005 $published = 'true';
1007 $published = 'false';
1010 $result = db_query($link,
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 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1015 $last_read_qpart, $marked, $published, '$score', '', '', '')");
1017 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1018 $rss_link = get_self_url_prefix() .
1019 "/public.php?op=rss&id=-2&key=" .
1020 get_feed_access_key($link, -2, false, $owner_uid);
1022 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1024 $pubsub_result = $p->publish_update($rss_link);
1027 $result = db_query($link,
1028 "SELECT int_id FROM ttrss_user_entries WHERE
1029 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1030 feed_id = '$feed' LIMIT 1");
1032 if (db_num_rows($result) == 1) {
1033 $entry_int_id = db_fetch_result($result, 0, "int_id");
1036 if ($debug_enabled) {
1037 _debug("update_rss_feed: user record FOUND");
1040 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1041 $entry_int_id = db_fetch_result($result, 0, "int_id");
1044 if ($debug_enabled) {
1045 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1048 $post_needs_update = false;
1049 $update_insignificant = false;
1051 if ($orig_num_comments != $num_comments) {
1052 $post_needs_update = true;
1053 $update_insignificant = true;
1056 if ($content_hash != $orig_content_hash) {
1057 $post_needs_update = true;
1058 $update_insignificant = false;
1061 if (db_escape_string($orig_title) != $entry_title) {
1062 $post_needs_update = true;
1063 $update_insignificant = false;
1066 // if post needs update, update it and mark all user entries
1067 // linking to this post as updated
1068 if ($post_needs_update) {
1070 if (defined('DAEMON_EXTENDED_DEBUG')) {
1071 _debug("update_rss_feed: post $entry_guid needs update...");
1074 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1076 db_query($link, "UPDATE ttrss_entries
1077 SET title = '$entry_title', content = '$entry_content',
1078 content_hash = '$content_hash',
1079 updated = '$entry_timestamp_fmt',
1080 num_comments = '$num_comments'
1081 WHERE id = '$ref_id'");
1083 if (!$update_insignificant) {
1084 if ($mark_unread_on_update) {
1085 db_query($link, "UPDATE ttrss_user_entries
1086 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1087 } else if ($update_on_checksum_change) {
1088 db_query($link, "UPDATE ttrss_user_entries
1089 SET last_read = null WHERE ref_id = '$ref_id'
1090 AND unread = false");
1096 db_query($link, "COMMIT");
1098 if ($debug_enabled) {
1099 _debug("update_rss_feed: assigning labels...");
1102 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1105 if ($debug_enabled) {
1106 _debug("update_rss_feed: looking for enclosures...");
1111 $enclosures = array();
1113 if ($use_simplepie) {
1114 $encs = $item->get_enclosures();
1116 if (is_array($encs)) {
1117 foreach ($encs as $e) {
1119 $e->link
, $e->type
, $e->length
);
1121 array_push($enclosures, $e_item);
1128 $e_ctr = $item['enclosure#'];
1131 $e_item = array($item['enclosure@url'],
1132 $item['enclosure@type'],
1133 $item['enclosure@length']);
1135 array_push($enclosures, $e_item);
1137 for ($i = 0; $i <= $e_ctr; $i++
) {
1139 if ($item["enclosure#$i@url"]) {
1140 $e_item = array($item["enclosure#$i@url"],
1141 $item["enclosure#$i@type"],
1142 $item["enclosure#$i@length"]);
1143 array_push($enclosures, $e_item);
1149 // can there be many of those? yes -fox
1151 $m_ctr = $item['media']['content#'];
1154 $e_item = array($item['media']['content@url'],
1155 $item['media']['content@medium'],
1156 $item['media']['content@length']);
1158 array_push($enclosures, $e_item);
1160 for ($i = 0; $i <= $m_ctr; $i++
) {
1162 if ($item["media"]["content#$i@url"]) {
1163 $e_item = array($item["media"]["content#$i@url"],
1164 $item["media"]["content#$i@medium"],
1165 $item["media"]["content#$i@length"]);
1166 array_push($enclosures, $e_item);
1174 if ($debug_enabled) {
1175 _debug("update_rss_feed: article enclosures:");
1176 print_r($enclosures);
1179 db_query($link, "BEGIN");
1181 foreach ($enclosures as $enc) {
1182 $enc_url = db_escape_string($enc[0]);
1183 $enc_type = db_escape_string($enc[1]);
1184 $enc_dur = db_escape_string($enc[2]);
1186 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1187 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1189 if (db_num_rows($result) == 0) {
1190 db_query($link, "INSERT INTO ttrss_enclosures
1191 (content_url, content_type, title, duration, post_id) VALUES
1192 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1196 db_query($link, "COMMIT");
1198 // check for manual tags (we have to do it here since they're loaded from filters)
1200 foreach ($article_filters as $f) {
1201 if ($f[0] == "tag") {
1203 $manual_tags = trim_array(explode(",", $f[1]));
1205 foreach ($manual_tags as $tag) {
1206 if (tag_is_valid($tag)) {
1207 array_push($entry_tags, $tag);
1215 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1216 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1218 $filtered_tags = array();
1219 $tags_to_cache = array();
1221 if ($entry_tags && is_array($entry_tags)) {
1222 foreach ($entry_tags as $tag) {
1223 if (array_search($tag, $boring_tags) === false) {
1224 array_push($filtered_tags, $tag);
1229 $filtered_tags = array_unique($filtered_tags);
1231 if ($debug_enabled) {
1232 _debug("update_rss_feed: filtered article tags:");
1233 print_r($filtered_tags);
1236 // Save article tags in the database
1238 if (count($filtered_tags) > 0) {
1240 db_query($link, "BEGIN");
1242 foreach ($filtered_tags as $tag) {
1244 $tag = sanitize_tag($tag);
1245 $tag = db_escape_string($tag);
1247 if (!tag_is_valid($tag)) continue;
1249 $result = db_query($link, "SELECT id FROM ttrss_tags
1250 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1251 owner_uid = '$owner_uid' LIMIT 1");
1253 if ($result && db_num_rows($result) == 0) {
1255 db_query($link, "INSERT INTO ttrss_tags
1256 (owner_uid,tag_name,post_int_id)
1257 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1260 array_push($tags_to_cache, $tag);
1263 /* update the cache */
1265 $tags_to_cache = array_unique($tags_to_cache);
1267 $tags_str = db_escape_string(join(",", $tags_to_cache));
1269 db_query($link, "UPDATE ttrss_user_entries
1270 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1271 AND owner_uid = $owner_uid");
1273 db_query($link, "COMMIT");
1276 if ($debug_enabled) {
1277 _debug("update_rss_feed: article processed");
1281 if (!$last_updated) {
1282 if ($debug_enabled) {
1283 _debug("update_rss_feed: new feed, catching it up...");
1285 catchup_feed($link, $feed, false, $owner_uid);
1288 if ($debug_enabled) {
1289 _debug("purging feed...");
1292 purge_feed($link, $feed, 0, $debug_enabled);
1294 db_query($link, "UPDATE ttrss_feeds
1295 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1297 // db_query($link, "COMMIT");
1301 if ($use_simplepie) {
1302 $error_msg = mb_substr($rss->error(), 0, 250);
1304 $error_msg = mb_substr(magpie_error(), 0, 250);
1307 if ($debug_enabled) {
1308 _debug("update_rss_feed: error fetching feed: $error_msg");
1311 $error_msg = db_escape_string($error_msg);
1314 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1315 last_updated = NOW() WHERE id = '$feed'");
1318 if ($use_simplepie) {
1322 if ($debug_enabled) {
1323 _debug("update_rss_feed: done");
1328 function cache_images($html, $site_url, $debug) {
1329 $cache_dir = CACHE_DIR
. "/images";
1331 libxml_use_internal_errors(true);
1333 $charset_hack = '<head>
1334 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1337 $doc = new DOMDocument();
1338 $doc->loadHTML($charset_hack . $html);
1339 $xpath = new DOMXPath($doc);
1341 $entries = $xpath->query('(//img[@src])');
1343 foreach ($entries as $entry) {
1344 if ($entry->hasAttribute('src')) {
1345 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1347 $local_filename = CACHE_DIR
. "/images/" . sha1($src) . ".png";
1349 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1351 if (!file_exists($local_filename)) {
1352 $file_content = fetch_file_contents($src);
1354 if ($file_content && strlen($file_content) > 1024) {
1355 file_put_contents($local_filename, $file_content);
1359 if (file_exists($local_filename)) {
1360 $entry->setAttribute('src', SELF_URL_PATH
. '/image.php?url=' .
1361 base64_encode($src));
1366 $node = $doc->getElementsByTagName('body')->item(0);
1368 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
1371 function expire_cached_files($debug) {
1372 foreach (array("magpie", "simplepie", "images") as $dir) {
1373 $cache_dir = CACHE_DIR
. "/$dir";
1375 if ($debug) _debug("Expiring $cache_dir");
1379 if (is_writable($cache_dir)) {
1380 $files = glob("$cache_dir/*");
1383 foreach ($files as $file) {
1384 if (time() - filemtime($file) > 86400*7) {
1392 if ($debug) _debug("Removed $num_deleted files.");
1397 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1398 * Returns the url query as associative array
1400 * @param string query
1401 * @return array params
1403 function convertUrlQuery($query) {
1404 $queryParts = explode('&', $query);
1408 foreach ($queryParts as $param) {
1409 $item = explode('=', $param);
1410 $params[$item[0]] = $item[1];