3 date_default_timezone_set('UTC');
4 if (defined('E_DEPRECATED')) {
5 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
7 error_reporting(E_ALL
& ~E_NOTICE
);
10 require_once 'config.php';
12 if (DB_TYPE
== "pgsql") {
13 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 define('THEME_VERSION_REQUIRED', 1.1);
21 * Return available translations names.
24 * @return array A array of available translations.
26 function get_translations() {
28 "auto" => "Detect automatically",
33 "fr_FR" => "Français",
34 "hu_HU" => "Magyar (Hungarian)",
35 "it_IT" => "Italiano",
36 "ja_JP" => "日本語 (Japanese)",
37 "nb_NO" => "Norwegian bokmål",
39 "pt_BR" => "Portuguese/Brazil",
40 "zh_CN" => "Simplified Chinese");
45 require_once "lib/accept-to-gettext.php";
46 require_once "lib/gettext/gettext.inc";
48 function startup_gettext() {
50 # Get locale from Accept-Language header
51 $lang = al2gt(array_keys(get_translations()), "text/html");
53 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
54 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
57 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
58 $lang = $_COOKIE["ttrss_lang"];
61 /* In login action of mobile version */
62 if ($_POST["language"] && defined('MOBILE_VERSION')) {
63 $lang = $_POST["language"];
64 $_COOKIE["ttrss_lang"] = $lang;
68 if (defined('LC_MESSAGES')) {
69 _setlocale(LC_MESSAGES
, $lang);
70 } else if (defined('LC_ALL')) {
71 _setlocale(LC_ALL
, $lang);
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
77 _bindtextdomain("messages", "locale");
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
87 if (defined('MEMCACHE_SERVER')) {
88 $memcache = new Memcache
;
89 $memcache->connect(MEMCACHE_SERVER
, 11211);
92 require_once 'db-prefs.php';
93 require_once 'errors.php';
94 require_once 'version.php';
96 require_once 'lib/phpmailer/class.phpmailer.php';
97 require_once 'lib/sphinxapi.php';
98 require_once 'lib/tmhoauth/tmhOAuth.php';
100 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
101 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
104 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
106 ini_set('user_agent', SELF_USER_AGENT
);
108 require_once "lib/simplepie/simplepie.inc";
109 require_once "lib/magpierss/rss_fetch.inc";
110 require_once 'lib/magpierss/rss_utils.inc';
111 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
112 require_once 'lib/pubsubhubbub/publisher.php';
113 require_once 'lib/pubsubhubbub/subscriber.php';
115 $config = HTMLPurifier_Config
::createDefault();
117 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
119 $config->set('HTML.SafeObject', true);
120 @$config->set('HTML', 'Allowed', $allowed);
121 $config->set('Output.FlashCompat', true);
122 $config->set('Attr.EnableID', true);
123 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
125 $purifier = new HTMLPurifier($config);
128 $utc_tz = new DateTimeZone('UTC');
129 $schema_version = false;
132 * Print a timestamped debug message.
134 * @param string $msg The debug message.
137 function _debug($msg) {
138 $ts = strftime("%H:%M:%S", time());
139 if (function_exists('posix_getpid')) {
140 $ts = "$ts/" . posix_getpid();
142 print "[$ts] $msg\n";
146 * Purge a feed old posts.
148 * @param mixed $link A database connection.
149 * @param mixed $feed_id The id of the purged feed.
150 * @param mixed $purge_interval Olderness of purged posts.
151 * @param boolean $debug Set to True to enable the debug. False by default.
155 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
157 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
161 $result = db_query($link,
162 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
166 if (db_num_rows($result) == 1) {
167 $owner_uid = db_fetch_result($result, 0, "owner_uid");
170 if ($purge_interval == -1 ||
!$purge_interval) {
172 ccache_update($link, $feed_id, $owner_uid);
177 if (!$owner_uid) return;
179 if (FORCE_ARTICLE_PURGE
== 0) {
180 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
183 $purge_unread = true;
184 $purge_interval = FORCE_ARTICLE_PURGE
;
187 if (!$purge_unread) $query_limit = " unread = false AND ";
189 if (DB_TYPE
== "pgsql") {
190 $pg_version = get_pgsql_version($link);
192 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
194 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
195 ttrss_entries.id = ref_id AND
197 feed_id = '$feed_id' AND
199 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
203 $result = db_query($link, "DELETE FROM ttrss_user_entries
205 WHERE ttrss_entries.id = ref_id AND
207 feed_id = '$feed_id' AND
209 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
212 $rows = pg_affected_rows($result);
216 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
217 marked = false AND feed_id = '$feed_id' AND
218 (SELECT date_updated FROM ttrss_entries WHERE
219 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
221 $result = db_query($link, "DELETE FROM ttrss_user_entries
222 USING ttrss_user_entries, ttrss_entries
223 WHERE ttrss_entries.id = ref_id AND
225 feed_id = '$feed_id' AND
227 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
229 $rows = mysql_affected_rows($link);
233 ccache_update($link, $feed_id, $owner_uid);
236 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
238 } // function purge_feed
241 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
243 * @param mixed $link A database connection
244 * @param boolean $do_output Set to true to enable printed output, false by default.
245 * @param integer $limit The maximal number of removed posts.
249 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
251 $random_qpart = sql_random_function();
254 $limit_qpart = "LIMIT $limit";
259 $result = db_query($link,
260 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
261 ORDER BY $random_qpart $limit_qpart");
263 while ($line = db_fetch_assoc($result)) {
265 $feed_id = $line["id"];
266 $purge_interval = $line["purge_interval"];
267 $owner_uid = $line["owner_uid"];
269 if ($purge_interval == 0) {
271 $tmp_result = db_query($link,
272 "SELECT value FROM ttrss_user_prefs WHERE
273 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
275 if (db_num_rows($tmp_result) != 0) {
276 $purge_interval = db_fetch_result($tmp_result, 0, "value");
281 // print "Feed $feed_id: purge interval = $purge_interval\n";
284 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
285 purge_feed($link, $feed_id, $purge_interval, $do_output);
289 purge_orphans($link, $do_output);
291 } // function global_purge_old_posts */
293 function feed_purge_interval($link, $feed_id) {
295 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
296 WHERE id = '$feed_id'");
298 if (db_num_rows($result) == 1) {
299 $purge_interval = db_fetch_result($result, 0, "purge_interval");
300 $owner_uid = db_fetch_result($result, 0, "owner_uid");
302 if ($purge_interval == 0) $purge_interval = get_pref($link,
303 'PURGE_OLD_DAYS', $owner_uid);
305 return $purge_interval;
312 function purge_old_posts($link) {
314 $user_id = $_SESSION["uid"];
316 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
317 WHERE owner_uid = '$user_id'");
319 while ($line = db_fetch_assoc($result)) {
321 $feed_id = $line["id"];
322 $purge_interval = $line["purge_interval"];
324 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
326 if ($purge_interval > 0) {
327 purge_feed($link, $feed_id, $purge_interval);
331 purge_orphans($link);
334 function purge_orphans($link, $do_output = false) {
336 // purge orphaned posts in main content table
337 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
338 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
341 $rows = db_affected_rows($link, $result);
342 _debug("Purged $rows orphaned posts.");
346 function get_feed_update_interval($link, $feed_id) {
347 $result = db_query($link, "SELECT owner_uid, update_interval FROM
348 ttrss_feeds WHERE id = '$feed_id'");
350 if (db_num_rows($result) == 1) {
351 $update_interval = db_fetch_result($result, 0, "update_interval");
352 $owner_uid = db_fetch_result($result, 0, "owner_uid");
354 if ($update_interval != 0) {
355 return $update_interval;
357 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
365 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
366 $login = urlencode($login);
367 $pass = urlencode($pass);
369 if (function_exists('curl_init') && !ini_get("open_basedir")) {
370 $ch = curl_init($url);
372 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
373 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
374 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
375 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
376 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
377 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
378 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
379 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
380 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
383 curl_setopt($ch, CURLOPT_POST
, true);
384 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
388 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
390 $contents = @curl_exec
($ch);
391 if ($contents === false) {
396 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
397 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
400 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
406 if ($login && $pass ){
407 $url_parts = array();
409 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
411 if ($url_parts[1] && $url_parts[2]) {
412 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
416 return @file_get_contents
($url);
422 * Try to determine the favicon URL for a feed.
423 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
424 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
426 * @param string $url A feed or page URL
428 * @return mixed The favicon URL, or false if none was found.
430 function get_favicon_url($url) {
432 $favicon_url = false;
434 if ($html = @fetch_file_contents
($url)) {
436 libxml_use_internal_errors(true);
438 $doc = new DOMDocument();
439 $doc->loadHTML($html);
440 $xpath = new DOMXPath($doc);
442 $base = $xpath->query('/html/head/base');
443 foreach ($base as $b) {
444 $url = $b->getAttribute("href");
448 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
449 if (count($entries) > 0) {
450 foreach ($entries as $entry) {
451 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
458 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
461 } // function get_favicon_url
463 function check_feed_favicon($site_url, $feed, $link) {
464 $favicon_url = get_favicon_url($site_url);
466 # print "FAVICON [$site_url]: $favicon_url\n";
468 $icon_file = ICONS_DIR
. "/$feed.ico";
470 if ($favicon_url && !file_exists($icon_file)) {
471 $contents = fetch_file_contents($favicon_url, "image");
473 $fp = fopen($icon_file, "w");
476 fwrite($fp, $contents);
478 chmod($icon_file, 0644);
484 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
488 /* Update all feeds with the same URL to utilize memcache */
491 $result = db_query($link, "SELECT f1.id
492 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
493 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
495 while ($line = db_fetch_assoc($result)) {
496 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
499 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
503 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false) {
507 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
509 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
513 if ($debug_enabled) {
514 _debug("update_rss_feed: start");
517 if (!$ignore_daemon) {
519 if (DB_TYPE
== "pgsql") {
520 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
522 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
525 $result = db_query($link, "SELECT id,update_interval,auth_login,
526 auth_pass,cache_images,update_method
527 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
531 $result = db_query($link, "SELECT id,update_interval,auth_login,
532 feed_url,auth_pass,cache_images,update_method,last_updated,
533 mark_unread_on_update, owner_uid, update_on_checksum_change,
535 FROM ttrss_feeds WHERE id = '$feed'");
539 if (db_num_rows($result) == 0) {
540 if ($debug_enabled) {
541 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
546 $update_method = db_fetch_result($result, 0, "update_method");
547 $last_updated = db_fetch_result($result, 0, "last_updated");
548 $owner_uid = db_fetch_result($result, 0, "owner_uid");
549 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
550 0, "mark_unread_on_update"));
551 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
552 0, "update_on_checksum_change"));
553 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
555 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
556 WHERE id = '$feed'");
558 $auth_login = db_fetch_result($result, 0, "auth_login");
559 $auth_pass = db_fetch_result($result, 0, "auth_pass");
561 if ($update_method == 0)
562 $update_method = DEFAULT_UPDATE_METHOD +
1;
568 if ($update_method == 2)
569 $use_simplepie = true;
571 $use_simplepie = false;
573 if ($debug_enabled) {
574 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
577 if ($update_method == 1) {
578 $auth_login = urlencode($auth_login);
579 $auth_pass = urlencode($auth_pass);
582 $update_interval = db_fetch_result($result, 0, "update_interval");
583 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
584 $fetch_url = db_fetch_result($result, 0, "feed_url");
586 if ($update_interval < 0) { return false; }
588 $feed = db_escape_string($feed);
590 if ($auth_login && $auth_pass ){
591 $url_parts = array();
592 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
594 if ($url_parts[1] && $url_parts[2]) {
595 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
600 if ($debug_enabled) {
601 _debug("update_rss_feed: fetching [$fetch_url]...");
604 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
606 if ($memcache && $obj = $memcache->get($obj_id)) {
608 if ($debug_enabled) {
609 _debug("update_rss_feed: data found in memcache.");
616 if ($update_method == 3) {
617 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
618 } else if ($update_method == 1) {
620 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
621 define('MAGPIE_CACHE_ON', !$no_cache);
622 define('MAGPIE_FETCH_TIME_OUT', 60);
623 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
625 $rss = @fetch_rss
($fetch_url);
627 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
629 if (!is_dir($simplepie_cache_dir)) {
630 mkdir($simplepie_cache_dir);
633 $rss = new SimplePie();
634 $rss->set_useragent(SELF_USER_AGENT
);
635 # $rss->set_timeout(10);
636 $rss->set_feed_url($fetch_url);
637 $rss->set_output_encoding('UTF-8');
639 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
641 if ($debug_enabled) {
642 _debug("enabling image cache");
645 $rss->set_image_handler("image.php", 'i');
648 if ($debug_enabled) {
649 _debug("feed update interval (sec): " .
650 get_feed_update_interval($link, $feed)*60);
653 $rss->enable_cache(!$no_cache);
656 $rss->set_cache_location($simplepie_cache_dir);
657 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
663 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
668 if ($debug_enabled) {
669 _debug("update_rss_feed: fetch done, parsing...");
672 $feed = db_escape_string($feed);
674 if ($update_method == 2) {
675 $fetch_ok = !$rss->error();
682 if ($debug_enabled) {
683 _debug("update_rss_feed: processing feed data...");
686 // db_query($link, "BEGIN");
688 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
689 FROM ttrss_feeds WHERE id = '$feed'");
691 $registered_title = db_fetch_result($result, 0, "title");
692 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
693 $orig_site_url = db_fetch_result($result, 0, "site_url");
695 $owner_uid = db_fetch_result($result, 0, "owner_uid");
697 if ($use_simplepie) {
698 $site_url = $rss->get_link();
700 $site_url = $rss->channel
["link"];
703 $site_url = rewrite_relative_url($fetch_url, $site_url);
705 if ($debug_enabled) {
706 _debug("update_rss_feed: checking favicon...");
709 check_feed_favicon($site_url, $feed, $link);
711 if (!$registered_title ||
$registered_title == "[Unknown]") {
713 if ($use_simplepie) {
714 $feed_title = db_escape_string($rss->get_title());
716 $feed_title = db_escape_string($rss->channel
["title"]);
719 if ($debug_enabled) {
720 _debug("update_rss_feed: registering title: $feed_title");
723 db_query($link, "UPDATE ttrss_feeds SET
724 title = '$feed_title' WHERE id = '$feed'");
727 // weird, weird Magpie
728 if (!$use_simplepie) {
729 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
732 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
733 db_query($link, "UPDATE ttrss_feeds SET
734 site_url = '$site_url' WHERE id = '$feed'");
737 // print "I: " . $rss->channel["image"]["url"];
739 if (!$use_simplepie) {
740 $icon_url = db_escape_string($rss->image
["url"]);
742 $icon_url = db_escape_string($rss->get_image_url());
745 $icon_url = substr($icon_url, 0, 250);
747 if ($icon_url && $orig_icon_url != $icon_url) {
748 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
751 if ($debug_enabled) {
752 _debug("update_rss_feed: loading filters...");
755 $filters = load_filters($link, $feed, $owner_uid);
757 // if ($debug_enabled) {
758 // print_r($filters);
761 if ($use_simplepie) {
762 $iterator = $rss->get_items();
764 $iterator = $rss->items
;
765 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
766 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
769 if (!is_array($iterator)) {
770 /* db_query($link, "UPDATE ttrss_feeds
771 SET last_error = 'Parse error: can\'t find any articles.'
772 WHERE id = '$feed'"); */
774 // clear any errors and mark feed as updated if fetched okay
775 // even if it's blank
777 if ($debug_enabled) {
778 _debug("update_rss_feed: entry iterator is not an array, no articles?");
781 db_query($link, "UPDATE ttrss_feeds
782 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
784 return; // no articles
787 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
789 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
791 $feed_hub_url = false;
792 if ($use_simplepie) {
793 $links = $rss->get_links('hub');
795 if ($links && is_array($links)) {
796 foreach ($links as $l) {
803 $atom = $rss->channel
['atom'];
806 if ($atom['link@rel'] == 'hub') {
807 $feed_hub_url = $atom['link@href'];
810 if (!$feed_hub_url && $atom['link#'] > 1) {
811 for ($i = 2; $i <= $atom['link#']; $i++
) {
812 if ($atom["link#$i@rel"] == 'hub') {
813 $feed_hub_url = $atom["link#$i@href"];
819 $feed_hub_url = $rss->channel
['link_hub'];
823 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
825 if ($feed_hub_url && function_exists('curl_init') &&
826 !ini_get("open_basedir")) {
828 $callback_url = get_self_url_prefix() .
829 "/backend.php?op=pubsub&id=$feed";
831 $s = new Subscriber($feed_hub_url, $callback_url);
833 $rc = $s->subscribe($fetch_url);
836 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
838 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
839 WHERE id = '$feed'");
843 if ($debug_enabled) {
844 _debug("update_rss_feed: processing articles...");
847 foreach ($iterator as $item) {
849 if ($_REQUEST['xdebug'] == 2) {
853 if ($use_simplepie) {
854 $entry_guid = $item->get_id();
855 if (!$entry_guid) $entry_guid = $item->get_link();
856 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
860 $entry_guid = $item["id"];
862 if (!$entry_guid) $entry_guid = $item["guid"];
863 if (!$entry_guid) $entry_guid = $item["about"];
864 if (!$entry_guid) $entry_guid = $item["link"];
865 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
868 if ($debug_enabled) {
869 _debug("update_rss_feed: guid $entry_guid");
872 if (!$entry_guid) continue;
874 $entry_timestamp = "";
876 if ($use_simplepie) {
877 $entry_timestamp = strtotime($item->get_date());
879 $rss_2_date = $item['pubdate'];
880 $rss_1_date = $item['dc']['date'];
881 $atom_date = $item['issued'];
882 if (!$atom_date) $atom_date = $item['updated'];
884 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
885 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
886 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
890 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
891 $entry_timestamp = time();
892 $no_orig_date = 'true';
894 $no_orig_date = 'false';
897 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
899 if ($debug_enabled) {
900 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
903 if ($use_simplepie) {
904 $entry_title = $item->get_title();
906 $entry_title = trim(strip_tags($item["title"]));
909 if ($use_simplepie) {
910 $entry_link = $item->get_link();
912 // strange Magpie workaround
913 $entry_link = $item["link_"];
914 if (!$entry_link) $entry_link = $item["link"];
917 $entry_link = rewrite_relative_url($site_url, $entry_link);
919 if ($debug_enabled) {
920 _debug("update_rss_feed: title $entry_title");
921 _debug("update_rss_feed: link $entry_link");
924 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
926 $entry_link = strip_tags($entry_link);
928 if ($use_simplepie) {
929 $entry_content = $item->get_content();
930 if (!$entry_content) $entry_content = $item->get_description();
932 $entry_content = $item["content:escaped"];
934 if (!$entry_content) $entry_content = $item["content:encoded"];
935 if (!$entry_content) $entry_content = $item["content"]["encoded"];
936 if (!$entry_content) $entry_content = $item["content"];
938 // Magpie bugs are getting ridiculous
939 if (trim($entry_content) == "Array") $entry_content = false;
941 if (!$entry_content) $entry_content = $item["atom_content"];
942 if (!$entry_content) $entry_content = $item["summary"];
944 if (!$entry_content ||
945 strlen($entry_content) < strlen($item["description"])) {
946 $entry_content = $item["description"];
950 if (is_array($entry_content)) {
951 $entry_content = $entry_content["encoded"];
952 if (!$entry_content) $entry_content = $entry_content["escaped"];
956 if ($_REQUEST["xdebug"] == 2) {
957 print "update_rss_feed: content: ";
958 print_r(htmlspecialchars($entry_content));
961 $entry_content_unescaped = $entry_content;
963 if ($use_simplepie) {
964 $entry_comments = strip_tags($item->data
["comments"]);
965 if ($item->get_author()) {
966 $entry_author_item = $item->get_author();
967 $entry_author = $entry_author_item->get_name();
968 if (!$entry_author) $entry_author = $entry_author_item->get_email();
970 $entry_author = db_escape_string($entry_author);
973 $entry_comments = strip_tags($item["comments"]);
975 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
977 if ($item['author']) {
979 if (is_array($item['author'])) {
981 if (!$entry_author) {
982 $entry_author = db_escape_string(strip_tags($item['author']['name']));
985 if (!$entry_author) {
986 $entry_author = db_escape_string(strip_tags($item['author']['email']));
990 if (!$entry_author) {
991 $entry_author = db_escape_string(strip_tags($item['author']));
996 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
998 $entry_guid = db_escape_string(strip_tags($entry_guid));
999 $entry_guid = mb_substr($entry_guid, 0, 250);
1001 $result = db_query($link, "SELECT id FROM ttrss_entries
1002 WHERE guid = '$entry_guid'");
1004 $entry_content = db_escape_string($entry_content, false);
1006 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
1008 $entry_title = db_escape_string($entry_title);
1009 $entry_link = db_escape_string($entry_link);
1010 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
1011 $entry_author = mb_substr($entry_author, 0, 250);
1013 if ($use_simplepie) {
1014 $num_comments = 0; #FIXME#
1016 $num_comments = db_escape_string($item["slash"]["comments"]);
1019 if (!$num_comments) $num_comments = 0;
1021 if ($debug_enabled) {
1022 _debug("update_rss_feed: looking for tags [1]...");
1025 // parse <category> entries into tags
1027 $additional_tags = array();
1029 if ($use_simplepie) {
1031 $additional_tags_src = $item->get_categories();
1033 if (is_array($additional_tags_src)) {
1034 foreach ($additional_tags_src as $tobj) {
1035 array_push($additional_tags, $tobj->get_term());
1039 if ($debug_enabled) {
1040 _debug("update_rss_feed: category tags:");
1041 print_r($additional_tags);
1046 $t_ctr = $item['category#'];
1049 $additional_tags = array();
1050 } else if ($t_ctr > 0) {
1051 $additional_tags = array($item['category']);
1053 if ($item['category@term']) {
1054 array_push($additional_tags, $item['category@term']);
1057 for ($i = 0; $i <= $t_ctr; $i++
) {
1058 if ($item["category#$i"]) {
1059 array_push($additional_tags, $item["category#$i"]);
1062 if ($item["category#$i@term"]) {
1063 array_push($additional_tags, $item["category#$i@term"]);
1068 // parse <dc:subject> elements
1070 $t_ctr = $item['dc']['subject#'];
1073 array_push($additional_tags, $item['dc']['subject']);
1075 for ($i = 0; $i <= $t_ctr; $i++
) {
1076 if ($item['dc']["subject#$i"]) {
1077 array_push($additional_tags, $item['dc']["subject#$i"]);
1083 if ($debug_enabled) {
1084 _debug("update_rss_feed: looking for tags [2]...");
1088 // <a href="..." rel="tag">Xorg</a>, //
1092 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1093 $entry_content_unescaped, $entry_tags);
1095 $entry_tags = $entry_tags[1];
1097 $entry_tags = array_merge($entry_tags, $additional_tags);
1098 $entry_tags = array_unique($entry_tags);
1100 for ($i = 0; $i < count($entry_tags); $i++
)
1101 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1103 if ($debug_enabled) {
1104 _debug("update_rss_feed: unfiltered tags found:");
1105 print_r($entry_tags);
1110 $entry_content = sanitize_article_content($entry_content);
1111 $entry_title = sanitize_article_content($entry_title);
1113 if ($debug_enabled) {
1114 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1117 db_query($link, "BEGIN");
1119 if (db_num_rows($result) == 0) {
1121 if ($debug_enabled) {
1122 _debug("update_rss_feed: base guid not found");
1125 // base post entry does not exist, create it
1127 $result = db_query($link,
1128 "INSERT INTO ttrss_entries
1145 '$entry_timestamp_fmt',
1155 // we keep encountering the entry in feeds, so we need to
1156 // update date_updated column so that we don't get horrible
1157 // dupes when the entry gets purged and reinserted again e.g.
1158 // in the case of SLOW SLOW OMG SLOW updating feeds
1160 $base_entry_id = db_fetch_result($result, 0, "id");
1162 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1163 WHERE id = '$base_entry_id'");
1166 // now it should exist, if not - bad luck then
1168 $result = db_query($link, "SELECT
1169 id,content_hash,no_orig_date,title,
1170 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1171 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1175 WHERE guid = '$entry_guid'");
1180 if (db_num_rows($result) == 1) {
1182 if ($debug_enabled) {
1183 _debug("update_rss_feed: base guid found, checking for user record");
1186 // this will be used below in update handler
1187 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1188 $orig_title = db_fetch_result($result, 0, "title");
1189 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1190 $orig_date_updated = strtotime(db_fetch_result($result,
1191 0, "date_updated"));
1193 $ref_id = db_fetch_result($result, 0, "id");
1194 $entry_ref_id = $ref_id;
1196 // check for user post link to main table
1198 // do we allow duplicate posts with same GUID in different feeds?
1199 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1200 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1202 $dupcheck_qpart = "";
1205 /* Collect article tags here so we could filter by them: */
1207 $article_filters = get_article_filters($filters, $entry_title,
1208 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1211 if ($debug_enabled) {
1212 _debug("update_rss_feed: article filters: ");
1213 if (count($article_filters) != 0) {
1214 print_r($article_filters);
1218 if (find_article_filter($article_filters, "filter")) {
1219 db_query($link, "COMMIT"); // close transaction in progress
1223 $score = calculate_article_score($article_filters);
1225 if ($debug_enabled) {
1226 _debug("update_rss_feed: initial score: $score");
1229 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1230 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1233 // if ($_REQUEST["xdebug"]) print "$query\n";
1235 $result = db_query($link, $query);
1237 // okay it doesn't exist - create user entry
1238 if (db_num_rows($result) == 0) {
1240 if ($debug_enabled) {
1241 _debug("update_rss_feed: user record not found, creating...");
1244 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1246 $last_read_qpart = 'NULL';
1249 $last_read_qpart = 'NOW()';
1252 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1258 if (find_article_filter($article_filters, 'publish')) {
1259 $published = 'true';
1261 $published = 'false';
1264 $result = db_query($link,
1265 "INSERT INTO ttrss_user_entries
1266 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1267 published, score, tag_cache, label_cache)
1268 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1269 $last_read_qpart, $marked, $published, '$score', '', '')");
1271 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1272 $rss_link = get_self_url_prefix() .
1273 "/backend.php?op=rss&id=-2&key=" .
1274 get_feed_access_key($link, -2, false, $owner_uid);
1276 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1278 $pubsub_result = $p->publish_update($rss_link);
1281 $result = db_query($link,
1282 "SELECT int_id FROM ttrss_user_entries WHERE
1283 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1284 feed_id = '$feed' LIMIT 1");
1286 if (db_num_rows($result) == 1) {
1287 $entry_int_id = db_fetch_result($result, 0, "int_id");
1290 if ($debug_enabled) {
1291 _debug("update_rss_feed: user record FOUND");
1294 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1295 $entry_int_id = db_fetch_result($result, 0, "int_id");
1298 if ($debug_enabled) {
1299 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1302 $post_needs_update = false;
1303 $update_insignificant = false;
1305 if ($orig_num_comments != $num_comments) {
1306 $post_needs_update = true;
1307 $update_insignificant = true;
1310 if ($content_hash != $orig_content_hash) {
1311 $post_needs_update = true;
1312 $update_insignificant = false;
1315 if (db_escape_string($orig_title) != $entry_title) {
1316 $post_needs_update = true;
1317 $update_insignificant = false;
1320 // if post needs update, update it and mark all user entries
1321 // linking to this post as updated
1322 if ($post_needs_update) {
1324 if (defined('DAEMON_EXTENDED_DEBUG')) {
1325 _debug("update_rss_feed: post $entry_guid needs update...");
1328 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1330 db_query($link, "UPDATE ttrss_entries
1331 SET title = '$entry_title', content = '$entry_content',
1332 content_hash = '$content_hash',
1333 updated = '$entry_timestamp_fmt',
1334 num_comments = '$num_comments'
1335 WHERE id = '$ref_id'");
1337 if (!$update_insignificant) {
1338 if ($mark_unread_on_update) {
1339 db_query($link, "UPDATE ttrss_user_entries
1340 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1341 } else if ($update_on_checksum_change) {
1342 db_query($link, "UPDATE ttrss_user_entries
1343 SET last_read = null WHERE ref_id = '$ref_id'
1344 AND unread = false");
1350 db_query($link, "COMMIT");
1352 if ($debug_enabled) {
1353 _debug("update_rss_feed: assigning labels...");
1356 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1359 if ($debug_enabled) {
1360 _debug("update_rss_feed: looking for enclosures...");
1365 $enclosures = array();
1367 if ($use_simplepie) {
1368 $encs = $item->get_enclosures();
1370 if (is_array($encs)) {
1371 foreach ($encs as $e) {
1373 $e->link
, $e->type
, $e->length
);
1375 array_push($enclosures, $e_item);
1382 $e_ctr = $item['enclosure#'];
1385 $e_item = array($item['enclosure@url'],
1386 $item['enclosure@type'],
1387 $item['enclosure@length']);
1389 array_push($enclosures, $e_item);
1391 for ($i = 0; $i <= $e_ctr; $i++
) {
1393 if ($item["enclosure#$i@url"]) {
1394 $e_item = array($item["enclosure#$i@url"],
1395 $item["enclosure#$i@type"],
1396 $item["enclosure#$i@length"]);
1397 array_push($enclosures, $e_item);
1403 // can there be many of those? yes -fox
1405 $m_ctr = $item['media']['content#'];
1408 $e_item = array($item['media']['content@url'],
1409 $item['media']['content@medium'],
1410 $item['media']['content@length']);
1412 array_push($enclosures, $e_item);
1414 for ($i = 0; $i <= $m_ctr; $i++
) {
1416 if ($item["media"]["content#$i@url"]) {
1417 $e_item = array($item["media"]["content#$i@url"],
1418 $item["media"]["content#$i@medium"],
1419 $item["media"]["content#$i@length"]);
1420 array_push($enclosures, $e_item);
1428 if ($debug_enabled) {
1429 _debug("update_rss_feed: article enclosures:");
1430 print_r($enclosures);
1433 db_query($link, "BEGIN");
1435 foreach ($enclosures as $enc) {
1436 $enc_url = db_escape_string($enc[0]);
1437 $enc_type = db_escape_string($enc[1]);
1438 $enc_dur = db_escape_string($enc[2]);
1440 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1441 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1443 if (db_num_rows($result) == 0) {
1444 db_query($link, "INSERT INTO ttrss_enclosures
1445 (content_url, content_type, title, duration, post_id) VALUES
1446 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1450 db_query($link, "COMMIT");
1452 // check for manual tags (we have to do it here since they're loaded from filters)
1454 foreach ($article_filters as $f) {
1455 if ($f[0] == "tag") {
1457 $manual_tags = trim_array(explode(",", $f[1]));
1459 foreach ($manual_tags as $tag) {
1460 if (tag_is_valid($tag)) {
1461 array_push($entry_tags, $tag);
1469 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1470 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1472 $filtered_tags = array();
1473 $tags_to_cache = array();
1475 if ($entry_tags && is_array($entry_tags)) {
1476 foreach ($entry_tags as $tag) {
1477 if (array_search($tag, $boring_tags) === false) {
1478 array_push($filtered_tags, $tag);
1483 $filtered_tags = array_unique($filtered_tags);
1485 if ($debug_enabled) {
1486 _debug("update_rss_feed: filtered article tags:");
1487 print_r($filtered_tags);
1490 // Save article tags in the database
1492 if (count($filtered_tags) > 0) {
1494 db_query($link, "BEGIN");
1496 foreach ($filtered_tags as $tag) {
1498 $tag = sanitize_tag($tag);
1499 $tag = db_escape_string($tag);
1501 if (!tag_is_valid($tag)) continue;
1503 $result = db_query($link, "SELECT id FROM ttrss_tags
1504 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1505 owner_uid = '$owner_uid' LIMIT 1");
1507 if ($result && db_num_rows($result) == 0) {
1509 db_query($link, "INSERT INTO ttrss_tags
1510 (owner_uid,tag_name,post_int_id)
1511 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1514 array_push($tags_to_cache, $tag);
1517 /* update the cache */
1519 $tags_to_cache = array_unique($tags_to_cache);
1521 $tags_str = db_escape_string(join(",", $tags_to_cache));
1523 db_query($link, "UPDATE ttrss_user_entries
1524 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1525 AND owner_uid = $owner_uid");
1527 db_query($link, "COMMIT");
1530 if ($debug_enabled) {
1531 _debug("update_rss_feed: article processed");
1535 if (!$last_updated) {
1536 if ($debug_enabled) {
1537 _debug("update_rss_feed: new feed, catching it up...");
1539 catchup_feed($link, $feed, false, $owner_uid);
1542 if ($debug_enabled) {
1543 _debug("purging feed...");
1546 purge_feed($link, $feed, 0, $debug_enabled);
1548 db_query($link, "UPDATE ttrss_feeds
1549 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1551 // db_query($link, "COMMIT");
1555 if ($use_simplepie) {
1556 $error_msg = mb_substr($rss->error(), 0, 250);
1558 $error_msg = mb_substr(magpie_error(), 0, 250);
1561 if ($debug_enabled) {
1562 _debug("update_rss_feed: error fetching feed: $error_msg");
1565 $error_msg = db_escape_string($error_msg);
1568 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1569 last_updated = NOW() WHERE id = '$feed'");
1572 if ($use_simplepie) {
1576 if ($debug_enabled) {
1577 _debug("update_rss_feed: done");
1582 function print_select($id, $default, $values, $attributes = "") {
1583 print "<select name=\"$id\" id=\"$id\" $attributes>";
1584 foreach ($values as $v) {
1586 $sel = "selected=\"1\"";
1590 print "<option value=\"$v\" $sel>$v</option>";
1595 function print_select_hash($id, $default, $values, $attributes = "") {
1596 print "<select name=\"$id\" id='$id' $attributes>";
1597 foreach (array_keys($values) as $v) {
1599 $sel = 'selected="selected"';
1603 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1609 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1612 if ($filters["title"]) {
1613 foreach ($filters["title"] as $filter) {
1614 $reg_exp = $filter["reg_exp"];
1615 $inverse = $filter["inverse"];
1616 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1617 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1619 array_push($matches, array($filter["action"], $filter["action_param"]));
1624 if ($filters["content"]) {
1625 foreach ($filters["content"] as $filter) {
1626 $reg_exp = $filter["reg_exp"];
1627 $inverse = $filter["inverse"];
1629 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1630 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1632 array_push($matches, array($filter["action"], $filter["action_param"]));
1637 if ($filters["both"]) {
1638 foreach ($filters["both"] as $filter) {
1639 $reg_exp = $filter["reg_exp"];
1640 $inverse = $filter["inverse"];
1643 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1644 array_push($matches, array($filter["action"], $filter["action_param"]));
1647 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1648 array_push($matches, array($filter["action"], $filter["action_param"]));
1654 if ($filters["link"]) {
1655 $reg_exp = $filter["reg_exp"];
1656 foreach ($filters["link"] as $filter) {
1657 $reg_exp = $filter["reg_exp"];
1658 $inverse = $filter["inverse"];
1660 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1661 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1663 array_push($matches, array($filter["action"], $filter["action_param"]));
1668 if ($filters["date"]) {
1669 $reg_exp = $filter["reg_exp"];
1670 foreach ($filters["date"] as $filter) {
1671 $date_modifier = $filter["filter_param"];
1672 $inverse = $filter["inverse"];
1673 $check_timestamp = strtotime($filter["reg_exp"]);
1675 # no-op when timestamp doesn't parse to prevent misfires
1677 if ($check_timestamp) {
1680 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1681 $date_modifier == "after" && $timestamp > $check_timestamp) {
1685 if ($inverse) $match_ok = !$match_ok;
1688 array_push($matches, array($filter["action"], $filter["action_param"]));
1694 if ($filters["author"]) {
1695 foreach ($filters["author"] as $filter) {
1696 $reg_exp = $filter["reg_exp"];
1697 $inverse = $filter["inverse"];
1698 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1699 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1701 array_push($matches, array($filter["action"], $filter["action_param"]));
1706 if ($filters["tag"]) {
1708 $tag_string = join(",", $tags);
1710 foreach ($filters["tag"] as $filter) {
1711 $reg_exp = $filter["reg_exp"];
1712 $inverse = $filter["inverse"];
1714 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1715 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1717 array_push($matches, array($filter["action"], $filter["action_param"]));
1726 function find_article_filter($filters, $filter_name) {
1727 foreach ($filters as $f) {
1728 if ($f[0] == $filter_name) {
1735 function calculate_article_score($filters) {
1738 foreach ($filters as $f) {
1739 if ($f[0] == "score") {
1746 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1747 foreach ($filters as $f) {
1748 if ($f[0] == "label") {
1749 label_add_article($link, $id, $f[1], $owner_uid);
1754 function getmicrotime() {
1755 list($usec, $sec) = explode(" ",microtime());
1756 return ((float)$usec +
(float)$sec);
1759 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1760 foreach ($values as $v) {
1767 if ($v == $true_is) {
1768 $sel .= " value=\"1\"";
1770 $sel .= " value=\"0\"";
1773 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1774 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1779 function initialize_user_prefs($link, $uid, $profile = false) {
1781 $uid = db_escape_string($uid);
1785 $profile_qpart = "AND profile IS NULL";
1787 $profile_qpart = "AND profile = '$profile'";
1790 if (get_schema_version($link) < 63) $profile_qpart = "";
1792 db_query($link, "BEGIN");
1794 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1796 $u_result = db_query($link, "SELECT pref_name
1797 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1799 $active_prefs = array();
1801 while ($line = db_fetch_assoc($u_result)) {
1802 array_push($active_prefs, $line["pref_name"]);
1805 while ($line = db_fetch_assoc($result)) {
1806 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1807 // print "adding " . $line["pref_name"] . "<br>";
1809 if (get_schema_version($link) < 63) {
1810 db_query($link, "INSERT INTO ttrss_user_prefs
1811 (owner_uid,pref_name,value) VALUES
1812 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1815 db_query($link, "INSERT INTO ttrss_user_prefs
1816 (owner_uid,pref_name,value, profile) VALUES
1817 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1823 db_query($link, "COMMIT");
1827 function lookup_user_id($link, $user) {
1829 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$user'");
1831 if (db_num_rows($result) == 1) {
1832 return db_fetch_result($result, 0, "id");
1838 /* function http_authenticate_user($link) {
1839 if (!$_SERVER["PHP_AUTH_USER"]) {
1841 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1842 header('HTTP/1.0 401 Unauthorized');
1846 $auth_result = authenticate_user($link,
1847 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1849 if (!$auth_result) {
1850 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1851 header('HTTP/1.0 401 Unauthorized');
1859 function get_ssl_certificate_id() {
1860 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1861 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1862 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1863 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1864 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1869 function get_login_by_ssl_certificate($link) {
1871 $cert_serial = db_escape_string(get_ssl_certificate_id());
1874 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1875 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1876 owner_uid = ttrss_users.id");
1878 if (db_num_rows($result) != 0) {
1879 return db_escape_string(db_fetch_result($result, 0, "login"));
1886 function get_remote_user($link) {
1888 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
1889 return db_escape_string($_SERVER["REMOTE_USER"]);
1892 return db_escape_string(get_login_by_ssl_certificate($link));
1895 function get_remote_fakepass($link) {
1896 if (get_remote_user($link))
1902 function authenticate_user($link, $login, $password, $force_auth = false) {
1904 if (!SINGLE_USER_MODE
) {
1906 $pwd_hash1 = encrypt_password($password);
1907 $pwd_hash2 = encrypt_password($password, $login);
1908 $login = db_escape_string($login);
1910 $remote_user = get_remote_user($link);
1912 if ($remote_user && $remote_user == $login && $login != "admin") {
1914 $login = $remote_user;
1916 $query = "SELECT id,login,access_level,pwd_hash
1917 FROM ttrss_users WHERE
1920 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1921 && $_SERVER["REMOTE_USER"]) {
1922 $result = db_query($link, $query);
1925 if (db_num_rows($result) == 0) {
1926 $query = "INSERT INTO ttrss_users
1927 (login,access_level,last_login,created)
1928 VALUES ('$login', 0, null, NOW())";
1929 db_query($link, $query);
1934 $query = "SELECT id,login,access_level,pwd_hash
1935 FROM ttrss_users WHERE
1936 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1937 pwd_hash = '$pwd_hash2')";
1940 $result = db_query($link, $query);
1942 if (db_num_rows($result) == 1) {
1943 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1944 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1945 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1947 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1951 // LemonLDAP can send user informations via HTTP HEADER
1952 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
1954 if ($_SERVER['HTTP_USER_NAME']){
1955 $fullname = db_escape_string($_SERVER['HTTP_USER_NAME']);
1956 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1960 if ($_SERVER['HTTP_USER_MAIL']){
1961 $email = db_escape_string($_SERVER['HTTP_USER_MAIL']);
1962 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1967 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1968 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1970 $_SESSION["last_version_check"] = time();
1972 initialize_user_prefs($link, $_SESSION["uid"]);
1981 $_SESSION["uid"] = 1;
1982 $_SESSION["name"] = "admin";
1984 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1986 initialize_user_prefs($link, $_SESSION["uid"]);
1992 function make_password($length = 8) {
1995 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1999 while ($i < $length) {
2000 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
2002 if (!strstr($password, $char)) {
2010 // this is called after user is created to initialize default feeds, labels
2013 // user preferences are checked on every login, not here
2015 function initialize_user($link, $uid) {
2017 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2018 values ('$uid', 'Tiny Tiny RSS: New Releases',
2019 'http://tt-rss.org/releases.rss')");
2021 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2022 values ('$uid', 'Tiny Tiny RSS: Forum',
2023 'http://tt-rss.org/forum/rss.php')");
2026 function logout_user() {
2028 if (isset($_COOKIE[session_name()])) {
2029 setcookie(session_name(), '', time()-42000, '/');
2033 function get_script_urlpath() {
2034 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
2037 function validate_session($link) {
2038 if (SINGLE_USER_MODE
) return true;
2040 $check_ip = $_SESSION['ip_address'];
2042 switch (SESSION_CHECK_ADDRESS
) {
2047 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2050 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
2051 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2055 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
2056 $_SESSION["login_error_msg"] =
2057 __("Session failed to validate (incorrect IP)");
2061 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
2064 if ($_SESSION["uid"]) {
2066 $result = db_query($link,
2067 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
2069 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
2071 if ($pwd_hash != $_SESSION["pwd_hash"]) {
2076 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
2078 //print_r($_SESSION);
2080 if (time() > $_SESSION["cookie_lifetime"]) {
2088 function login_sequence($link, $mobile = false) {
2089 if (!SINGLE_USER_MODE
) {
2091 $login_action = $_POST["login_action"];
2093 # try to authenticate user if called from login form
2094 if ($login_action == "do_login") {
2095 $login = $_POST["login"];
2096 $password = $_POST["password"];
2097 $remember_me = $_POST["remember_me"];
2099 if (authenticate_user($link, $login, $password)) {
2100 $_POST["password"] = "";
2102 $_SESSION["language"] = $_POST["language"];
2103 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2104 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
2106 if ($_POST["profile"]) {
2108 $profile = db_escape_string($_POST["profile"]);
2110 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2111 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2113 if (db_num_rows($result) != 0) {
2114 $_SESSION["profile"] = $profile;
2115 $_SESSION["prefs_cache"] = array();
2119 if ($_REQUEST['return']) {
2120 header("Location: " . $_REQUEST['return']);
2122 header("Location: " . $_SERVER["REQUEST_URI"]);
2129 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2133 if (!$_SESSION["uid"] ||
!validate_session($link)) {
2135 if (get_remote_user($link) && AUTO_LOGIN
) {
2136 authenticate_user($link, get_remote_user($link), null);
2137 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2139 render_login_form($link, $mobile);
2140 //header("Location: login.php");
2144 /* bump login timestamp */
2145 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2148 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
2149 setcookie("ttrss_lang", $_SESSION["language"],
2150 time() + SESSION_COOKIE_LIFETIME
);
2155 return authenticate_user($link, "admin", null);
2159 function truncate_string($str, $max_len, $suffix = '…') {
2160 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2161 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2167 function theme_image($link, $filename) {
2169 $theme_path = get_user_theme_path($link);
2171 if ($theme_path && is_file($theme_path.$filename)) {
2172 return $theme_path.$filename;
2181 function get_user_theme($link) {
2183 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2184 $theme_name = get_pref($link, "_THEME_ID");
2185 if (is_dir("themes/$theme_name")) {
2196 function get_user_theme_path($link) {
2199 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2200 $theme_name = get_pref($link, "_THEME_ID");
2202 if ($theme_name && is_dir("themes/$theme_name")) {
2203 $theme_path = "themes/$theme_name/";
2212 if (is_file("$theme_path/theme.ini")) {
2213 $ini = parse_ini_file("$theme_path/theme.ini", true);
2214 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2222 function get_user_theme_options($link) {
2223 $t = get_user_theme_path($link);
2226 if (is_file("$t/theme.ini")) {
2227 $ini = parse_ini_file("$t/theme.ini", true);
2228 if ($ini['theme']['version']) {
2229 return $ini['theme']['options'];
2236 function print_theme_includes($link) {
2238 $t = get_user_theme_path($link);
2242 print "<link rel=\"stylesheet\" type=\"text/css\"
2243 href=\"$t/theme.css?$time \">";
2244 if (file_exists("$t/theme.js")) {
2245 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2251 function get_all_themes() {
2252 $themes = glob("themes/*");
2258 foreach ($themes as $t) {
2259 if (is_file("$t/theme.ini")) {
2260 $ini = parse_ini_file("$t/theme.ini", true);
2261 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2262 !$ini['theme']['disabled']) {
2264 $entry["path"] = $t;
2265 $entry["base"] = basename($t);
2266 $entry["name"] = $ini['theme']['name'];
2267 $entry["version"] = $ini['theme']['version'];
2268 $entry["author"] = $ini['theme']['author'];
2269 $entry["options"] = $ini['theme']['options'];
2270 array_push($rv, $entry);
2278 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2281 $source_tz = new DateTimeZone($source_tz);
2282 } catch (Exception
$e) {
2283 $source_tz = new DateTimeZone('UTC');
2287 $dest_tz = new DateTimeZone($dest_tz);
2288 } catch (Exception
$e) {
2289 $dest_tz = new DateTimeZone('UTC');
2292 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2293 return $dt->format('U') +
$dest_tz->getOffset($dt);
2296 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2297 $no_smart_dt = false) {
2299 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2300 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2305 # We store date in UTC internally
2306 $dt = new DateTime($timestamp, $utc_tz);
2308 if ($tz_offset == -1) {
2310 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2313 $user_tz = new DateTimeZone($user_tz_string);
2314 } catch (Exception
$e) {
2318 $tz_offset = $user_tz->getOffset($dt);
2321 $user_timestamp = $dt->format('U') +
$tz_offset;
2323 if (!$no_smart_dt) {
2324 return smart_date_time($link, $user_timestamp,
2325 $tz_offset, $owner_uid);
2328 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2330 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2332 return date($format, $user_timestamp);
2336 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2337 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2339 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2340 return date("G:i", $timestamp);
2341 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2342 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2343 return date($format, $timestamp);
2345 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2346 return date($format, $timestamp);
2350 function smart_date($timestamp) {
2351 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2353 } else if (date("Y", $timestamp) == date("Y")) {
2354 return date("D m", $timestamp);
2356 return date("Y/m/d", $timestamp);
2360 function sql_bool_to_string($s) {
2361 if ($s == "t" ||
$s == "1") {
2368 function sql_bool_to_bool($s) {
2369 if ($s == "t" ||
$s == "1" ||
$s == "true") {
2376 function bool_to_sql_bool($s) {
2384 function toggleEvenOdd($a) {
2391 // Session caching removed due to causing wrong redirects to upgrade
2392 // script when get_schema_version() is called on an obsolete session
2393 // created on a previous schema version.
2394 function get_schema_version($link, $nocache = false) {
2395 global $schema_version;
2397 if (!$schema_version) {
2398 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2399 $version = db_fetch_result($result, 0, "schema_version");
2400 $schema_version = $version;
2403 return $schema_version;
2407 function sanity_check($link) {
2412 $schema_version = get_schema_version($link, true);
2414 if ($schema_version != SCHEMA_VERSION
) {
2418 if (DB_TYPE
== "mysql") {
2419 $result = db_query($link, "SELECT true", false);
2420 if (db_num_rows($result) != 1) {
2425 if (db_escape_string("testTEST") != "testTEST") {
2429 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2432 function file_is_locked($filename) {
2433 if (function_exists('flock')) {
2434 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2436 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2437 flock($fp, LOCK_UN
);
2447 return true; // consider the file always locked and skip the test
2450 function make_lockfile($filename) {
2451 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2453 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2454 if (function_exists('posix_getpid')) {
2455 fwrite($fp, posix_getpid() . "\n");
2463 function make_stampfile($filename) {
2464 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2466 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2467 fwrite($fp, time() . "\n");
2468 flock($fp, LOCK_UN
);
2476 function sql_random_function() {
2477 if (DB_TYPE
== "mysql") {
2484 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2486 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2488 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2495 $cat_qpart = "cat_id = '$feed'";
2497 $cat_qpart = "cat_id IS NULL";
2500 $tmp_result = db_query($link, "SELECT id
2501 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2503 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2505 $tmp_feed = $tmp_line["id"];
2507 db_query($link, "UPDATE ttrss_user_entries
2508 SET unread = false,last_read = NOW()
2509 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2511 } else if ($feed == -2) {
2514 db_query($link, "UPDATE ttrss_user_entries
2515 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2516 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2517 AND unread = true AND owner_uid = $owner_uid");
2520 } else if ($feed > 0) {
2522 db_query($link, "UPDATE ttrss_user_entries
2523 SET unread = false,last_read = NOW()
2524 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2526 } else if ($feed < 0 && $feed > -10) { // special, like starred
2529 db_query($link, "UPDATE ttrss_user_entries
2530 SET unread = false,last_read = NOW()
2531 WHERE marked = true AND owner_uid = $owner_uid");
2535 db_query($link, "UPDATE ttrss_user_entries
2536 SET unread = false,last_read = NOW()
2537 WHERE published = true AND owner_uid = $owner_uid");
2542 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2544 if (DB_TYPE
== "pgsql") {
2545 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2547 $match_part = "updated > DATE_SUB(NOW(),
2548 INTERVAL $intl HOUR) ";
2551 $result = db_query($link, "SELECT id FROM ttrss_entries,
2552 ttrss_user_entries WHERE $match_part AND
2554 ttrss_user_entries.ref_id = ttrss_entries.id AND
2555 owner_uid = $owner_uid");
2557 $affected_ids = array();
2559 while ($line = db_fetch_assoc($result)) {
2560 array_push($affected_ids, $line["id"]);
2563 catchupArticlesById($link, $affected_ids, 0);
2567 db_query($link, "UPDATE ttrss_user_entries
2568 SET unread = false,last_read = NOW()
2569 WHERE owner_uid = $owner_uid");
2572 } else if ($feed < -10) { // label
2574 $label_id = -$feed - 11;
2576 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2577 SET unread = false, last_read = NOW()
2578 WHERE label_id = '$label_id' AND unread = true
2579 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2583 ccache_update($link, $feed, $owner_uid, $cat_view);
2586 db_query($link, "BEGIN");
2588 $tag_name = db_escape_string($feed);
2590 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2591 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2593 while ($line = db_fetch_assoc($result)) {
2594 db_query($link, "UPDATE ttrss_user_entries SET
2595 unread = false, last_read = NOW()
2596 WHERE int_id = " . $line["post_int_id"]);
2598 db_query($link, "COMMIT");
2602 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2604 if (!$omode) $omode = "flc";
2606 $data = getGlobalCounters($link);
2608 $data = array_merge($data, getVirtCounters($link));
2610 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2611 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2612 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2613 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
2618 function getCategoryCounters($link) {
2621 /* Labels category */
2623 $cv = array("id" => -2, "kind" => "cat",
2624 "counter" => getCategoryUnread($link, -2));
2626 array_push($ret_arr, $cv);
2628 $age_qpart = getMaxAgeSubquery();
2630 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2631 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2632 WHERE ttrss_cat_counters_cache.feed_id = id AND
2633 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2635 while ($line = db_fetch_assoc($result)) {
2636 $line["cat_id"] = (int) $line["cat_id"];
2638 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2639 "counter" => $line["unread"]);
2641 array_push($ret_arr, $cv);
2644 /* Special case: NULL category doesn't actually exist in the DB */
2646 $cv = array("id" => 0, "kind" => "cat",
2647 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2649 array_push($ret_arr, $cv);
2654 function getCategoryUnread($link, $cat, $owner_uid = false) {
2656 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2661 $cat_query = "cat_id = '$cat'";
2663 $cat_query = "cat_id IS NULL";
2666 $age_qpart = getMaxAgeSubquery();
2668 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2669 AND owner_uid = " . $owner_uid);
2671 $cat_feeds = array();
2672 while ($line = db_fetch_assoc($result)) {
2673 array_push($cat_feeds, "feed_id = " . $line["id"]);
2676 if (count($cat_feeds) == 0) return 0;
2678 $match_part = implode(" OR ", $cat_feeds);
2680 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2681 FROM ttrss_user_entries,ttrss_entries
2682 WHERE unread = true AND ($match_part) AND id = ref_id
2683 AND $age_qpart AND owner_uid = " . $owner_uid);
2687 # this needs to be rewritten
2688 while ($line = db_fetch_assoc($result)) {
2689 $unread +
= $line["unread"];
2693 } else if ($cat == -1) {
2694 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2695 } else if ($cat == -2) {
2697 $result = db_query($link, "
2698 SELECT COUNT(unread) AS unread FROM
2699 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2700 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2701 ttrss_labels2.owner_uid = '$owner_uid'
2702 AND unread = true AND feed_id = ttrss_feeds.id
2703 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2705 $unread = db_fetch_result($result, 0, "unread");
2712 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2713 if (DB_TYPE
== "pgsql") {
2714 return "ttrss_entries.date_updated >
2715 NOW() - INTERVAL '$days days'";
2717 return "ttrss_entries.date_updated >
2718 DATE_SUB(NOW(), INTERVAL $days DAY)";
2722 function getFeedUnread($link, $feed, $is_cat = false) {
2723 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2726 function getLabelUnread($link, $label_id, $owner_uid = false) {
2727 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2729 $result = db_query($link, "
2730 SELECT COUNT(unread) AS unread FROM
2731 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2732 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2733 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2734 AND unread = true AND feed_id = ttrss_feeds.id
2735 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2737 if (db_num_rows($result) != 0) {
2738 return db_fetch_result($result, 0, "unread");
2744 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2745 $owner_uid = false) {
2747 $n_feed = (int) $feed;
2749 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2752 $unread_qpart = "unread = true";
2754 $unread_qpart = "true";
2757 $age_qpart = getMaxAgeSubquery();
2760 return getCategoryUnread($link, $n_feed, $owner_uid);
2761 } if ($feed != "0" && $n_feed == 0) {
2763 $feed = db_escape_string($feed);
2765 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2766 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2767 AND ref_id = id AND $age_qpart
2768 AND $unread_qpart)) AS count FROM ttrss_tags
2769 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2770 return db_fetch_result($result, 0, "count");
2772 } else if ($n_feed == -1) {
2773 $match_part = "marked = true";
2774 } else if ($n_feed == -2) {
2775 $match_part = "published = true";
2776 } else if ($n_feed == -3) {
2777 $match_part = "unread = true AND score >= 0";
2779 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2781 if (DB_TYPE
== "pgsql") {
2782 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2784 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2786 } else if ($n_feed == -4) {
2787 $match_part = "true";
2788 } else if ($n_feed >= 0) {
2791 $match_part = "feed_id = '$n_feed'";
2793 $match_part = "feed_id IS NULL";
2796 } else if ($feed < -10) {
2798 $label_id = -$feed - 11;
2800 return getLabelUnread($link, $label_id, $owner_uid);
2807 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2808 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2810 $from_qpart = "ttrss_user_entries,ttrss_entries";
2814 $query = "SELECT count(int_id) AS unread
2815 FROM $from_qpart WHERE
2816 ttrss_user_entries.ref_id = ttrss_entries.id AND
2819 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2821 $result = db_query($link, $query);
2825 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2826 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2827 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2828 AND $unread_qpart AND $age_qpart AND
2829 ttrss_tags.owner_uid = " . $owner_uid);
2832 $unread = db_fetch_result($result, 0, "unread");
2837 function getGlobalUnread($link, $user_id = false) {
2840 $user_id = $_SESSION["uid"];
2843 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2844 WHERE owner_uid = '$user_id' AND feed_id > 0");
2846 $c_id = db_fetch_result($result, 0, "c_id");
2851 function getGlobalCounters($link, $global_unread = -1) {
2854 if ($global_unread == -1) {
2855 $global_unread = getGlobalUnread($link);
2858 $cv = array("id" => "global-unread",
2859 "counter" => $global_unread);
2861 array_push($ret_arr, $cv);
2863 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2864 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2866 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2868 $cv = array("id" => "subscribed-feeds",
2869 "counter" => $subscribed_feeds);
2871 array_push($ret_arr, $cv);
2876 function getSubscribedFeeds($link) {
2877 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2878 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2880 return db_fetch_result($result, 0, "fn");
2883 function getTagCounters($link) {
2887 $age_qpart = getMaxAgeSubquery();
2889 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2890 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2891 AND ref_id = id AND $age_qpart
2892 AND unread = true)) AS count FROM ttrss_tags
2893 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2894 ORDER BY count DESC LIMIT 55");
2898 while ($line = db_fetch_assoc($result)) {
2899 $tags[$line["tag_name"]] +
= $line["count"];
2902 foreach (array_keys($tags) as $tag) {
2903 $unread = $tags[$tag];
2904 $tag = htmlspecialchars($tag);
2906 $cv = array("id" => $tag,
2908 "counter" => $unread);
2910 array_push($ret_arr, $cv);
2916 function getVirtCounters($link) {
2920 for ($i = 0; $i >= -4; $i--) {
2922 $count = getFeedUnread($link, $i);
2924 $cv = array("id" => $i,
2925 "counter" => $count);
2927 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2928 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2930 array_push($ret_arr, $cv);
2936 function getLabelCounters($link, $descriptions = false) {
2940 $age_qpart = getMaxAgeSubquery();
2942 $owner_uid = $_SESSION["uid"];
2944 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2945 WHERE owner_uid = '$owner_uid'");
2947 while ($line = db_fetch_assoc($result)) {
2949 $id = -$line["id"] - 11;
2951 $label_name = $line["caption"];
2952 $count = getFeedUnread($link, $id);
2954 $cv = array("id" => $id,
2955 "counter" => $count);
2958 $cv["description"] = $label_name;
2960 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2961 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2963 array_push($ret_arr, $cv);
2969 function getFeedCounters($link, $active_feed = false) {
2973 $age_qpart = getMaxAgeSubquery();
2975 $query = "SELECT ttrss_feeds.id,
2977 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2978 last_error, value AS count
2979 FROM ttrss_feeds, ttrss_counters_cache
2980 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2981 AND ttrss_counters_cache.feed_id = id";
2983 $result = db_query($link, $query);
2984 $fctrs_modified = false;
2986 while ($line = db_fetch_assoc($result)) {
2989 $count = $line["count"];
2990 $last_error = htmlspecialchars($line["last_error"]);
2992 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2994 $has_img = feed_has_icon($id);
2996 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2999 $cv = array("id" => $id,
3000 "updated" => $last_updated,
3001 "counter" => $count,
3002 "has_img" => (int) $has_img);
3005 $cv["error"] = $last_error;
3007 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
3008 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
3010 if ($active_feed && $id == $active_feed)
3011 $cv["title"] = truncate_string($line["title"], 30);
3013 array_push($ret_arr, $cv);
3020 function get_pgsql_version($link) {
3021 $result = db_query($link, "SELECT version() AS version");
3022 $version = explode(" ", db_fetch_result($result, 0, "version"));
3027 * Subscribes the user to the given feed
3029 * @param resource $link Database connection
3030 * @param string $url Feed URL to subscribe to
3031 * @param integer $cat_id Category ID the feed shall be added to
3032 * @param string $auth_login (optional) Feed username
3033 * @param string $auth_pass (optional) Feed password
3035 * @return integer Status code:
3036 * 0 - OK, Feed already exists
3037 * 1 - OK, Feed added
3039 * 3 - URL content is HTML, no feeds available
3040 * 4 - URL content is HTML which contains multiple feeds.
3041 * Here you should call extractfeedurls in rpc-backend
3042 * to get all possible feeds.
3043 * 5 - Couldn't download the URL content.
3045 function subscribe_to_feed($link, $url, $cat_id = 0,
3046 $auth_login = '', $auth_pass = '') {
3048 $url = fix_url($url);
3050 if (!$url ||
!validate_feed_url($url)) return 2;
3054 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
3055 WHERE id = ".$_SESSION['uid']);
3057 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
3059 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
3060 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
3062 if (url_is_html($url, $auth_login, $auth_pass)) {
3063 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
3064 if (count($feedUrls) == 0) {
3066 } else if (count($feedUrls) > 1) {
3069 //use feed url as new URL
3070 $url = key($feedUrls);
3074 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
3079 if ($cat_id == "0" ||
!$cat_id) {
3080 $cat_qpart = "NULL";
3082 $cat_qpart = "'$cat_id'";
3085 $result = db_query($link,
3086 "SELECT id FROM ttrss_feeds
3087 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
3089 if (db_num_rows($result) == 0) {
3090 $result = db_query($link,
3091 "INSERT INTO ttrss_feeds
3092 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
3093 VALUES ('".$_SESSION["uid"]."', '$url',
3094 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
3096 $result = db_query($link,
3097 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
3098 AND owner_uid = " . $_SESSION["uid"]);
3100 $feed_id = db_fetch_result($result, 0, "id");
3103 update_rss_feed($link, $feed_id, true);
3112 function print_feed_select($link, $id, $default_id = "",
3113 $attributes = "", $include_all_feeds = true) {
3115 print "<select id=\"$id\" name=\"$id\" $attributes>";
3116 if ($include_all_feeds) {
3117 print "<option value=\"0\">".__('All feeds')."</option>";
3120 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
3121 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3123 if (db_num_rows($result) > 0 && $include_all_feeds) {
3124 print "<option disabled>--------</option>";
3127 while ($line = db_fetch_assoc($result)) {
3128 if ($line["id"] == $default_id) {
3129 $is_selected = "selected=\"1\"";
3134 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3136 printf("<option $is_selected value='%d'>%s</option>",
3137 $line["id"], $title);
3143 function print_feed_cat_select($link, $id, $default_id = "",
3144 $attributes = "", $include_all_cats = true) {
3146 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3148 if ($include_all_cats) {
3149 print "<option value=\"0\">".__('Uncategorized')."</option>";
3152 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3153 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3155 if (db_num_rows($result) > 0 && $include_all_cats) {
3156 print "<option disabled=\"1\">--------</option>";
3159 while ($line = db_fetch_assoc($result)) {
3160 if ($line["id"] == $default_id) {
3161 $is_selected = "selected=\"1\"";
3167 printf("<option $is_selected value='%d'>%s</option>",
3168 $line["id"], htmlspecialchars($line["title"]));
3171 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3176 function checkbox_to_sql_bool($val) {
3177 return ($val == "on") ?
"true" : "false";
3180 function getFeedCatTitle($link, $id) {
3182 return __("Special");
3183 } else if ($id < -10) {
3184 return __("Labels");
3185 } else if ($id > 0) {
3186 $result = db_query($link, "SELECT ttrss_feed_categories.title
3187 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3188 cat_id = ttrss_feed_categories.id");
3189 if (db_num_rows($result) == 1) {
3190 return db_fetch_result($result, 0, "title");
3192 return __("Uncategorized");
3195 return "getFeedCatTitle($id) failed";
3200 function getFeedIcon($id) {
3203 return "images/archive.png";
3206 return "images/mark_set.png";
3209 return "images/pub_set.png";
3212 return "images/fresh.png";
3215 return "images/tag.png";
3219 return "images/label.png";
3221 if (file_exists(ICONS_DIR
. "/$id.ico"))
3222 return ICONS_URL
. "/$id.ico";
3228 function getFeedTitle($link, $id) {
3230 return __("Starred articles");
3231 } else if ($id == -2) {
3232 return __("Published articles");
3233 } else if ($id == -3) {
3234 return __("Fresh articles");
3235 } else if ($id == -4) {
3236 return __("All articles");
3237 } else if ($id === 0 ||
$id === "0") {
3238 return __("Archived articles");
3239 } else if ($id < -10) {
3240 $label_id = -$id - 11;
3241 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3242 if (db_num_rows($result) == 1) {
3243 return db_fetch_result($result, 0, "caption");
3245 return "Unknown label ($label_id)";
3248 } else if ($id > 0) {
3249 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3250 if (db_num_rows($result) == 1) {
3251 return db_fetch_result($result, 0, "title");
3253 return "Unknown feed ($id)";
3260 function get_session_cookie_name() {
3261 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3264 function make_init_params($link) {
3267 $params["theme"] = get_user_theme($link);
3268 $params["theme_options"] = get_user_theme_options($link);
3270 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3271 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3272 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3273 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3275 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3276 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3277 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3278 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3280 $params[strtolower($param)] = (int) get_pref($link, $param);
3283 $params["icons_url"] = ICONS_URL
;
3284 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3285 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3286 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3287 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3288 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3290 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3291 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3293 $max_feed_id = db_fetch_result($result, 0, "mid");
3294 $num_feeds = db_fetch_result($result, 0, "nf");
3296 $params["max_feed_id"] = (int) $max_feed_id;
3297 $params["num_feeds"] = (int) $num_feeds;
3299 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3304 function print_runtime_info($link) {
3305 print "<runtime-info><![CDATA[";
3306 print json_encode(make_runtime_info($link));
3307 print "]]></runtime-info>";
3310 function make_runtime_info($link) {
3313 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3314 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3316 $max_feed_id = db_fetch_result($result, 0, "mid");
3317 $num_feeds = db_fetch_result($result, 0, "nf");
3319 $data["max_feed_id"] = (int) $max_feed_id;
3320 $data["num_feeds"] = (int) $num_feeds;
3322 $data['last_article_id'] = getLastArticleId($link);
3323 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3325 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
3327 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3329 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3331 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3334 $stamp_delta = time() - $stamp;
3336 if ($stamp_delta > 1800) {
3340 $_SESSION["daemon_stamp_check"] = time();
3343 $data['daemon_stamp_ok'] = $stamp_check;
3345 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3347 $data['daemon_stamp'] = $stamp_fmt;
3352 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3353 $new_version_details = @check_for_update
($link);
3355 $data['new_version_available'] = (int) ($new_version_details != false);
3357 $_SESSION["last_version_check"] = time();
3363 function search_to_sql($link, $search, $match_on) {
3365 $search_query_part = "";
3367 $keywords = explode(" ", $search);
3368 $query_keywords = array();
3370 foreach ($keywords as $k) {
3371 if (strpos($k, "-") === 0) {
3378 $commandpair = explode(":", mb_strtolower($k), 2);
3380 if ($commandpair[0] == "note" && $commandpair[1]) {
3382 if ($commandpair[1] == "true")
3383 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3385 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3387 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3389 if ($commandpair[1] == "true")
3390 array_push($query_keywords, "($not (marked = true))");
3392 array_push($query_keywords, "($not (marked = false))");
3394 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3396 if ($commandpair[1] == "true")
3397 array_push($query_keywords, "($not (published = true))");
3399 array_push($query_keywords, "($not (published = false))");
3401 } else if (strpos($k, "@") === 0) {
3403 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3404 $orig_ts = strtotime(substr($k, 1));
3405 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3407 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3409 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3410 } else if ($match_on == "both") {
3411 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3412 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3413 } else if ($match_on == "title") {
3414 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3415 } else if ($match_on == "content") {
3416 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3420 $search_query_part = implode("AND", $query_keywords);
3422 return $search_query_part;
3425 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false) {
3427 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3429 $ext_tables_part = "";
3433 if (SPHINX_ENABLED
) {
3434 $ids = join(",", @sphinx_search
($search, 0, 500));
3437 $search_query_part = "ref_id IN ($ids) AND ";
3439 $search_query_part = "ref_id = -1 AND ";
3442 $search_query_part = search_to_sql($link, $search, $match_on);
3443 $search_query_part .= " AND ";
3447 $search_query_part = "";
3451 $filter_query_part = filter_to_sql($filter);
3453 $filter_query_part = "";
3456 $view_query_part = "";
3458 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3460 $view_query_part = " ";
3461 } else if ($feed != -1) {
3462 $unread = getFeedUnread($link, $feed, $cat_view);
3464 $view_query_part = " unread = true AND ";
3469 if ($view_mode == "marked") {
3470 $view_query_part = " marked = true AND ";
3473 if ($view_mode == "published") {
3474 $view_query_part = " published = true AND ";
3477 if ($view_mode == "unread") {
3478 $view_query_part = " unread = true AND ";
3481 if ($view_mode == "updated") {
3482 $view_query_part = " (last_read is null and unread = false) AND ";
3486 $limit_query_part = "LIMIT " . $limit;
3489 $vfeed_query_part = "";
3491 // override query strategy and enable feed display when searching globally
3492 if ($search && $search_mode == "all_feeds") {
3493 $query_strategy_part = "ttrss_entries.id > 0";
3494 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3496 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3497 $query_strategy_part = "ttrss_entries.id > 0";
3498 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3499 id = feed_id) as feed_title,";
3500 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3502 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3504 $tmp_result = false;
3507 $tmp_result = db_query($link, "SELECT id
3508 FROM ttrss_feeds WHERE cat_id = '$feed'");
3510 $tmp_result = db_query($link, "SELECT id
3511 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3512 WHERE id = '$feed') AND id != '$feed'");
3515 $cat_siblings = array();
3517 if (db_num_rows($tmp_result) > 0) {
3518 while ($p = db_fetch_assoc($tmp_result)) {
3519 array_push($cat_siblings, "feed_id = " . $p["id"]);
3522 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3523 $feed, implode(" OR ", $cat_siblings));
3526 $query_strategy_part = "ttrss_entries.id > 0";
3529 } else if ($feed > 0) {
3534 $query_strategy_part = "cat_id = '$feed'";
3536 $query_strategy_part = "cat_id IS NULL";
3539 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3542 $query_strategy_part = "feed_id = '$feed'";
3544 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3545 $query_strategy_part = "feed_id IS NULL";
3546 } else if ($feed == 0 && $cat_view) { // uncategorized
3547 $query_strategy_part = "cat_id IS NULL";
3548 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3549 } else if ($feed == -1) { // starred virtual feed
3550 $query_strategy_part = "marked = true";
3551 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3552 } else if ($feed == -2) { // published virtual feed OR labels category
3555 $query_strategy_part = "published = true";
3556 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3558 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3560 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3562 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3563 ttrss_user_labels2.article_id = ref_id";
3567 } else if ($feed == -3) { // fresh virtual feed
3568 $query_strategy_part = "unread = true AND score >= 0";
3570 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3572 if (DB_TYPE
== "pgsql") {
3573 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3575 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3578 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3579 } else if ($feed == -4) { // all articles virtual feed
3580 $query_strategy_part = "true";
3581 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3582 } else if ($feed <= -10) { // labels
3583 $label_id = -$feed - 11;
3585 $query_strategy_part = "label_id = '$label_id' AND
3586 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3587 ttrss_user_labels2.article_id = ref_id";
3589 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3590 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3593 $query_strategy_part = "id > 0"; // dumb
3596 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3597 $date_sort_field = "updated";
3599 $date_sort_field = "date_entered";
3602 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3603 $order_by = "$date_sort_field";
3605 $order_by = "$date_sort_field DESC";
3608 if ($view_mode != "noscores") {
3609 $order_by = "score DESC, $order_by";
3612 if ($override_order) {
3613 $order_by = $override_order;
3619 $feed_title = "Search results";
3622 $feed_title = getCategoryTitle($link, $feed);
3624 if ((int)$feed == $feed && $feed > 0) {
3625 $result = db_query($link, "SELECT title,site_url,last_error
3626 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3628 $feed_title = db_fetch_result($result, 0, "title");
3629 $feed_site_url = db_fetch_result($result, 0, "site_url");
3630 $last_error = db_fetch_result($result, 0, "last_error");
3632 $feed_title = getFeedTitle($link, $feed);
3637 $content_query_part = "content as content_preview,";
3639 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3642 $feed_kind = "Feeds";
3644 $feed_kind = "Labels";
3647 if ($limit_query_part) {
3648 $offset_query_part = "OFFSET $offset";
3651 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3652 if (!$override_order) {
3653 $order_by = "ttrss_feeds.title, $order_by";
3658 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3659 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3662 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3663 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3666 $query = "SELECT DISTINCT
3669 ttrss_entries.id,ttrss_entries.title,
3672 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3673 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3676 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3682 ttrss_user_entries.ref_id = ttrss_entries.id AND
3683 ttrss_user_entries.owner_uid = '$owner_uid' AND
3687 $query_strategy_part ORDER BY $order_by
3688 $limit_query_part $offset_query_part";
3690 if ($_REQUEST["debug"]) print $query;
3692 $result = db_query($link, $query);
3697 $feed_kind = "Tags";
3699 $result = db_query($link, "SELECT DISTINCT
3703 ttrss_entries.id as id,title,
3705 unread,feed_id,orig_feed_id,
3706 marked,link,last_read,
3707 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3710 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3713 ttrss_entries,ttrss_user_entries,ttrss_tags
3715 ref_id = ttrss_entries.id AND
3716 ttrss_user_entries.owner_uid = '$owner_uid' AND
3717 post_int_id = int_id AND tag_name = '$feed' AND
3720 $query_strategy_part ORDER BY $order_by
3721 $limit_query_part");
3724 return array($result, $feed_title, $feed_site_url, $last_error);
3728 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3729 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3731 require_once "lib/MiniTemplator.class.php";
3733 $note_style = "background-color : #fff7d5;
3734 border-width : 1px; ".
3735 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3736 "margin-bottom : 1em; color : #9a8c59;";
3738 if (!$limit) $limit = 30;
3740 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3741 $date_sort_field = "updated";
3743 $date_sort_field = "date_entered";
3746 $qfh_ret = queryFeedHeadlines($link, $feed,
3747 $limit, $view_mode, $is_cat, $search, $search_mode,
3748 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3750 $result = $qfh_ret[0];
3751 $feed_title = htmlspecialchars($qfh_ret[1]);
3752 $feed_site_url = $qfh_ret[2];
3753 $last_error = $qfh_ret[3];
3755 $feed_self_url = get_self_url_prefix() .
3756 "/backend.php?op=rss&id=-2&key=" .
3757 get_feed_access_key($link, -2, false);
3759 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3761 $tpl = new MiniTemplator
;
3763 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3765 $tpl->setVariable('FEED_TITLE', $feed_title);
3766 $tpl->setVariable('VERSION', VERSION
);
3767 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3769 if (PUBSUBHUBBUB_HUB
&& $feed == -2) {
3770 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB
));
3771 $tpl->addBlock('feed_hub');
3774 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3776 while ($line = db_fetch_assoc($result)) {
3777 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3778 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3779 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3780 $tpl->setVariable('ARTICLE_EXCERPT',
3781 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3783 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3785 if ($line['note']) {
3786 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
3790 $tpl->setVariable('ARTICLE_CONTENT', $content);
3792 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3793 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3795 $tags = get_article_tags($link, $line["id"], $owner_uid);
3797 foreach ($tags as $tag) {
3798 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3799 $tpl->addBlock('category');
3802 $enclosures = get_article_enclosures($link, $line["id"]);
3804 foreach ($enclosures as $e) {
3805 $type = htmlspecialchars($e['content_type']);
3806 $url = htmlspecialchars($e['content_url']);
3807 $length = $e['duration'];
3809 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3810 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3811 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3813 $tpl->addBlock('enclosure');
3816 $tpl->addBlock('entry');
3821 $tpl->addBlock('feed');
3822 $tpl->generateOutputToString($tmp);
3827 function getCategoryTitle($link, $cat_id) {
3829 if ($cat_id == -1) {
3830 return __("Special");
3831 } else if ($cat_id == -2) {
3832 return __("Labels");
3835 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3838 if (db_num_rows($result) == 1) {
3839 return db_fetch_result($result, 0, "title");
3841 return "Uncategorized";
3846 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3849 if (!$owner) $owner = $_SESSION["uid"];
3851 $res = trim($str); if (!$res) return '';
3853 // if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3854 $res = $purifier->purify($res);
3857 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3858 $res = preg_replace('/<img[^>]+>/is', '', $res);
3861 if (strpos($res, "href=") === false)
3862 $res = rewrite_urls($res);
3864 $charset_hack = '<head>
3865 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3868 $res = trim($res); if (!$res) return '';
3870 libxml_use_internal_errors(true);
3872 $doc = new DOMDocument();
3873 $doc->loadHTML($charset_hack . $res);
3874 $xpath = new DOMXPath($doc);
3876 $entries = $xpath->query('(//a[@href]|//img[@src])');
3879 foreach ($entries as $entry) {
3883 if ($entry->hasAttribute('href'))
3884 $entry->setAttribute('href',
3885 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3887 if ($entry->hasAttribute('src'))
3888 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3889 $entry->setAttribute('src',
3890 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3893 if (strtolower($entry->nodeName
) == "a") {
3894 $entry->setAttribute("target", "_blank");
3897 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3898 $br = $doc->createElement("br");
3900 if ($entry->parentNode
->nextSibling
) {
3901 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3908 $node = $doc->getElementsByTagName('body')->item(0);
3910 return $doc->saveXML($node);
3914 * Send by mail a digest of last articles.
3916 * @param mixed $link The database connection.
3917 * @param integer $limit The maximum number of articles by digest.
3918 * @return boolean Return false if digests are not enabled.
3920 function send_headlines_digests($link, $limit = 100) {
3922 if (!DIGEST_ENABLE
) return false;
3924 $user_limit = DIGEST_EMAIL_LIMIT
;
3927 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3929 if (DB_TYPE
== "pgsql") {
3930 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3931 } else if (DB_TYPE
== "mysql") {
3932 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3935 $result = db_query($link, "SELECT id,email FROM ttrss_users
3936 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3938 while ($line = db_fetch_assoc($result)) {
3940 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3941 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3943 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3945 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3946 $digest = $tuple[0];
3947 $headlines_count = $tuple[1];
3948 $affected_ids = $tuple[2];
3949 $digest_text = $tuple[3];
3951 if ($headlines_count > 0) {
3953 $mail = new PHPMailer();
3955 $mail->PluginDir
= "lib/phpmailer/";
3956 $mail->SetLanguage("en", "lib/phpmailer/language/");
3958 $mail->CharSet
= "UTF-8";
3960 $mail->From
= DIGEST_FROM_ADDRESS
;
3961 $mail->FromName
= DIGEST_FROM_NAME
;
3962 $mail->AddAddress($line["email"], $line["login"]);
3964 if (DIGEST_SMTP_HOST
) {
3965 $mail->Host
= DIGEST_SMTP_HOST
;
3966 $mail->Mailer
= "smtp";
3967 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3968 $mail->Username
= DIGEST_SMTP_LOGIN
;
3969 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3972 $mail->IsHTML(true);
3973 $mail->Subject
= DIGEST_SUBJECT
;
3974 $mail->Body
= $digest;
3975 $mail->AltBody
= $digest_text;
3977 $rc = $mail->Send();
3979 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3983 if ($rc && $do_catchup) {
3984 print "Marking affected articles as read...\n";
3985 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3988 print "No headlines\n";
3991 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3992 WHERE id = " . $line["id"]);
3996 print "All done.\n";
4000 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
4002 require_once "lib/MiniTemplator.class.php";
4004 $tpl = new MiniTemplator
;
4005 $tpl_t = new MiniTemplator
;
4007 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
4008 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
4010 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
4011 $tpl->setVariable('CUR_TIME', date('G:i'));
4013 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
4014 $tpl_t->setVariable('CUR_TIME', date('G:i'));
4016 $affected_ids = array();
4018 if (DB_TYPE
== "pgsql") {
4019 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
4020 } else if (DB_TYPE
== "mysql") {
4021 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
4024 $result = db_query($link, "SELECT ttrss_entries.title,
4025 ttrss_feeds.title AS feed_title,
4027 ttrss_user_entries.ref_id,
4029 SUBSTRING(content, 1, 120) AS excerpt,
4030 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4032 ttrss_user_entries,ttrss_entries,ttrss_feeds
4034 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
4035 AND include_in_digest = true
4037 AND ttrss_user_entries.owner_uid = $user_id
4039 ORDER BY ttrss_feeds.title, date_updated DESC
4042 $cur_feed_title = "";
4044 $headlines_count = db_num_rows($result);
4046 $headlines = array();
4048 while ($line = db_fetch_assoc($result)) {
4049 array_push($headlines, $line);
4052 for ($i = 0; $i < sizeof($headlines); $i++
) {
4054 $line = $headlines[$i];
4056 array_push($affected_ids, $line["ref_id"]);
4058 $updated = make_local_datetime($link, $line['last_updated'], false,
4061 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
4062 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
4063 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
4064 $tpl->setVariable('ARTICLE_UPDATED', $updated);
4065 $tpl->setVariable('ARTICLE_EXCERPT',
4066 truncate_string(strip_tags($line["excerpt"]), 100));
4068 $tpl->addBlock('article');
4070 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
4071 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4072 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4073 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4074 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4075 // truncate_string(strip_tags($line["excerpt"]), 100));
4077 $tpl_t->addBlock('article');
4079 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
4080 $tpl->addBlock('feed');
4081 $tpl_t->addBlock('feed');
4086 $tpl->addBlock('digest');
4087 $tpl->generateOutputToString($tmp);
4089 $tpl_t->addBlock('digest');
4090 $tpl_t->generateOutputToString($tmp_t);
4092 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4095 function check_for_update($link) {
4096 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
4097 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
4099 $version_data = @fetch_file_contents
($version_url);
4101 if ($version_data) {
4102 $version_data = json_decode($version_data, true);
4103 if ($version_data && $version_data['version']) {
4105 if (version_compare(VERSION
, $version_data['version']) == -1) {
4106 return $version_data;
4114 function markArticlesById($link, $ids, $cmode) {
4118 foreach ($ids as $id) {
4119 array_push($tmp_ids, "ref_id = '$id'");
4122 $ids_qpart = join(" OR ", $tmp_ids);
4125 db_query($link, "UPDATE ttrss_user_entries SET
4126 marked = false,last_read = NOW()
4127 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4128 } else if ($cmode == 1) {
4129 db_query($link, "UPDATE ttrss_user_entries SET
4131 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4133 db_query($link, "UPDATE ttrss_user_entries SET
4134 marked = NOT marked,last_read = NOW()
4135 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4139 function publishArticlesById($link, $ids, $cmode) {
4143 foreach ($ids as $id) {
4144 array_push($tmp_ids, "ref_id = '$id'");
4147 $ids_qpart = join(" OR ", $tmp_ids);
4150 db_query($link, "UPDATE ttrss_user_entries SET
4151 published = false,last_read = NOW()
4152 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4153 } else if ($cmode == 1) {
4154 db_query($link, "UPDATE ttrss_user_entries SET
4156 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4158 db_query($link, "UPDATE ttrss_user_entries SET
4159 published = NOT published,last_read = NOW()
4160 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4163 if (PUBSUBHUBBUB_HUB
) {
4164 $rss_link = get_self_url_prefix() .
4165 "/backend.php?op=rss&id=-2&key=" .
4166 get_feed_access_key($link, -2, false);
4168 $p = new Publisher(PUBSUBHUBBUB_HUB
);
4170 $pubsub_result = $p->publish_update($rss_link);
4174 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4176 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4177 if (count($ids) == 0) return;
4181 foreach ($ids as $id) {
4182 array_push($tmp_ids, "ref_id = '$id'");
4185 $ids_qpart = join(" OR ", $tmp_ids);
4188 db_query($link, "UPDATE ttrss_user_entries SET
4189 unread = false,last_read = NOW()
4190 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4191 } else if ($cmode == 1) {
4192 db_query($link, "UPDATE ttrss_user_entries SET
4194 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4196 db_query($link, "UPDATE ttrss_user_entries SET
4197 unread = NOT unread,last_read = NOW()
4198 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4203 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4204 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4206 while ($line = db_fetch_assoc($result)) {
4207 ccache_update($link, $line["feed_id"], $owner_uid);
4211 function catchupArticleById($link, $id, $cmode) {
4214 db_query($link, "UPDATE ttrss_user_entries SET
4215 unread = false,last_read = NOW()
4216 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4217 } else if ($cmode == 1) {
4218 db_query($link, "UPDATE ttrss_user_entries SET
4220 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4222 db_query($link, "UPDATE ttrss_user_entries SET
4223 unread = NOT unread,last_read = NOW()
4224 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4227 $feed_id = getArticleFeed($link, $id);
4228 ccache_update($link, $feed_id, $_SESSION["uid"]);
4231 function make_guid_from_title($title) {
4232 return preg_replace("/[ \"\',.:;]/", "-",
4233 mb_strtolower(strip_tags($title), 'utf-8'));
4236 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4237 $feed_id, $is_cat, $search, $match_on,
4238 $search_mode, $view_mode, $error) {
4240 $page_prev_link = "viewFeedGoPage(-1)";
4241 $page_next_link = "viewFeedGoPage(1)";
4242 $page_first_link = "viewFeedGoPage(0)";
4244 $catchup_page_link = "catchupPage()";
4245 $catchup_feed_link = "catchupCurrentFeed()";
4246 $catchup_sel_link = "catchupSelection()";
4248 $archive_sel_link = "archiveSelection()";
4249 $delete_sel_link = "deleteSelection()";
4251 $sel_all_link = "selectArticles('all')";
4252 $sel_unread_link = "selectArticles('unread')";
4253 $sel_none_link = "selectArticles('none')";
4254 $sel_inv_link = "selectArticles('invert')";
4256 $tog_unread_link = "selectionToggleUnread()";
4257 $tog_marked_link = "selectionToggleMarked()";
4258 $tog_published_link = "selectionTogglePublished()";
4260 $reply = "<div id=\"subtoolbar_main\">";
4262 $reply .= __('Select:')."
4263 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4264 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4265 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4266 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4270 $reply .= "<select dojoType=\"dijit.form.Select\"
4271 onchange=\"headlineActionsChange(this)\">";
4272 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4274 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4276 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4277 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4278 <option value=\"$tog_published_link\">".__('Published')."</option>";
4280 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4282 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4284 if ($feed_id != "0") {
4285 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4287 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4288 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4292 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4295 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4298 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4303 $rss_link = htmlspecialchars(get_self_url_prefix() .
4304 "/backend.php?op=rss&id=$feed_id$cat_q$search_q");
4306 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4308 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4310 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4312 $reply .= "</select>";
4316 $reply .= "<div id=\"subtoolbar_ftitle\">";
4318 if ($feed_site_url) {
4319 $target = "target=\"_blank\"";
4320 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4321 truncate_string($feed_title,30)."</a>";
4324 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4328 if ($feed_id < -10) {
4329 $label_id = -11-$feed_id;
4331 $result = db_query($link, "SELECT fg_color, bg_color
4332 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4335 if (db_num_rows($result) != 0) {
4336 $fg_color = db_fetch_result($result, 0, "fg_color");
4337 $bg_color = db_fetch_result($result, 0, "bg_color");
4339 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
4340 $reply .= $feed_title;
4341 $reply .= "</span>";
4343 $reply .= $feed_title;
4347 $reply .= $feed_title;
4353 title=\"".__("View as RSS feed")."\"
4354 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4355 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4362 function outputFeedList($link, $special = true) {
4364 $feedlist = array();
4366 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4368 $feedlist['identifier'] = 'id';
4369 $feedlist['label'] = 'name';
4370 $feedlist['items'] = array();
4372 $owner_uid = $_SESSION["uid"];
4379 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4380 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4382 $cat['items'] = array();
4385 foreach (array(-4, -3, -1, -2, 0) as $i) {
4386 array_push($cat['items'], feedlist_init_feed($link, $i));
4390 array_push($feedlist['items'], $cat);
4392 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4395 $result = db_query($link, "SELECT * FROM
4396 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4398 if (db_num_rows($result) > 0) {
4400 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4401 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4402 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4404 $cat['items'] = array();
4407 while ($line = db_fetch_assoc($result)) {
4409 $label_id = -$line['id'] - 11;
4410 $count = getFeedUnread($link, $label_id);
4412 $feed = feedlist_init_feed($link, $label_id, false, $count);
4414 $feed['fg_color'] = $line['fg_color'];
4415 $feed['bg_color'] = $line['bg_color'];
4417 array_push($cat['items'], $feed);
4421 array_push($feedlist['items'], $cat);
4423 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4428 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4429 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4430 $order_by_qpart = "order_id,category,unread DESC,title";
4432 $order_by_qpart = "order_id,category,title";
4435 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4436 $order_by_qpart = "unread DESC,title";
4438 $order_by_qpart = "title";
4445 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4446 ttrss_feeds.order_id,title";
4448 $order_by_qpart = "title";
4450 $age_qpart = getMaxAgeSubquery();
4452 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4453 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4455 ttrss_feed_categories.title AS category,
4456 ttrss_feed_categories.collapsed,
4458 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4459 ON (ttrss_feed_categories.id = cat_id)
4460 LEFT JOIN ttrss_counters_cache
4462 (ttrss_feeds.id = feed_id)
4464 ttrss_feeds.owner_uid = '$owner_uid'
4465 ORDER BY $order_by_qpart";
4467 $result = db_query($link, $query);
4469 $actid = $_REQUEST["actid"];
4471 if (db_num_rows($result) > 0) {
4476 $cat['items'] = array();
4480 while ($line = db_fetch_assoc($result)) {
4482 $feed = htmlspecialchars(trim($line["title"]));
4484 if (!$feed) $feed = "[Untitled]";
4486 $feed_id = $line["id"];
4487 $unread = $line["unread"];
4489 $cat_id = $line["cat_id"];
4490 $tmp_category = $line["category"];
4491 if (!$tmp_category) $tmp_category = __("Uncategorized");
4493 if ($category != $tmp_category && $enable_cats) {
4495 $category = $tmp_category;
4497 $collapsed = sql_bool_to_bool($line["collapsed"]);
4499 // workaround for NULL category
4500 if ($category == __("Uncategorized")) {
4501 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4504 if ($cat) array_push($feedlist['items'], $cat);
4506 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4509 $updated = make_local_datetime($link, $line["updated_noms"], false);
4511 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4512 $feed, $unread, $line['last_error'], $updated));
4516 array_push($feedlist['items'], $cat);
4518 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4526 function get_article_tags($link, $id, $owner_uid = 0) {
4530 $a_id = db_escape_string($id);
4532 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4534 $query = "SELECT DISTINCT tag_name,
4535 owner_uid as owner FROM
4536 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4537 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4539 $obj_id = md5("TAGS:$owner_uid:$id");
4542 if ($memcache && $obj = $memcache->get($obj_id)) {
4545 /* check cache first */
4547 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4548 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4550 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4553 $tags = explode(",", $tag_cache);
4556 /* do it the hard way */
4558 $tmp_result = db_query($link, $query);
4560 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4561 array_push($tags, $tmp_line["tag_name"]);
4564 /* update the cache */
4566 $tags_str = db_escape_string(join(",", $tags));
4568 db_query($link, "UPDATE ttrss_user_entries
4569 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4570 AND owner_uid = " . $_SESSION["uid"]);
4573 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4579 function trim_value(&$value) {
4580 $value = trim($value);
4583 function trim_array($array) {
4585 array_walk($tmp, 'trim_value');
4589 function tag_is_valid($tag) {
4590 if ($tag == '') return false;
4591 if (preg_match("/^[0-9]*$/", $tag)) return false;
4592 if (mb_strlen($tag) > 250) return false;
4594 if (function_exists('iconv')) {
4595 $tag = iconv("utf-8", "utf-8", $tag);
4598 if (!$tag) return false;
4603 function render_login_form($link, $mobile = 0) {
4606 require_once "login_form.php";
4609 require_once "mobile/login_form.php";
4612 require_once "mobile/classic/login_form.php";
4616 // from http://developer.apple.com/internet/safari/faq.html
4617 function no_cache_incantation() {
4618 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4619 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4620 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4621 header("Cache-Control: post-check=0, pre-check=0", false);
4622 header("Pragma: no-cache"); // HTTP/1.0
4625 function format_warning($msg, $id = "") {
4627 return "<div class=\"warning\" id=\"$id\">
4628 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4631 function format_notice($msg, $id = "") {
4633 return "<div class=\"notice\" id=\"$id\">
4634 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4637 function format_error($msg, $id = "") {
4639 return "<div class=\"error\" id=\"$id\">
4640 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4643 function print_notice($msg) {
4644 return print format_notice($msg);
4647 function print_warning($msg) {
4648 return print format_warning($msg);
4651 function print_error($msg) {
4652 return print format_error($msg);
4656 function T_sprintf() {
4657 $args = func_get_args();
4658 return vsprintf(__(array_shift($args)), $args);
4661 function format_inline_player($link, $url, $ctype) {
4665 if (strpos($ctype, "audio/") === 0) {
4667 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4668 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4669 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4671 $id = 'AUDIO-' . uniqid();
4673 $entry .= "<audio id=\"$id\"\">
4674 <source src=\"$url\"></source>
4677 $entry .= "<span onclick=\"player(this)\"
4678 title=\"".__("Click to play")."\" status=\"0\"
4679 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4683 $entry .= "<object type=\"application/x-shockwave-flash\"
4684 data=\"lib/button/musicplayer.swf?song_url=$url\"
4685 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4686 <param name=\"movie\"
4687 value=\"lib/button/musicplayer.swf?song_url=$url\" />
4692 $filename = substr($url, strrpos($url, "/")+
1);
4694 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4695 $filename . " (" . $ctype . ")" . "</a>";
4700 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
4706 /* we can figure out feed_id from article id anyway, why do we
4707 * pass feed_id here? let's ignore the argument :( */
4709 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4710 WHERE ref_id = '$id'");
4712 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4714 $rv['feed_id'] = $feed_id;
4716 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4718 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4719 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4721 if (db_num_rows($result) == 1) {
4722 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4723 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4725 $rtl_content = false;
4726 $always_display_enclosures = false;
4730 $rtl_tag = "dir=\"RTL\"";
4737 if ($mark_as_read) {
4738 $result = db_query($link, "UPDATE ttrss_user_entries
4739 SET unread = false,last_read = NOW()
4740 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4742 ccache_update($link, $feed_id, $_SESSION["uid"]);
4745 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4746 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4747 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4748 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4753 FROM ttrss_entries,ttrss_user_entries
4754 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4758 $line = db_fetch_assoc($result);
4760 if ($line["icon_url"]) {
4761 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4763 $feed_icon = " ";
4766 $feed_site_url = $line['site_url'];
4768 $num_comments = $line["num_comments"];
4769 $entry_comments = "";
4771 if ($num_comments > 0) {
4772 if ($line["comments"]) {
4773 $comments_url = $line["comments"];
4775 $comments_url = $line["link"];
4777 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4779 if ($line["comments"] && $line["link"] != $line["comments"]) {
4780 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4785 header("Content-Type: text/html");
4786 $rv['content'] .= "<html><head>
4787 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4788 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4789 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4793 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4794 truncate_string(strip_tags($line['title']), 15) . "</div>";
4796 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4798 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4799 class=\"postHeader\" id=\"POSTHDR-$id\">";
4801 $entry_author = $line["author"];
4803 if ($entry_author) {
4804 $entry_author = __(" - ") . $entry_author;
4807 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4810 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4812 if ($line["link"]) {
4813 $rv['content'] .= "<div clear='both'><a target='_blank'
4814 title=\"".htmlspecialchars($line['title'])."\"
4816 $line["link"] . "\">" .
4817 truncate_string($line["title"], 100) .
4818 "<span class='author'>$entry_author</span></a></div>";
4820 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4823 $tags = get_article_tags($link, $id);
4824 $tags_str = format_tags_string($tags, $id);
4825 $tags_str_full = join(", ", $tags);
4827 if (!$tags_str_full) $tags_str_full = __("no tags");
4829 if (!$entry_comments) $entry_comments = " "; # placeholder
4831 $rv['content'] .= "<div style='float : right'>
4832 <img src='".theme_image($link, 'images/tag.png')."'
4833 class='tagsPic' alt='Tags' title='Tags'> ";
4836 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4837 <a title=\"".__('Edit tags for this article')."\"
4838 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4840 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4841 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4842 position=\"below\">$tags_str_full</div>";
4844 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4845 class='tagsPic' style=\"cursor : pointer\"
4846 onclick=\"postOpenInNewTab(event, $id)\"
4847 alt='Zoom' title='".__('Open article in new tab')."'>";
4849 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4851 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4852 class='tagsPic' style=\"cursor : pointer\"
4853 onclick=\"editArticleNote($id)\"
4854 alt='PubNote' title='".__('Edit article note')."'>";
4856 if (DIGEST_ENABLE
) {
4857 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4858 class='tagsPic' style=\"cursor : pointer\"
4859 onclick=\"emailArticle($id)\"
4860 alt='Zoom' title='".__('Forward by email')."'>";
4863 if (ENABLE_TWEET_BUTTON
) {
4864 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4865 class='tagsPic' style=\"cursor : pointer\"
4866 onclick=\"tweetArticle($id)\"
4867 alt='Zoom' title='".__('Share on Twitter')."'>";
4870 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4871 class='tagsPic' style=\"cursor : pointer\"
4872 onclick=\"closeArticlePanel($id)\"
4873 alt='Zoom' title='".__('Close this panel')."'>";
4876 $tags_str = strip_tags($tags_str);
4877 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4879 $rv['content'] .= "</div>";
4880 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4882 if ($line["orig_feed_id"]) {
4884 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4885 WHERE id = ".$line["orig_feed_id"]);
4887 if (db_num_rows($tmp_result) != 0) {
4889 $rv['content'] .= "<div clear='both'>";
4890 $rv['content'] .= __("Originally from:");
4892 $rv['content'] .= " ";
4894 $tmp_line = db_fetch_assoc($tmp_result);
4896 $rv['content'] .= "<a target='_blank'
4897 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4898 $tmp_line['title'] . "</a>";
4900 $rv['content'] .= " ";
4902 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4903 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4905 $rv['content'] .= "</div>";
4909 $rv['content'] .= "</div>";
4911 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4912 if ($line['note']) {
4913 $rv['content'] .= format_article_note($id, $line['note']);
4915 $rv['content'] .= "</div>";
4917 $rv['content'] .= "<div class=\"postIcon\">" .
4918 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4919 href=\"".htmlspecialchars($feed_site_url)."\">".
4920 $feed_icon . "</a></div>";
4922 $rv['content'] .= "<div class=\"postContent\">";
4924 $article_content = sanitize_rss($link, $line["content"], false, false,
4927 $rv['content'] .= $article_content;
4929 $rv['content'] .= format_article_enclosures($link, $id,
4930 $always_display_enclosures, $article_content);
4932 $rv['content'] .= "</div>";
4934 $rv['content'] .= "</div>";
4940 <div style=\"text-align : center\">
4941 <button onclick=\"return window.close()\">".
4942 __("Close this window")."</button></div>";
4943 $rv['content'] .= "</body></html>";
4950 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4951 $next_unread_feed, $offset, $vgr_last_feed = false,
4952 $override_order = false) {
4954 $disable_cache = false;
4958 $timing_info = getmicrotime();
4960 $topmost_article_ids = array();
4962 if (!$offset) $offset = 0;
4963 if ($subop == "undefined") $subop = "";
4965 $subop_split = explode(":", $subop);
4967 /* if ($subop == "CatchupSelected") {
4968 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
4969 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4971 catchupArticlesById($link, $ids, $cmode);
4974 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4975 update_rss_feed($link, $feed, true);
4978 if ($subop == "MarkAllRead") {
4979 catchup_feed($link, $feed, $cat_view);
4981 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4982 if ($next_unread_feed) {
4983 $feed = $next_unread_feed;
4988 if ($subop_split[0] == "MarkAllReadGR") {
4989 catchup_feed($link, $subop_split[1], false);
4992 // FIXME: might break tag display?
4994 if ($feed > 0 && !$cat_view) {
4995 $result = db_query($link,
4996 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4998 if (db_num_rows($result) == 0) {
4999 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
5003 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
5005 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
5006 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
5008 if (db_num_rows($result) == 1) {
5009 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
5011 $rtl_content = false;
5015 $rtl_tag = "dir=\"RTL\"";
5021 $rtl_content = false;
5024 @$search = db_escape_string($_REQUEST["query"]);
5027 $disable_cache = true;
5030 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
5031 @$match_on = db_escape_string($_REQUEST["match_on"]);
5037 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5039 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
5040 $search, $search_mode, $match_on, $override_order, $offset);
5042 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5044 $result = $qfh_ret[0];
5045 $feed_title = $qfh_ret[1];
5046 $feed_site_url = $qfh_ret[2];
5047 $last_error = $qfh_ret[3];
5049 $vgroup_last_feed = $vgr_last_feed;
5053 if (db_num_rows($result) > 0) {
5054 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
5056 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5061 $headlines_count = db_num_rows($result);
5063 if (db_num_rows($result) > 0) {
5068 $cur_feed_title = '';
5070 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5072 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5074 while ($line = db_fetch_assoc($result)) {
5076 $class = ($lnum %
2) ?
"even" : "odd";
5079 $feed_id = $line["feed_id"];
5081 $labels = get_article_labels($link, $id);
5083 $labels_str = "<span id=\"HLLCTR-$id\">";
5084 $labels_str .= format_article_labels($labels, $id);
5085 $labels_str .= "</span>";
5087 if (count($topmost_article_ids) < 3) {
5088 array_push($topmost_article_ids, $id);
5091 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5093 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5094 theme_image($link, 'images/updated.png')."\"
5097 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5101 if (sql_bool_to_bool($line["unread"]) &&
5102 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5104 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5105 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5108 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5109 $class .= " Unread";
5116 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5117 $marked_pic = "<img id=\"FMPIC-$id\"
5118 src=\"".theme_image($link, 'images/mark_set.png')."\"
5119 class=\"markedPic\" alt=\"Unstar article\"
5120 onclick='javascript:tMark($id)'>";
5122 $marked_pic = "<img id=\"FMPIC-$id\"
5123 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5124 class=\"markedPic\" alt=\"Star article\"
5125 onclick='javascript:tMark($id)'>";
5128 if ($line["published"] == "t" ||
$line["published"] == "1") {
5129 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5130 'images/pub_set.png')."\"
5132 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5134 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5135 'images/pub_unset.png')."\"
5137 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5140 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5141 # $line["title"] . "</a>";
5143 # $content_link = "<a
5144 # href=\"" . htmlspecialchars($line["link"]) . "\"
5145 # onclick=\"view($id,$feed_id);\">" .
5146 # $line["title"] . "</a>";
5148 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5149 # $line["title"] . "</a>";
5151 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5153 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5154 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5158 $score = $line["score"];
5160 $score_pic = theme_image($link,
5161 "images/" . get_score_pic($score));
5163 /* $score_title = __("(Click to change)");
5164 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5165 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5167 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5172 } else if ($score < -100) {
5178 $entry_author = $line["author"];
5180 if ($entry_author) {
5181 $entry_author = " - $entry_author";
5184 $has_feed_icon = feed_has_icon($feed_id);
5186 if ($has_feed_icon) {
5187 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5189 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5192 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5194 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5195 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5197 $cur_feed_title = $line["feed_title"];
5198 $vgroup_last_feed = $feed_id;
5200 $cur_feed_title = htmlspecialchars($cur_feed_title);
5202 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5204 $reply['content'] .= "<div class='cdmFeedTitle'>".
5205 "<div style=\"float : right\">$feed_icon_img</div>".
5206 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5207 $line["feed_title"]."</a> $vf_catchup_link</div>";
5212 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5213 onmouseout='postMouseOut($id)'";
5215 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5217 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5219 $reply['content'] .= "<div class='hlLeft'>";
5221 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5224 $reply['content'] .= "$marked_pic";
5225 $reply['content'] .= "$published_pic";
5227 $reply['content'] .= "</div>";
5229 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5230 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5231 $reply['content'] .= "<a id=\"RTITLE-$id\"
5232 href=\"" . htmlspecialchars($line["link"]) . "\"
5236 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5237 if ($content_preview) {
5238 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5242 $reply['content'] .= "</a></span>";
5244 $reply['content'] .= $labels_str;
5246 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5247 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5248 if (@$line["feed_title"]) {
5249 $reply['content'] .= "<span class=\"hlFeed\">
5250 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5251 $line["feed_title"]."</a>)
5256 $reply['content'] .= "</div>";
5258 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5259 $reply['content'] .= "<div class=\"hlRight\">";
5261 $reply['content'] .= $score_pic;
5263 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5265 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5266 style=\"cursor : pointer\"
5267 title=\"".htmlspecialchars($line['feed_title'])."\">
5268 $feed_icon_img<span>";
5271 $reply['content'] .= "</div>";
5272 $reply['content'] .= "</div>";
5276 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5277 if ($feed_id != $vgroup_last_feed) {
5279 $cur_feed_title = $line["feed_title"];
5280 $vgroup_last_feed = $feed_id;
5282 $cur_feed_title = htmlspecialchars($cur_feed_title);
5284 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5286 $has_feed_icon = feed_has_icon($feed_id);
5288 if ($has_feed_icon) {
5289 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5291 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5294 $reply['content'] .= "<div class='cdmFeedTitle'>".
5295 "<div style=\"float : right\">$feed_icon_img</div>".
5296 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5297 $line["feed_title"]."</a> $vf_catchup_link</div>";
5301 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5303 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5304 onmouseout='postMouseOut($id)'";
5306 $reply['content'] .= "<div class=\"$class\"
5307 id=\"RROW-$id\" $mouseover_attrs'>";
5309 $reply['content'] .= "<div class=\"cdmHeader\">";
5311 $reply['content'] .= "<div style='float : right'>";
5312 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5313 $reply['content'] .= "$score_pic";
5315 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5316 $reply['content'] .= "<span style=\"cursor : pointer\"
5317 title=\"".htmlspecialchars($line["feed_title"])."\"
5318 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5320 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5322 $reply['content'] .= "</div>";
5324 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5325 'RROW-$id')\" id=\"RCHK-$id\"/>";
5327 $reply['content'] .= "$marked_pic";
5328 $reply['content'] .= "$published_pic";
5330 $reply['content'] .= "<span id=\"RTITLE-$id\"
5331 onclick=\"return cdmClicked(event, $id);\"
5332 class=\"titleWrap$hlc_suffix\">
5334 title=\"".htmlspecialchars($line['title'])."\"
5335 target=\"_blank\" href=\"".
5336 htmlspecialchars($line["link"])."\">".
5337 truncate_string($line["title"], 100) .
5338 " $entry_author</a>";
5340 $reply['content'] .= $labels_str;
5342 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5343 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5344 if (@$line["feed_title"]) {
5345 $reply['content'] .= "<span class=\"hlFeed\">
5346 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5347 $line["feed_title"]."</a>)
5353 $content_hidden = "style=\"display : none\"";
5355 $excerpt_hidden = "style=\"display : none\"";
5357 $reply['content'] .= "<span $excerpt_hidden
5358 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5360 $reply['content'] .= "</span>";
5362 $reply['content'] .= "</div>";
5364 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5365 onclick=\"return cdmClicked(event, $id);\"
5368 $reply['content'] .= "<div class=\"cdmContentInner\">";
5370 if ($line["orig_feed_id"]) {
5372 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5373 WHERE id = ".$line["orig_feed_id"]);
5375 if (db_num_rows($tmp_result) != 0) {
5377 $reply['content'] .= "<div clear='both'>";
5378 $reply['content'] .= __("Originally from:");
5380 $reply['content'] .= " ";
5382 $tmp_line = db_fetch_assoc($tmp_result);
5384 $reply['content'] .= "<a target='_blank'
5385 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5386 $tmp_line['title'] . "</a>";
5388 $reply['content'] .= " ";
5390 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5391 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5393 $reply['content'] .= "</div>";
5397 // FIXME: make this less of a hack
5399 $feed_site_url = false;
5401 if ($line["feed_id"]) {
5402 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5403 WHERE id = " . $line["feed_id"]);
5405 if (db_num_rows($tmp_result) == 1) {
5406 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5411 $article_content = sanitize_rss($link, $line["content_preview"],
5412 false, false, $feed_site_url);
5414 if (!$article_content) $article_content = " ";
5416 $article_content = '';
5419 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5420 if ($line['note']) {
5421 $reply['content'] .= format_article_note($id, $line['note']);
5423 $reply['content'] .= "</div>";
5425 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5427 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5428 ttrss_feeds WHERE id = ".
5429 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5430 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5432 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5433 0, "always_display_enclosures"));
5435 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5438 $reply['content'] .= "</div>";
5440 $reply['content'] .= "<div class=\"cdmFooter\">";
5442 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5444 $reply['content'] .= "<img src='".theme_image($link,
5445 'images/tag.png')."' alt='Tags' title='Tags'>
5446 <span id=\"ATSTR-$id\">$tags_str</span>
5447 <a title=\"".__('Edit tags for this article')."\"
5448 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5450 $reply['content'] .= "<div style=\"float : right\">";
5452 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5453 onclick=\"zoomToArticle(event, $id)\"
5454 style=\"cursor : pointer\"
5456 title='".__('Open article in new tab')."'>";
5458 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5460 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5461 style=\"cursor : pointer\" style=\"cursor : pointer\"
5462 onclick=\"editArticleNote($id)\"
5463 alt='PubNote' title='".__('Edit article note')."'>";
5465 if (DIGEST_ENABLE
) {
5466 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5467 style=\"cursor : pointer\"
5468 onclick=\"emailArticle($id)\"
5469 alt='Zoom' title='".__('Forward by email')."'>";
5472 if (ENABLE_TWEET_BUTTON
) {
5473 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5474 class='tagsPic' style=\"cursor : pointer\"
5475 onclick=\"tweetArticle($id)\"
5476 alt='Zoom' title='".__('Share on Twitter')."'>";
5479 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5480 style=\"cursor : pointer\" style=\"cursor : pointer\"
5481 onclick=\"dismissArticle($id)\"
5482 alt='Dismiss' title='".__('Dismiss article')."'>";
5484 $reply['content'] .= "</div>";
5485 $reply['content'] .= "</div>";
5487 $reply['content'] .= "</div>";
5489 $reply['content'] .= "</div>";
5496 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5501 switch ($view_mode) {
5503 $message = __("No unread articles found to display.");
5506 $message = __("No updated articles found to display.");
5509 $message = __("No starred articles found to display.");
5513 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5515 $message = __("No articles found to display.");
5519 if (!$offset && $message) {
5520 $reply['content'] .= "<div class='whiteBox'>$message";
5522 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5524 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5525 WHERE owner_uid = " . $_SESSION['uid']);
5527 $last_updated = db_fetch_result($result, 0, "last_updated");
5528 $last_updated = make_local_datetime($link, $last_updated, false);
5530 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5532 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5533 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5535 $num_errors = db_fetch_result($result, 0, "num_errors");
5537 if ($num_errors > 0) {
5538 $reply['content'] .= "<br/>";
5539 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5540 __('Some feeds have update errors (click for details)')."</a>";
5542 $reply['content'] .= "</span></p></div>";
5546 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5548 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5549 $vgroup_last_feed, $reply);
5552 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5554 function printTagCloud($link) {
5556 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5557 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5558 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5560 $result = db_query($link, $query);
5564 while ($line = db_fetch_assoc($result)) {
5565 $tags[$line["tag_name"]] = $line["count"];
5568 if( count($tags) == 0 ){ return; }
5572 $max_size = 32; // max font size in pixels
5573 $min_size = 11; // min font size in pixels
5575 // largest and smallest array values
5576 $max_qty = max(array_values($tags));
5577 $min_qty = min(array_values($tags));
5579 // find the range of values
5580 $spread = $max_qty - $min_qty;
5581 if ($spread == 0) { // we don't want to divide by zero
5585 // set the font-size increment
5586 $step = ($max_size - $min_size) / ($spread);
5588 // loop through the tag array
5589 foreach ($tags as $key => $value) {
5590 // calculate font-size
5591 // find the $value in excess of $min_qty
5592 // multiply by the font-size increment ($size)
5593 // and add the $min_size set above
5594 $size = round($min_size +
(($value - $min_qty) * $step));
5596 $key_escaped = str_replace("'", "\\'", $key);
5598 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5599 $size . "px\" title=\"$value articles tagged with " .
5600 $key . '">' . $key . '</a> ';
5604 function print_checkpoint($n, $s) {
5605 $ts = getmicrotime();
5606 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5610 function sanitize_tag($tag) {
5613 $tag = mb_strtolower($tag, 'utf-8');
5615 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5617 // $tag = str_replace('"', "", $tag);
5618 // $tag = str_replace("+", " ", $tag);
5619 $tag = str_replace("technorati tag: ", "", $tag);
5624 function get_self_url_prefix() {
5625 return SELF_URL_PATH
;
5628 function opml_publish_url($link){
5630 $url_path = get_self_url_prefix();
5631 $url_path .= "/opml.php?op=publish&key=" .
5632 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5638 * Purge a feed contents, marked articles excepted.
5640 * @param mixed $link The database connection.
5641 * @param integer $id The id of the feed to purge.
5644 function clear_feed_articles($link, $id) {
5647 $result = db_query($link, "DELETE FROM ttrss_user_entries
5648 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5650 $result = db_query($link, "DELETE FROM ttrss_user_entries
5651 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5654 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5655 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5657 ccache_update($link, $id, $_SESSION['uid']);
5658 } // function clear_feed_articles
5661 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5663 * @return string The Mozilla Firefox feed adding URL.
5665 function add_feed_url() {
5666 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5668 $url_path = get_self_url_prefix() .
5669 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5671 } // function add_feed_url
5674 * Encrypt a password in SHA1.
5676 * @param string $pass The password to encrypt.
5677 * @param string $login A optionnal login.
5678 * @return string The encrypted password.
5680 function encrypt_password($pass, $login = '') {
5682 return "SHA1X:" . sha1("$login:$pass");
5684 return "SHA1:" . sha1($pass);
5686 } // function encrypt_password
5689 * Update a feed batch.
5690 * Used by daemons to update n feeds by run.
5691 * Only update feed needing a update, and not being processed
5692 * by another process.
5694 * @param mixed $link Database link
5695 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5696 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5697 * @param boolean $debug Set to false to disable debug output. Default to true.
5700 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5701 // Process all other feeds using last_updated and interval parameters
5703 // Test if the user has loggued in recently. If not, it does not update its feeds.
5704 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5705 if (DB_TYPE
== "pgsql") {
5706 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5708 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5711 $login_thresh_qpart = "";
5714 // Test if the feed need a update (update interval exceded).
5715 if (DB_TYPE
== "pgsql") {
5716 $update_limit_qpart = "AND ((
5717 ttrss_feeds.update_interval = 0
5718 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5720 ttrss_feeds.update_interval > 0
5721 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5722 ) OR ttrss_feeds.last_updated IS NULL)";
5724 $update_limit_qpart = "AND ((
5725 ttrss_feeds.update_interval = 0
5726 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5728 ttrss_feeds.update_interval > 0
5729 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5730 ) OR ttrss_feeds.last_updated IS NULL)";
5733 // Test if feed is currently being updated by another process.
5734 if (DB_TYPE
== "pgsql") {
5735 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5737 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5740 // Test if there is a limit to number of updated feeds
5742 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5744 $random_qpart = sql_random_function();
5746 // We search for feed needing update.
5747 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5748 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5749 ttrss_feeds.update_interval
5751 ttrss_feeds, ttrss_users, ttrss_user_prefs
5753 ttrss_feeds.owner_uid = ttrss_users.id
5754 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5755 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5756 $login_thresh_qpart $update_limit_qpart
5757 $updstart_thresh_qpart
5758 ORDER BY $random_qpart $query_limit");
5760 $user_prefs_cache = array();
5762 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5764 // Here is a little cache magic in order to minimize risk of double feed updates.
5765 $feeds_to_update = array();
5766 while ($line = db_fetch_assoc($result)) {
5767 $feeds_to_update[$line['id']] = $line;
5770 // We update the feed last update started date before anything else.
5771 // There is no lag due to feed contents downloads
5772 // It prevent an other process to update the same feed.
5773 $feed_ids = array_keys($feeds_to_update);
5775 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5776 WHERE id IN (%s)", implode(',', $feed_ids)));
5779 // For each feed, we call the feed update function.
5780 while ($line = array_pop($feeds_to_update)) {
5782 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5784 update_rss_feed($link, $line["id"], true);
5786 sleep(1); // prevent flood (FIXME make this an option?)
5789 // Send feed digests by email if needed.
5790 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5792 } // function update_daemon_common
5794 function sanitize_article_content($text) {
5795 # we don't support CDATA sections in articles, they break our own escaping
5796 $text = preg_replace("/\[\[CDATA/", "", $text);
5797 $text = preg_replace("/\]\]\>/", "", $text);
5801 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5806 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5808 if ($memcache && $obj = $memcache->get($obj_id)) {
5814 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5816 $result = db_query($link, "SELECT reg_exp,
5817 ttrss_filter_types.name AS name,
5818 ttrss_filter_actions.name AS action,
5822 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5825 owner_uid = $owner_uid AND
5826 ttrss_filter_types.id = filter_type AND
5827 ttrss_filter_actions.id = action_id AND
5828 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5830 while ($line = db_fetch_assoc($result)) {
5831 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5832 $filter["reg_exp"] = $line["reg_exp"];
5833 $filter["action"] = $line["action"];
5834 $filter["action_param"] = $line["action_param"];
5835 $filter["filter_param"] = $line["filter_param"];
5836 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5838 array_push($filters[$line["name"]], $filter);
5841 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5847 function get_score_pic($score) {
5849 return "score_high.png";
5850 } else if ($score > 0) {
5851 return "score_half_high.png";
5852 } else if ($score < -100) {
5853 return "score_low.png";
5854 } else if ($score < 0) {
5855 return "score_half_low.png";
5857 return "score_neutral.png";
5861 function rounded_table_start($classname, $header = " ") {
5862 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5863 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5864 print "<tr><td class='left'> </td><td class='content'>";
5867 function rounded_table_end($footer = " ") {
5868 print "</td><td class='right'> </td></tr>";
5869 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5873 function feed_has_icon($id) {
5874 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5877 function init_connection($link) {
5878 if (DB_TYPE
== "pgsql") {
5879 pg_query($link, "set client_encoding = 'UTF-8'");
5880 pg_set_client_encoding("UNICODE");
5881 pg_query($link, "set datestyle = 'ISO, european'");
5882 pg_query($link, "set TIME ZONE 0");
5884 db_query($link, "SET time_zone = '+0:0'");
5886 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5887 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5888 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5893 function update_feedbrowser_cache($link) {
5895 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
5896 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5897 WHERE tf.feed_url = ttrss_feeds.feed_url
5898 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
5899 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
5901 db_query($link, "BEGIN");
5903 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5907 while ($line = db_fetch_assoc($result)) {
5908 $subscribers = db_escape_string($line["subscribers"]);
5909 $feed_url = db_escape_string($line["feed_url"]);
5910 $title = db_escape_string($line["title"]);
5911 $site_url = db_escape_string($line["site_url"]);
5913 $tmp_result = db_query($link, "SELECT subscribers FROM
5914 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5916 if (db_num_rows($tmp_result) == 0) {
5918 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5919 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5920 '$site_url', '$title', '$subscribers')");
5928 db_query($link, "COMMIT");
5934 function ccache_zero($link, $feed_id, $owner_uid) {
5935 db_query($link, "UPDATE ttrss_counters_cache SET
5936 value = 0, updated = NOW() WHERE
5937 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5940 function ccache_zero_all($link, $owner_uid) {
5941 db_query($link, "UPDATE ttrss_counters_cache SET
5942 value = 0 WHERE owner_uid = '$owner_uid'");
5944 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5945 value = 0 WHERE owner_uid = '$owner_uid'");
5948 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5951 $table = "ttrss_counters_cache";
5953 $table = "ttrss_cat_counters_cache";
5956 db_query($link, "DELETE FROM $table WHERE
5957 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5961 function ccache_update_all($link, $owner_uid) {
5963 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5965 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5966 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5968 while ($line = db_fetch_assoc($result)) {
5969 ccache_update($link, $line["feed_id"], $owner_uid, true);
5972 /* We have to manually include category 0 */
5974 ccache_update($link, 0, $owner_uid, true);
5977 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5978 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5980 while ($line = db_fetch_assoc($result)) {
5981 print ccache_update($link, $line["feed_id"], $owner_uid);
5988 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5989 $no_update = false) {
5991 if (!is_numeric($feed_id)) return;
5994 $table = "ttrss_counters_cache";
5996 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5997 WHERE id = '$feed_id'");
5998 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6001 $table = "ttrss_cat_counters_cache";
6004 if (DB_TYPE
== "pgsql") {
6005 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
6006 } else if (DB_TYPE
== "mysql") {
6007 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
6010 $result = db_query($link, "SELECT value FROM $table
6011 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
6014 if (db_num_rows($result) == 1) {
6015 return db_fetch_result($result, 0, "value");
6020 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
6026 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6027 $update_pcat = true) {
6029 if (!is_numeric($feed_id)) return;
6031 if (!$is_cat && $feed_id > 0) {
6032 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
6033 WHERE id = '$feed_id'");
6034 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6037 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6039 /* When updating a label, all we need to do is recalculate feed counters
6040 * because labels are not cached */
6043 ccache_update_all($link, $owner_uid);
6048 $table = "ttrss_counters_cache";
6050 $table = "ttrss_cat_counters_cache";
6053 if ($is_cat && $feed_id >= 0) {
6054 if ($feed_id != 0) {
6055 $cat_qpart = "cat_id = '$feed_id'";
6057 $cat_qpart = "cat_id IS NULL";
6060 /* Recalculate counters for child feeds */
6062 $result = db_query($link, "SELECT id FROM ttrss_feeds
6063 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6065 while ($line = db_fetch_assoc($result)) {
6066 ccache_update($link, $line["id"], $owner_uid, false, false);
6069 $result = db_query($link, "SELECT SUM(value) AS sv
6070 FROM ttrss_counters_cache, ttrss_feeds
6071 WHERE id = feed_id AND $cat_qpart AND
6072 ttrss_feeds.owner_uid = '$owner_uid'");
6074 $unread = (int) db_fetch_result($result, 0, "sv");
6077 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6080 db_query($link, "BEGIN");
6082 $result = db_query($link, "SELECT feed_id FROM $table
6083 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6085 if (db_num_rows($result) == 1) {
6086 db_query($link, "UPDATE $table SET
6087 value = '$unread', updated = NOW() WHERE
6088 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6091 db_query($link, "INSERT INTO $table
6092 (feed_id, value, owner_uid, updated)
6094 ($feed_id, $unread, $owner_uid, NOW())");
6097 db_query($link, "COMMIT");
6099 if ($feed_id > 0 && $prev_unread != $unread) {
6103 /* Update parent category */
6107 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6108 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6110 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6112 ccache_update($link, $cat_id, $owner_uid, true);
6116 } else if ($feed_id < 0) {
6117 ccache_update_all($link, $owner_uid);
6123 function label_find_id($link, $label, $owner_uid) {
6124 $result = db_query($link,
6125 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6126 AND owner_uid = '$owner_uid' LIMIT 1");
6128 if (db_num_rows($result) == 1) {
6129 return db_fetch_result($result, 0, "id");
6135 function get_article_labels($link, $id) {
6138 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6142 if ($memcache && $obj = $memcache->get($obj_id)) {
6146 $result = db_query($link, "SELECT label_cache FROM
6147 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6150 $label_cache = db_fetch_result($result, 0, "label_cache");
6154 $label_cache = json_decode($label_cache, true);
6156 if ($label_cache["no-labels"] == 1)
6159 return $label_cache;
6162 $result = db_query($link,
6163 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6164 FROM ttrss_labels2, ttrss_user_labels2
6166 AND article_id = '$id'
6167 AND owner_uid = ".$_SESSION["uid"] . "
6170 while ($line = db_fetch_assoc($result)) {
6171 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6173 array_push($rv, $rk);
6175 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6178 label_update_cache($link, $id, $rv);
6180 label_update_cache($link, $id, array("no-labels" => 1));
6187 function label_find_caption($link, $label, $owner_uid) {
6188 $result = db_query($link,
6189 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6190 AND owner_uid = '$owner_uid' LIMIT 1");
6192 if (db_num_rows($result) == 1) {
6193 return db_fetch_result($result, 0, "caption");
6199 function label_update_cache($link, $id, $labels = false, $force = false) {
6202 label_clear_cache($link, $id);
6205 $labels = get_article_labels($link, $id);
6207 $labels = db_escape_string(json_encode($labels));
6209 db_query($link, "UPDATE ttrss_user_entries SET
6210 label_cache = '$labels' WHERE ref_id = '$id'");
6214 function label_clear_cache($link, $id) {
6216 db_query($link, "UPDATE ttrss_user_entries SET
6217 label_cache = '' WHERE ref_id = '$id'");
6221 function label_remove_article($link, $id, $label, $owner_uid) {
6223 $label_id = label_find_id($link, $label, $owner_uid);
6225 if (!$label_id) return;
6227 $result = db_query($link,
6228 "DELETE FROM ttrss_user_labels2
6230 label_id = '$label_id' AND
6231 article_id = '$id'");
6233 label_clear_cache($link, $id);
6236 function label_add_article($link, $id, $label, $owner_uid) {
6241 $obj_id = md5("LABELS:$id:$owner_uid");
6242 $memcache->delete($obj_id);
6245 $label_id = label_find_id($link, $label, $owner_uid);
6247 if (!$label_id) return;
6249 $result = db_query($link,
6251 article_id FROM ttrss_labels2, ttrss_user_labels2
6254 label_id = '$label_id' AND
6255 article_id = '$id' AND owner_uid = '$owner_uid'
6258 if (db_num_rows($result) == 0) {
6259 db_query($link, "INSERT INTO ttrss_user_labels2
6260 (label_id, article_id) VALUES ('$label_id', '$id')");
6263 label_clear_cache($link, $id);
6267 function label_remove($link, $id, $owner_uid) {
6270 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6273 $obj_id = md5("LABELS:$id:$owner_uid");
6274 $memcache->delete($obj_id);
6277 db_query($link, "BEGIN");
6279 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6282 $caption = db_fetch_result($result, 0, "caption");
6284 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6285 AND owner_uid = " . $owner_uid);
6287 if (db_affected_rows($link, $result) != 0 && $caption) {
6289 /* Remove access key for the label */
6291 $ext_id = -11 - $id;
6293 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6294 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6296 /* Disable filters that reference label being removed */
6298 db_query($link, "UPDATE ttrss_filters SET
6299 enabled = false WHERE action_param = '$caption'
6301 AND owner_uid = " . $owner_uid);
6303 /* Remove cached data */
6305 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6306 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6310 db_query($link, "COMMIT");
6313 function label_create($link, $caption) {
6315 db_query($link, "BEGIN");
6319 $result = db_query($link, "SELECT id FROM ttrss_labels2
6320 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6322 if (db_num_rows($result) == 0) {
6323 $result = db_query($link,
6324 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6325 VALUES ('$caption', '".$_SESSION["uid"]."')");
6327 $result = db_affected_rows($link, $result) != 0;
6330 db_query($link, "COMMIT");
6335 function print_labels_headlines_dropdown($link, $feed_id) {
6336 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6338 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6339 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6341 while ($line = db_fetch_assoc($result)) {
6343 $label_id = $line["id"];
6344 $label_caption = $line["caption"];
6347 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6348 print "<option id=\"LHDL-$id\"
6349 value=\"selectionRemoveLabel($label_id)\">".
6350 __('Remove:') . " $label_caption</option>";
6352 print "<option id=\"LHDL-$id\"
6353 value=\"selectionAssignLabel($label_id)\">".
6354 __('Assign:') . " $label_caption</option>";
6359 function format_tags_string($tags, $id) {
6362 $tags_nolinks_str = "";
6368 $formatted_tags = array();
6370 foreach ($tags as $tag) {
6372 $tag_escaped = str_replace("'", "\\'", $tag);
6374 if (mb_strlen($tag) > 30) {
6375 $tag = truncate_string($tag, 30);
6378 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6380 array_push($formatted_tags, $tag_str);
6382 $tmp_tags_str = implode(", ", $formatted_tags);
6384 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6389 $tags_str = implode(", ", $formatted_tags);
6391 if ($num_tags < count($tags)) {
6392 $tags_str .= ", …";
6395 if ($num_tags == 0) {
6396 $tags_str = __("no tags");
6403 function format_article_labels($labels, $id) {
6407 foreach ($labels as $l) {
6408 $labels_str .= sprintf("<span class='hlLabelRef'
6409 style='color : %s; background-color : %s'>%s</span>",
6410 $l[2], $l[3], $l[1]);
6417 function format_article_note($id, $note) {
6419 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6420 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6421 __('(edit note)')."</div>$note</div>";
6426 function toggle_collapse_cat($link, $cat_id, $mode) {
6428 $mode = bool_to_sql_bool($mode);
6430 db_query($link, "UPDATE ttrss_feed_categories SET
6431 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6438 $pref_name = '_COLLAPSED_SPECIAL';
6441 $pref_name = '_COLLAPSED_LABELS';
6444 $pref_name = '_COLLAPSED_UNCAT';
6450 set_pref($link, $pref_name, 'true');
6452 set_pref($link, $pref_name, 'false');
6458 function remove_feed($link, $id, $owner_uid) {
6462 /* save starred articles in Archived feed */
6464 db_query($link, "BEGIN");
6466 /* prepare feed if necessary */
6468 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6471 if (db_num_rows($result) == 0) {
6472 db_query($link, "INSERT INTO ttrss_archived_feeds
6473 (id, owner_uid, title, feed_url, site_url)
6474 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6478 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6479 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6480 marked = true AND owner_uid = $owner_uid");
6482 /* Remove access key for the feed */
6484 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6485 feed_id = '$id' AND owner_uid = $owner_uid");
6487 /* remove the feed */
6489 db_query($link, "DELETE FROM ttrss_feeds
6490 WHERE id = '$id' AND owner_uid = $owner_uid");
6492 db_query($link, "COMMIT");
6494 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6495 unlink(ICONS_DIR . "/$id.ico");
6498 ccache_remove($link, $id, $owner_uid);
6501 label_remove($link, -11-$id, $owner_uid);
6502 ccache_remove($link, -11-$id, $owner_uid);
6506 function add_feed_category($link, $feed_cat) {
6508 if (!$feed_cat) return false;
6510 db_query($link, "BEGIN");
6512 $result = db_query($link,
6513 "SELECT id FROM ttrss_feed_categories
6514 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6516 if (db_num_rows($result) == 0) {
6518 $result = db_query($link,
6519 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6520 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6522 db_query($link, "COMMIT");
6530 function remove_feed_category($link, $id, $owner_uid) {
6532 db_query($link, "DELETE FROM ttrss_feed_categories
6533 WHERE id = '$id' AND owner_uid = $owner_uid");
6535 ccache_remove($link, $id, $owner_uid, true);
6538 function archive_article($link, $id, $owner_uid) {
6539 db_query($link, "BEGIN");
6541 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6542 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6544 if (db_num_rows($result) != 0) {
6546 /* prepare the archived table */
6548 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6551 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6552 WHERE id = '$feed_id'");
6554 if (db_num_rows($result) == 0) {
6555 db_query($link, "INSERT INTO ttrss_archived_feeds
6556 (id, owner_uid, title, feed_url, site_url)
6557 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6558 WHERE id = '$feed_id'");
6561 db_query($link, "UPDATE ttrss_user_entries
6562 SET orig_feed_id = feed_id, feed_id = NULL
6563 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6567 db_query($link, "COMMIT");
6570 function getArticleFeed($link, $id) {
6571 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6572 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6574 if (db_num_rows($result) != 0) {
6575 return db_fetch_result($result, 0, "feed_id");
6581 function make_url_from_parts($parts) {
6582 $url = $parts['scheme'] . '://' . $parts['host'];
6584 if ($parts['path']) $url .= $parts['path'];
6585 if ($parts['query']) $url .= '?' . $parts['query'];
6591 * Fixes incomplete URLs by prepending "http://".
6592 * Also replaces feed:// with http://, and
6593 * prepends a trailing slash if the url is a domain name only.
6595 * @param string $url Possibly incomplete URL
6597 * @return string Fixed URL.
6599 function fix_url($url) {
6600 if (strpos($url, '://') === false) {
6601 $url = 'http://' . $url;
6602 } else if (substr($url, 0, 5) == 'feed:') {
6603 $url = 'http:' . substr($url, 5);
6606 //prepend slash if the URL has no slash in it
6607 // "http://www.example" -> "http://www.example/"
6608 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6612 if ($url != "http:///")
6618 function validate_feed_url($url) {
6619 $parts = parse_url($url);
6621 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6625 function get_article_enclosures($link, $id) {
6629 $query = "SELECT * FROM ttrss_enclosures
6630 WHERE post_id = '$id' AND content_url != ''";
6632 $obj_id = md5("ENCLOSURES:$id");
6636 if ($memcache && $obj = $memcache->get($obj_id)) {
6639 $result = db_query($link, $query);
6641 if (db_num_rows($result) > 0) {
6642 while ($line = db_fetch_assoc($result)) {
6643 array_push($rv, $line);
6645 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6652 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6658 if ($cat_id == -4 ||
$cat_id == -2) {
6659 $counters = getLabelCounters($link, true);
6661 foreach (array_values($counters) as $cv) {
6663 $unread = $cv["counter"];
6665 if ($unread ||
!$unread_only) {
6669 "title" => $cv["description"],
6670 "unread" => $cv["counter"],
6674 array_push($feeds, $row);
6681 if ($cat_id == -4 ||
$cat_id == -1) {
6682 foreach (array(-1, -2, -3, -4, 0) as $i) {
6683 $unread = getFeedUnread($link, $i);
6685 if ($unread ||
!$unread_only) {
6686 $title = getFeedTitle($link, $i);
6691 "unread" => $unread,
6694 array_push($feeds, $row);
6703 $limit_qpart = "LIMIT $limit OFFSET $offset";
6708 if ($cat_id == -4 ||
$cat_id == -3) {
6709 $result = db_query($link, "SELECT
6710 id, feed_url, cat_id, title, ".
6711 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6712 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6713 " ORDER BY cat_id, title " . $limit_qpart);
6717 $cat_qpart = "cat_id = '$cat_id'";
6719 $cat_qpart = "cat_id IS NULL";
6721 $result = db_query($link, "SELECT
6722 id, feed_url, cat_id, title, ".
6723 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6724 FROM ttrss_feeds WHERE
6725 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6726 " ORDER BY cat_id, title " . $limit_qpart);
6729 while ($line = db_fetch_assoc($result)) {
6731 $unread = getFeedUnread($link, $line["id"]);
6733 $has_icon = feed_has_icon($line['id']);
6735 if ($unread ||
!$unread_only) {
6738 "feed_url" => $line["feed_url"],
6739 "title" => $line["title"],
6740 "id" => (int)$line["id"],
6741 "unread" => (int)$unread,
6742 "has_icon" => $has_icon,
6743 "cat_id" => (int)$line["cat_id"],
6744 "last_updated" => strtotime($line["last_updated"])
6747 array_push($feeds, $row);
6754 function api_get_headlines($link, $feed_id, $limit, $offset,
6755 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6756 $include_attachments) {
6758 /* do not rely on params below */
6760 $search = db_escape_string($_REQUEST["search"]);
6761 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6762 $match_on = db_escape_string($_REQUEST["match_on"]);
6764 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6765 $view_mode, $is_cat, $search, $search_mode, $match_on,
6768 $result = $qfh_ret[0];
6769 $feed_title = $qfh_ret[1];
6771 $headlines = array();
6773 while ($line = db_fetch_assoc($result)) {
6774 $is_updated = ($line["last_read"] == "" &&
6775 ($line["unread"] != "t" && $line["unread"] != "1"));
6777 $headline_row = array(
6778 "id" => (int)$line["id"],
6779 "unread" => sql_bool_to_bool($line["unread"]),
6780 "marked" => sql_bool_to_bool($line["marked"]),
6781 "published" => sql_bool_to_bool($line["published"]),
6782 "updated" => strtotime($line["updated"]),
6783 "is_updated" => $is_updated,
6784 "title" => $line["title"],
6785 "link" => $line["link"],
6786 "feed_id" => $line["feed_id"],
6787 "tags" => get_article_tags($link, $line["id"]),
6790 if ($include_attachments)
6791 $headline_row['attachments'] = get_article_enclosures($link,
6794 if ($show_excerpt) {
6795 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6796 $headline_row["excerpt"] = $excerpt;
6799 if ($show_content) {
6800 $headline_row["content"] = $line["content_preview"];
6803 array_push($headlines, $headline_row);
6809 function generate_error_feed($link, $error) {
6812 $reply['headlines']['id'] = -6;
6813 $reply['headlines']['is_cat'] = false;
6815 $reply['headlines']['toolbar'] = '';
6816 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6818 $reply['headlines-info'] = array("count" => 0,
6819 "vgroup_last_feed" => '',
6821 "disable_cache" => true);
6827 function generate_dashboard_feed($link) {
6830 $reply['headlines']['id'] = -5;
6831 $reply['headlines']['is_cat'] = false;
6833 $reply['headlines']['toolbar'] = '';
6834 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6836 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6838 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6839 WHERE owner_uid = " . $_SESSION['uid']);
6841 $last_updated = db_fetch_result($result, 0, "last_updated");
6842 $last_updated = make_local_datetime($link, $last_updated, false);
6844 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6846 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6847 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6849 $num_errors = db_fetch_result($result, 0, "num_errors");
6851 if ($num_errors > 0) {
6852 $reply['headlines']['content'] .= "<br/>";
6853 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6854 __('Some feeds have update errors (click for details)')."</a>";
6856 $reply['headlines']['content'] .= "</span></p>";
6858 $reply['headlines-info'] = array("count" => 0,
6859 "vgroup_last_feed" => '',
6861 "disable_cache" => true);
6866 function save_email_address($link, $email) {
6867 // FIXME: implement persistent storage of emails
6869 if (!$_SESSION['stored_emails'])
6870 $_SESSION['stored_emails'] = array();
6872 if (!in_array($email, $_SESSION['stored_emails']))
6873 array_push($_SESSION['stored_emails'], $email);
6876 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6877 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6879 $sql_is_cat = bool_to_sql_bool($is_cat);
6881 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6882 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6883 AND owner_uid = " . $owner_uid);
6885 if (db_num_rows($result) == 1) {
6886 $key = db_escape_string(sha1(uniqid(rand(), true)));
6888 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6889 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6890 AND owner_uid = " . $owner_uid);
6895 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6899 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6901 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6903 $sql_is_cat = bool_to_sql_bool($is_cat);
6905 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6906 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6907 AND owner_uid = " . $owner_uid);
6909 if (db_num_rows($result) == 1) {
6910 return db_fetch_result($result, 0, "access_key");
6912 $key = db_escape_string(sha1(uniqid(rand(), true)));
6914 $result = db_query($link, "INSERT INTO ttrss_access_keys
6915 (access_key, feed_id, is_cat, owner_uid)
6916 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6924 * Extracts RSS/Atom feed URLs from the given HTML URL.
6926 * @param string $url HTML page URL
6928 * @return array Array of feeds. Key is the full URL, value the title
6930 function get_feeds_from_html($url, $login = false, $pass = false)
6932 $url = fix_url($url);
6933 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6935 libxml_use_internal_errors(true);
6937 $content = @fetch_file_contents
($url, false, $login, $pass);
6939 $doc = new DOMDocument();
6940 $doc->loadHTML($content);
6941 $xpath = new DOMXPath($doc);
6942 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6943 $feedUrls = array();
6944 foreach ($entries as $entry) {
6945 if ($entry->hasAttribute('href')) {
6946 $title = $entry->getAttribute('title');
6948 $title = $entry->getAttribute('type');
6950 $feedUrl = rewrite_relative_url(
6951 $baseUrl, $entry->getAttribute('href')
6953 $feedUrls[$feedUrl] = $title;
6960 * Checks if the content behind the given URL is a HTML file
6962 * @param string $url URL to check
6964 * @return boolean True if the URL contains HTML content
6966 function url_is_html($url, $login = false, $pass = false) {
6967 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6969 if (stripos($content, '<html>') === false
6970 && stripos($content, '<html ') === false
6978 function print_label_select($link, $name, $value, $attributes = "") {
6980 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6981 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6983 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6984 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6986 while ($line = db_fetch_assoc($result)) {
6988 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6990 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6991 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6995 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
7002 function format_article_enclosures($link, $id, $always_display_enclosures,
7005 $result = get_article_enclosures($link, $id);
7008 if (count($result) > 0) {
7010 $entries_html = array();
7013 foreach ($result as $line) {
7015 $url = $line["content_url"];
7016 $ctype = $line["content_type"];
7018 if (!$ctype) $ctype = __("unknown type");
7020 # $filename = substr($url, strrpos($url, "/")+1);
7022 $entry = format_inline_player($link, $url, $ctype);
7024 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
7025 # $filename . " (" . $ctype . ")" . "</a>";
7027 array_push($entries_html, $entry);
7031 $entry["type"] = $ctype;
7032 $entry["filename"] = $filename;
7033 $entry["url"] = $url;
7035 array_push($entries, $entry);
7038 $rv .= "<div class=\"postEnclosures\">";
7040 if (!get_pref($link, "STRIP_IMAGES")) {
7041 if ($always_display_enclosures ||
7042 !preg_match("/<img/i", $article_content)) {
7044 foreach ($entries as $entry) {
7046 if (preg_match("/image/", $entry["type"]) ||
7047 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
7050 alt=\"".htmlspecialchars($entry["filename"])."\"
7051 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7057 if (count($entries) == 1) {
7058 $rv .= __("Attachment:") . " ";
7060 $rv .= __("Attachments:") . " ";
7063 $rv .= join(", ", $entries_html);
7071 function getLastArticleId($link) {
7072 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7073 WHERE owner_uid = " . $_SESSION["uid"]);
7075 if (db_num_rows($result) == 1) {
7076 return db_fetch_result($result, 0, "id");
7082 function build_url($parts) {
7083 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7087 * Converts a (possibly) relative URL to a absolute one.
7089 * @param string $url Base URL (i.e. from where the document is)
7090 * @param string $rel_url Possibly relative URL in the document
7092 * @return string Absolute URL
7094 function rewrite_relative_url($url, $rel_url) {
7095 if (strpos($rel_url, "://") !== false) {
7097 } else if (strpos($rel_url, "/") === 0)
7099 $parts = parse_url($url);
7100 $parts['path'] = $rel_url;
7102 return build_url($parts);
7105 $parts = parse_url($url);
7106 if (!isset($parts['path'])) {
7107 $parts['path'] = '/';
7109 $dir = $parts['path'];
7110 if (substr($dir, -1) !== '/') {
7111 $dir = dirname($parts['path']);
7112 $dir !== '/' && $dir .= '/';
7114 $parts['path'] = $dir . $rel_url;
7116 return build_url($parts);
7120 function sphinx_search($query, $offset = 0, $limit = 30) {
7121 $sphinxClient = new SphinxClient();
7123 $sphinxClient->SetServer('localhost', 9312);
7124 $sphinxClient->SetConnectTimeout(1);
7126 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7127 'feed_title' => 20));
7129 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
7130 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
7131 $sphinxClient->SetLimits($offset, $limit, 1000);
7132 $sphinxClient->SetArrayResult(false);
7133 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7135 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
7139 if (is_array($result['matches'])) {
7140 foreach (array_keys($result['matches']) as $int_id) {
7141 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7142 array_push($ids, $ref_id);
7149 function cleanup_tags($link, $days = 14, $limit = 1000) {
7151 if (DB_TYPE
== "pgsql") {
7152 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7153 } else if (DB_TYPE
== "mysql") {
7154 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7159 while ($limit > 0) {
7162 $query = "SELECT ttrss_tags.id AS id
7163 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7164 WHERE post_int_id = int_id AND $interval_query AND
7165 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7167 $result = db_query($link, $query);
7171 while ($line = db_fetch_assoc($result)) {
7172 array_push($ids, $line['id']);
7175 if (count($ids) > 0) {
7176 $ids = join(",", $ids);
7179 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7180 $tags_deleted +
= db_affected_rows($link, $tmp_result);
7185 $limit -= $limit_part;
7190 return $tags_deleted;
7193 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7195 $cat_id = (int) $cat_id;
7198 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7199 } else if ($cat_id == 0 ||
$cat_id == -2) {
7200 $cat_unread = getCategoryUnread($link, $cat_id);
7203 $obj['id'] = 'CAT:' . $cat_id;
7204 $obj['items'] = array();
7205 $obj['name'] = getCategoryTitle($link, $cat_id);
7206 $obj['type'] = 'feed';
7207 $obj['unread'] = (int) $cat_unread;
7208 $obj['hidden'] = $hidden;
7209 $obj['bare_id'] = $cat_id;
7214 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7216 $feed_id = (int) $feed_id;
7219 $title = getFeedTitle($link, $feed_id, false);
7221 if ($unread === false)
7222 $unread = getFeedUnread($link, $feed_id, false);
7224 $obj['id'] = 'FEED:' . $feed_id;
7225 $obj['name'] = $title;
7226 $obj['unread'] = (int) $unread;
7227 $obj['type'] = 'feed';
7228 $obj['error'] = $error;
7229 $obj['updated'] = $updated;
7230 $obj['icon'] = getFeedIcon($feed_id);
7231 $obj['bare_id'] = $feed_id;
7237 function fetch_twitter_rss($link, $url, $owner_uid) {
7238 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7239 WHERE id = $owner_uid");
7241 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7242 $url_escaped = db_escape_string($url);
7244 if ($access_token) {
7246 $tmhOAuth = new tmhOAuth(array(
7247 'consumer_key' => CONSUMER_KEY
,
7248 'consumer_secret' => CONSUMER_SECRET
,
7249 'user_token' => $access_token['oauth_token'],
7250 'user_secret' => $access_token['oauth_token_secret'],
7253 $code = $tmhOAuth->request('GET', $url);
7257 $content = $tmhOAuth->response
['response'];
7259 define('MAGPIE_CACHE_ON', false);
7261 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7262 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7268 db_query($link, "UPDATE ttrss_feeds
7269 SET last_error = 'OAuth authorization failed ($code).'
7270 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7275 db_query($link, "UPDATE ttrss_feeds
7276 SET last_error = 'OAuth information not found.'
7277 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7283 function print_user_stylesheet($link) {
7284 $value = get_pref($link, 'USER_STYLESHEET');
7287 print "<style type=\"text/css\">";
7288 print str_replace("<br/>", "\n", $value);
7294 function rewrite_urls($line) {
7299 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7300 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7305 function filter_to_sql($filter) {
7308 if (DB_TYPE
== "pgsql")
7311 $reg_qpart = "REGEXP";
7313 switch ($filter["type"]) {
7315 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7316 $filter['reg_exp'] . "')";
7319 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7320 $filter['reg_exp'] . "')";
7323 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7324 $filter['reg_exp'] . "') OR LOWER(" .
7325 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7328 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7329 $filter['reg_exp'] . "')";
7332 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7333 $filter['reg_exp'] . "')";
7337 if ($filter["filter_param"] == "before")
7342 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7343 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7346 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7347 $filter['reg_exp'] . "')";
7351 if ($filter["inverse"])
7352 $query = "NOT ($query)";
7355 if (DB_TYPE
== "pgsql") {
7356 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
7358 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
7368 // -1 - never connected
7369 // 0 - no data received
7370 // 1 - data received successfully
7371 // 2 - did not receive valid data
7372 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7374 function get_linked_feeds($link, $instance_id = false) {
7376 $instance_qpart = "id = '$instance_id' AND ";
7378 $instance_qpart = "";
7380 if (DB_TYPE
== "pgsql") {
7381 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
7383 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
7386 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7387 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7389 while ($line = db_fetch_assoc($result)) {
7392 _debug("Updating: " . $line['access_url'] . " ($id)");
7394 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7395 $post_query = 'key=' . $line['access_key'];
7397 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7400 $feeds = json_decode($feeds, true);
7403 if ($feeds['error']) {
7404 $status = $feeds['error']['code'] +
10;
7408 if (count($feeds['feeds']) > 0) {
7410 db_query($link, "DELETE FROM ttrss_linked_feeds
7411 WHERE instance_id = '$id'");
7413 foreach ($feeds['feeds'] as $feed) {
7414 $feed_url = db_escape_string($feed['feed_url']);
7415 $title = db_escape_string($feed['title']);
7416 $subscribers = db_escape_string($feed['subscribers']);
7417 $site_url = db_escape_string($feed['site_url']);
7419 db_query($link, "INSERT INTO ttrss_linked_feeds
7420 (feed_url, site_url, title, subscribers, instance_id, created, updated)
7422 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
7425 // received 0 feeds, this might indicate that
7426 // the instance on the other hand is rebuilding feedbrowser cache
7427 // we will try again later
7429 // TODO: maybe perform expiration based on updated here?
7432 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7442 _debug("Status: $status");
7444 db_query($link, "UPDATE ttrss_linked_instances SET
7445 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");