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]";
119 $config->set('HTML.SafeObject', true);
120 @$config->set('HTML', 'Allowed', $allowed);
121 $config->set('Output.FlashCompat', true);
122 $config->set('Attr.EnableID', true);
124 $purifier = new HTMLPurifier($config);
127 * Print a timestamped debug message.
129 * @param string $msg The debug message.
132 function _debug($msg) {
133 $ts = strftime("%H:%M:%S", time());
134 if (function_exists('posix_getpid')) {
135 $ts = "$ts/" . posix_getpid();
137 print "[$ts] $msg\n";
141 * Purge a feed old posts.
143 * @param mixed $link A database connection.
144 * @param mixed $feed_id The id of the purged feed.
145 * @param mixed $purge_interval Olderness of purged posts.
146 * @param boolean $debug Set to True to enable the debug. False by default.
150 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
152 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
156 $result = db_query($link,
157 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
161 if (db_num_rows($result) == 1) {
162 $owner_uid = db_fetch_result($result, 0, "owner_uid");
165 if ($purge_interval == -1 ||
!$purge_interval) {
167 ccache_update($link, $feed_id, $owner_uid);
172 if (!$owner_uid) return;
174 if (FORCE_ARTICLE_PURGE
== 0) {
175 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
178 $purge_unread = true;
179 $purge_interval = FORCE_ARTICLE_PURGE
;
182 if (!$purge_unread) $query_limit = " unread = false AND ";
184 if (DB_TYPE
== "pgsql") {
185 $pg_version = get_pgsql_version($link);
187 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
189 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
190 ttrss_entries.id = ref_id AND
192 feed_id = '$feed_id' AND
194 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
198 $result = db_query($link, "DELETE FROM ttrss_user_entries
200 WHERE ttrss_entries.id = ref_id AND
202 feed_id = '$feed_id' AND
204 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
207 $rows = pg_affected_rows($result);
211 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
212 marked = false AND feed_id = '$feed_id' AND
213 (SELECT date_updated FROM ttrss_entries WHERE
214 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
216 $result = db_query($link, "DELETE FROM ttrss_user_entries
217 USING ttrss_user_entries, ttrss_entries
218 WHERE ttrss_entries.id = ref_id AND
220 feed_id = '$feed_id' AND
222 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
224 $rows = mysql_affected_rows($link);
228 ccache_update($link, $feed_id, $owner_uid);
231 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
233 } // function purge_feed
236 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
238 * @param mixed $link A database connection
239 * @param boolean $do_output Set to true to enable printed output, false by default.
240 * @param integer $limit The maximal number of removed posts.
244 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
246 $random_qpart = sql_random_function();
249 $limit_qpart = "LIMIT $limit";
254 $result = db_query($link,
255 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
256 ORDER BY $random_qpart $limit_qpart");
258 while ($line = db_fetch_assoc($result)) {
260 $feed_id = $line["id"];
261 $purge_interval = $line["purge_interval"];
262 $owner_uid = $line["owner_uid"];
264 if ($purge_interval == 0) {
266 $tmp_result = db_query($link,
267 "SELECT value FROM ttrss_user_prefs WHERE
268 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
270 if (db_num_rows($tmp_result) != 0) {
271 $purge_interval = db_fetch_result($tmp_result, 0, "value");
276 // print "Feed $feed_id: purge interval = $purge_interval\n";
279 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
280 purge_feed($link, $feed_id, $purge_interval, $do_output);
284 purge_orphans($link, $do_output);
286 } // function global_purge_old_posts */
288 function feed_purge_interval($link, $feed_id) {
290 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
291 WHERE id = '$feed_id'");
293 if (db_num_rows($result) == 1) {
294 $purge_interval = db_fetch_result($result, 0, "purge_interval");
295 $owner_uid = db_fetch_result($result, 0, "owner_uid");
297 if ($purge_interval == 0) $purge_interval = get_pref($link,
298 'PURGE_OLD_DAYS', $owner_uid);
300 return $purge_interval;
307 function purge_old_posts($link) {
309 $user_id = $_SESSION["uid"];
311 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
312 WHERE owner_uid = '$user_id'");
314 while ($line = db_fetch_assoc($result)) {
316 $feed_id = $line["id"];
317 $purge_interval = $line["purge_interval"];
319 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
321 if ($purge_interval > 0) {
322 purge_feed($link, $feed_id, $purge_interval);
326 purge_orphans($link);
329 function purge_orphans($link, $do_output = false) {
331 // purge orphaned posts in main content table
332 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
333 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
336 $rows = db_affected_rows($link, $result);
337 _debug("Purged $rows orphaned posts.");
341 function get_feed_update_interval($link, $feed_id) {
342 $result = db_query($link, "SELECT owner_uid, update_interval FROM
343 ttrss_feeds WHERE id = '$feed_id'");
345 if (db_num_rows($result) == 1) {
346 $update_interval = db_fetch_result($result, 0, "update_interval");
347 $owner_uid = db_fetch_result($result, 0, "owner_uid");
349 if ($update_interval != 0) {
350 return $update_interval;
352 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
360 function fetch_file_contents($url, $type = false, $login = false, $pass = false) {
361 $login = urlencode($login);
362 $pass = urlencode($pass);
364 if (function_exists('curl_init')) {
365 $ch = curl_init($url);
367 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
368 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
369 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
370 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
371 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
372 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
373 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
374 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
377 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
379 $contents = @curl_exec
($ch);
380 if ($contents === false) {
385 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
386 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
389 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
395 if ($login && $pass && $updated != 3) {
396 $url_parts = array();
398 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
400 if ($url_parts[1] && $url_parts[2]) {
401 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
405 return @file_get_contents
($url);
411 * Try to determine the favicon URL for a feed.
412 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
413 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
415 * @param string $url A feed or page URL
417 * @return mixed The favicon URL, or false if none was found.
419 function get_favicon_url($url) {
421 $favicon_url = false;
423 if ($html = @fetch_file_contents
($url)) {
425 libxml_use_internal_errors(true);
427 $doc = new DOMDocument();
428 $doc->loadHTML($html);
429 $xpath = new DOMXPath($doc);
431 $base = $xpath->query('/html/head/base');
432 foreach ($base as $b) {
433 $url = $b->getAttribute("href");
437 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
438 if (count($entries) > 0) {
439 foreach ($entries as $entry) {
440 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
447 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
450 } // function get_favicon_url
452 function check_feed_favicon($site_url, $feed, $link) {
453 $favicon_url = get_favicon_url($site_url);
455 # print "FAVICON [$site_url]: $favicon_url\n";
457 $icon_file = ICONS_DIR
. "/$feed.ico";
459 if ($favicon_url && !file_exists($icon_file)) {
460 $contents = fetch_file_contents($favicon_url, "image");
462 $fp = fopen($icon_file, "w");
465 fwrite($fp, $contents);
467 chmod($icon_file, 0644);
473 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
477 /* Update all feeds with the same URL to utilize memcache */
480 $result = db_query($link, "SELECT f1.id
481 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
482 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
484 while ($line = db_fetch_assoc($result)) {
485 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
488 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
492 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false) {
496 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
498 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
502 if ($debug_enabled) {
503 _debug("update_rss_feed: start");
506 if (!$ignore_daemon) {
508 if (DB_TYPE
== "pgsql") {
509 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
511 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
514 $result = db_query($link, "SELECT id,update_interval,auth_login,
515 auth_pass,cache_images,update_method
516 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
520 $result = db_query($link, "SELECT id,update_interval,auth_login,
521 feed_url,auth_pass,cache_images,update_method,last_updated,
522 mark_unread_on_update, owner_uid, update_on_checksum_change,
524 FROM ttrss_feeds WHERE id = '$feed'");
528 if (db_num_rows($result) == 0) {
529 if ($debug_enabled) {
530 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
535 $update_method = db_fetch_result($result, 0, "update_method");
536 $last_updated = db_fetch_result($result, 0, "last_updated");
537 $owner_uid = db_fetch_result($result, 0, "owner_uid");
538 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
539 0, "mark_unread_on_update"));
540 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
541 0, "update_on_checksum_change"));
542 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
544 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
545 WHERE id = '$feed'");
547 $auth_login = db_fetch_result($result, 0, "auth_login");
548 $auth_pass = db_fetch_result($result, 0, "auth_pass");
550 if ($update_method == 0)
551 $update_method = DEFAULT_UPDATE_METHOD +
1;
557 if ($update_method == 2)
558 $use_simplepie = true;
560 $use_simplepie = false;
562 if ($debug_enabled) {
563 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
566 if ($update_method == 1) {
567 $auth_login = urlencode($auth_login);
568 $auth_pass = urlencode($auth_pass);
571 $update_interval = db_fetch_result($result, 0, "update_interval");
572 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
573 $fetch_url = db_fetch_result($result, 0, "feed_url");
575 if ($update_interval < 0) { return; }
577 $feed = db_escape_string($feed);
579 if ($auth_login && $auth_pass && $updated != 3) {
580 $url_parts = array();
581 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
583 if ($url_parts[1] && $url_parts[2]) {
584 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
589 if ($debug_enabled) {
590 _debug("update_rss_feed: fetching [$fetch_url]...");
593 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
595 if ($memcache && $obj = $memcache->get($obj_id)) {
597 if ($debug_enabled) {
598 _debug("update_rss_feed: data found in memcache.");
605 if ($update_method == 3) {
606 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
607 } else if ($update_method == 1) {
609 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
610 define('MAGPIE_CACHE_ON', !$no_cache);
611 define('MAGPIE_FETCH_TIME_OUT', 60);
612 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
614 $rss = @fetch_rss
($fetch_url);
616 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
618 if (!is_dir($simplepie_cache_dir)) {
619 mkdir($simplepie_cache_dir);
622 $rss = new SimplePie();
623 $rss->set_useragent(SELF_USER_AGENT
);
624 # $rss->set_timeout(10);
625 $rss->set_feed_url($fetch_url);
626 $rss->set_output_encoding('UTF-8');
628 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
630 if ($debug_enabled) {
631 _debug("enabling image cache");
634 $rss->set_image_handler("image.php", 'i');
637 if ($debug_enabled) {
638 _debug("feed update interval (sec): " .
639 get_feed_update_interval($link, $feed)*60);
642 $rss->enable_cache(!$no_cache);
645 $rss->set_cache_location($simplepie_cache_dir);
646 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
652 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
657 if ($debug_enabled) {
658 _debug("update_rss_feed: fetch done, parsing...");
661 $feed = db_escape_string($feed);
663 if ($update_method == 2) {
664 $fetch_ok = !$rss->error();
671 if ($debug_enabled) {
672 _debug("update_rss_feed: processing feed data...");
675 // db_query($link, "BEGIN");
677 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
678 FROM ttrss_feeds WHERE id = '$feed'");
680 $registered_title = db_fetch_result($result, 0, "title");
681 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
682 $orig_site_url = db_fetch_result($result, 0, "site_url");
684 $owner_uid = db_fetch_result($result, 0, "owner_uid");
686 if ($use_simplepie) {
687 $site_url = $rss->get_link();
689 $site_url = $rss->channel
["link"];
692 if ($debug_enabled) {
693 _debug("update_rss_feed: checking favicon...");
696 check_feed_favicon($site_url, $feed, $link);
698 if (!$registered_title ||
$registered_title == "[Unknown]") {
700 if ($use_simplepie) {
701 $feed_title = db_escape_string($rss->get_title());
703 $feed_title = db_escape_string($rss->channel
["title"]);
706 if ($debug_enabled) {
707 _debug("update_rss_feed: registering title: $feed_title");
710 db_query($link, "UPDATE ttrss_feeds SET
711 title = '$feed_title' WHERE id = '$feed'");
714 // weird, weird Magpie
715 if (!$use_simplepie) {
716 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
719 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
720 db_query($link, "UPDATE ttrss_feeds SET
721 site_url = '$site_url' WHERE id = '$feed'");
724 // print "I: " . $rss->channel["image"]["url"];
726 if (!$use_simplepie) {
727 $icon_url = db_escape_string($rss->image
["url"]);
729 $icon_url = db_escape_string($rss->get_image_url());
732 $icon_url = substr($icon_url, 0, 250);
734 if ($icon_url && $orig_icon_url != $icon_url) {
735 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
738 if ($debug_enabled) {
739 _debug("update_rss_feed: loading filters...");
742 $filters = load_filters($link, $feed, $owner_uid);
744 // if ($debug_enabled) {
745 // print_r($filters);
748 if ($use_simplepie) {
749 $iterator = $rss->get_items();
751 $iterator = $rss->items
;
752 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
753 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
756 if (!is_array($iterator)) {
757 /* db_query($link, "UPDATE ttrss_feeds
758 SET last_error = 'Parse error: can\'t find any articles.'
759 WHERE id = '$feed'"); */
761 // clear any errors and mark feed as updated if fetched okay
762 // even if it's blank
764 if ($debug_enabled) {
765 _debug("update_rss_feed: entry iterator is not an array, no articles?");
768 db_query($link, "UPDATE ttrss_feeds
769 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
771 return; // no articles
774 if ($pubsub_state != 2) {
776 $feed_hub_url = false;
777 if ($use_simplepie) {
778 $links = $rss->get_links('hub');
780 if ($links && is_array($links)) {
781 foreach ($links as $l) {
788 $atom = $rss->channel
['atom'];
791 if ($atom['link@rel'] == 'hub') {
792 $feed_hub_url = $atom['link@href'];
795 if (!$feed_hub_url && $atom['link#'] > 1) {
796 for ($i = 2; $i <= $atom['link#']; $i++
) {
797 if ($atom["link#$i@rel"] == 'hub') {
798 $feed_hub_url = $atom["link#$i@href"];
804 $feed_hub_url = $rss->channel
['link_hub'];
808 if ($feed_hub_url && function_exists('curl_init')) {
809 $callback_url = get_self_url_prefix() .
810 "/backend.php?op=pubsub&id=$feed";
812 $s = new Subscriber($feed_hub_url, $callback_url);
814 $s->subscribe($fetch_url);
816 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
817 WHERE id = '$feed'");
821 if ($debug_enabled) {
822 _debug("update_rss_feed: processing articles...");
825 foreach ($iterator as $item) {
827 if ($_REQUEST['xdebug'] == 2) {
831 if ($use_simplepie) {
832 $entry_guid = $item->get_id();
833 if (!$entry_guid) $entry_guid = $item->get_link();
834 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
838 $entry_guid = $item["id"];
840 if (!$entry_guid) $entry_guid = $item["guid"];
841 if (!$entry_guid) $entry_guid = $item["about"];
842 if (!$entry_guid) $entry_guid = $item["link"];
843 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
846 if ($debug_enabled) {
847 _debug("update_rss_feed: guid $entry_guid");
850 if (!$entry_guid) continue;
852 $entry_timestamp = "";
854 if ($use_simplepie) {
855 $entry_timestamp = strtotime($item->get_date());
857 $rss_2_date = $item['pubdate'];
858 $rss_1_date = $item['dc']['date'];
859 $atom_date = $item['issued'];
860 if (!$atom_date) $atom_date = $item['updated'];
862 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
863 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
864 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
868 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
869 $entry_timestamp = time();
870 $no_orig_date = 'true';
872 $no_orig_date = 'false';
875 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
877 if ($debug_enabled) {
878 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
881 if ($use_simplepie) {
882 $entry_title = $item->get_title();
884 $entry_title = trim(strip_tags($item["title"]));
887 if ($use_simplepie) {
888 $entry_link = $item->get_link();
890 // strange Magpie workaround
891 $entry_link = $item["link_"];
892 if (!$entry_link) $entry_link = $item["link"];
895 if ($debug_enabled) {
896 _debug("update_rss_feed: title $entry_title");
899 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
901 $entry_link = strip_tags($entry_link);
903 if ($use_simplepie) {
904 $entry_content = $item->get_content();
905 if (!$entry_content) $entry_content = $item->get_description();
907 $entry_content = $item["content:escaped"];
909 if (!$entry_content) $entry_content = $item["content:encoded"];
910 if (!$entry_content) $entry_content = $item["content"]["encoded"];
911 if (!$entry_content) $entry_content = $item["content"];
913 // Magpie bugs are getting ridiculous
914 if (trim($entry_content) == "Array") $entry_content = false;
916 if (!$entry_content) $entry_content = $item["atom_content"];
917 if (!$entry_content) $entry_content = $item["summary"];
919 if (!$entry_content ||
920 strlen($entry_content) < strlen($item["description"])) {
921 $entry_content = $item["description"];
925 if (is_array($entry_content)) {
926 $entry_content = $entry_content["encoded"];
927 if (!$entry_content) $entry_content = $entry_content["escaped"];
931 if ($_REQUEST["xdebug"] == 2) {
932 print "update_rss_feed: content: ";
933 print_r(htmlspecialchars($entry_content));
936 $entry_content_unescaped = $entry_content;
938 if ($use_simplepie) {
939 $entry_comments = strip_tags($item->data
["comments"]);
940 if ($item->get_author()) {
941 $entry_author_item = $item->get_author();
942 $entry_author = $entry_author_item->get_name();
943 if (!$entry_author) $entry_author = $entry_author_item->get_email();
945 $entry_author = db_escape_string($entry_author);
948 $entry_comments = strip_tags($item["comments"]);
950 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
952 if ($item['author']) {
954 if (is_array($item['author'])) {
956 if (!$entry_author) {
957 $entry_author = db_escape_string(strip_tags($item['author']['name']));
960 if (!$entry_author) {
961 $entry_author = db_escape_string(strip_tags($item['author']['email']));
965 if (!$entry_author) {
966 $entry_author = db_escape_string(strip_tags($item['author']));
971 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
973 $entry_guid = db_escape_string(strip_tags($entry_guid));
974 $entry_guid = mb_substr($entry_guid, 0, 250);
976 $result = db_query($link, "SELECT id FROM ttrss_entries
977 WHERE guid = '$entry_guid'");
979 $entry_content = db_escape_string($entry_content, false);
981 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
983 $entry_title = db_escape_string($entry_title);
984 $entry_link = db_escape_string($entry_link);
985 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
986 $entry_author = mb_substr($entry_author, 0, 250);
988 if ($use_simplepie) {
989 $num_comments = 0; #FIXME#
991 $num_comments = db_escape_string($item["slash"]["comments"]);
994 if (!$num_comments) $num_comments = 0;
996 if ($debug_enabled) {
997 _debug("update_rss_feed: looking for tags [1]...");
1000 // parse <category> entries into tags
1002 $additional_tags = array();
1004 if ($use_simplepie) {
1006 $additional_tags_src = $item->get_categories();
1008 if (is_array($additional_tags_src)) {
1009 foreach ($additional_tags_src as $tobj) {
1010 array_push($additional_tags, $tobj->get_term());
1014 if ($debug_enabled) {
1015 _debug("update_rss_feed: category tags:");
1016 print_r($additional_tags);
1021 $t_ctr = $item['category#'];
1024 $additional_tags = array();
1025 } else if ($t_ctr > 0) {
1026 $additional_tags = array($item['category']);
1028 if ($item['category@term']) {
1029 array_push($additional_tags, $item['category@term']);
1032 for ($i = 0; $i <= $t_ctr; $i++
) {
1033 if ($item["category#$i"]) {
1034 array_push($additional_tags, $item["category#$i"]);
1037 if ($item["category#$i@term"]) {
1038 array_push($additional_tags, $item["category#$i@term"]);
1043 // parse <dc:subject> elements
1045 $t_ctr = $item['dc']['subject#'];
1048 array_push($additional_tags, $item['dc']['subject']);
1050 for ($i = 0; $i <= $t_ctr; $i++
) {
1051 if ($item['dc']["subject#$i"]) {
1052 array_push($additional_tags, $item['dc']["subject#$i"]);
1058 if ($debug_enabled) {
1059 _debug("update_rss_feed: looking for tags [2]...");
1063 // <a href="..." rel="tag">Xorg</a>, //
1067 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1068 $entry_content_unescaped, $entry_tags);
1070 $entry_tags = $entry_tags[1];
1072 $entry_tags = array_merge($entry_tags, $additional_tags);
1073 $entry_tags = array_unique($entry_tags);
1075 for ($i = 0; $i < count($entry_tags); $i++
)
1076 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1078 if ($debug_enabled) {
1079 _debug("update_rss_feed: unfiltered tags found:");
1080 print_r($entry_tags);
1085 $entry_content = sanitize_article_content($entry_content);
1086 $entry_title = sanitize_article_content($entry_title);
1088 if ($debug_enabled) {
1089 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1092 db_query($link, "BEGIN");
1094 if (db_num_rows($result) == 0) {
1096 if ($debug_enabled) {
1097 _debug("update_rss_feed: base guid not found");
1100 // base post entry does not exist, create it
1102 $result = db_query($link,
1103 "INSERT INTO ttrss_entries
1120 '$entry_timestamp_fmt',
1130 // we keep encountering the entry in feeds, so we need to
1131 // update date_updated column so that we don't get horrible
1132 // dupes when the entry gets purged and reinserted again e.g.
1133 // in the case of SLOW SLOW OMG SLOW updating feeds
1135 $base_entry_id = db_fetch_result($result, 0, "id");
1137 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1138 WHERE id = '$base_entry_id'");
1141 // now it should exist, if not - bad luck then
1143 $result = db_query($link, "SELECT
1144 id,content_hash,no_orig_date,title,
1145 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1146 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1150 WHERE guid = '$entry_guid'");
1155 if (db_num_rows($result) == 1) {
1157 if ($debug_enabled) {
1158 _debug("update_rss_feed: base guid found, checking for user record");
1161 // this will be used below in update handler
1162 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1163 $orig_title = db_fetch_result($result, 0, "title");
1164 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1165 $orig_date_updated = strtotime(db_fetch_result($result,
1166 0, "date_updated"));
1168 $ref_id = db_fetch_result($result, 0, "id");
1169 $entry_ref_id = $ref_id;
1171 // check for user post link to main table
1173 // do we allow duplicate posts with same GUID in different feeds?
1174 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1175 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1177 $dupcheck_qpart = "";
1180 /* Collect article tags here so we could filter by them: */
1182 $article_filters = get_article_filters($filters, $entry_title,
1183 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1186 if ($debug_enabled) {
1187 _debug("update_rss_feed: article filters: ");
1188 if (count($article_filters) != 0) {
1189 print_r($article_filters);
1193 if (find_article_filter($article_filters, "filter")) {
1194 db_query($link, "COMMIT"); // close transaction in progress
1198 $score = calculate_article_score($article_filters);
1200 if ($debug_enabled) {
1201 _debug("update_rss_feed: initial score: $score");
1204 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1205 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1208 // if ($_REQUEST["xdebug"]) print "$query\n";
1210 $result = db_query($link, $query);
1212 // okay it doesn't exist - create user entry
1213 if (db_num_rows($result) == 0) {
1215 if ($debug_enabled) {
1216 _debug("update_rss_feed: user record not found, creating...");
1219 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1221 $last_read_qpart = 'NULL';
1224 $last_read_qpart = 'NOW()';
1227 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1233 if (find_article_filter($article_filters, 'publish')) {
1234 $published = 'true';
1236 $published = 'false';
1239 $result = db_query($link,
1240 "INSERT INTO ttrss_user_entries
1241 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1242 published, score, tag_cache, label_cache)
1243 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1244 $last_read_qpart, $marked, $published, '$score', '', '')");
1246 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1247 $rss_link = get_self_url_prefix() .
1248 "/backend.php?op=rss&id=-2&key=" .
1249 get_feed_access_key($link, -2, false, $owner_uid);
1251 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1253 $pubsub_result = $p->publish_update($rss_link);
1256 $result = db_query($link,
1257 "SELECT int_id FROM ttrss_user_entries WHERE
1258 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1259 feed_id = '$feed' LIMIT 1");
1261 if (db_num_rows($result) == 1) {
1262 $entry_int_id = db_fetch_result($result, 0, "int_id");
1265 if ($debug_enabled) {
1266 _debug("update_rss_feed: user record FOUND");
1269 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1270 $entry_int_id = db_fetch_result($result, 0, "int_id");
1273 if ($debug_enabled) {
1274 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1277 $post_needs_update = false;
1279 if ($content_hash != $orig_content_hash) {
1280 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1281 $post_needs_update = true;
1284 if (db_escape_string($orig_title) != $entry_title) {
1285 $post_needs_update = true;
1288 if ($orig_num_comments != $num_comments) {
1289 $post_needs_update = true;
1292 // this doesn't seem to be very reliable
1294 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1295 // $post_needs_update = true;
1298 // if post needs update, update it and mark all user entries
1299 // linking to this post as updated
1300 if ($post_needs_update) {
1302 if (defined('DAEMON_EXTENDED_DEBUG')) {
1303 _debug("update_rss_feed: post $entry_guid needs update...");
1306 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1308 db_query($link, "UPDATE ttrss_entries
1309 SET title = '$entry_title', content = '$entry_content',
1310 content_hash = '$content_hash',
1311 updated = '$entry_timestamp_fmt',
1312 num_comments = '$num_comments'
1313 WHERE id = '$ref_id'");
1315 if ($mark_unread_on_update) {
1316 db_query($link, "UPDATE ttrss_user_entries
1317 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1318 } else if ($update_on_checksum_change) {
1319 db_query($link, "UPDATE ttrss_user_entries
1320 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1326 db_query($link, "COMMIT");
1328 if ($debug_enabled) {
1329 _debug("update_rss_feed: assigning labels...");
1332 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1335 if ($debug_enabled) {
1336 _debug("update_rss_feed: looking for enclosures...");
1341 $enclosures = array();
1343 if ($use_simplepie) {
1344 $encs = $item->get_enclosures();
1346 if (is_array($encs)) {
1347 foreach ($encs as $e) {
1349 $e->link
, $e->type
, $e->length
);
1351 array_push($enclosures, $e_item);
1358 $e_ctr = $item['enclosure#'];
1361 $e_item = array($item['enclosure@url'],
1362 $item['enclosure@type'],
1363 $item['enclosure@length']);
1365 array_push($enclosures, $e_item);
1367 for ($i = 0; $i <= $e_ctr; $i++
) {
1369 if ($item["enclosure#$i@url"]) {
1370 $e_item = array($item["enclosure#$i@url"],
1371 $item["enclosure#$i@type"],
1372 $item["enclosure#$i@length"]);
1373 array_push($enclosures, $e_item);
1379 // can there be many of those? yes -fox
1381 $m_ctr = $item['media']['content#'];
1384 $e_item = array($item['media']['content@url'],
1385 $item['media']['content@medium'],
1386 $item['media']['content@length']);
1388 array_push($enclosures, $e_item);
1390 for ($i = 0; $i <= $m_ctr; $i++
) {
1392 if ($item["media"]["content#$i@url"]) {
1393 $e_item = array($item["media"]["content#$i@url"],
1394 $item["media"]["content#$i@medium"],
1395 $item["media"]["content#$i@length"]);
1396 array_push($enclosures, $e_item);
1404 if ($debug_enabled) {
1405 _debug("update_rss_feed: article enclosures:");
1406 print_r($enclosures);
1409 db_query($link, "BEGIN");
1411 foreach ($enclosures as $enc) {
1412 $enc_url = db_escape_string($enc[0]);
1413 $enc_type = db_escape_string($enc[1]);
1414 $enc_dur = db_escape_string($enc[2]);
1416 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1417 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1419 if (db_num_rows($result) == 0) {
1420 db_query($link, "INSERT INTO ttrss_enclosures
1421 (content_url, content_type, title, duration, post_id) VALUES
1422 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1426 db_query($link, "COMMIT");
1428 // check for manual tags (we have to do it here since they're loaded from filters)
1430 foreach ($article_filters as $f) {
1431 if ($f[0] == "tag") {
1433 $manual_tags = trim_array(split(",", $f[1]));
1435 foreach ($manual_tags as $tag) {
1436 if (tag_is_valid($tag)) {
1437 array_push($entry_tags, $tag);
1445 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1446 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1448 $filtered_tags = array();
1449 $tags_to_cache = array();
1451 if ($entry_tags && is_array($entry_tags)) {
1452 foreach ($entry_tags as $tag) {
1453 if (array_search($tag, $boring_tags) === false) {
1454 array_push($filtered_tags, $tag);
1459 $filtered_tags = array_unique($filtered_tags);
1461 if ($debug_enabled) {
1462 _debug("update_rss_feed: filtered article tags:");
1463 print_r($filtered_tags);
1466 // Save article tags in the database
1468 if (count($filtered_tags) > 0) {
1470 db_query($link, "BEGIN");
1472 foreach ($filtered_tags as $tag) {
1474 $tag = sanitize_tag($tag);
1475 $tag = db_escape_string($tag);
1477 if (!tag_is_valid($tag)) continue;
1479 $result = db_query($link, "SELECT id FROM ttrss_tags
1480 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1481 owner_uid = '$owner_uid' LIMIT 1");
1483 if ($result && db_num_rows($result) == 0) {
1485 db_query($link, "INSERT INTO ttrss_tags
1486 (owner_uid,tag_name,post_int_id)
1487 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1490 array_push($tags_to_cache, $tag);
1493 /* update the cache */
1495 $tags_to_cache = array_unique($tags_to_cache);
1497 $tags_str = db_escape_string(join(",", $tags_to_cache));
1499 db_query($link, "UPDATE ttrss_user_entries
1500 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1501 AND owner_uid = $owner_uid");
1503 db_query($link, "COMMIT");
1506 if ($debug_enabled) {
1507 _debug("update_rss_feed: article processed");
1511 if (!$last_updated) {
1512 if ($debug_enabled) {
1513 _debug("update_rss_feed: new feed, catching it up...");
1515 catchup_feed($link, $feed, false, $owner_uid);
1518 if ($debug_enabled) {
1519 _debug("purging feed...");
1522 purge_feed($link, $feed, 0, $debug_enabled);
1524 db_query($link, "UPDATE ttrss_feeds
1525 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1527 // db_query($link, "COMMIT");
1531 if ($use_simplepie) {
1532 $error_msg = mb_substr($rss->error(), 0, 250);
1534 $error_msg = mb_substr(magpie_error(), 0, 250);
1537 if ($debug_enabled) {
1538 _debug("update_rss_feed: error fetching feed: $error_msg");
1541 $error_msg = db_escape_string($error_msg);
1544 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1545 last_updated = NOW() WHERE id = '$feed'");
1548 if ($use_simplepie) {
1552 if ($debug_enabled) {
1553 _debug("update_rss_feed: done");
1558 function print_select($id, $default, $values, $attributes = "") {
1559 print "<select name=\"$id\" id=\"$id\" $attributes>";
1560 foreach ($values as $v) {
1562 $sel = "selected=\"1\"";
1566 print "<option value=\"$v\" $sel>$v</option>";
1571 function print_select_hash($id, $default, $values, $attributes = "") {
1572 print "<select name=\"$id\" id='$id' $attributes>";
1573 foreach (array_keys($values) as $v) {
1575 $sel = 'selected="selected"';
1579 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1585 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1588 if ($filters["title"]) {
1589 foreach ($filters["title"] as $filter) {
1590 $reg_exp = $filter["reg_exp"];
1591 $inverse = $filter["inverse"];
1592 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1593 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1595 array_push($matches, array($filter["action"], $filter["action_param"]));
1600 if ($filters["content"]) {
1601 foreach ($filters["content"] as $filter) {
1602 $reg_exp = $filter["reg_exp"];
1603 $inverse = $filter["inverse"];
1605 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1606 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1608 array_push($matches, array($filter["action"], $filter["action_param"]));
1613 if ($filters["both"]) {
1614 foreach ($filters["both"] as $filter) {
1615 $reg_exp = $filter["reg_exp"];
1616 $inverse = $filter["inverse"];
1619 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1620 array_push($matches, array($filter["action"], $filter["action_param"]));
1623 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1624 array_push($matches, array($filter["action"], $filter["action_param"]));
1630 if ($filters["link"]) {
1631 $reg_exp = $filter["reg_exp"];
1632 foreach ($filters["link"] as $filter) {
1633 $reg_exp = $filter["reg_exp"];
1634 $inverse = $filter["inverse"];
1636 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1637 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1639 array_push($matches, array($filter["action"], $filter["action_param"]));
1644 if ($filters["date"]) {
1645 $reg_exp = $filter["reg_exp"];
1646 foreach ($filters["date"] as $filter) {
1647 $date_modifier = $filter["filter_param"];
1648 $inverse = $filter["inverse"];
1649 $check_timestamp = strtotime($filter["reg_exp"]);
1651 # no-op when timestamp doesn't parse to prevent misfires
1653 if ($check_timestamp) {
1656 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1657 $date_modifier == "after" && $timestamp > $check_timestamp) {
1661 if ($inverse) $match_ok = !$match_ok;
1664 array_push($matches, array($filter["action"], $filter["action_param"]));
1670 if ($filters["author"]) {
1671 foreach ($filters["author"] as $filter) {
1672 $reg_exp = $filter["reg_exp"];
1673 $inverse = $filter["inverse"];
1674 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1675 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1677 array_push($matches, array($filter["action"], $filter["action_param"]));
1682 if ($filters["tag"]) {
1684 $tag_string = join(",", $tags);
1686 foreach ($filters["tag"] as $filter) {
1687 $reg_exp = $filter["reg_exp"];
1688 $inverse = $filter["inverse"];
1690 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1691 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1693 array_push($matches, array($filter["action"], $filter["action_param"]));
1702 function find_article_filter($filters, $filter_name) {
1703 foreach ($filters as $f) {
1704 if ($f[0] == $filter_name) {
1711 function calculate_article_score($filters) {
1714 foreach ($filters as $f) {
1715 if ($f[0] == "score") {
1722 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1723 foreach ($filters as $f) {
1724 if ($f[0] == "label") {
1725 label_add_article($link, $id, $f[1], $owner_uid);
1730 function getmicrotime() {
1731 list($usec, $sec) = explode(" ",microtime());
1732 return ((float)$usec +
(float)$sec);
1735 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1736 foreach ($values as $v) {
1743 if ($v == $true_is) {
1744 $sel .= " value=\"1\"";
1746 $sel .= " value=\"0\"";
1749 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1750 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1755 function initialize_user_prefs($link, $uid, $profile = false) {
1757 $uid = db_escape_string($uid);
1761 $profile_qpart = "AND profile IS NULL";
1763 $profile_qpart = "AND profile = '$profile'";
1766 if (get_schema_version($link) < 63) $profile_qpart = "";
1768 db_query($link, "BEGIN");
1770 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1772 $u_result = db_query($link, "SELECT pref_name
1773 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1775 $active_prefs = array();
1777 while ($line = db_fetch_assoc($u_result)) {
1778 array_push($active_prefs, $line["pref_name"]);
1781 while ($line = db_fetch_assoc($result)) {
1782 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1783 // print "adding " . $line["pref_name"] . "<br>";
1785 if (get_schema_version($link) < 63) {
1786 db_query($link, "INSERT INTO ttrss_user_prefs
1787 (owner_uid,pref_name,value) VALUES
1788 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1791 db_query($link, "INSERT INTO ttrss_user_prefs
1792 (owner_uid,pref_name,value, profile) VALUES
1793 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1799 db_query($link, "COMMIT");
1803 function lookup_user_id($link, $user) {
1805 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1808 if (db_num_rows($result) == 1) {
1809 return db_fetch_result($result, 0, "id");
1815 function http_authenticate_user($link) {
1817 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1819 if (!$_SERVER["PHP_AUTH_USER"]) {
1821 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1822 header('HTTP/1.0 401 Unauthorized');
1826 $auth_result = authenticate_user($link,
1827 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1829 if (!$auth_result) {
1830 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1831 header('HTTP/1.0 401 Unauthorized');
1839 function get_ssl_certificate_id() {
1840 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1841 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1842 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1843 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1844 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1849 function get_login_by_ssl_certificate($link) {
1851 $cert_serial = db_escape_string(get_ssl_certificate_id());
1854 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1855 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1856 owner_uid = ttrss_users.id");
1858 if (db_num_rows($result) != 0) {
1859 return db_escape_string(db_fetch_result($result, 0, "login"));
1866 function get_remote_user($link) {
1868 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
1869 return db_escape_string($_SERVER["REMOTE_USER"]);
1872 return db_escape_string(get_login_by_ssl_certificate($link));
1875 function get_remote_fakepass($link) {
1876 if (get_remote_user($link))
1882 function authenticate_user($link, $login, $password, $force_auth = false) {
1884 if (!SINGLE_USER_MODE
) {
1886 $pwd_hash1 = encrypt_password($password);
1887 $pwd_hash2 = encrypt_password($password, $login);
1888 $login = db_escape_string($login);
1890 $remote_user = get_remote_user($link);
1892 if ($remote_user && $remote_user == $login && $login != "admin") {
1894 $login = $remote_user;
1896 $query = "SELECT id,login,access_level,pwd_hash
1897 FROM ttrss_users WHERE
1900 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1901 && $_SERVER["REMOTE_USER"]) {
1902 $result = db_query($link, $query);
1905 if (db_num_rows($result) == 0) {
1906 $query = "INSERT INTO ttrss_users
1907 (login,access_level,last_login,created)
1908 VALUES ('$login', 0, null, NOW())";
1909 db_query($link, $query);
1914 $query = "SELECT id,login,access_level,pwd_hash
1915 FROM ttrss_users WHERE
1916 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1917 pwd_hash = '$pwd_hash2')";
1920 $result = db_query($link, $query);
1922 if (db_num_rows($result) == 1) {
1923 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1924 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1925 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1927 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1931 // LemonLDAP can send user informations via HTTP HEADER
1932 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
1934 if ($_SERVER['HTTP_USER_NAME']){
1935 $fullname = db_escape_string($_SERVER['HTTP_USER_NAME']);
1936 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1940 if ($_SERVER['HTTP_USER_MAIL']){
1941 $email = db_escape_string($_SERVER['HTTP_USER_MAIL']);
1942 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1947 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1948 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1950 $_SESSION["last_version_check"] = time();
1952 initialize_user_prefs($link, $_SESSION["uid"]);
1961 $_SESSION["uid"] = 1;
1962 $_SESSION["name"] = "admin";
1964 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1966 initialize_user_prefs($link, $_SESSION["uid"]);
1972 function make_password($length = 8) {
1975 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1979 while ($i < $length) {
1980 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1982 if (!strstr($password, $char)) {
1990 // this is called after user is created to initialize default feeds, labels
1993 // user preferences are checked on every login, not here
1995 function initialize_user($link, $uid) {
1997 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1998 values ('$uid', 'Tiny Tiny RSS: New Releases',
1999 'http://tt-rss.org/releases.rss')");
2001 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2002 values ('$uid', 'Tiny Tiny RSS: Forum',
2003 'http://tt-rss.org/forum/rss.php')");
2006 function logout_user() {
2008 if (isset($_COOKIE[session_name()])) {
2009 setcookie(session_name(), '', time()-42000, '/');
2013 function get_script_urlpath() {
2014 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
2017 function validate_session($link) {
2018 if (SINGLE_USER_MODE
) return true;
2020 $check_ip = $_SESSION['ip_address'];
2022 switch (SESSION_CHECK_ADDRESS
) {
2027 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2030 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
2031 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2035 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
2036 $_SESSION["login_error_msg"] =
2037 __("Session failed to validate (incorrect IP)");
2041 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
2044 if ($_SESSION["uid"]) {
2046 $result = db_query($link,
2047 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
2049 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
2051 if ($pwd_hash != $_SESSION["pwd_hash"]) {
2056 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
2058 //print_r($_SESSION);
2060 if (time() > $_SESSION["cookie_lifetime"]) {
2068 function login_sequence($link, $mobile = false) {
2069 if (!SINGLE_USER_MODE
) {
2071 $login_action = $_POST["login_action"];
2073 # try to authenticate user if called from login form
2074 if ($login_action == "do_login") {
2075 $login = $_POST["login"];
2076 $password = $_POST["password"];
2077 $remember_me = $_POST["remember_me"];
2079 if (authenticate_user($link, $login, $password)) {
2080 $_POST["password"] = "";
2082 $_SESSION["language"] = $_POST["language"];
2083 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2084 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
2086 if ($_POST["profile"]) {
2088 $profile = db_escape_string($_POST["profile"]);
2090 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2091 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2093 if (db_num_rows($result) != 0) {
2094 $_SESSION["profile"] = $profile;
2095 $_SESSION["prefs_cache"] = array();
2099 if ($_REQUEST['return']) {
2100 header("Location: " . $_REQUEST['return']);
2102 header("Location: " . $_SERVER["REQUEST_URI"]);
2109 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2113 if (!$_SESSION["uid"] ||
!validate_session($link)) {
2115 if (get_remote_user($link) && AUTO_LOGIN
) {
2116 authenticate_user($link, get_remote_user($link), null);
2117 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2119 render_login_form($link, $mobile);
2120 //header("Location: login.php");
2124 /* bump login timestamp */
2125 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2128 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
2129 setcookie("ttrss_lang", $_SESSION["language"],
2130 time() + SESSION_COOKIE_LIFETIME
);
2135 return authenticate_user($link, "admin", null);
2139 function truncate_string($str, $max_len, $suffix = '…') {
2140 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2141 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2147 function theme_image($link, $filename) {
2149 $theme_path = get_user_theme_path($link);
2151 if ($theme_path && is_file($theme_path.$filename)) {
2152 return $theme_path.$filename;
2161 function get_user_theme($link) {
2163 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2164 $theme_name = get_pref($link, "_THEME_ID");
2165 if (is_dir("themes/$theme_name")) {
2176 function get_user_theme_path($link) {
2179 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2180 $theme_name = get_pref($link, "_THEME_ID");
2182 if ($theme_name && is_dir("themes/$theme_name")) {
2183 $theme_path = "themes/$theme_name/";
2192 if (is_file("$theme_path/theme.ini")) {
2193 $ini = parse_ini_file("$theme_path/theme.ini", true);
2194 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2202 function get_user_theme_options($link) {
2203 $t = get_user_theme_path($link);
2206 if (is_file("$t/theme.ini")) {
2207 $ini = parse_ini_file("$t/theme.ini", true);
2208 if ($ini['theme']['version']) {
2209 return $ini['theme']['options'];
2216 function print_theme_includes($link) {
2218 $t = get_user_theme_path($link);
2222 print "<link rel=\"stylesheet\" type=\"text/css\"
2223 href=\"$t/theme.css?$time \">";
2224 if (file_exists("$t/theme.js")) {
2225 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2231 function get_all_themes() {
2232 $themes = glob("themes/*");
2238 foreach ($themes as $t) {
2239 if (is_file("$t/theme.ini")) {
2240 $ini = parse_ini_file("$t/theme.ini", true);
2241 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2242 !$ini['theme']['disabled']) {
2244 $entry["path"] = $t;
2245 $entry["base"] = basename($t);
2246 $entry["name"] = $ini['theme']['name'];
2247 $entry["version"] = $ini['theme']['version'];
2248 $entry["author"] = $ini['theme']['author'];
2249 $entry["options"] = $ini['theme']['options'];
2250 array_push($rv, $entry);
2258 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2261 $source_tz = new DateTimeZone($source_tz);
2262 } catch (Exception
$e) {
2263 $source_tz = new DateTimeZone('UTC');
2267 $dest_tz = new DateTimeZone($dest_tz);
2268 } catch (Exception
$e) {
2269 $dest_tz = new DateTimeZone('UTC');
2272 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2273 return $dt->format('U') +
$dest_tz->getOffset($dt);
2276 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2277 $no_smart_dt = false) {
2279 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2280 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2282 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2285 $user_tz = new DateTimeZone($user_tz_string);
2286 } catch (Exception
$e) {
2287 $user_tz = new DateTimeZone('UTC');
2290 # We store date in UTC internally
2291 $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
2292 $user_timestamp = $dt->format('U') +
$user_tz->getOffset($dt);
2294 if (!$no_smart_dt) {
2295 return smart_date_time($link, $user_timestamp,
2296 $user_tz->getOffset($dt), $owner_uid);
2299 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2301 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2303 return date($format, $user_timestamp);
2307 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2308 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2310 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2311 return date("G:i", $timestamp);
2312 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2313 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2314 return date($format, $timestamp);
2316 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2317 return date($format, $timestamp);
2321 function smart_date($timestamp) {
2322 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2324 } else if (date("Y", $timestamp) == date("Y")) {
2325 return date("D m", $timestamp);
2327 return date("Y/m/d", $timestamp);
2331 function sql_bool_to_string($s) {
2332 if ($s == "t" ||
$s == "1") {
2339 function sql_bool_to_bool($s) {
2340 if ($s == "t" ||
$s == "1") {
2347 function bool_to_sql_bool($s) {
2355 function toggleEvenOdd($a) {
2362 function get_schema_version($link, $nocache = false) {
2363 if (!$_SESSION["schema_version"] ||
$nocache) {
2364 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2365 $version = db_fetch_result($result, 0, "schema_version");
2366 $_SESSION["schema_version"] = $version;
2369 return $_SESSION["schema_version"];
2373 function sanity_check($link) {
2378 $schema_version = get_schema_version($link);
2380 if ($schema_version != SCHEMA_VERSION
) {
2384 if (DB_TYPE
== "mysql") {
2385 $result = db_query($link, "SELECT true", false);
2386 if (db_num_rows($result) != 1) {
2391 if (db_escape_string("testTEST") != "testTEST") {
2395 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2398 function file_is_locked($filename) {
2399 if (function_exists('flock')) {
2400 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2402 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2403 flock($fp, LOCK_UN
);
2413 return true; // consider the file always locked and skip the test
2416 function make_lockfile($filename) {
2417 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2419 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2420 if (function_exists('posix_getpid')) {
2421 fwrite($fp, posix_getpid() . "\n");
2429 function make_stampfile($filename) {
2430 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2432 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2433 fwrite($fp, time() . "\n");
2434 flock($fp, LOCK_UN
);
2442 function sql_random_function() {
2443 if (DB_TYPE
== "mysql") {
2450 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2452 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2454 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2461 $cat_qpart = "cat_id = '$feed'";
2463 $cat_qpart = "cat_id IS NULL";
2466 $tmp_result = db_query($link, "SELECT id
2467 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2469 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2471 $tmp_feed = $tmp_line["id"];
2473 db_query($link, "UPDATE ttrss_user_entries
2474 SET unread = false,last_read = NOW()
2475 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2477 } else if ($feed == -2) {
2480 db_query($link, "UPDATE ttrss_user_entries
2481 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2482 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2483 AND unread = true AND owner_uid = $owner_uid");
2486 } else if ($feed > 0) {
2488 db_query($link, "UPDATE ttrss_user_entries
2489 SET unread = false,last_read = NOW()
2490 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2492 } else if ($feed < 0 && $feed > -10) { // special, like starred
2495 db_query($link, "UPDATE ttrss_user_entries
2496 SET unread = false,last_read = NOW()
2497 WHERE marked = true AND owner_uid = $owner_uid");
2501 db_query($link, "UPDATE ttrss_user_entries
2502 SET unread = false,last_read = NOW()
2503 WHERE published = true AND owner_uid = $owner_uid");
2508 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2510 if (DB_TYPE
== "pgsql") {
2511 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2513 $match_part = "updated > DATE_SUB(NOW(),
2514 INTERVAL $intl HOUR) ";
2517 $result = db_query($link, "SELECT id FROM ttrss_entries,
2518 ttrss_user_entries WHERE $match_part AND
2520 ttrss_user_entries.ref_id = ttrss_entries.id AND
2521 owner_uid = $owner_uid");
2523 $affected_ids = array();
2525 while ($line = db_fetch_assoc($result)) {
2526 array_push($affected_ids, $line["id"]);
2529 catchupArticlesById($link, $affected_ids, 0);
2533 db_query($link, "UPDATE ttrss_user_entries
2534 SET unread = false,last_read = NOW()
2535 WHERE owner_uid = $owner_uid");
2538 } else if ($feed < -10) { // label
2540 $label_id = -$feed - 11;
2542 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2543 SET unread = false, last_read = NOW()
2544 WHERE label_id = '$label_id' AND unread = true
2545 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2549 ccache_update($link, $feed, $owner_uid, $cat_view);
2552 db_query($link, "BEGIN");
2554 $tag_name = db_escape_string($feed);
2556 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2557 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2559 while ($line = db_fetch_assoc($result)) {
2560 db_query($link, "UPDATE ttrss_user_entries SET
2561 unread = false, last_read = NOW()
2562 WHERE int_id = " . $line["post_int_id"]);
2564 db_query($link, "COMMIT");
2568 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2570 if (!$omode) $omode = "flc";
2572 $data = getGlobalCounters($link);
2574 $data = array_merge($data, getVirtCounters($link));
2576 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2577 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2578 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2579 if (strchr($omode, "c")) {
2580 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2581 $data = array_merge($data, getCategoryCounters($link));
2588 function getCategoryCounters($link) {
2591 /* Labels category */
2593 $cv = array("id" => -2, "kind" => "cat",
2594 "counter" => getCategoryUnread($link, -2));
2596 array_push($ret_arr, $cv);
2598 $age_qpart = getMaxAgeSubquery();
2600 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2601 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2602 WHERE ttrss_cat_counters_cache.feed_id = id AND
2603 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2605 while ($line = db_fetch_assoc($result)) {
2606 $line["cat_id"] = (int) $line["cat_id"];
2608 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2609 "counter" => $line["unread"]);
2611 array_push($ret_arr, $cv);
2614 /* Special case: NULL category doesn't actually exist in the DB */
2616 $cv = array("id" => 0, "kind" => "cat",
2617 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2619 array_push($ret_arr, $cv);
2624 function getCategoryUnread($link, $cat, $owner_uid = false) {
2626 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2631 $cat_query = "cat_id = '$cat'";
2633 $cat_query = "cat_id IS NULL";
2636 $age_qpart = getMaxAgeSubquery();
2638 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2639 AND owner_uid = " . $owner_uid);
2641 $cat_feeds = array();
2642 while ($line = db_fetch_assoc($result)) {
2643 array_push($cat_feeds, "feed_id = " . $line["id"]);
2646 if (count($cat_feeds) == 0) return 0;
2648 $match_part = implode(" OR ", $cat_feeds);
2650 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2651 FROM ttrss_user_entries,ttrss_entries
2652 WHERE unread = true AND ($match_part) AND id = ref_id
2653 AND $age_qpart AND owner_uid = " . $owner_uid);
2657 # this needs to be rewritten
2658 while ($line = db_fetch_assoc($result)) {
2659 $unread +
= $line["unread"];
2663 } else if ($cat == -1) {
2664 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2665 } else if ($cat == -2) {
2667 $result = db_query($link, "
2668 SELECT COUNT(unread) AS unread FROM
2669 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2670 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2671 ttrss_labels2.owner_uid = '$owner_uid'
2672 AND unread = true AND feed_id = ttrss_feeds.id
2673 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2675 $unread = db_fetch_result($result, 0, "unread");
2682 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2683 if (DB_TYPE
== "pgsql") {
2684 return "ttrss_entries.date_updated >
2685 NOW() - INTERVAL '$days days'";
2687 return "ttrss_entries.date_updated >
2688 DATE_SUB(NOW(), INTERVAL $days DAY)";
2692 function getFeedUnread($link, $feed, $is_cat = false) {
2693 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2696 function getLabelUnread($link, $label_id, $owner_uid = false) {
2697 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2699 $result = db_query($link, "
2700 SELECT COUNT(unread) AS unread FROM
2701 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2702 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2703 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2704 AND unread = true AND feed_id = ttrss_feeds.id
2705 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2707 if (db_num_rows($result) != 0) {
2708 return db_fetch_result($result, 0, "unread");
2714 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2715 $owner_uid = false) {
2717 $n_feed = (int) $feed;
2719 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2722 $unread_qpart = "unread = true";
2724 $unread_qpart = "true";
2727 $age_qpart = getMaxAgeSubquery();
2730 return getCategoryUnread($link, $n_feed, $owner_uid);
2731 } if ($feed != "0" && $n_feed == 0) {
2733 $feed = db_escape_string($feed);
2735 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2736 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2737 AND ref_id = id AND $age_qpart
2738 AND $unread_qpart)) AS count FROM ttrss_tags
2739 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2740 return db_fetch_result($result, 0, "count");
2742 } else if ($n_feed == -1) {
2743 $match_part = "marked = true";
2744 } else if ($n_feed == -2) {
2745 $match_part = "published = true";
2746 } else if ($n_feed == -3) {
2747 $match_part = "unread = true AND score >= 0";
2749 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2751 if (DB_TYPE
== "pgsql") {
2752 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2754 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2756 } else if ($n_feed == -4) {
2757 $match_part = "true";
2758 } else if ($n_feed >= 0) {
2761 $match_part = "feed_id = '$n_feed'";
2763 $match_part = "feed_id IS NULL";
2766 } else if ($feed < -10) {
2768 $label_id = -$feed - 11;
2770 return getLabelUnread($link, $label_id, $owner_uid);
2777 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2778 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2780 $from_qpart = "ttrss_user_entries,ttrss_entries";
2784 $query = "SELECT count(int_id) AS unread
2785 FROM $from_qpart WHERE
2786 ttrss_user_entries.ref_id = ttrss_entries.id AND
2789 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2791 $result = db_query($link, $query);
2795 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2796 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2797 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2798 AND $unread_qpart AND $age_qpart AND
2799 ttrss_tags.owner_uid = " . $owner_uid);
2802 $unread = db_fetch_result($result, 0, "unread");
2807 function getGlobalUnread($link, $user_id = false) {
2810 $user_id = $_SESSION["uid"];
2813 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2814 WHERE owner_uid = '$user_id' AND feed_id > 0");
2816 $c_id = db_fetch_result($result, 0, "c_id");
2821 function getGlobalCounters($link, $global_unread = -1) {
2824 if ($global_unread == -1) {
2825 $global_unread = getGlobalUnread($link);
2828 $cv = array("id" => "global-unread",
2829 "counter" => $global_unread);
2831 array_push($ret_arr, $cv);
2833 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2834 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2836 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2838 $cv = array("id" => "subscribed-feeds",
2839 "counter" => $subscribed_feeds);
2841 array_push($ret_arr, $cv);
2846 function getSubscribedFeeds($link) {
2847 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2848 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2850 return db_fetch_result($result, 0, "fn");
2853 function getTagCounters($link) {
2857 $age_qpart = getMaxAgeSubquery();
2859 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2860 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2861 AND ref_id = id AND $age_qpart
2862 AND unread = true)) AS count FROM ttrss_tags
2863 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2864 ORDER BY count DESC LIMIT 55");
2868 while ($line = db_fetch_assoc($result)) {
2869 $tags[$line["tag_name"]] +
= $line["count"];
2872 foreach (array_keys($tags) as $tag) {
2873 $unread = $tags[$tag];
2874 $tag = htmlspecialchars($tag);
2876 $cv = array("id" => $tag,
2878 "counter" => $unread);
2880 array_push($ret_arr, $cv);
2886 function getVirtCounters($link) {
2890 for ($i = 0; $i >= -4; $i--) {
2892 $count = getFeedUnread($link, $i);
2894 $cv = array("id" => $i,
2895 "counter" => $count);
2897 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2898 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2900 array_push($ret_arr, $cv);
2906 function getLabelCounters($link, $descriptions = false) {
2910 $age_qpart = getMaxAgeSubquery();
2912 $owner_uid = $_SESSION["uid"];
2914 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2915 WHERE owner_uid = '$owner_uid'");
2917 while ($line = db_fetch_assoc($result)) {
2919 $id = -$line["id"] - 11;
2921 $label_name = $line["caption"];
2922 $count = getFeedUnread($link, $id);
2924 $cv = array("id" => $id,
2925 "counter" => $count);
2928 $cv["description"] = $label_name;
2930 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2931 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2933 array_push($ret_arr, $cv);
2939 function getFeedCounters($link, $active_feed = false) {
2943 $age_qpart = getMaxAgeSubquery();
2945 $query = "SELECT ttrss_feeds.id,
2947 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2948 last_error, value AS count
2949 FROM ttrss_feeds, ttrss_counters_cache
2950 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2951 AND ttrss_counters_cache.feed_id = id";
2953 $result = db_query($link, $query);
2954 $fctrs_modified = false;
2956 while ($line = db_fetch_assoc($result)) {
2959 $count = $line["count"];
2960 $last_error = htmlspecialchars($line["last_error"]);
2962 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2964 $has_img = feed_has_icon($id);
2966 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2969 $cv = array("id" => $id,
2970 "updated" => $last_updated,
2971 "counter" => $count,
2972 "has_img" => (int) $has_img);
2975 $cv["error"] = $last_error;
2977 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2978 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2980 if ($active_feed && $id == $active_feed)
2981 $cv["title"] = truncate_string($line["title"], 30);
2983 array_push($ret_arr, $cv);
2990 function get_pgsql_version($link) {
2991 $result = db_query($link, "SELECT version() AS version");
2992 $version = split(" ", db_fetch_result($result, 0, "version"));
2997 * Subscribes the user to the given feed
2999 * @param resource $link Database connection
3000 * @param string $url Feed URL to subscribe to
3001 * @param integer $cat_id Category ID the feed shall be added to
3002 * @param string $auth_login (optional) Feed username
3003 * @param string $auth_pass (optional) Feed password
3005 * @return integer Status code:
3006 * 0 - OK, Feed already exists
3007 * 1 - OK, Feed added
3009 * 3 - URL content is HTML, no feeds available
3010 * 4 - URL content is HTML which contains multiple feeds.
3011 * Here you should call extractfeedurls in rpc-backend
3012 * to get all possible feeds.
3013 * 5 - Couldn't download the URL content.
3015 function subscribe_to_feed($link, $url, $cat_id = 0,
3016 $auth_login = '', $auth_pass = '') {
3018 $url = fix_url($url);
3020 if (!$url ||
!validate_feed_url($url)) return 2;
3024 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
3025 WHERE id = ".$_SESSION['uid']);
3027 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
3029 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
3030 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
3032 if (url_is_html($url, $auth_login, $auth_pass)) {
3033 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
3034 if (count($feedUrls) == 0) {
3036 } else if (count($feedUrls) > 1) {
3039 //use feed url as new URL
3040 $url = key($feedUrls);
3044 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
3049 if ($cat_id == "0" ||
!$cat_id) {
3050 $cat_qpart = "NULL";
3052 $cat_qpart = "'$cat_id'";
3055 $result = db_query($link,
3056 "SELECT id FROM ttrss_feeds
3057 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
3059 if (db_num_rows($result) == 0) {
3060 $result = db_query($link,
3061 "INSERT INTO ttrss_feeds
3062 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
3063 VALUES ('".$_SESSION["uid"]."', '$url',
3064 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
3066 $result = db_query($link,
3067 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
3068 AND owner_uid = " . $_SESSION["uid"]);
3070 $feed_id = db_fetch_result($result, 0, "id");
3073 update_rss_feed($link, $feed_id, true);
3082 function print_feed_select($link, $id, $default_id = "",
3083 $attributes = "", $include_all_feeds = true) {
3085 print "<select id=\"$id\" name=\"$id\" $attributes>";
3086 if ($include_all_feeds) {
3087 print "<option value=\"0\">".__('All feeds')."</option>";
3090 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
3091 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3093 if (db_num_rows($result) > 0 && $include_all_feeds) {
3094 print "<option disabled>--------</option>";
3097 while ($line = db_fetch_assoc($result)) {
3098 if ($line["id"] == $default_id) {
3099 $is_selected = "selected=\"1\"";
3104 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3106 printf("<option $is_selected value='%d'>%s</option>",
3107 $line["id"], $title);
3113 function print_feed_cat_select($link, $id, $default_id = "",
3114 $attributes = "", $include_all_cats = true) {
3116 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3118 if ($include_all_cats) {
3119 print "<option value=\"0\">".__('Uncategorized')."</option>";
3122 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3123 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3125 if (db_num_rows($result) > 0 && $include_all_cats) {
3126 print "<option disabled=\"1\">--------</option>";
3129 while ($line = db_fetch_assoc($result)) {
3130 if ($line["id"] == $default_id) {
3131 $is_selected = "selected=\"1\"";
3137 printf("<option $is_selected value='%d'>%s</option>",
3138 $line["id"], htmlspecialchars($line["title"]));
3141 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3146 function checkbox_to_sql_bool($val) {
3147 return ($val == "on") ?
"true" : "false";
3150 function getFeedCatTitle($link, $id) {
3152 return __("Special");
3153 } else if ($id < -10) {
3154 return __("Labels");
3155 } else if ($id > 0) {
3156 $result = db_query($link, "SELECT ttrss_feed_categories.title
3157 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3158 cat_id = ttrss_feed_categories.id");
3159 if (db_num_rows($result) == 1) {
3160 return db_fetch_result($result, 0, "title");
3162 return __("Uncategorized");
3165 return "getFeedCatTitle($id) failed";
3170 function getFeedIcon($id) {
3173 return "images/archive.png";
3176 return "images/mark_set.png";
3179 return "images/pub_set.png";
3182 return "images/fresh.png";
3185 return "images/tag.png";
3189 return "images/label.png";
3191 if (file_exists(ICONS_DIR
. "/$id.ico"))
3192 return ICONS_URL
. "/$id.ico";
3198 function getFeedTitle($link, $id) {
3200 return __("Starred articles");
3201 } else if ($id == -2) {
3202 return __("Published articles");
3203 } else if ($id == -3) {
3204 return __("Fresh articles");
3205 } else if ($id == -4) {
3206 return __("All articles");
3207 } else if ($id === 0 ||
$id === "0") {
3208 return __("Archived articles");
3209 } else if ($id < -10) {
3210 $label_id = -$id - 11;
3211 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3212 if (db_num_rows($result) == 1) {
3213 return db_fetch_result($result, 0, "caption");
3215 return "Unknown label ($label_id)";
3218 } else if ($id > 0) {
3219 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3220 if (db_num_rows($result) == 1) {
3221 return db_fetch_result($result, 0, "title");
3223 return "Unknown feed ($id)";
3230 function get_session_cookie_name() {
3231 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3234 function make_init_params($link) {
3237 $params["theme"] = get_user_theme($link);
3238 $params["theme_options"] = get_user_theme_options($link);
3240 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3241 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3242 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3243 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3245 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3246 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3247 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3248 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3250 $params[strtolower($param)] = (int) get_pref($link, $param);
3253 $params["icons_url"] = ICONS_URL
;
3254 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3255 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3256 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3257 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3258 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3260 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3261 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3263 $max_feed_id = db_fetch_result($result, 0, "mid");
3264 $num_feeds = db_fetch_result($result, 0, "nf");
3266 $params["max_feed_id"] = (int) $max_feed_id;
3267 $params["num_feeds"] = (int) $num_feeds;
3269 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3274 function print_runtime_info($link) {
3275 print "<runtime-info><![CDATA[";
3276 print json_encode(make_runtime_info($link));
3277 print "]]></runtime-info>";
3280 function make_runtime_info($link) {
3283 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3284 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3286 $max_feed_id = db_fetch_result($result, 0, "mid");
3287 $num_feeds = db_fetch_result($result, 0, "nf");
3289 $data["max_feed_id"] = (int) $max_feed_id;
3290 $data["num_feeds"] = (int) $num_feeds;
3292 $data['last_article_id'] = getLastArticleId($link);
3293 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3295 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
3297 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3299 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3301 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3304 $stamp_delta = time() - $stamp;
3306 if ($stamp_delta > 1800) {
3310 $_SESSION["daemon_stamp_check"] = time();
3313 $data['daemon_stamp_ok'] = $stamp_check;
3315 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3317 $data['daemon_stamp'] = $stamp_fmt;
3322 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3323 $new_version_details = @check_for_update
($link);
3325 $data['new_version_available'] = (int) ($new_version_details != false);
3327 $_SESSION["last_version_check"] = time();
3333 function getSearchSql($link, $search, $match_on) {
3335 $search_query_part = "";
3337 $keywords = split(" ", $search);
3338 $query_keywords = array();
3340 foreach ($keywords as $k) {
3341 if (strpos($k, "-") === 0) {
3348 if (strpos($k, "@") === 0) {
3350 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3351 $orig_ts = strtotime(substr($k, 1));
3353 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3355 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3356 } else if ($match_on == "both") {
3357 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3358 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3359 } else if ($match_on == "title") {
3360 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3361 } else if ($match_on == "content") {
3362 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3366 $search_query_part = implode("AND", $query_keywords);
3368 return $search_query_part;
3371 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3373 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3375 $ext_tables_part = "";
3379 if (SPHINX_ENABLED
) {
3380 $ids = join(",", @sphinx_search
($search, 0, 500));
3383 $search_query_part = "ref_id IN ($ids) AND ";
3385 $search_query_part = "ref_id = -1 AND ";
3388 $search_query_part = getSearchSql($link, $search, $match_on);
3389 $search_query_part .= " AND ";
3393 $search_query_part = "";
3396 $view_query_part = "";
3398 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3400 $view_query_part = " ";
3401 } else if ($feed != -1) {
3402 $unread = getFeedUnread($link, $feed, $cat_view);
3404 $view_query_part = " unread = true AND ";
3409 if ($view_mode == "marked") {
3410 $view_query_part = " marked = true AND ";
3413 if ($view_mode == "published") {
3414 $view_query_part = " published = true AND ";
3417 if ($view_mode == "unread") {
3418 $view_query_part = " unread = true AND ";
3421 if ($view_mode == "updated") {
3422 $view_query_part = " (last_read is null and unread = false) AND ";
3426 $limit_query_part = "LIMIT " . $limit;
3429 $vfeed_query_part = "";
3431 // override query strategy and enable feed display when searching globally
3432 if ($search && $search_mode == "all_feeds") {
3433 $query_strategy_part = "ttrss_entries.id > 0";
3434 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3436 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3437 $query_strategy_part = "ttrss_entries.id > 0";
3438 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3439 id = feed_id) as feed_title,";
3440 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3442 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3444 $tmp_result = false;
3447 $tmp_result = db_query($link, "SELECT id
3448 FROM ttrss_feeds WHERE cat_id = '$feed'");
3450 $tmp_result = db_query($link, "SELECT id
3451 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3452 WHERE id = '$feed') AND id != '$feed'");
3455 $cat_siblings = array();
3457 if (db_num_rows($tmp_result) > 0) {
3458 while ($p = db_fetch_assoc($tmp_result)) {
3459 array_push($cat_siblings, "feed_id = " . $p["id"]);
3462 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3463 $feed, implode(" OR ", $cat_siblings));
3466 $query_strategy_part = "ttrss_entries.id > 0";
3469 } else if ($feed > 0) {
3474 $query_strategy_part = "cat_id = '$feed'";
3476 $query_strategy_part = "cat_id IS NULL";
3479 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3482 $query_strategy_part = "feed_id = '$feed'";
3484 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3485 $query_strategy_part = "feed_id IS NULL";
3486 } else if ($feed == 0 && $cat_view) { // uncategorized
3487 $query_strategy_part = "cat_id IS NULL";
3488 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3489 } else if ($feed == -1) { // starred virtual feed
3490 $query_strategy_part = "marked = true";
3491 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3492 } else if ($feed == -2) { // published virtual feed OR labels category
3495 $query_strategy_part = "published = true";
3496 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3498 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3500 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3502 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3503 ttrss_user_labels2.article_id = ref_id";
3507 } else if ($feed == -3) { // fresh virtual feed
3508 $query_strategy_part = "unread = true AND score >= 0";
3510 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3512 if (DB_TYPE
== "pgsql") {
3513 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3515 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3518 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3519 } else if ($feed == -4) { // all articles virtual feed
3520 $query_strategy_part = "true";
3521 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3522 } else if ($feed <= -10) { // labels
3523 $label_id = -$feed - 11;
3525 $query_strategy_part = "label_id = '$label_id' AND
3526 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3527 ttrss_user_labels2.article_id = ref_id";
3529 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3530 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3533 $query_strategy_part = "id > 0"; // dumb
3536 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3537 $date_sort_field = "updated";
3539 $date_sort_field = "date_entered";
3542 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3543 $order_by = "$date_sort_field";
3545 $order_by = "$date_sort_field DESC";
3548 if ($view_mode != "noscores") {
3549 $order_by = "score DESC, $order_by";
3552 if ($override_order) {
3553 $order_by = $override_order;
3559 $feed_title = "Search results";
3562 $feed_title = getCategoryTitle($link, $feed);
3564 if ((int)$feed == $feed && $feed > 0) {
3565 $result = db_query($link, "SELECT title,site_url,last_error
3566 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3568 $feed_title = db_fetch_result($result, 0, "title");
3569 $feed_site_url = db_fetch_result($result, 0, "site_url");
3570 $last_error = db_fetch_result($result, 0, "last_error");
3572 $feed_title = getFeedTitle($link, $feed);
3577 $content_query_part = "content as content_preview,";
3579 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3582 $feed_kind = "Feeds";
3584 $feed_kind = "Labels";
3587 if ($limit_query_part) {
3588 $offset_query_part = "OFFSET $offset";
3591 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3592 if (!$override_order) {
3593 $order_by = "ttrss_feeds.title, $order_by";
3598 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3599 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3602 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3603 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3606 $query = "SELECT DISTINCT
3609 ttrss_entries.id,ttrss_entries.title,
3612 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3613 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3616 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3622 ttrss_user_entries.ref_id = ttrss_entries.id AND
3623 ttrss_user_entries.owner_uid = '$owner_uid' AND
3626 $query_strategy_part ORDER BY $order_by
3627 $limit_query_part $offset_query_part";
3629 if ($_REQUEST["debug"]) print $query;
3631 $result = db_query($link, $query);
3636 $feed_kind = "Tags";
3638 $result = db_query($link, "SELECT DISTINCT
3642 ttrss_entries.id as id,title,
3644 unread,feed_id,orig_feed_id,
3645 marked,link,last_read,
3646 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3649 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3652 ttrss_entries,ttrss_user_entries,ttrss_tags
3654 ref_id = ttrss_entries.id AND
3655 ttrss_user_entries.owner_uid = '$owner_uid' AND
3656 post_int_id = int_id AND tag_name = '$feed' AND
3659 $query_strategy_part ORDER BY $order_by
3660 $limit_query_part");
3663 return array($result, $feed_title, $feed_site_url, $last_error);
3667 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3668 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3670 require_once "lib/MiniTemplator.class.php";
3672 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3673 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3674 "margin-bottom : 1em; color : #9a8c59;";
3676 if (!$limit) $limit = 30;
3678 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3679 $date_sort_field = "updated";
3681 $date_sort_field = "date_entered";
3684 $qfh_ret = queryFeedHeadlines($link, $feed,
3685 $limit, $view_mode, $is_cat, $search, $search_mode,
3686 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3688 $result = $qfh_ret[0];
3689 $feed_title = htmlspecialchars($qfh_ret[1]);
3690 $feed_site_url = $qfh_ret[2];
3691 $last_error = $qfh_ret[3];
3693 $feed_self_url = get_self_url_prefix() .
3694 "/backend.php?op=rss&id=-2&key=" .
3695 get_feed_access_key($link, -2, false);
3697 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3699 $tpl = new MiniTemplator
;
3701 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3703 $tpl->setVariable('FEED_TITLE', $feed_title);
3704 $tpl->setVariable('VERSION', VERSION
);
3705 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3707 if (PUBSUBHUBBUB_HUB
&& $feed == -2) {
3708 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB
));
3709 $tpl->addBlock('feed_hub');
3712 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3714 while ($line = db_fetch_assoc($result)) {
3715 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3716 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3717 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3718 $tpl->setVariable('ARTICLE_EXCERPT',
3719 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3721 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3723 if ($line['note']) {
3724 $content = "<div style=\"$note_style\">" . $line['note'] . "</div>" .
3728 $tpl->setVariable('ARTICLE_CONTENT', $content);
3730 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3731 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3733 $tags = get_article_tags($link, $line["id"], $owner_uid);
3735 foreach ($tags as $tag) {
3736 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3737 $tpl->addBlock('category');
3740 $enclosures = get_article_enclosures($link, $line["id"]);
3742 foreach ($enclosures as $e) {
3743 $type = htmlspecialchars($e['content_type']);
3744 $url = htmlspecialchars($e['content_url']);
3745 $length = $e['duration'];
3747 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3748 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3749 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3751 $tpl->addBlock('enclosure');
3754 $tpl->addBlock('entry');
3759 $tpl->addBlock('feed');
3760 $tpl->generateOutputToString($tmp);
3765 function getCategoryTitle($link, $cat_id) {
3767 if ($cat_id == -1) {
3768 return __("Special");
3769 } else if ($cat_id == -2) {
3770 return __("Labels");
3773 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3776 if (db_num_rows($result) == 1) {
3777 return db_fetch_result($result, 0, "title");
3779 return "Uncategorized";
3784 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3787 if (!$owner) $owner = $_SESSION["uid"];
3789 $res = trim($str); if (!$res) return '';
3791 // if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3792 $res = $purifier->purify($res);
3795 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3796 $res = preg_replace('/<img[^>]+>/is', '', $res);
3799 if (strpos($res, "href=") === false)
3800 $res = rewrite_urls($res);
3802 $charset_hack = '<head>
3803 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3806 $res = trim($res); if (!$res) return '';
3808 libxml_use_internal_errors(true);
3810 $doc = new DOMDocument();
3811 $doc->loadHTML($charset_hack . $res);
3812 $xpath = new DOMXPath($doc);
3814 $entries = $xpath->query('(//a[@href]|//img[@src])');
3817 foreach ($entries as $entry) {
3821 if ($entry->hasAttribute('href'))
3822 $entry->setAttribute('href',
3823 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3825 if ($entry->hasAttribute('src'))
3826 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3827 $entry->setAttribute('src',
3828 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3831 if (strtolower($entry->nodeName
) == "a") {
3832 $entry->setAttribute("target", "_blank");
3835 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3836 $br = $doc->createElement("br");
3838 if ($entry->parentNode
->nextSibling
) {
3839 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3846 $node = $doc->getElementsByTagName('body')->item(0);
3848 return $doc->saveXML($node);
3852 * Send by mail a digest of last articles.
3854 * @param mixed $link The database connection.
3855 * @param integer $limit The maximum number of articles by digest.
3856 * @return boolean Return false if digests are not enabled.
3858 function send_headlines_digests($link, $limit = 100) {
3860 if (!DIGEST_ENABLE
) return false;
3862 $user_limit = DIGEST_EMAIL_LIMIT
;
3865 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3867 if (DB_TYPE
== "pgsql") {
3868 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3869 } else if (DB_TYPE
== "mysql") {
3870 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3873 $result = db_query($link, "SELECT id,email FROM ttrss_users
3874 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3876 while ($line = db_fetch_assoc($result)) {
3878 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3879 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3881 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3883 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3884 $digest = $tuple[0];
3885 $headlines_count = $tuple[1];
3886 $affected_ids = $tuple[2];
3887 $digest_text = $tuple[3];
3889 if ($headlines_count > 0) {
3891 $mail = new PHPMailer();
3893 $mail->PluginDir
= "lib/phpmailer/";
3894 $mail->SetLanguage("en", "lib/phpmailer/language/");
3896 $mail->CharSet
= "UTF-8";
3898 $mail->From
= DIGEST_FROM_ADDRESS
;
3899 $mail->FromName
= DIGEST_FROM_NAME
;
3900 $mail->AddAddress($line["email"], $line["login"]);
3902 if (DIGEST_SMTP_HOST
) {
3903 $mail->Host
= DIGEST_SMTP_HOST
;
3904 $mail->Mailer
= "smtp";
3905 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3906 $mail->Username
= DIGEST_SMTP_LOGIN
;
3907 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3910 $mail->IsHTML(true);
3911 $mail->Subject
= DIGEST_SUBJECT
;
3912 $mail->Body
= $digest;
3913 $mail->AltBody
= $digest_text;
3915 $rc = $mail->Send();
3917 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3921 if ($rc && $do_catchup) {
3922 print "Marking affected articles as read...\n";
3923 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3926 print "No headlines\n";
3929 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3930 WHERE id = " . $line["id"]);
3934 print "All done.\n";
3938 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3940 require_once "lib/MiniTemplator.class.php";
3942 $tpl = new MiniTemplator
;
3943 $tpl_t = new MiniTemplator
;
3945 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3946 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3948 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3949 $tpl->setVariable('CUR_TIME', date('G:i'));
3951 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3952 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3954 $affected_ids = array();
3956 if (DB_TYPE
== "pgsql") {
3957 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3958 } else if (DB_TYPE
== "mysql") {
3959 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3962 $result = db_query($link, "SELECT ttrss_entries.title,
3963 ttrss_feeds.title AS feed_title,
3965 ttrss_user_entries.ref_id,
3967 SUBSTRING(content, 1, 120) AS excerpt,
3968 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3970 ttrss_user_entries,ttrss_entries,ttrss_feeds
3972 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3973 AND include_in_digest = true
3975 AND ttrss_user_entries.owner_uid = $user_id
3977 ORDER BY ttrss_feeds.title, date_updated DESC
3980 $cur_feed_title = "";
3982 $headlines_count = db_num_rows($result);
3984 $headlines = array();
3986 while ($line = db_fetch_assoc($result)) {
3987 array_push($headlines, $line);
3990 for ($i = 0; $i < sizeof($headlines); $i++
) {
3992 $line = $headlines[$i];
3994 array_push($affected_ids, $line["ref_id"]);
3996 $updated = make_local_datetime($link, $line['last_updated'], false,
3999 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
4000 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
4001 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
4002 $tpl->setVariable('ARTICLE_UPDATED', $updated);
4003 $tpl->setVariable('ARTICLE_EXCERPT',
4004 truncate_string(strip_tags($line["excerpt"]), 100));
4006 $tpl->addBlock('article');
4008 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
4009 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4010 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4011 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4012 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4013 // truncate_string(strip_tags($line["excerpt"]), 100));
4015 $tpl_t->addBlock('article');
4017 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
4018 $tpl->addBlock('feed');
4019 $tpl_t->addBlock('feed');
4024 $tpl->addBlock('digest');
4025 $tpl->generateOutputToString($tmp);
4027 $tpl_t->addBlock('digest');
4028 $tpl_t->generateOutputToString($tmp_t);
4030 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4033 function check_for_update($link) {
4034 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
4035 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
4037 $version_data = @fetch_file_contents
($version_url);
4039 if ($version_data) {
4040 $version_data = json_decode($version_data, true);
4041 if ($version_data && $version_data['version']) {
4043 if (version_compare(VERSION
, $version_data['version']) == -1) {
4044 return $version_data;
4052 function markArticlesById($link, $ids, $cmode) {
4056 foreach ($ids as $id) {
4057 array_push($tmp_ids, "ref_id = '$id'");
4060 $ids_qpart = join(" OR ", $tmp_ids);
4063 db_query($link, "UPDATE ttrss_user_entries SET
4064 marked = false,last_read = NOW()
4065 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4066 } else if ($cmode == 1) {
4067 db_query($link, "UPDATE ttrss_user_entries SET
4069 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4071 db_query($link, "UPDATE ttrss_user_entries SET
4072 marked = NOT marked,last_read = NOW()
4073 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4077 function publishArticlesById($link, $ids, $cmode) {
4081 foreach ($ids as $id) {
4082 array_push($tmp_ids, "ref_id = '$id'");
4085 $ids_qpart = join(" OR ", $tmp_ids);
4088 db_query($link, "UPDATE ttrss_user_entries SET
4089 published = false,last_read = NOW()
4090 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4091 } else if ($cmode == 1) {
4092 db_query($link, "UPDATE ttrss_user_entries SET
4094 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4096 db_query($link, "UPDATE ttrss_user_entries SET
4097 published = NOT published,last_read = NOW()
4098 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4101 if (PUBSUBHUBBUB_HUB
) {
4102 $rss_link = get_self_url_prefix() .
4103 "/backend.php?op=rss&id=-2&key=" .
4104 get_feed_access_key($link, -2, false);
4106 $p = new Publisher(PUBSUBHUBBUB_HUB
);
4108 $pubsub_result = $p->publish_update($rss_link);
4112 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4114 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4115 if (count($ids) == 0) return;
4119 foreach ($ids as $id) {
4120 array_push($tmp_ids, "ref_id = '$id'");
4123 $ids_qpart = join(" OR ", $tmp_ids);
4126 db_query($link, "UPDATE ttrss_user_entries SET
4127 unread = false,last_read = NOW()
4128 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4129 } else if ($cmode == 1) {
4130 db_query($link, "UPDATE ttrss_user_entries SET
4132 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4134 db_query($link, "UPDATE ttrss_user_entries SET
4135 unread = NOT unread,last_read = NOW()
4136 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4141 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4142 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4144 while ($line = db_fetch_assoc($result)) {
4145 ccache_update($link, $line["feed_id"], $owner_uid);
4149 function catchupArticleById($link, $id, $cmode) {
4152 db_query($link, "UPDATE ttrss_user_entries SET
4153 unread = false,last_read = NOW()
4154 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4155 } else if ($cmode == 1) {
4156 db_query($link, "UPDATE ttrss_user_entries SET
4158 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4160 db_query($link, "UPDATE ttrss_user_entries SET
4161 unread = NOT unread,last_read = NOW()
4162 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4165 $feed_id = getArticleFeed($link, $id);
4166 ccache_update($link, $feed_id, $_SESSION["uid"]);
4169 function make_guid_from_title($title) {
4170 return preg_replace("/[ \"\',.:;]/", "-",
4171 mb_strtolower(strip_tags($title), 'utf-8'));
4174 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4175 $feed_id, $is_cat, $search, $match_on,
4176 $search_mode, $view_mode, $error) {
4178 $page_prev_link = "viewFeedGoPage(-1)";
4179 $page_next_link = "viewFeedGoPage(1)";
4180 $page_first_link = "viewFeedGoPage(0)";
4182 $catchup_page_link = "catchupPage()";
4183 $catchup_feed_link = "catchupCurrentFeed()";
4184 $catchup_sel_link = "catchupSelection()";
4186 $archive_sel_link = "archiveSelection()";
4187 $delete_sel_link = "deleteSelection()";
4189 $sel_all_link = "selectArticles('all')";
4190 $sel_unread_link = "selectArticles('unread')";
4191 $sel_none_link = "selectArticles('none')";
4192 $sel_inv_link = "selectArticles('invert')";
4194 $tog_unread_link = "selectionToggleUnread()";
4195 $tog_marked_link = "selectionToggleMarked()";
4196 $tog_published_link = "selectionTogglePublished()";
4198 $reply = "<div id=\"subtoolbar_main\">";
4200 $reply .= __('Select:')."
4201 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4202 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4203 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4204 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4208 $reply .= "<select dojoType=\"dijit.form.Select\"
4209 onchange=\"headlineActionsChange(this)\">";
4210 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4212 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4214 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4215 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4216 <option value=\"$tog_published_link\">".__('Published')."</option>";
4218 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4220 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4222 if ($feed_id != "0") {
4223 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4225 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4226 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4230 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4233 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4235 $rss_link = htmlspecialchars(get_self_url_prefix() .
4236 "/backend.php?op=rss&id=$feed_id$cat_q$search_q");
4238 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4240 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4242 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4244 $reply .= "</select>";
4248 $reply .= "<div id=\"subtoolbar_ftitle\">";
4250 if ($feed_site_url) {
4251 $target = "target=\"_blank\"";
4252 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4253 truncate_string($feed_title,30)."</a>";
4256 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4260 if ($feed_id < -10) {
4261 $label_id = -11-$feed_id;
4263 $result = db_query($link, "SELECT fg_color, bg_color
4264 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4267 if (db_num_rows($result) != 0) {
4268 $fg_color = db_fetch_result($result, 0, "fg_color");
4269 $bg_color = db_fetch_result($result, 0, "bg_color");
4271 $reply .= "<span style='background : $bg_color; color : $fg_color'>";
4272 $reply .= $feed_title;
4273 $reply .= "</span>";
4275 $reply .= $feed_title;
4279 $reply .= $feed_title;
4284 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4291 title=\"".__("View as RSS feed")."\"
4292 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4293 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4300 function outputFeedList($link, $special = true) {
4302 $feedlist = array();
4304 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4306 $feedlist['identifier'] = 'id';
4307 $feedlist['label'] = 'name';
4308 $feedlist['items'] = array();
4310 $owner_uid = $_SESSION["uid"];
4317 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4318 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4320 $cat['items'] = array();
4323 foreach (array(-4, -3, -1, -2, 0) as $i) {
4324 array_push($cat['items'], feedlist_init_feed($link, $i));
4328 array_push($feedlist['items'], $cat);
4330 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4333 $result = db_query($link, "SELECT * FROM
4334 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4336 if (db_num_rows($result) > 0) {
4338 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4339 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4340 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4342 $cat['items'] = array();
4345 while ($line = db_fetch_assoc($result)) {
4347 $label_id = -$line['id'] - 11;
4348 $count = getFeedUnread($link, $label_id);
4350 $feed = feedlist_init_feed($link, $label_id, false, $count);
4352 $feed['fg_color'] = $line['fg_color'];
4353 $feed['bg_color'] = $line['bg_color'];
4355 array_push($cat['items'], $feed);
4359 array_push($feedlist['items'], $cat);
4361 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4366 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4367 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4368 $order_by_qpart = "order_id,category,unread DESC,title";
4370 $order_by_qpart = "order_id,category,title";
4373 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4374 $order_by_qpart = "unread DESC,title";
4376 $order_by_qpart = "title";
4383 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4384 ttrss_feeds.order_id,title";
4386 $order_by_qpart = "title";
4388 $age_qpart = getMaxAgeSubquery();
4390 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4391 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4393 ttrss_feed_categories.title AS category,
4394 ttrss_feed_categories.collapsed,
4396 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4397 ON (ttrss_feed_categories.id = cat_id)
4398 LEFT JOIN ttrss_counters_cache
4400 (ttrss_feeds.id = feed_id)
4402 ttrss_feeds.owner_uid = '$owner_uid'
4403 ORDER BY $order_by_qpart";
4405 $result = db_query($link, $query);
4407 $actid = $_REQUEST["actid"];
4409 if (db_num_rows($result) > 0) {
4414 $cat['items'] = array();
4418 while ($line = db_fetch_assoc($result)) {
4420 $feed = htmlspecialchars(trim($line["title"]));
4422 if (!$feed) $feed = "[Untitled]";
4424 $feed_id = $line["id"];
4425 $unread = $line["unread"];
4427 $cat_id = $line["cat_id"];
4428 $tmp_category = $line["category"];
4429 if (!$tmp_category) $tmp_category = __("Uncategorized");
4431 if ($category != $tmp_category && $enable_cats) {
4433 $category = $tmp_category;
4435 $collapsed = sql_bool_to_bool($line["collapsed"]);
4437 // workaround for NULL category
4438 if ($category == __("Uncategorized")) {
4439 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4442 if ($cat) array_push($feedlist['items'], $cat);
4444 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4447 $updated = make_local_datetime($link, $line["updated_noms"], false);
4449 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4450 $feed, $unread, $line['last_error'], $updated));
4454 array_push($feedlist['items'], $cat);
4456 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4464 function get_article_tags($link, $id, $owner_uid = 0) {
4468 $a_id = db_escape_string($id);
4470 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4472 $query = "SELECT DISTINCT tag_name,
4473 owner_uid as owner FROM
4474 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4475 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4477 $obj_id = md5("TAGS:$owner_uid:$id");
4480 if ($memcache && $obj = $memcache->get($obj_id)) {
4483 /* check cache first */
4485 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4486 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4488 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4491 $tags = explode(",", $tag_cache);
4494 /* do it the hard way */
4496 $tmp_result = db_query($link, $query);
4498 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4499 array_push($tags, $tmp_line["tag_name"]);
4502 /* update the cache */
4504 $tags_str = db_escape_string(join(",", $tags));
4506 db_query($link, "UPDATE ttrss_user_entries
4507 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4508 AND owner_uid = " . $_SESSION["uid"]);
4511 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4517 function trim_value(&$value) {
4518 $value = trim($value);
4521 function trim_array($array) {
4523 array_walk($tmp, 'trim_value');
4527 function tag_is_valid($tag) {
4528 if ($tag == '') return false;
4529 if (preg_match("/^[0-9]*$/", $tag)) return false;
4530 if (mb_strlen($tag) > 250) return false;
4532 if (function_exists('iconv')) {
4533 $tag = iconv("utf-8", "utf-8", $tag);
4536 if (!$tag) return false;
4541 function render_login_form($link, $mobile = 0) {
4544 require_once "login_form.php";
4547 require_once "mobile/login_form.php";
4550 require_once "mobile/classic/login_form.php";
4554 // from http://developer.apple.com/internet/safari/faq.html
4555 function no_cache_incantation() {
4556 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4557 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4558 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4559 header("Cache-Control: post-check=0, pre-check=0", false);
4560 header("Pragma: no-cache"); // HTTP/1.0
4563 function format_warning($msg, $id = "") {
4565 return "<div class=\"warning\" id=\"$id\">
4566 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4569 function format_notice($msg, $id = "") {
4571 return "<div class=\"notice\" id=\"$id\">
4572 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4575 function format_error($msg, $id = "") {
4577 return "<div class=\"error\" id=\"$id\">
4578 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4581 function print_notice($msg) {
4582 return print format_notice($msg);
4585 function print_warning($msg) {
4586 return print format_warning($msg);
4589 function print_error($msg) {
4590 return print format_error($msg);
4594 function T_sprintf() {
4595 $args = func_get_args();
4596 return vsprintf(__(array_shift($args)), $args);
4599 function format_inline_player($link, $url, $ctype) {
4603 if (strpos($ctype, "audio/") === 0) {
4605 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4606 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4607 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4609 $id = 'AUDIO-' . uniqid();
4611 $entry .= "<audio id=\"$id\"\">
4612 <source src=\"$url\"></source>
4615 $entry .= "<span onclick=\"player(this)\"
4616 title=\"".__("Click to play")."\" status=\"0\"
4617 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4621 $entry .= "<object type=\"application/x-shockwave-flash\"
4622 data=\"extras/button/musicplayer.swf?song_url=$url\"
4623 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4624 <param name=\"movie\"
4625 value=\"extras/button/musicplayer.swf?song_url=$url\" />
4630 $filename = substr($url, strrpos($url, "/")+
1);
4632 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4633 $filename . " (" . $ctype . ")" . "</a>";
4638 function format_article($link, $id, $feed_id, $mark_as_read = true,
4639 $zoom_mode = false) {
4645 /* we can figure out feed_id from article id anyway, why do we
4646 * pass feed_id here? let's ignore the argument :( */
4648 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4649 WHERE ref_id = '$id'");
4651 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4653 $rv['feed_id'] = $feed_id;
4655 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4657 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4658 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4660 if (db_num_rows($result) == 1) {
4661 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4662 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4664 $rtl_content = false;
4665 $always_display_enclosures = false;
4669 $rtl_tag = "dir=\"RTL\"";
4676 if ($mark_as_read) {
4677 $result = db_query($link, "UPDATE ttrss_user_entries
4678 SET unread = false,last_read = NOW()
4679 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4681 ccache_update($link, $feed_id, $_SESSION["uid"]);
4684 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4685 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4686 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4687 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4692 FROM ttrss_entries,ttrss_user_entries
4693 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4697 $line = db_fetch_assoc($result);
4699 if ($line["icon_url"]) {
4700 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4702 $feed_icon = " ";
4705 $feed_site_url = $line['site_url'];
4707 $num_comments = $line["num_comments"];
4708 $entry_comments = "";
4710 if ($num_comments > 0) {
4711 if ($line["comments"]) {
4712 $comments_url = $line["comments"];
4714 $comments_url = $line["link"];
4716 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4718 if ($line["comments"] && $line["link"] != $line["comments"]) {
4719 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4724 header("Content-Type: text/html");
4725 $rv['content'] .= "<html><head>
4726 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4727 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4728 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4732 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4733 truncate_string(strip_tags($line['title']), 15) . "</div>";
4735 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4737 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4738 class=\"postHeader\" id=\"POSTHDR-$id\">";
4740 $entry_author = $line["author"];
4742 if ($entry_author) {
4743 $entry_author = __(" - ") . $entry_author;
4746 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4749 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4751 if ($line["link"]) {
4752 $rv['content'] .= "<div clear='both'><a target='_blank'
4753 title=\"".htmlspecialchars($line['title'])."\"
4755 $line["link"] . "\">" .
4756 truncate_string($line["title"], 100) .
4757 "<span class='author'>$entry_author</span></a></div>";
4759 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4762 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4764 if (!$entry_comments) $entry_comments = " "; # placeholder
4766 $rv['content'] .= "<div style='float : right'>
4767 <img src='".theme_image($link, 'images/tag.png')."'
4768 class='tagsPic' alt='Tags' title='Tags'> ";
4771 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4772 <a title=\"".__('Edit tags for this article')."\"
4773 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4775 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4776 class='tagsPic' style=\"cursor : pointer\"
4777 onclick=\"postOpenInNewTab(event, $id)\"
4778 alt='Zoom' title='".__('Open article in new tab')."'>";
4780 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4782 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4783 class='tagsPic' style=\"cursor : pointer\"
4784 onclick=\"editArticleNote($id)\"
4785 alt='PubNote' title='".__('Edit article note')."'>";
4787 if (DIGEST_ENABLE
) {
4788 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4789 class='tagsPic' style=\"cursor : pointer\"
4790 onclick=\"emailArticle($id)\"
4791 alt='Zoom' title='".__('Forward by email')."'>";
4794 if (ENABLE_TWEET_BUTTON
) {
4795 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4796 class='tagsPic' style=\"cursor : pointer\"
4797 onclick=\"tweetArticle($id)\"
4798 alt='Zoom' title='".__('Share on Twitter')."'>";
4801 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4802 class='tagsPic' style=\"cursor : pointer\"
4803 onclick=\"closeArticlePanel($id)\"
4804 alt='Zoom' title='".__('Close this panel')."'>";
4807 $tags_str = strip_tags($tags_str);
4808 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4810 $rv['content'] .= "</div>";
4811 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4813 if ($line["orig_feed_id"]) {
4815 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4816 WHERE id = ".$line["orig_feed_id"]);
4818 if (db_num_rows($tmp_result) != 0) {
4820 $rv['content'] .= "<div clear='both'>";
4821 $rv['content'] .= __("Originally from:");
4823 $rv['content'] .= " ";
4825 $tmp_line = db_fetch_assoc($tmp_result);
4827 $rv['content'] .= "<a target='_blank'
4828 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4829 $tmp_line['title'] . "</a>";
4831 $rv['content'] .= " ";
4833 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4834 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4836 $rv['content'] .= "</div>";
4840 $rv['content'] .= "</div>";
4842 $rv['content'] .= "<div class=\"postIcon\">" .
4843 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4844 href=\"".htmlspecialchars($feed_site_url)."\">".
4845 $feed_icon . "</a></div>";
4847 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4848 if ($line['note']) {
4849 $rv['content'] .= format_article_note($id, $line['note']);
4851 $rv['content'] .= "</div>";
4853 $rv['content'] .= "<div class=\"postContent\">";
4855 $article_content = sanitize_rss($link, $line["content"], false, false,
4858 $rv['content'] .= $article_content;
4860 $rv['content'] .= format_article_enclosures($link, $id,
4861 $always_display_enclosures, $article_content);
4863 $rv['content'] .= "</div>";
4865 $rv['content'] .= "</div>";
4871 <div style=\"text-align : center\">
4872 <button onclick=\"return window.close()\">".
4873 __("Close this window")."</button></div>";
4874 $rv['content'] .= "</body></html>";
4881 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4882 $next_unread_feed, $offset, $vgr_last_feed = false,
4883 $override_order = false) {
4885 $disable_cache = false;
4889 $timing_info = getmicrotime();
4891 $topmost_article_ids = array();
4897 if ($subop == "undefined") $subop = "";
4899 $subop_split = split(":", $subop);
4901 if ($subop == "CatchupSelected") {
4902 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4903 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4905 catchupArticlesById($link, $ids, $cmode);
4908 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4909 update_rss_feed($link, $feed, true);
4912 if ($subop == "MarkAllRead") {
4913 catchup_feed($link, $feed, $cat_view);
4915 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4916 if ($next_unread_feed) {
4917 $feed = $next_unread_feed;
4922 if ($subop_split[0] == "MarkAllReadGR") {
4923 catchup_feed($link, $subop_split[1], false);
4926 // FIXME: might break tag display?
4928 if ($feed > 0 && !$cat_view) {
4929 $result = db_query($link,
4930 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4932 if (db_num_rows($result) == 0) {
4933 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4937 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4939 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4940 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4942 if (db_num_rows($result) == 1) {
4943 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4945 $rtl_content = false;
4949 $rtl_tag = "dir=\"RTL\"";
4955 $rtl_content = false;
4958 /// START /////////////////////////////////////////////////////////////////////////////////
4960 @$search = db_escape_string($_REQUEST["query"]);
4963 $disable_cache = true;
4966 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4967 @$match_on = db_escape_string($_REQUEST["match_on"]);
4973 $real_offset = $offset * $limit;
4975 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4977 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4978 $search, $search_mode, $match_on, $override_order, $real_offset);
4980 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4982 $result = $qfh_ret[0];
4983 $feed_title = $qfh_ret[1];
4984 $feed_site_url = $qfh_ret[2];
4985 $last_error = $qfh_ret[3];
4987 $vgroup_last_feed = $vgr_last_feed;
4989 /// STOP //////////////////////////////////////////////////////////////////////////////////
4993 if (db_num_rows($result) > 0) {
4994 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4995 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5000 $headlines_count = db_num_rows($result);
5002 if (db_num_rows($result) > 0) {
5004 $lnum = $limit*$offset;
5007 $cur_feed_title = '';
5009 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5011 while ($line = db_fetch_assoc($result)) {
5013 $class = ($lnum %
2) ?
"even" : "odd";
5016 $feed_id = $line["feed_id"];
5018 $labels = get_article_labels($link, $id);
5020 $labels_str = "<span id=\"HLLCTR-$id\">";
5021 $labels_str .= format_article_labels($labels, $id);
5022 $labels_str .= "</span>";
5024 if (count($topmost_article_ids) < 3) {
5025 array_push($topmost_article_ids, $id);
5028 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5030 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5031 theme_image($link, 'images/updated.png')."\"
5034 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5038 if (sql_bool_to_bool($line["unread"]) &&
5039 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5041 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5042 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5045 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5046 $class .= " Unread";
5053 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5054 $marked_pic = "<img id=\"FMPIC-$id\"
5055 src=\"".theme_image($link, 'images/mark_set.png')."\"
5056 class=\"markedPic\" alt=\"Unstar article\"
5057 onclick='javascript:tMark($id)'>";
5059 $marked_pic = "<img id=\"FMPIC-$id\"
5060 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5061 class=\"markedPic\" alt=\"Star article\"
5062 onclick='javascript:tMark($id)'>";
5065 if ($line["published"] == "t" ||
$line["published"] == "1") {
5066 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5067 'images/pub_set.png')."\"
5069 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5071 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5072 'images/pub_unset.png')."\"
5074 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5077 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5078 # $line["title"] . "</a>";
5080 # $content_link = "<a
5081 # href=\"" . htmlspecialchars($line["link"]) . "\"
5082 # onclick=\"view($id,$feed_id);\">" .
5083 # $line["title"] . "</a>";
5085 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5086 # $line["title"] . "</a>";
5088 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5090 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5091 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5095 $score = $line["score"];
5097 $score_pic = theme_image($link,
5098 "images/" . get_score_pic($score));
5100 /* $score_title = __("(Click to change)");
5101 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5102 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5104 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5109 } else if ($score < -100) {
5115 $entry_author = $line["author"];
5117 if ($entry_author) {
5118 $entry_author = " - $entry_author";
5121 $has_feed_icon = feed_has_icon($feed_id);
5123 if ($has_feed_icon) {
5124 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5126 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5129 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5131 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5132 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5134 $cur_feed_title = $line["feed_title"];
5135 $vgroup_last_feed = $feed_id;
5137 $cur_feed_title = htmlspecialchars($cur_feed_title);
5139 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5141 $reply['content'] .= "<div class='cdmFeedTitle'>".
5142 "<div style=\"float : right\">$feed_icon_img</div>".
5143 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5144 $line["feed_title"]."</a> $vf_catchup_link</div>";
5149 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5150 onmouseout='postMouseOut($id)'";
5152 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5154 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5156 $reply['content'] .= "<div class='hlLeft'>";
5158 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5161 $reply['content'] .= "$marked_pic";
5162 $reply['content'] .= "$published_pic";
5164 $reply['content'] .= "</div>";
5166 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5167 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5168 $reply['content'] .= "<a id=\"RTITLE-$id\"
5169 href=\"" . htmlspecialchars($line["link"]) . "\"
5173 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5174 if ($content_preview) {
5175 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5179 $reply['content'] .= "</a></span>";
5181 $reply['content'] .= $labels_str;
5183 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5184 if (@$line["feed_title"]) {
5185 print "<span class=\"hlFeed\">
5186 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5187 $line["feed_title"]."</a>)
5192 $reply['content'] .= "</div>";
5194 $reply['content'] .= "<div class=\"hlRight\">";
5195 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5196 $reply['content'] .= $score_pic;
5198 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5200 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5201 title=\"".htmlspecialchars($line['feed_title'])."\">
5202 $feed_icon_img<span>";
5205 $reply['content'] .= "</div>";
5206 $reply['content'] .= "</div>";
5210 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5211 if ($feed_id != $vgroup_last_feed) {
5213 $cur_feed_title = $line["feed_title"];
5214 $vgroup_last_feed = $feed_id;
5216 $cur_feed_title = htmlspecialchars($cur_feed_title);
5218 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5220 $has_feed_icon = feed_has_icon($feed_id);
5222 if ($has_feed_icon) {
5223 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5225 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5228 $reply['content'] .= "<div class='cdmFeedTitle'>".
5229 "<div style=\"float : right\">$feed_icon_img</div>".
5230 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5231 $line["feed_title"]."</a> $vf_catchup_link</div>";
5235 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5237 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5238 onmouseout='postMouseOut($id)'";
5240 $reply['content'] .= "<div class=\"$class\"
5241 id=\"RROW-$id\" $mouseover_attrs'>";
5243 $reply['content'] .= "<div class=\"cdmHeader\">";
5245 $reply['content'] .= "<div style='float : right'>";
5246 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5247 $reply['content'] .= "$score_pic";
5249 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5250 $reply['content'] .= "<span style=\"cursor : pointer\"
5251 title=\"".htmlspecialchars($line["feed_title"])."\"
5252 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5254 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5256 $reply['content'] .= "</div>";
5258 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5259 'RROW-$id')\" id=\"RCHK-$id\"/>";
5261 $reply['content'] .= "$marked_pic";
5262 $reply['content'] .= "$published_pic";
5264 $reply['content'] .= "<span id=\"RTITLE-$id\"
5265 onclick=\"return cdmClicked(event, $id);\"
5266 class=\"titleWrap$hlc_suffix\">
5268 title=\"".htmlspecialchars($line['title'])."\"
5269 target=\"_blank\" href=\"".
5270 htmlspecialchars($line["link"])."\">".
5271 truncate_string($line["title"], 100) .
5272 " $entry_author</a>";
5274 $reply['content'] .= $labels_str;
5277 $content_hidden = "style=\"display : none\"";
5279 $excerpt_hidden = "style=\"display : none\"";
5281 $reply['content'] .= "<span $excerpt_hidden
5282 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5284 $reply['content'] .= "</span>";
5286 $reply['content'] .= "</div>";
5288 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5289 onclick=\"return cdmClicked(event, $id);\"
5292 $reply['content'] .= "<div class=\"cdmContentInner\">";
5294 if ($line["orig_feed_id"]) {
5296 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5297 WHERE id = ".$line["orig_feed_id"]);
5299 if (db_num_rows($tmp_result) != 0) {
5301 $reply['content'] .= "<div clear='both'>";
5302 $reply['content'] .= __("Originally from:");
5304 $reply['content'] .= " ";
5306 $tmp_line = db_fetch_assoc($tmp_result);
5308 $reply['content'] .= "<a target='_blank'
5309 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5310 $tmp_line['title'] . "</a>";
5312 $reply['content'] .= " ";
5314 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5315 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5317 $reply['content'] .= "</div>";
5321 // FIXME: make this less of a hack
5323 $feed_site_url = false;
5325 if ($line["feed_id"]) {
5326 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5327 WHERE id = " . $line["feed_id"]);
5329 if (db_num_rows($tmp_result) == 1) {
5330 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5335 $article_content = sanitize_rss($link, $line["content_preview"],
5336 false, false, $feed_site_url);
5338 if (!$article_content) $article_content = " ";
5340 $article_content = '';
5343 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5344 if ($line['note']) {
5345 $reply['content'] .= format_article_note($id, $line['note']);
5347 $reply['content'] .= "</div>";
5349 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5351 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5352 ttrss_feeds WHERE id = ".
5353 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5354 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5356 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5357 0, "always_display_enclosures"));
5359 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5362 $reply['content'] .= "</div>";
5364 $reply['content'] .= "<div class=\"cdmFooter\">";
5366 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5368 $reply['content'] .= "<img src='".theme_image($link,
5369 'images/tag.png')."' alt='Tags' title='Tags'>
5370 <span id=\"ATSTR-$id\">$tags_str</span>
5371 <a title=\"".__('Edit tags for this article')."\"
5372 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5374 $reply['content'] .= "<div style=\"float : right\">";
5376 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5377 onclick=\"zoomToArticle(event, $id)\"
5378 style=\"cursor : pointer\"
5380 title='".__('Open article in new tab')."'>";
5382 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5384 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5385 style=\"cursor : pointer\" style=\"cursor : pointer\"
5386 onclick=\"editArticleNote($id)\"
5387 alt='PubNote' title='".__('Edit article note')."'>";
5389 if (DIGEST_ENABLE
) {
5390 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5391 style=\"cursor : pointer\"
5392 onclick=\"emailArticle($id)\"
5393 alt='Zoom' title='".__('Forward by email')."'>";
5396 if (ENABLE_TWEET_BUTTON
) {
5397 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5398 class='tagsPic' style=\"cursor : pointer\"
5399 onclick=\"tweetArticle($id)\"
5400 alt='Zoom' title='".__('Share on Twitter')."'>";
5403 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5404 style=\"cursor : pointer\" style=\"cursor : pointer\"
5405 onclick=\"dismissArticle($id)\"
5406 alt='Dismiss' title='".__('Dismiss article')."'>";
5408 $reply['content'] .= "</div>";
5409 $reply['content'] .= "</div>";
5411 $reply['content'] .= "</div>";
5413 $reply['content'] .= "</div>";
5423 switch ($view_mode) {
5425 $message = __("No unread articles found to display.");
5428 $message = __("No updated articles found to display.");
5431 $message = __("No starred articles found to display.");
5435 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5437 $message = __("No articles found to display.");
5441 if (!$offset && $message) {
5442 $reply['content'] .= "<div class='whiteBox'>$message";
5444 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5446 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5447 WHERE owner_uid = " . $_SESSION['uid']);
5449 $last_updated = db_fetch_result($result, 0, "last_updated");
5450 $last_updated = make_local_datetime($link, $last_updated, false);
5452 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5454 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5455 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5457 $num_errors = db_fetch_result($result, 0, "num_errors");
5459 if ($num_errors > 0) {
5460 $reply['content'] .= "<br/>";
5461 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5462 __('Some feeds have update errors (click for details)')."</a>";
5464 $reply['content'] .= "</span></p></div>";
5469 # if ($headlines_count > 0) print "</div>";
5473 #print "]]></content>";
5475 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5476 $vgroup_last_feed, $reply['content'], $reply['toolbar']);
5479 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5481 function printTagCloud($link) {
5483 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5484 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5485 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5487 $result = db_query($link, $query);
5491 while ($line = db_fetch_assoc($result)) {
5492 $tags[$line["tag_name"]] = $line["count"];
5497 $max_size = 32; // max font size in pixels
5498 $min_size = 11; // min font size in pixels
5500 // largest and smallest array values
5501 $max_qty = max(array_values($tags));
5502 $min_qty = min(array_values($tags));
5504 // find the range of values
5505 $spread = $max_qty - $min_qty;
5506 if ($spread == 0) { // we don't want to divide by zero
5510 // set the font-size increment
5511 $step = ($max_size - $min_size) / ($spread);
5513 // loop through the tag array
5514 foreach ($tags as $key => $value) {
5515 // calculate font-size
5516 // find the $value in excess of $min_qty
5517 // multiply by the font-size increment ($size)
5518 // and add the $min_size set above
5519 $size = round($min_size +
(($value - $min_qty) * $step));
5521 $key_escaped = str_replace("'", "\\'", $key);
5523 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5524 $size . "px\" title=\"$value articles tagged with " .
5525 $key . '">' . $key . '</a> ';
5529 function print_checkpoint($n, $s) {
5530 $ts = getmicrotime();
5531 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5535 function sanitize_tag($tag) {
5538 $tag = mb_strtolower($tag, 'utf-8');
5540 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5542 // $tag = str_replace('"', "", $tag);
5543 // $tag = str_replace("+", " ", $tag);
5544 $tag = str_replace("technorati tag: ", "", $tag);
5549 function get_self_url_prefix() {
5553 if ($_SERVER['HTTPS'] != "on") {
5554 $url_path = "http://";
5556 $url_path = "https://";
5559 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5561 return $url_path; */
5563 return SELF_URL_PATH
;
5566 function opml_publish_url($link){
5568 $url_path = get_self_url_prefix();
5569 $url_path .= "/opml.php?op=publish&key=" .
5570 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5576 * Purge a feed contents, marked articles excepted.
5578 * @param mixed $link The database connection.
5579 * @param integer $id The id of the feed to purge.
5582 function clear_feed_articles($link, $id) {
5585 $result = db_query($link, "DELETE FROM ttrss_user_entries
5586 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5588 $result = db_query($link, "DELETE FROM ttrss_user_entries
5589 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5592 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5593 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5595 ccache_update($link, $id, $_SESSION['uid']);
5596 } // function clear_feed_articles
5599 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5601 * @return string The Mozilla Firefox feed adding URL.
5603 function add_feed_url() {
5604 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5606 $url_path = get_self_url_prefix() .
5607 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5609 } // function add_feed_url
5612 * Encrypt a password in SHA1.
5614 * @param string $pass The password to encrypt.
5615 * @param string $login A optionnal login.
5616 * @return string The encrypted password.
5618 function encrypt_password($pass, $login = '') {
5620 return "SHA1X:" . sha1("$login:$pass");
5622 return "SHA1:" . sha1($pass);
5624 } // function encrypt_password
5627 * Update a feed batch.
5628 * Used by daemons to update n feeds by run.
5629 * Only update feed needing a update, and not being processed
5630 * by another process.
5632 * @param mixed $link Database link
5633 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5634 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5635 * @param boolean $debug Set to false to disable debug output. Default to true.
5638 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5639 // Process all other feeds using last_updated and interval parameters
5641 // Test if the user has loggued in recently. If not, it does not update its feeds.
5642 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5643 if (DB_TYPE
== "pgsql") {
5644 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5646 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5649 $login_thresh_qpart = "";
5652 // Test if the feed need a update (update interval exceded).
5653 if (DB_TYPE
== "pgsql") {
5654 $update_limit_qpart = "AND ((
5655 ttrss_feeds.update_interval = 0
5656 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5658 ttrss_feeds.update_interval > 0
5659 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5660 ) OR ttrss_feeds.last_updated IS NULL)";
5662 $update_limit_qpart = "AND ((
5663 ttrss_feeds.update_interval = 0
5664 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5666 ttrss_feeds.update_interval > 0
5667 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5668 ) OR ttrss_feeds.last_updated IS NULL)";
5671 // Test if feed is currently being updated by another process.
5672 if (DB_TYPE
== "pgsql") {
5673 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5675 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5678 // Test if there is a limit to number of updated feeds
5680 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5682 $random_qpart = sql_random_function();
5684 // We search for feed needing update.
5685 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5686 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5687 ttrss_feeds.update_interval
5689 ttrss_feeds, ttrss_users, ttrss_user_prefs
5691 ttrss_feeds.owner_uid = ttrss_users.id
5692 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5693 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5694 $login_thresh_qpart $update_limit_qpart
5695 $updstart_thresh_qpart
5696 ORDER BY $random_qpart $query_limit");
5698 $user_prefs_cache = array();
5700 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5702 // Here is a little cache magic in order to minimize risk of double feed updates.
5703 $feeds_to_update = array();
5704 while ($line = db_fetch_assoc($result)) {
5705 $feeds_to_update[$line['id']] = $line;
5708 // We update the feed last update started date before anything else.
5709 // There is no lag due to feed contents downloads
5710 // It prevent an other process to update the same feed.
5711 $feed_ids = array_keys($feeds_to_update);
5713 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5714 WHERE id IN (%s)", implode(',', $feed_ids)));
5717 // For each feed, we call the feed update function.
5718 while ($line = array_pop($feeds_to_update)) {
5720 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5722 update_rss_feed($link, $line["id"], true);
5724 sleep(1); // prevent flood (FIXME make this an option?)
5727 // Send feed digests by email if needed.
5728 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5730 } // function update_daemon_common
5732 function sanitize_article_content($text) {
5733 # we don't support CDATA sections in articles, they break our own escaping
5734 $text = preg_replace("/\[\[CDATA/", "", $text);
5735 $text = preg_replace("/\]\]\>/", "", $text);
5739 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5744 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5746 if ($memcache && $obj = $memcache->get($obj_id)) {
5752 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5754 $result = db_query($link, "SELECT reg_exp,
5755 ttrss_filter_types.name AS name,
5756 ttrss_filter_actions.name AS action,
5760 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5763 owner_uid = $owner_uid AND
5764 ttrss_filter_types.id = filter_type AND
5765 ttrss_filter_actions.id = action_id AND
5766 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5768 while ($line = db_fetch_assoc($result)) {
5769 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5770 $filter["reg_exp"] = $line["reg_exp"];
5771 $filter["action"] = $line["action"];
5772 $filter["action_param"] = $line["action_param"];
5773 $filter["filter_param"] = $line["filter_param"];
5774 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5776 array_push($filters[$line["name"]], $filter);
5779 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5785 function get_score_pic($score) {
5787 return "score_high.png";
5788 } else if ($score > 0) {
5789 return "score_half_high.png";
5790 } else if ($score < -100) {
5791 return "score_low.png";
5792 } else if ($score < 0) {
5793 return "score_half_low.png";
5795 return "score_neutral.png";
5799 function rounded_table_start($classname, $header = " ") {
5800 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5801 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5802 print "<tr><td class='left'> </td><td class='content'>";
5805 function rounded_table_end($footer = " ") {
5806 print "</td><td class='right'> </td></tr>";
5807 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5811 function feed_has_icon($id) {
5812 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5815 function init_connection($link) {
5816 if (DB_TYPE
== "pgsql") {
5817 pg_query($link, "set client_encoding = 'UTF-8'");
5818 pg_set_client_encoding("UNICODE");
5819 pg_query($link, "set datestyle = 'ISO, european'");
5820 pg_query($link, "set TIME ZONE 0");
5822 db_query($link, "SET time_zone = '+0:0'");
5824 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5825 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5826 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5831 function update_feedbrowser_cache($link) {
5833 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5834 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5835 WHERE tf.feed_url = ttrss_feeds.feed_url
5836 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5837 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5839 db_query($link, "BEGIN");
5841 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5845 while ($line = db_fetch_assoc($result)) {
5846 $subscribers = db_escape_string($line["subscribers"]);
5847 $feed_url = db_escape_string($line["feed_url"]);
5848 $title = db_escape_string($line["title"]);
5850 $tmp_result = db_query($link, "SELECT subscribers FROM
5851 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5853 if (db_num_rows($tmp_result) == 0) {
5855 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5856 (feed_url, title, subscribers) VALUES ('$feed_url',
5857 '$title', '$subscribers')");
5865 db_query($link, "COMMIT");
5871 function ccache_zero($link, $feed_id, $owner_uid) {
5872 db_query($link, "UPDATE ttrss_counters_cache SET
5873 value = 0, updated = NOW() WHERE
5874 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5877 function ccache_zero_all($link, $owner_uid) {
5878 db_query($link, "UPDATE ttrss_counters_cache SET
5879 value = 0 WHERE owner_uid = '$owner_uid'");
5881 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5882 value = 0 WHERE owner_uid = '$owner_uid'");
5885 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5888 $table = "ttrss_counters_cache";
5890 $table = "ttrss_cat_counters_cache";
5893 db_query($link, "DELETE FROM $table WHERE
5894 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5898 function ccache_update_all($link, $owner_uid) {
5900 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5902 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5903 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5905 while ($line = db_fetch_assoc($result)) {
5906 ccache_update($link, $line["feed_id"], $owner_uid, true);
5909 /* We have to manually include category 0 */
5911 ccache_update($link, 0, $owner_uid, true);
5914 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5915 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5917 while ($line = db_fetch_assoc($result)) {
5918 print ccache_update($link, $line["feed_id"], $owner_uid);
5925 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5926 $no_update = false) {
5928 if (!is_numeric($feed_id)) return;
5931 $table = "ttrss_counters_cache";
5933 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5934 WHERE id = '$feed_id'");
5935 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5938 $table = "ttrss_cat_counters_cache";
5941 if (DB_TYPE
== "pgsql") {
5942 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5943 } else if (DB_TYPE
== "mysql") {
5944 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5947 $result = db_query($link, "SELECT value FROM $table
5948 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5951 if (db_num_rows($result) == 1) {
5952 return db_fetch_result($result, 0, "value");
5957 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5963 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5964 $update_pcat = true) {
5966 if (!is_numeric($feed_id)) return;
5968 if (!$is_cat && $feed_id > 0) {
5969 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5970 WHERE id = '$feed_id'");
5971 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5974 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5976 /* When updating a label, all we need to do is recalculate feed counters
5977 * because labels are not cached */
5980 ccache_update_all($link, $owner_uid);
5985 $table = "ttrss_counters_cache";
5987 $table = "ttrss_cat_counters_cache";
5990 if ($is_cat && $feed_id >= 0) {
5991 if ($feed_id != 0) {
5992 $cat_qpart = "cat_id = '$feed_id'";
5994 $cat_qpart = "cat_id IS NULL";
5997 /* Recalculate counters for child feeds */
5999 $result = db_query($link, "SELECT id FROM ttrss_feeds
6000 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6002 while ($line = db_fetch_assoc($result)) {
6003 ccache_update($link, $line["id"], $owner_uid, false, false);
6006 $result = db_query($link, "SELECT SUM(value) AS sv
6007 FROM ttrss_counters_cache, ttrss_feeds
6008 WHERE id = feed_id AND $cat_qpart AND
6009 ttrss_feeds.owner_uid = '$owner_uid'");
6011 $unread = (int) db_fetch_result($result, 0, "sv");
6014 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6017 db_query($link, "BEGIN");
6019 $result = db_query($link, "SELECT feed_id FROM $table
6020 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6022 if (db_num_rows($result) == 1) {
6023 db_query($link, "UPDATE $table SET
6024 value = '$unread', updated = NOW() WHERE
6025 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6028 db_query($link, "INSERT INTO $table
6029 (feed_id, value, owner_uid, updated)
6031 ($feed_id, $unread, $owner_uid, NOW())");
6034 db_query($link, "COMMIT");
6036 if ($feed_id > 0 && $prev_unread != $unread) {
6040 /* Update parent category */
6044 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6045 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6047 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6049 ccache_update($link, $cat_id, $owner_uid, true);
6053 } else if ($feed_id < 0) {
6054 ccache_update_all($link, $owner_uid);
6060 function label_find_id($link, $label, $owner_uid) {
6061 $result = db_query($link,
6062 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6063 AND owner_uid = '$owner_uid' LIMIT 1");
6065 if (db_num_rows($result) == 1) {
6066 return db_fetch_result($result, 0, "id");
6072 function get_article_labels($link, $id) {
6075 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6079 if ($memcache && $obj = $memcache->get($obj_id)) {
6083 $result = db_query($link, "SELECT label_cache FROM
6084 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6087 $label_cache = db_fetch_result($result, 0, "label_cache");
6091 $label_cache = json_decode($label_cache, true);
6093 if ($label_cache["no-labels"] == 1)
6096 return $label_cache;
6099 $result = db_query($link,
6100 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6101 FROM ttrss_labels2, ttrss_user_labels2
6103 AND article_id = '$id'
6104 AND owner_uid = ".$_SESSION["uid"] . "
6107 while ($line = db_fetch_assoc($result)) {
6108 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6110 array_push($rv, $rk);
6112 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6115 label_update_cache($link, $id, $rv);
6117 label_update_cache($link, $id, array("no-labels" => 1));
6124 function label_find_caption($link, $label, $owner_uid) {
6125 $result = db_query($link,
6126 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6127 AND owner_uid = '$owner_uid' LIMIT 1");
6129 if (db_num_rows($result) == 1) {
6130 return db_fetch_result($result, 0, "caption");
6136 function label_update_cache($link, $id, $labels = false, $force = false) {
6139 label_clear_cache($link, $id);
6142 $labels = get_article_labels($link, $id);
6144 $labels = db_escape_string(json_encode($labels));
6146 db_query($link, "UPDATE ttrss_user_entries SET
6147 label_cache = '$labels' WHERE ref_id = '$id'");
6151 function label_clear_cache($link, $id) {
6153 db_query($link, "UPDATE ttrss_user_entries SET
6154 label_cache = '' WHERE ref_id = '$id'");
6158 function label_remove_article($link, $id, $label, $owner_uid) {
6160 $label_id = label_find_id($link, $label, $owner_uid);
6162 if (!$label_id) return;
6164 $result = db_query($link,
6165 "DELETE FROM ttrss_user_labels2
6167 label_id = '$label_id' AND
6168 article_id = '$id'");
6170 label_clear_cache($link, $id);
6173 function label_add_article($link, $id, $label, $owner_uid) {
6178 $obj_id = md5("LABELS:$id:$owner_uid");
6179 $memcache->delete($obj_id);
6182 $label_id = label_find_id($link, $label, $owner_uid);
6184 if (!$label_id) return;
6186 $result = db_query($link,
6188 article_id FROM ttrss_labels2, ttrss_user_labels2
6191 label_id = '$label_id' AND
6192 article_id = '$id' AND owner_uid = '$owner_uid'
6195 if (db_num_rows($result) == 0) {
6196 db_query($link, "INSERT INTO ttrss_user_labels2
6197 (label_id, article_id) VALUES ('$label_id', '$id')");
6200 label_clear_cache($link, $id);
6204 function label_remove($link, $id, $owner_uid) {
6207 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6210 $obj_id = md5("LABELS:$id:$owner_uid");
6211 $memcache->delete($obj_id);
6214 db_query($link, "BEGIN");
6216 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6219 $caption = db_fetch_result($result, 0, "caption");
6221 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6222 AND owner_uid = " . $owner_uid);
6224 if (db_affected_rows($link, $result) != 0 && $caption) {
6226 /* Remove access key for the label */
6228 $ext_id = -11 - $id;
6230 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6231 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6233 /* Disable filters that reference label being removed */
6235 db_query($link, "UPDATE ttrss_filters SET
6236 enabled = false WHERE action_param = '$caption'
6238 AND owner_uid = " . $owner_uid);
6240 /* Remove cached data */
6242 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6243 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6247 db_query($link, "COMMIT");
6250 function label_create($link, $caption) {
6252 db_query($link, "BEGIN");
6256 $result = db_query($link, "SELECT id FROM ttrss_labels2
6257 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6259 if (db_num_rows($result) == 0) {
6260 $result = db_query($link,
6261 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6262 VALUES ('$caption', '".$_SESSION["uid"]."')");
6264 $result = db_affected_rows($link, $result) != 0;
6267 db_query($link, "COMMIT");
6272 function print_labels_headlines_dropdown($link, $feed_id) {
6273 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6275 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6276 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6278 while ($line = db_fetch_assoc($result)) {
6280 $label_id = $line["id"];
6281 $label_caption = $line["caption"];
6284 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6285 print "<option id=\"LHDL-$id\"
6286 value=\"selectionRemoveLabel($label_id)\">".
6287 __('Remove:') . " $label_caption</option>";
6289 print "<option id=\"LHDL-$id\"
6290 value=\"selectionAssignLabel($label_id)\">".
6291 __('Assign:') . " $label_caption</option>";
6296 function format_tags_string($tags, $id) {
6299 $tags_nolinks_str = "";
6303 /* if (get_user_theme($link) == "3pane") {
6311 $formatted_tags = array();
6313 foreach ($tags as $tag) {
6315 $tag_escaped = str_replace("'", "\\'", $tag);
6317 if (mb_strlen($tag) > 30) {
6318 $tag = truncate_string($tag, 30);
6321 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6323 array_push($formatted_tags, $tag_str);
6325 $tmp_tags_str = implode(", ", $formatted_tags);
6327 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6332 $tags_str = implode(", ", $formatted_tags);
6334 if ($num_tags < count($tags)) {
6335 $tags_str .= ", …";
6338 if ($num_tags == 0) {
6339 $tags_str = __("no tags");
6346 function format_article_labels($labels, $id) {
6350 foreach ($labels as $l) {
6351 $labels_str .= sprintf("<span class='hlLabelRef'
6352 style='color : %s; background-color : %s'>%s</span>",
6353 $l[2], $l[3], $l[1]);
6360 function format_article_note($id, $note) {
6362 $str = "<div class='articleNote' title=\"".__('edit note')."\"
6363 onclick=\"editArticleNote($id)\">$note</div>";
6368 function toggle_collapse_cat($link, $cat_id, $mode) {
6370 $mode = bool_to_sql_bool($mode);
6372 db_query($link, "UPDATE ttrss_feed_categories SET
6373 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6380 $pref_name = '_COLLAPSED_SPECIAL';
6383 $pref_name = '_COLLAPSED_LABELS';
6386 $pref_name = '_COLLAPSED_UNCAT';
6392 set_pref($link, $pref_name, 'true');
6394 set_pref($link, $pref_name, 'false');
6400 function remove_feed($link, $id, $owner_uid) {
6404 /* save starred articles in Archived feed */
6406 db_query($link, "BEGIN");
6408 /* prepare feed if necessary */
6410 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6413 if (db_num_rows($result) == 0) {
6414 db_query($link, "INSERT INTO ttrss_archived_feeds
6415 (id, owner_uid, title, feed_url, site_url)
6416 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6420 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6421 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6422 marked = true AND owner_uid = $owner_uid");
6424 /* Remove access key for the feed */
6426 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6427 feed_id = '$id' AND owner_uid = $owner_uid");
6429 /* remove the feed */
6431 db_query($link, "DELETE FROM ttrss_feeds
6432 WHERE id = '$id' AND owner_uid = $owner_uid");
6434 db_query($link, "COMMIT");
6436 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6437 unlink(ICONS_DIR . "/$id.ico");
6440 ccache_remove($link, $id, $owner_uid);
6443 label_remove($link, -11-$id, $owner_uid);
6444 ccache_remove($link, -11-$id, $owner_uid);
6448 function add_feed_category($link, $feed_cat) {
6450 if (!$feed_cat) return false;
6452 db_query($link, "BEGIN");
6454 $result = db_query($link,
6455 "SELECT id FROM ttrss_feed_categories
6456 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6458 if (db_num_rows($result) == 0) {
6460 $result = db_query($link,
6461 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6462 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6464 db_query($link, "COMMIT");
6472 function remove_feed_category($link, $id, $owner_uid) {
6474 db_query($link, "DELETE FROM ttrss_feed_categories
6475 WHERE id = '$id' AND owner_uid = $owner_uid");
6477 ccache_remove($link, $id, $owner_uid, true);
6480 function archive_article($link, $id, $owner_uid) {
6481 db_query($link, "BEGIN");
6483 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6484 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6486 if (db_num_rows($result) != 0) {
6488 /* prepare the archived table */
6490 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6493 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6494 WHERE id = '$feed_id'");
6496 if (db_num_rows($result) == 0) {
6497 db_query($link, "INSERT INTO ttrss_archived_feeds
6498 (id, owner_uid, title, feed_url, site_url)
6499 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6500 WHERE id = '$feed_id'");
6503 db_query($link, "UPDATE ttrss_user_entries
6504 SET orig_feed_id = feed_id, feed_id = NULL
6505 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6509 db_query($link, "COMMIT");
6512 function getArticleFeed($link, $id) {
6513 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6514 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6516 if (db_num_rows($result) != 0) {
6517 return db_fetch_result($result, 0, "feed_id");
6523 function make_url_from_parts($parts) {
6524 $url = $parts['scheme'] . '://' . $parts['host'];
6526 if ($parts['path']) $url .= $parts['path'];
6527 if ($parts['query']) $url .= '?' . $parts['query'];
6533 * Fixes incomplete URLs by prepending "http://".
6534 * Also replaces feed:// with http://, and
6535 * prepends a trailing slash if the url is a domain name only.
6537 * @param string $url Possibly incomplete URL
6539 * @return string Fixed URL.
6541 function fix_url($url) {
6542 if (strpos($url, '://') === false) {
6543 $url = 'http://' . $url;
6544 } else if (substr($url, 0, 5) == 'feed:') {
6545 $url = 'http:' . substr($url, 5);
6548 //prepend slash if the URL has no slash in it
6549 // "http://www.example" -> "http://www.example/"
6550 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6554 if ($url != "http:///")
6560 function validate_feed_url($url) {
6561 $parts = parse_url($url);
6563 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6567 function get_article_enclosures($link, $id) {
6571 $query = "SELECT * FROM ttrss_enclosures
6572 WHERE post_id = '$id' AND content_url != ''";
6574 $obj_id = md5("ENCLOSURES:$id");
6578 if ($memcache && $obj = $memcache->get($obj_id)) {
6581 $result = db_query($link, $query);
6583 if (db_num_rows($result) > 0) {
6584 while ($line = db_fetch_assoc($result)) {
6585 array_push($rv, $line);
6587 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6594 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6600 if ($cat_id == -4 ||
$cat_id == -2) {
6601 $counters = getLabelCounters($link, true);
6603 foreach (array_values($counters) as $cv) {
6605 $unread = $cv["counter"];
6607 if ($unread ||
!$unread_only) {
6611 "title" => $cv["description"],
6612 "unread" => $cv["counter"],
6616 array_push($feeds, $row);
6623 if ($cat_id == -4 ||
$cat_id == -1) {
6624 foreach (array(-1, -2, -3, -4, 0) as $i) {
6625 $unread = getFeedUnread($link, $i);
6627 if ($unread ||
!$unread_only) {
6628 $title = getFeedTitle($link, $i);
6633 "unread" => $unread,
6636 array_push($feeds, $row);
6645 $limit_qpart = "LIMIT $limit OFFSET $offset";
6650 if ($cat_id == -4 ||
$cat_id == -3) {
6651 $result = db_query($link, "SELECT
6652 id, feed_url, cat_id, title, ".
6653 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6654 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6655 " ORDER BY cat_id, title " . $limit_qpart);
6659 $cat_qpart = "cat_id = '$cat_id'";
6661 $cat_qpart = "cat_id IS NULL";
6663 $result = db_query($link, "SELECT
6664 id, feed_url, cat_id, title, ".
6665 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6666 FROM ttrss_feeds WHERE
6667 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6668 " ORDER BY cat_id, title " . $limit_qpart);
6671 while ($line = db_fetch_assoc($result)) {
6673 $unread = getFeedUnread($link, $line["id"]);
6675 $has_icon = feed_has_icon($line['id']);
6677 if ($unread ||
!$unread_only) {
6680 "feed_url" => $line["feed_url"],
6681 "title" => $line["title"],
6682 "id" => (int)$line["id"],
6683 "unread" => (int)$unread,
6684 "has_icon" => $has_icon,
6685 "cat_id" => (int)$line["cat_id"],
6686 "last_updated" => strtotime($line["last_updated"])
6689 array_push($feeds, $row);
6696 function api_get_headlines($link, $feed_id, $limit, $offset,
6697 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6698 $include_attachments) {
6700 /* do not rely on params below */
6702 $search = db_escape_string($_REQUEST["search"]);
6703 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6704 $match_on = db_escape_string($_REQUEST["match_on"]);
6706 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6707 $view_mode, $is_cat, $search, $search_mode, $match_on,
6710 $result = $qfh_ret[0];
6711 $feed_title = $qfh_ret[1];
6713 $headlines = array();
6715 while ($line = db_fetch_assoc($result)) {
6716 $is_updated = ($line["last_read"] == "" &&
6717 ($line["unread"] != "t" && $line["unread"] != "1"));
6719 $headline_row = array(
6720 "id" => (int)$line["id"],
6721 "unread" => sql_bool_to_bool($line["unread"]),
6722 "marked" => sql_bool_to_bool($line["marked"]),
6723 "published" => sql_bool_to_bool($line["published"]),
6724 "updated" => strtotime($line["updated"]),
6725 "is_updated" => $is_updated,
6726 "title" => $line["title"],
6727 "link" => $line["link"],
6728 "feed_id" => $line["feed_id"],
6729 "tags" => get_article_tags($link, $line["id"]),
6732 if ($include_attachments)
6733 $headline_row['attachments'] = get_article_enclosures($link,
6736 if ($show_excerpt) {
6737 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6738 $headline_row["excerpt"] = $excerpt;
6741 if ($show_content) {
6742 $headline_row["content"] = $line["content_preview"];
6745 array_push($headlines, $headline_row);
6751 function generate_error_feed($link, $error) {
6754 $reply['headlines']['id'] = -6;
6755 $reply['headlines']['is_cat'] = false;
6757 $reply['headlines']['toolbar'] = '';
6758 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6760 $reply['headlines-info'] = array("count" => 0,
6761 "vgroup_last_feed" => '',
6763 "disable_cache" => true);
6769 function generate_dashboard_feed($link) {
6772 $reply['headlines']['id'] = -5;
6773 $reply['headlines']['is_cat'] = false;
6775 $reply['headlines']['toolbar'] = '';
6776 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6778 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6780 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6781 WHERE owner_uid = " . $_SESSION['uid']);
6783 $last_updated = db_fetch_result($result, 0, "last_updated");
6784 $last_updated = make_local_datetime($link, $last_updated, false);
6786 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6788 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6789 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6791 $num_errors = db_fetch_result($result, 0, "num_errors");
6793 if ($num_errors > 0) {
6794 $reply['headlines']['content'] .= "<br/>";
6795 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6796 __('Some feeds have update errors (click for details)')."</a>";
6798 $reply['headlines']['content'] .= "</span></p>";
6800 $reply['headlines-info'] = array("count" => 0,
6801 "vgroup_last_feed" => '',
6803 "disable_cache" => true);
6808 function save_email_address($link, $email) {
6809 // FIXME: implement persistent storage of emails
6811 if (!$_SESSION['stored_emails'])
6812 $_SESSION['stored_emails'] = array();
6814 if (!in_array($email, $_SESSION['stored_emails']))
6815 array_push($_SESSION['stored_emails'], $email);
6818 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6819 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6821 $sql_is_cat = bool_to_sql_bool($is_cat);
6823 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6824 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6825 AND owner_uid = " . $owner_uid);
6827 if (db_num_rows($result) == 1) {
6828 $key = db_escape_string(sha1(uniqid(rand(), true)));
6830 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6831 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6832 AND owner_uid = " . $owner_uid);
6837 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6841 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6843 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6845 $sql_is_cat = bool_to_sql_bool($is_cat);
6847 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6848 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6849 AND owner_uid = " . $owner_uid);
6851 if (db_num_rows($result) == 1) {
6852 return db_fetch_result($result, 0, "access_key");
6854 $key = db_escape_string(sha1(uniqid(rand(), true)));
6856 $result = db_query($link, "INSERT INTO ttrss_access_keys
6857 (access_key, feed_id, is_cat, owner_uid)
6858 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6866 * Extracts RSS/Atom feed URLs from the given HTML URL.
6868 * @param string $url HTML page URL
6870 * @return array Array of feeds. Key is the full URL, value the title
6872 function get_feeds_from_html($url, $login = false, $pass = false)
6874 $url = fix_url($url);
6875 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6877 libxml_use_internal_errors(true);
6879 $content = @fetch_file_contents
($url, false, $login, $pass);
6881 $doc = new DOMDocument();
6882 $doc->loadHTML($content);
6883 $xpath = new DOMXPath($doc);
6884 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6885 $feedUrls = array();
6886 foreach ($entries as $entry) {
6887 if ($entry->hasAttribute('href')) {
6888 $title = $entry->getAttribute('title');
6890 $title = $entry->getAttribute('type');
6892 $feedUrl = rewrite_relative_url(
6893 $baseUrl, $entry->getAttribute('href')
6895 $feedUrls[$feedUrl] = $title;
6902 * Checks if the content behind the given URL is a HTML file
6904 * @param string $url URL to check
6906 * @return boolean True if the URL contains HTML content
6908 function url_is_html($url, $login = false, $pass = false) {
6909 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6911 if (stripos($content, '<html>') === false
6912 && stripos($content, '<html ') === false
6920 function print_label_select($link, $name, $value, $attributes = "") {
6922 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6923 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6925 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6926 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6928 while ($line = db_fetch_assoc($result)) {
6930 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6932 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6933 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6937 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6944 function format_article_enclosures($link, $id, $always_display_enclosures,
6947 $result = get_article_enclosures($link, $id);
6950 if (count($result) > 0) {
6952 $entries_html = array();
6955 foreach ($result as $line) {
6957 $url = $line["content_url"];
6958 $ctype = $line["content_type"];
6960 if (!$ctype) $ctype = __("unknown type");
6962 # $filename = substr($url, strrpos($url, "/")+1);
6964 $entry = format_inline_player($link, $url, $ctype);
6966 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6967 # $filename . " (" . $ctype . ")" . "</a>";
6969 array_push($entries_html, $entry);
6973 $entry["type"] = $ctype;
6974 $entry["filename"] = $filename;
6975 $entry["url"] = $url;
6977 array_push($entries, $entry);
6980 $rv .= "<div class=\"postEnclosures\">";
6982 if (!get_pref($link, "STRIP_IMAGES")) {
6983 if ($always_display_enclosures ||
6984 !preg_match("/<img/i", $article_content)) {
6986 foreach ($entries as $entry) {
6988 if (preg_match("/image/", $entry["type"]) ||
6989 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6992 alt=\"".htmlspecialchars($entry["filename"])."\"
6993 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6999 if (count($entries) == 1) {
7000 $rv .= __("Attachment:") . " ";
7002 $rv .= __("Attachments:") . " ";
7005 $rv .= join(", ", $entries_html);
7013 function getLastArticleId($link) {
7014 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7015 WHERE owner_uid = " . $_SESSION["uid"]);
7017 if (db_num_rows($result) == 1) {
7018 return db_fetch_result($result, 0, "id");
7024 function build_url($parts) {
7025 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7029 * Converts a (possibly) relative URL to a absolute one.
7031 * @param string $url Base URL (i.e. from where the document is)
7032 * @param string $rel_url Possibly relative URL in the document
7034 * @return string Absolute URL
7036 function rewrite_relative_url($url, $rel_url) {
7037 if (strpos($rel_url, "://") !== false) {
7039 } else if (strpos($rel_url, "/") === 0)
7041 $parts = parse_url($url);
7042 $parts['path'] = $rel_url;
7044 return build_url($parts);
7047 $parts = parse_url($url);
7048 if (!isset($parts['path'])) {
7049 $parts['path'] = '/';
7051 $dir = $parts['path'];
7052 if (substr($dir, -1) !== '/') {
7053 $dir = dirname($parts['path']);
7054 $dir !== '/' && $dir .= '/';
7056 $parts['path'] = $dir . $rel_url;
7058 return build_url($parts);
7062 function sphinx_search($query, $offset = 0, $limit = 30) {
7063 $sphinxClient = new SphinxClient();
7065 $sphinxClient->SetServer('localhost', 9312);
7066 $sphinxClient->SetConnectTimeout(1);
7068 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7069 'feed_title' => 20));
7071 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
7072 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
7073 $sphinxClient->SetLimits($offset, $limit, 1000);
7074 $sphinxClient->SetArrayResult(false);
7075 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7077 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
7081 if (is_array($result['matches'])) {
7082 foreach (array_keys($result['matches']) as $int_id) {
7083 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7084 array_push($ids, $ref_id);
7091 function cleanup_tags($link, $days = 14, $limit = 1000) {
7093 if (DB_TYPE
== "pgsql") {
7094 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7095 } else if (DB_TYPE
== "mysql") {
7096 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7101 while ($limit > 0) {
7104 $query = "SELECT ttrss_tags.id AS id
7105 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7106 WHERE post_int_id = int_id AND $interval_query AND
7107 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7109 $result = db_query($link, $query);
7113 while ($line = db_fetch_assoc($result)) {
7114 array_push($ids, $line['id']);
7117 if (count($ids) > 0) {
7118 $ids = join(",", $ids);
7121 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7122 $tags_deleted +
= db_affected_rows($link, $tmp_result);
7127 $limit -= $limit_part;
7132 return $tags_deleted;
7135 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7137 $cat_id = (int) $cat_id;
7140 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7141 } else if ($cat_id == 0 ||
$cat_id == -2) {
7142 $cat_unread = getCategoryUnread($link, $cat_id);
7145 $obj['id'] = 'CAT:' . $cat_id;
7146 $obj['items'] = array();
7147 $obj['name'] = getCategoryTitle($link, $cat_id);
7148 $obj['type'] = 'feed';
7149 $obj['unread'] = (int) $cat_unread;
7150 $obj['hidden'] = $hidden;
7151 $obj['bare_id'] = $cat_id;
7156 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7158 $feed_id = (int) $feed_id;
7161 $title = getFeedTitle($link, $feed_id, false);
7163 if ($unread === false)
7164 $unread = getFeedUnread($link, $feed_id, false);
7166 $obj['id'] = 'FEED:' . $feed_id;
7167 $obj['name'] = $title;
7168 $obj['unread'] = (int) $unread;
7169 $obj['type'] = 'feed';
7170 $obj['error'] = $error;
7171 $obj['updated'] = $updated;
7172 $obj['icon'] = getFeedIcon($feed_id);
7173 $obj['bare_id'] = $feed_id;
7179 function fetch_twitter_rss($link, $url, $owner_uid) {
7180 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7181 WHERE id = $owner_uid");
7183 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7184 $url_escaped = db_escape_string($url);
7186 if ($access_token) {
7188 $tmhOAuth = new tmhOAuth(array(
7189 'consumer_key' => CONSUMER_KEY
,
7190 'consumer_secret' => CONSUMER_SECRET
,
7191 'user_token' => $access_token['oauth_token'],
7192 'user_secret' => $access_token['oauth_token_secret'],
7195 $code = $tmhOAuth->request('GET', $url);
7199 $content = $tmhOAuth->response
['response'];
7201 define('MAGPIE_CACHE_ON', false);
7203 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7204 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7210 db_query($link, "UPDATE ttrss_feeds
7211 SET last_error = 'OAuth authorization failed ($code).'
7212 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7217 db_query($link, "UPDATE ttrss_feeds
7218 SET last_error = 'OAuth information not found.'
7219 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7225 function print_user_stylesheet($link) {
7226 $value = get_pref($link, 'USER_STYLESHEET');
7229 print "<style type=\"text/css\">";
7230 print str_replace("<br/>", "\n", $value);
7236 function rewrite_urls($line) {
7241 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7242 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);