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');
102 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
104 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
105 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
107 ini_set('user_agent', SELF_USER_AGENT
);
109 require_once "lib/simplepie/simplepie.inc";
110 require_once "lib/magpierss/rss_fetch.inc";
111 require_once 'lib/magpierss/rss_utils.inc';
112 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
114 $config = HTMLPurifier_Config
::createDefault();
116 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s";
118 $config->set('HTML', 'Allowed', $allowed);
119 $purifier = new HTMLPurifier($config);
122 * Print a timestamped debug message.
124 * @param string $msg The debug message.
127 function _debug($msg) {
128 $ts = strftime("%H:%M:%S", time());
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
132 print "[$ts] $msg\n";
136 * Purge a feed old posts.
138 * @param mixed $link A database connection.
139 * @param mixed $feed_id The id of the purged feed.
140 * @param mixed $purge_interval Olderness of purged posts.
141 * @param boolean $debug Set to True to enable the debug. False by default.
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
151 $result = db_query($link,
152 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
156 if (db_num_rows($result) == 1) {
157 $owner_uid = db_fetch_result($result, 0, "owner_uid");
160 if ($purge_interval == -1 ||
!$purge_interval) {
162 ccache_update($link, $feed_id, $owner_uid);
167 if (!$owner_uid) return;
169 if (FORCE_ARTICLE_PURGE
== 0) {
170 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
173 $purge_unread = true;
174 $purge_interval = FORCE_ARTICLE_PURGE
;
177 if (!$purge_unread) $query_limit = " unread = false AND ";
179 if (DB_TYPE
== "pgsql") {
180 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
181 marked = false AND feed_id = '$feed_id' AND
182 (SELECT date_updated FROM ttrss_entries WHERE
183 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
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);
430 $entries = $xpath->query('/html/head/link[@rel="shortcut icon"]');
432 if (count($entries) > 0) {
433 foreach ($entries as $entry) {
434 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
441 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
444 } // function get_favicon_url
446 function check_feed_favicon($site_url, $feed, $link) {
447 $favicon_url = get_favicon_url($site_url);
449 # print "FAVICON [$site_url]: $favicon_url\n";
451 $icon_file = ICONS_DIR
. "/$feed.ico";
453 if ($favicon_url && !file_exists($icon_file)) {
454 $contents = fetch_file_contents($favicon_url, "image");
457 $fp = fopen($icon_file, "w");
460 fwrite($fp, $contents);
462 chmod($icon_file, 0644);
468 function update_rss_feed($link, $feed, $ignore_daemon = false) {
472 /* Update all feeds with the same URL to utilize memcache */
475 $result = db_query($link, "SELECT f1.id
476 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
477 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
479 while ($line = db_fetch_assoc($result)) {
480 update_rss_feed_real($link, $line["id"], $ignore_daemon);
483 update_rss_feed_real($link, $feed, $ignore_daemon);
487 function update_rss_feed_real($link, $feed, $ignore_daemon = false) {
491 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
495 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
496 _debug("update_rss_feed: start");
499 if (!$ignore_daemon) {
501 if (DB_TYPE
== "pgsql") {
502 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
504 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
507 $result = db_query($link, "SELECT id,update_interval,auth_login,
508 auth_pass,cache_images,update_method
509 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
513 $result = db_query($link, "SELECT id,update_interval,auth_login,
514 feed_url,auth_pass,cache_images,update_method,last_updated,
516 FROM ttrss_feeds WHERE id = '$feed'");
520 if (db_num_rows($result) == 0) {
521 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
522 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
527 $update_method = db_fetch_result($result, 0, "update_method");
528 $last_updated = db_fetch_result($result, 0, "last_updated");
529 $owner_uid = db_fetch_result($result, 0, "owner_uid");
531 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
532 WHERE id = '$feed'");
534 $auth_login = db_fetch_result($result, 0, "auth_login");
535 $auth_pass = db_fetch_result($result, 0, "auth_pass");
537 if ($update_method == 0)
538 $update_method = DEFAULT_UPDATE_METHOD +
1;
544 if ($update_method == 2)
545 $use_simplepie = true;
547 $use_simplepie = false;
549 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
550 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
553 if ($update_method == 1) {
554 $auth_login = urlencode($auth_login);
555 $auth_pass = urlencode($auth_pass);
558 $update_interval = db_fetch_result($result, 0, "update_interval");
559 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
560 $fetch_url = db_fetch_result($result, 0, "feed_url");
562 if ($update_interval < 0) { return; }
564 $feed = db_escape_string($feed);
566 if ($auth_login && $auth_pass && $updated != 3) {
567 $url_parts = array();
568 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
570 if ($url_parts[1] && $url_parts[2]) {
571 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
576 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
577 _debug("update_rss_feed: fetching [$fetch_url]...");
580 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
582 if ($memcache && $obj = $memcache->get($obj_id)) {
584 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
585 _debug("update_rss_feed: data found in memcache.");
592 if ($update_method == 3) {
593 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
594 } else if ($update_method == 1) {
595 $rss = @fetch_rss
($fetch_url);
597 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
598 mkdir(SIMPLEPIE_CACHE_DIR
);
601 $rss = new SimplePie();
602 $rss->set_useragent(SELF_USER_AGENT
);
603 # $rss->set_timeout(10);
604 $rss->set_feed_url($fetch_url);
605 $rss->set_output_encoding('UTF-8');
607 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
609 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
610 _debug("enabling image cache");
613 $rss->set_image_handler("image.php", 'i');
616 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
617 _debug("feed update interval (sec): " .
618 get_feed_update_interval($link, $feed)*60);
621 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
622 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
623 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
629 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
634 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
635 _debug("update_rss_feed: fetch done, parsing...");
638 $feed = db_escape_string($feed);
640 if ($update_method == 2) {
641 $fetch_ok = !$rss->error();
648 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
649 _debug("update_rss_feed: processing feed data...");
652 // db_query($link, "BEGIN");
654 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
655 FROM ttrss_feeds WHERE id = '$feed'");
657 $registered_title = db_fetch_result($result, 0, "title");
658 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
659 $orig_site_url = db_fetch_result($result, 0, "site_url");
661 $owner_uid = db_fetch_result($result, 0, "owner_uid");
663 if ($use_simplepie) {
664 $site_url = $rss->get_link();
666 $site_url = $rss->channel
["link"];
669 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
670 _debug("update_rss_feed: checking favicon...");
673 check_feed_favicon($site_url, $feed, $link);
675 if (!$registered_title ||
$registered_title == "[Unknown]") {
677 if ($use_simplepie) {
678 $feed_title = db_escape_string($rss->get_title());
680 $feed_title = db_escape_string($rss->channel
["title"]);
683 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
684 _debug("update_rss_feed: registering title: $feed_title");
687 db_query($link, "UPDATE ttrss_feeds SET
688 title = '$feed_title' WHERE id = '$feed'");
691 // weird, weird Magpie
692 if (!$use_simplepie) {
693 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
696 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
697 db_query($link, "UPDATE ttrss_feeds SET
698 site_url = '$site_url' WHERE id = '$feed'");
701 // print "I: " . $rss->channel["image"]["url"];
703 if (!$use_simplepie) {
704 $icon_url = db_escape_string($rss->image
["url"]);
706 $icon_url = db_escape_string($rss->get_image_url());
709 $icon_url = substr($icon_url, 0, 250);
711 if ($icon_url && $orig_icon_url != $icon_url) {
712 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
715 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
716 _debug("update_rss_feed: loading filters...");
719 $filters = load_filters($link, $feed, $owner_uid);
721 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
725 if ($use_simplepie) {
726 $iterator = $rss->get_items();
728 $iterator = $rss->items
;
729 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
730 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
733 if (!is_array($iterator)) {
734 /* db_query($link, "UPDATE ttrss_feeds
735 SET last_error = 'Parse error: can\'t find any articles.'
736 WHERE id = '$feed'"); */
738 // clear any errors and mark feed as updated if fetched okay
739 // even if it's blank
741 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
742 _debug("update_rss_feed: entry iterator is not an array, no articles?");
745 db_query($link, "UPDATE ttrss_feeds
746 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
748 return; // no articles
751 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
752 _debug("update_rss_feed: processing articles...");
755 foreach ($iterator as $item) {
757 if ($_REQUEST['xdebug'] == 2) {
761 if ($use_simplepie) {
762 $entry_guid = $item->get_id();
763 if (!$entry_guid) $entry_guid = $item->get_link();
764 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
768 $entry_guid = $item["id"];
770 if (!$entry_guid) $entry_guid = $item["guid"];
771 if (!$entry_guid) $entry_guid = $item["about"];
772 if (!$entry_guid) $entry_guid = $item["link"];
773 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
776 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
777 _debug("update_rss_feed: guid $entry_guid");
780 if (!$entry_guid) continue;
782 $entry_timestamp = "";
784 if ($use_simplepie) {
785 $entry_timestamp = strtotime($item->get_date());
787 $rss_2_date = $item['pubdate'];
788 $rss_1_date = $item['dc']['date'];
789 $atom_date = $item['issued'];
790 if (!$atom_date) $atom_date = $item['updated'];
792 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
793 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
794 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
798 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
799 $entry_timestamp = time();
800 $no_orig_date = 'true';
802 $no_orig_date = 'false';
805 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
807 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
808 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
811 if ($use_simplepie) {
812 $entry_title = $item->get_title();
814 $entry_title = trim(strip_tags($item["title"]));
817 if ($use_simplepie) {
818 $entry_link = $item->get_link();
820 // strange Magpie workaround
821 $entry_link = $item["link_"];
822 if (!$entry_link) $entry_link = $item["link"];
825 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
826 _debug("update_rss_feed: title $entry_title");
829 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
831 $entry_link = strip_tags($entry_link);
833 if ($use_simplepie) {
834 $entry_content = $item->get_content();
835 if (!$entry_content) $entry_content = $item->get_description();
837 $entry_content = $item["content:escaped"];
839 if (!$entry_content) $entry_content = $item["content:encoded"];
840 if (!$entry_content) $entry_content = $item["content"]["encoded"];
841 if (!$entry_content) $entry_content = $item["content"];
843 // Magpie bugs are getting ridiculous
844 if (trim($entry_content) == "Array") $entry_content = false;
846 if (!$entry_content) $entry_content = $item["atom_content"];
847 if (!$entry_content) $entry_content = $item["summary"];
849 if (!$entry_content ||
850 strlen($entry_content) < strlen($item["description"])) {
851 $entry_content = $item["description"];
855 if (is_array($entry_content)) {
856 $entry_content = $entry_content["encoded"];
857 if (!$entry_content) $entry_content = $entry_content["escaped"];
861 if ($_REQUEST["xdebug"] == 2) {
862 print "update_rss_feed: content: ";
863 print_r(htmlspecialchars($entry_content));
866 $entry_content_unescaped = $entry_content;
868 if ($use_simplepie) {
869 $entry_comments = strip_tags($item->data
["comments"]);
870 if ($item->get_author()) {
871 $entry_author_item = $item->get_author();
872 $entry_author = $entry_author_item->get_name();
873 if (!$entry_author) $entry_author = $entry_author_item->get_email();
875 $entry_author = db_escape_string($entry_author);
878 $entry_comments = strip_tags($item["comments"]);
880 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
882 if ($item['author']) {
884 if (is_array($item['author'])) {
886 if (!$entry_author) {
887 $entry_author = db_escape_string(strip_tags($item['author']['name']));
890 if (!$entry_author) {
891 $entry_author = db_escape_string(strip_tags($item['author']['email']));
895 if (!$entry_author) {
896 $entry_author = db_escape_string(strip_tags($item['author']));
901 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
903 $entry_guid = db_escape_string(strip_tags($entry_guid));
904 $entry_guid = mb_substr($entry_guid, 0, 250);
906 $result = db_query($link, "SELECT id FROM ttrss_entries
907 WHERE guid = '$entry_guid'");
909 $entry_content = db_escape_string($entry_content, false);
911 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
913 $entry_title = db_escape_string($entry_title);
914 $entry_link = db_escape_string($entry_link);
915 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
916 $entry_author = mb_substr($entry_author, 0, 250);
918 if ($use_simplepie) {
919 $num_comments = 0; #FIXME#
921 $num_comments = db_escape_string($item["slash"]["comments"]);
924 if (!$num_comments) $num_comments = 0;
926 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
927 _debug("update_rss_feed: looking for tags [1]...");
930 // parse <category> entries into tags
932 $additional_tags = array();
934 if ($use_simplepie) {
936 $additional_tags_src = $item->get_categories();
938 if (is_array($additional_tags_src)) {
939 foreach ($additional_tags_src as $tobj) {
940 array_push($additional_tags, $tobj->get_term());
944 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
945 _debug("update_rss_feed: category tags:");
946 print_r($additional_tags);
951 $t_ctr = $item['category#'];
954 $additional_tags = array();
955 } else if ($t_ctr > 0) {
956 $additional_tags = array($item['category']);
958 if ($item['category@term']) {
959 array_push($additional_tags, $item['category@term']);
962 for ($i = 0; $i <= $t_ctr; $i++
) {
963 if ($item["category#$i"]) {
964 array_push($additional_tags, $item["category#$i"]);
967 if ($item["category#$i@term"]) {
968 array_push($additional_tags, $item["category#$i@term"]);
973 // parse <dc:subject> elements
975 $t_ctr = $item['dc']['subject#'];
978 array_push($additional_tags, $item['dc']['subject']);
980 for ($i = 0; $i <= $t_ctr; $i++
) {
981 if ($item['dc']["subject#$i"]) {
982 array_push($additional_tags, $item['dc']["subject#$i"]);
988 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
989 _debug("update_rss_feed: looking for tags [2]...");
993 // <a href="..." rel="tag">Xorg</a>, //
997 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
998 $entry_content_unescaped, $entry_tags);
1000 $entry_tags = $entry_tags[1];
1002 $entry_tags = array_merge($entry_tags, $additional_tags);
1003 $entry_tags = array_unique($entry_tags);
1005 for ($i = 0; $i < count($entry_tags); $i++
)
1006 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1008 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1009 _debug("update_rss_feed: unfiltered tags found:");
1010 print_r($entry_tags);
1015 $entry_content = sanitize_article_content($entry_content);
1016 $entry_title = sanitize_article_content($entry_title);
1018 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1019 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1022 db_query($link, "BEGIN");
1024 if (db_num_rows($result) == 0) {
1026 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1027 _debug("update_rss_feed: base guid not found");
1030 // base post entry does not exist, create it
1032 $result = db_query($link,
1033 "INSERT INTO ttrss_entries
1050 '$entry_timestamp_fmt',
1060 // we keep encountering the entry in feeds, so we need to
1061 // update date_updated column so that we don't get horrible
1062 // dupes when the entry gets purged and reinserted again e.g.
1063 // in the case of SLOW SLOW OMG SLOW updating feeds
1065 $base_entry_id = db_fetch_result($result, 0, "id");
1067 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1068 WHERE id = '$base_entry_id'");
1071 // now it should exist, if not - bad luck then
1073 $result = db_query($link, "SELECT
1074 id,content_hash,no_orig_date,title,
1075 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1076 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1080 WHERE guid = '$entry_guid'");
1085 if (db_num_rows($result) == 1) {
1087 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1088 _debug("update_rss_feed: base guid found, checking for user record");
1091 // this will be used below in update handler
1092 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1093 $orig_title = db_fetch_result($result, 0, "title");
1094 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1095 $orig_date_updated = strtotime(db_fetch_result($result,
1096 0, "date_updated"));
1098 $ref_id = db_fetch_result($result, 0, "id");
1099 $entry_ref_id = $ref_id;
1101 // check for user post link to main table
1103 // do we allow duplicate posts with same GUID in different feeds?
1104 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1105 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1107 $dupcheck_qpart = "";
1110 /* Collect article tags here so we could filter by them: */
1112 $article_filters = get_article_filters($filters, $entry_title,
1113 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1116 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1117 _debug("update_rss_feed: article filters: ");
1118 if (count($article_filters) != 0) {
1119 print_r($article_filters);
1123 if (find_article_filter($article_filters, "filter")) {
1124 db_query($link, "COMMIT"); // close transaction in progress
1128 $score = calculate_article_score($article_filters);
1130 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1131 _debug("update_rss_feed: initial score: $score");
1134 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1135 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1138 // if ($_REQUEST["xdebug"]) print "$query\n";
1140 $result = db_query($link, $query);
1142 // okay it doesn't exist - create user entry
1143 if (db_num_rows($result) == 0) {
1145 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1146 _debug("update_rss_feed: user record not found, creating...");
1149 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1151 $last_read_qpart = 'NULL';
1154 $last_read_qpart = 'NOW()';
1157 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1163 if (find_article_filter($article_filters, 'publish')) {
1164 $published = 'true';
1166 $published = 'false';
1169 $result = db_query($link,
1170 "INSERT INTO ttrss_user_entries
1171 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1172 published, score, tag_cache, label_cache)
1173 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1174 $last_read_qpart, $marked, $published, '$score', '', '')");
1176 $result = db_query($link,
1177 "SELECT int_id FROM ttrss_user_entries WHERE
1178 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1179 feed_id = '$feed' LIMIT 1");
1181 if (db_num_rows($result) == 1) {
1182 $entry_int_id = db_fetch_result($result, 0, "int_id");
1185 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1186 _debug("update_rss_feed: user record FOUND");
1189 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1190 $entry_int_id = db_fetch_result($result, 0, "int_id");
1193 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1194 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1197 $post_needs_update = false;
1199 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1200 ($content_hash != $orig_content_hash)) {
1201 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1202 $post_needs_update = true;
1205 if (db_escape_string($orig_title) != $entry_title) {
1206 $post_needs_update = true;
1209 if ($orig_num_comments != $num_comments) {
1210 $post_needs_update = true;
1213 // this doesn't seem to be very reliable
1215 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1216 // $post_needs_update = true;
1219 // if post needs update, update it and mark all user entries
1220 // linking to this post as updated
1221 if ($post_needs_update) {
1223 if (defined('DAEMON_EXTENDED_DEBUG')) {
1224 _debug("update_rss_feed: post $entry_guid needs update...");
1227 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1229 db_query($link, "UPDATE ttrss_entries
1230 SET title = '$entry_title', content = '$entry_content',
1231 content_hash = '$content_hash',
1232 num_comments = '$num_comments'
1233 WHERE id = '$ref_id'");
1235 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1236 db_query($link, "UPDATE ttrss_user_entries
1237 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1239 db_query($link, "UPDATE ttrss_user_entries
1240 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1246 db_query($link, "COMMIT");
1248 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1249 _debug("update_rss_feed: assigning labels...");
1252 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1255 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1256 _debug("update_rss_feed: looking for enclosures...");
1261 $enclosures = array();
1263 if ($use_simplepie) {
1264 $encs = $item->get_enclosures();
1266 if (is_array($encs)) {
1267 foreach ($encs as $e) {
1269 $e->link
, $e->type
, $e->length
);
1271 array_push($enclosures, $e_item);
1278 $e_ctr = $item['enclosure#'];
1281 $e_item = array($item['enclosure@url'],
1282 $item['enclosure@type'],
1283 $item['enclosure@length']);
1285 array_push($enclosures, $e_item);
1287 for ($i = 0; $i <= $e_ctr; $i++
) {
1289 if ($item["enclosure#$i@url"]) {
1290 $e_item = array($item["enclosure#$i@url"],
1291 $item["enclosure#$i@type"],
1292 $item["enclosure#$i@length"]);
1293 array_push($enclosures, $e_item);
1299 // can there be many of those? yes -fox
1301 $m_ctr = $item['media']['content#'];
1304 $e_item = array($item['media']['content@url'],
1305 $item['media']['content@medium'],
1306 $item['media']['content@length']);
1308 array_push($enclosures, $e_item);
1310 for ($i = 0; $i <= $m_ctr; $i++
) {
1312 if ($item["media"]["content#$i@url"]) {
1313 $e_item = array($item["media"]["content#$i@url"],
1314 $item["media"]["content#$i@medium"],
1315 $item["media"]["content#$i@length"]);
1316 array_push($enclosures, $e_item);
1324 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1325 _debug("update_rss_feed: article enclosures:");
1326 print_r($enclosures);
1329 db_query($link, "BEGIN");
1331 foreach ($enclosures as $enc) {
1332 $enc_url = db_escape_string($enc[0]);
1333 $enc_type = db_escape_string($enc[1]);
1334 $enc_dur = db_escape_string($enc[2]);
1336 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1337 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1339 if (db_num_rows($result) == 0) {
1340 db_query($link, "INSERT INTO ttrss_enclosures
1341 (content_url, content_type, title, duration, post_id) VALUES
1342 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1346 db_query($link, "COMMIT");
1348 // check for manual tags (we have to do it here since they're loaded from filters)
1350 foreach ($article_filters as $f) {
1351 if ($f[0] == "tag") {
1353 $manual_tags = trim_array(split(",", $f[1]));
1355 foreach ($manual_tags as $tag) {
1356 if (tag_is_valid($tag)) {
1357 array_push($entry_tags, $tag);
1365 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1366 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1368 $filtered_tags = array();
1369 $tags_to_cache = array();
1371 if ($entry_tags && is_array($entry_tags)) {
1372 foreach ($entry_tags as $tag) {
1373 if (array_search($tag, $boring_tags) === false) {
1374 array_push($filtered_tags, $tag);
1379 $filtered_tags = array_unique($filtered_tags);
1381 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1382 _debug("update_rss_feed: filtered article tags:");
1383 print_r($filtered_tags);
1386 // Save article tags in the database
1388 if (count($filtered_tags) > 0) {
1390 db_query($link, "BEGIN");
1392 foreach ($filtered_tags as $tag) {
1394 $tag = sanitize_tag($tag);
1395 $tag = db_escape_string($tag);
1397 if (!tag_is_valid($tag)) continue;
1399 $result = db_query($link, "SELECT id FROM ttrss_tags
1400 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1401 owner_uid = '$owner_uid' LIMIT 1");
1403 if ($result && db_num_rows($result) == 0) {
1405 db_query($link, "INSERT INTO ttrss_tags
1406 (owner_uid,tag_name,post_int_id)
1407 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1410 array_push($tags_to_cache, $tag);
1413 /* update the cache */
1415 $tags_to_cache = array_unique($tags_to_cache);
1417 $tags_str = db_escape_string(join(",", $tags_to_cache));
1419 db_query($link, "UPDATE ttrss_user_entries
1420 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1421 AND owner_uid = $owner_uid");
1423 db_query($link, "COMMIT");
1426 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1427 _debug("update_rss_feed: article processed");
1431 if (!$last_updated) {
1432 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1433 _debug("update_rss_feed: new feed, catching it up...");
1435 catchup_feed($link, $feed, false, $owner_uid);
1438 purge_feed($link, $feed, 0);
1440 db_query($link, "UPDATE ttrss_feeds
1441 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1443 // db_query($link, "COMMIT");
1447 if ($use_simplepie) {
1448 $error_msg = mb_substr($rss->error(), 0, 250);
1450 $error_msg = mb_substr(magpie_error(), 0, 250);
1453 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1454 _debug("update_rss_feed: error fetching feed: $error_msg");
1457 $error_msg = db_escape_string($error_msg);
1460 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1461 last_updated = NOW() WHERE id = '$feed'");
1464 if ($use_simplepie) {
1468 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1469 _debug("update_rss_feed: done");
1474 function print_select($id, $default, $values, $attributes = "") {
1475 print "<select name=\"$id\" id=\"$id\" $attributes>";
1476 foreach ($values as $v) {
1478 $sel = "selected=\"1\"";
1482 print "<option value=\"$v\" $sel>$v</option>";
1487 function print_select_hash($id, $default, $values, $attributes = "") {
1488 print "<select name=\"$id\" id='$id' $attributes>";
1489 foreach (array_keys($values) as $v) {
1491 $sel = 'selected="selected"';
1495 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1501 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1504 if ($filters["title"]) {
1505 foreach ($filters["title"] as $filter) {
1506 $reg_exp = $filter["reg_exp"];
1507 $inverse = $filter["inverse"];
1508 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1509 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1511 array_push($matches, array($filter["action"], $filter["action_param"]));
1516 if ($filters["content"]) {
1517 foreach ($filters["content"] as $filter) {
1518 $reg_exp = $filter["reg_exp"];
1519 $inverse = $filter["inverse"];
1521 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1522 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1524 array_push($matches, array($filter["action"], $filter["action_param"]));
1529 if ($filters["both"]) {
1530 foreach ($filters["both"] as $filter) {
1531 $reg_exp = $filter["reg_exp"];
1532 $inverse = $filter["inverse"];
1535 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1536 array_push($matches, array($filter["action"], $filter["action_param"]));
1539 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1540 array_push($matches, array($filter["action"], $filter["action_param"]));
1546 if ($filters["link"]) {
1547 $reg_exp = $filter["reg_exp"];
1548 foreach ($filters["link"] as $filter) {
1549 $reg_exp = $filter["reg_exp"];
1550 $inverse = $filter["inverse"];
1552 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1553 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1555 array_push($matches, array($filter["action"], $filter["action_param"]));
1560 if ($filters["date"]) {
1561 $reg_exp = $filter["reg_exp"];
1562 foreach ($filters["date"] as $filter) {
1563 $date_modifier = $filter["filter_param"];
1564 $inverse = $filter["inverse"];
1565 $check_timestamp = strtotime($filter["reg_exp"]);
1567 # no-op when timestamp doesn't parse to prevent misfires
1569 if ($check_timestamp) {
1572 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1573 $date_modifier == "after" && $timestamp > $check_timestamp) {
1577 if ($inverse) $match_ok = !$match_ok;
1580 array_push($matches, array($filter["action"], $filter["action_param"]));
1586 if ($filters["author"]) {
1587 foreach ($filters["author"] as $filter) {
1588 $reg_exp = $filter["reg_exp"];
1589 $inverse = $filter["inverse"];
1590 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1591 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1593 array_push($matches, array($filter["action"], $filter["action_param"]));
1598 if ($filters["tag"]) {
1600 $tag_string = join(",", $tags);
1602 foreach ($filters["tag"] as $filter) {
1603 $reg_exp = $filter["reg_exp"];
1604 $inverse = $filter["inverse"];
1606 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1607 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1609 array_push($matches, array($filter["action"], $filter["action_param"]));
1618 function find_article_filter($filters, $filter_name) {
1619 foreach ($filters as $f) {
1620 if ($f[0] == $filter_name) {
1627 function calculate_article_score($filters) {
1630 foreach ($filters as $f) {
1631 if ($f[0] == "score") {
1638 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1639 foreach ($filters as $f) {
1640 if ($f[0] == "label") {
1641 label_add_article($link, $id, $f[1], $owner_uid);
1646 function getmicrotime() {
1647 list($usec, $sec) = explode(" ",microtime());
1648 return ((float)$usec +
(float)$sec);
1651 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1652 foreach ($values as $v) {
1659 if ($v == $true_is) {
1660 $sel .= " value=\"1\"";
1662 $sel .= " value=\"0\"";
1665 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1666 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1671 function initialize_user_prefs($link, $uid, $profile = false) {
1673 $uid = db_escape_string($uid);
1677 $profile_qpart = "AND profile IS NULL";
1679 $profile_qpart = "AND profile = '$profile'";
1682 if (get_schema_version($link) < 63) $profile_qpart = "";
1684 db_query($link, "BEGIN");
1686 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1688 $u_result = db_query($link, "SELECT pref_name
1689 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1691 $active_prefs = array();
1693 while ($line = db_fetch_assoc($u_result)) {
1694 array_push($active_prefs, $line["pref_name"]);
1697 while ($line = db_fetch_assoc($result)) {
1698 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1699 // print "adding " . $line["pref_name"] . "<br>";
1701 if (get_schema_version($link) < 63) {
1702 db_query($link, "INSERT INTO ttrss_user_prefs
1703 (owner_uid,pref_name,value) VALUES
1704 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1707 db_query($link, "INSERT INTO ttrss_user_prefs
1708 (owner_uid,pref_name,value, profile) VALUES
1709 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1715 db_query($link, "COMMIT");
1719 function lookup_user_id($link, $user) {
1721 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1724 if (db_num_rows($result) == 1) {
1725 return db_fetch_result($result, 0, "id");
1731 function http_authenticate_user($link) {
1733 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1735 if (!$_SERVER["PHP_AUTH_USER"]) {
1737 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1738 header('HTTP/1.0 401 Unauthorized');
1742 $auth_result = authenticate_user($link,
1743 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1745 if (!$auth_result) {
1746 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1747 header('HTTP/1.0 401 Unauthorized');
1755 function authenticate_user($link, $login, $password, $force_auth = false) {
1757 if (!SINGLE_USER_MODE
) {
1759 $pwd_hash1 = encrypt_password($password);
1760 $pwd_hash2 = encrypt_password($password, $login);
1761 $login = db_escape_string($login);
1763 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1764 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1766 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1768 $query = "SELECT id,login,access_level,pwd_hash
1769 FROM ttrss_users WHERE
1773 $query = "SELECT id,login,access_level,pwd_hash
1774 FROM ttrss_users WHERE
1775 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1776 pwd_hash = '$pwd_hash2')";
1779 $result = db_query($link, $query);
1781 if (db_num_rows($result) == 1) {
1782 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1783 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1784 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1786 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1789 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1790 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1792 $_SESSION["last_version_check"] = time();
1794 initialize_user_prefs($link, $_SESSION["uid"]);
1803 $_SESSION["uid"] = 1;
1804 $_SESSION["name"] = "admin";
1806 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1808 initialize_user_prefs($link, $_SESSION["uid"]);
1814 function make_password($length = 8) {
1817 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1821 while ($i < $length) {
1822 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1824 if (!strstr($password, $char)) {
1832 // this is called after user is created to initialize default feeds, labels
1835 // user preferences are checked on every login, not here
1837 function initialize_user($link, $uid) {
1839 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1840 values ('$uid', 'Tiny Tiny RSS: New Releases',
1841 'http://tt-rss.org/releases.rss')");
1843 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1844 values ('$uid', 'Tiny Tiny RSS: Forum',
1845 'http://tt-rss.org/forum/rss.php')");
1848 function logout_user() {
1850 if (isset($_COOKIE[session_name()])) {
1851 setcookie(session_name(), '', time()-42000, '/');
1855 function get_script_urlpath() {
1856 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1859 function validate_session($link) {
1860 if (SINGLE_USER_MODE
) return true;
1862 $check_ip = $_SESSION['ip_address'];
1864 switch (SESSION_CHECK_ADDRESS
) {
1869 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1872 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1873 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1877 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
1878 $_SESSION["login_error_msg"] =
1879 __("Session failed to validate (incorrect IP)");
1883 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
1886 if ($_SESSION["uid"]) {
1888 $result = db_query($link,
1889 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1891 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1893 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1898 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1900 //print_r($_SESSION);
1902 if (time() > $_SESSION["cookie_lifetime"]) {
1910 function login_sequence($link, $mobile = false) {
1911 if (!SINGLE_USER_MODE
) {
1913 $login_action = $_POST["login_action"];
1915 # try to authenticate user if called from login form
1916 if ($login_action == "do_login") {
1917 $login = $_POST["login"];
1918 $password = $_POST["password"];
1919 $remember_me = $_POST["remember_me"];
1921 if (authenticate_user($link, $login, $password)) {
1922 $_POST["password"] = "";
1924 $_SESSION["language"] = $_POST["language"];
1925 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1926 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1928 if ($_POST["profile"]) {
1930 $profile = db_escape_string($_POST["profile"]);
1932 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
1933 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
1935 if (db_num_rows($result) != 0) {
1936 $_SESSION["profile"] = $profile;
1937 $_SESSION["prefs_cache"] = array();
1941 if ($_REQUEST['return']) {
1942 header("Location: " . $_REQUEST['return']);
1944 header("Location: " . $_SERVER["REQUEST_URI"]);
1951 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1955 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1956 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1957 && $_SERVER["REMOTE_USER"] && defined('AUTO_LOGIN') && AUTO_LOGIN
) {
1958 authenticate_user($link,$_SERVER['REMOTE_USER'],null);
1959 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1961 render_login_form($link, $mobile);
1962 //header("Location: login.php");
1966 /* bump login timestamp */
1967 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1970 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1971 setcookie("ttrss_lang", $_SESSION["language"],
1972 time() + SESSION_COOKIE_LIFETIME
);
1977 return authenticate_user($link, "admin", null);
1981 function truncate_string($str, $max_len, $suffix = '…') {
1982 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1983 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
1989 function theme_image($link, $filename) {
1991 $theme_path = get_user_theme_path($link);
1993 if ($theme_path && is_file($theme_path.$filename)) {
1994 return $theme_path.$filename;
2003 function get_user_theme($link) {
2005 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2006 $theme_name = get_pref($link, "_THEME_ID");
2007 if (is_dir("themes/$theme_name")) {
2018 function get_user_theme_path($link) {
2021 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2022 $theme_name = get_pref($link, "_THEME_ID");
2024 if ($theme_name && is_dir("themes/$theme_name")) {
2025 $theme_path = "themes/$theme_name/";
2034 if (is_file("$theme_path/theme.ini")) {
2035 $ini = parse_ini_file("$theme_path/theme.ini", true);
2036 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2044 function get_user_theme_options($link) {
2045 $t = get_user_theme_path($link);
2048 if (is_file("$t/theme.ini")) {
2049 $ini = parse_ini_file("$t/theme.ini", true);
2050 if ($ini['theme']['version']) {
2051 return $ini['theme']['options'];
2058 function print_theme_includes($link) {
2060 $t = get_user_theme_path($link);
2064 print "<link rel=\"stylesheet\" type=\"text/css\"
2065 href=\"$t/theme.css?$time \">";
2066 if (file_exists("$t/theme.js")) {
2067 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2073 function get_all_themes() {
2074 $themes = glob("themes/*");
2080 foreach ($themes as $t) {
2081 if (is_file("$t/theme.ini")) {
2082 $ini = parse_ini_file("$t/theme.ini", true);
2083 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2084 !$ini['theme']['disabled']) {
2086 $entry["path"] = $t;
2087 $entry["base"] = basename($t);
2088 $entry["name"] = $ini['theme']['name'];
2089 $entry["version"] = $ini['theme']['version'];
2090 $entry["author"] = $ini['theme']['author'];
2091 $entry["options"] = $ini['theme']['options'];
2092 array_push($rv, $entry);
2100 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2103 $source_tz = new DateTimeZone($source_tz);
2104 } catch (Exception
$e) {
2105 $source_tz = new DateTimeZone('UTC');
2109 $dest_tz = new DateTimeZone($dest_tz);
2110 } catch (Exception
$e) {
2111 $dest_tz = new DateTimeZone('UTC');
2114 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2115 return $dt->format('U') +
$dest_tz->getOffset($dt);
2118 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2119 $no_smart_dt = false) {
2121 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2122 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2124 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2127 $user_tz = new DateTimeZone($user_tz_string);
2128 } catch (Exception
$e) {
2129 $user_tz = new DateTimeZone('UTC');
2132 # We store date in UTC internally
2133 $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
2134 $user_timestamp = $dt->format('U') +
$user_tz->getOffset($dt);
2136 if (!$no_smart_dt && get_pref($link, 'HEADLINES_SMART_DATE', $owner_uid)) {
2137 return smart_date_time($link, $user_timestamp,
2138 $user_tz->getOffset($dt), $owner_uid);
2141 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2143 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2145 return date($format, $user_timestamp);
2149 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2150 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2152 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2153 return date("G:i", $timestamp);
2154 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2155 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2156 return date($format, $timestamp);
2158 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2159 return date($format, $timestamp);
2163 function smart_date($timestamp) {
2164 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2166 } else if (date("Y", $timestamp) == date("Y")) {
2167 return date("D m", $timestamp);
2169 return date("Y/m/d", $timestamp);
2173 function sql_bool_to_string($s) {
2174 if ($s == "t" ||
$s == "1") {
2181 function sql_bool_to_bool($s) {
2182 if ($s == "t" ||
$s == "1") {
2189 function bool_to_sql_bool($s) {
2197 function toggleEvenOdd($a) {
2204 function get_schema_version($link, $nocache = false) {
2205 if (!$_SESSION["schema_version"] ||
$nocache) {
2206 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2207 $version = db_fetch_result($result, 0, "schema_version");
2208 $_SESSION["schema_version"] = $version;
2211 return $_SESSION["schema_version"];
2215 function sanity_check($link) {
2220 $schema_version = get_schema_version($link);
2222 if ($schema_version != SCHEMA_VERSION
) {
2226 if (DB_TYPE
== "mysql") {
2227 $result = db_query($link, "SELECT true", false);
2228 if (db_num_rows($result) != 1) {
2233 if (db_escape_string("testTEST") != "testTEST") {
2237 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2240 function file_is_locked($filename) {
2241 if (function_exists('flock')) {
2242 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2244 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2245 flock($fp, LOCK_UN
);
2255 return true; // consider the file always locked and skip the test
2258 function make_lockfile($filename) {
2259 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2261 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2262 if (function_exists('posix_getpid')) {
2263 fwrite($fp, posix_getpid() . "\n");
2271 function make_stampfile($filename) {
2272 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2274 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2275 fwrite($fp, time() . "\n");
2276 flock($fp, LOCK_UN
);
2284 function sql_random_function() {
2285 if (DB_TYPE
== "mysql") {
2292 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2294 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2296 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2303 $cat_qpart = "cat_id = '$feed'";
2305 $cat_qpart = "cat_id IS NULL";
2308 $tmp_result = db_query($link, "SELECT id
2309 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2311 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2313 $tmp_feed = $tmp_line["id"];
2315 db_query($link, "UPDATE ttrss_user_entries
2316 SET unread = false,last_read = NOW()
2317 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2319 } else if ($feed == -2) {
2322 db_query($link, "UPDATE ttrss_user_entries
2323 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2324 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2325 AND unread = true AND owner_uid = $owner_uid");
2328 } else if ($feed > 0) {
2330 db_query($link, "UPDATE ttrss_user_entries
2331 SET unread = false,last_read = NOW()
2332 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2334 } else if ($feed < 0 && $feed > -10) { // special, like starred
2337 db_query($link, "UPDATE ttrss_user_entries
2338 SET unread = false,last_read = NOW()
2339 WHERE marked = true AND owner_uid = $owner_uid");
2343 db_query($link, "UPDATE ttrss_user_entries
2344 SET unread = false,last_read = NOW()
2345 WHERE published = true AND owner_uid = $owner_uid");
2350 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2352 if (DB_TYPE
== "pgsql") {
2353 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2355 $match_part = "updated > DATE_SUB(NOW(),
2356 INTERVAL $intl HOUR) ";
2359 $result = db_query($link, "SELECT id FROM ttrss_entries,
2360 ttrss_user_entries WHERE $match_part AND
2362 ttrss_user_entries.ref_id = ttrss_entries.id AND
2363 owner_uid = $owner_uid");
2365 $affected_ids = array();
2367 while ($line = db_fetch_assoc($result)) {
2368 array_push($affected_ids, $line["id"]);
2371 catchupArticlesById($link, $affected_ids, 0);
2375 db_query($link, "UPDATE ttrss_user_entries
2376 SET unread = false,last_read = NOW()
2377 WHERE owner_uid = $owner_uid");
2380 } else if ($feed < -10) { // label
2382 $label_id = -$feed - 11;
2384 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2385 SET unread = false, last_read = NOW()
2386 WHERE label_id = '$label_id' AND unread = true
2387 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2391 ccache_update($link, $feed, $owner_uid, $cat_view);
2394 db_query($link, "BEGIN");
2396 $tag_name = db_escape_string($feed);
2398 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2399 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2401 while ($line = db_fetch_assoc($result)) {
2402 db_query($link, "UPDATE ttrss_user_entries SET
2403 unread = false, last_read = NOW()
2404 WHERE int_id = " . $line["post_int_id"]);
2406 db_query($link, "COMMIT");
2410 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2412 if (!$omode) $omode = "flc";
2414 $data = getGlobalCounters($link);
2416 $data = array_merge($data, getVirtCounters($link));
2418 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2419 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2420 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2421 if (strchr($omode, "c")) {
2422 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2423 $data = array_merge($data, getCategoryCounters($link));
2430 function getCategoryCounters($link) {
2433 /* Labels category */
2435 $cv = array("id" => -2, "kind" => "cat",
2436 "counter" => getCategoryUnread($link, -2));
2438 array_push($ret_arr, $cv);
2440 $age_qpart = getMaxAgeSubquery();
2442 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2443 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2444 WHERE ttrss_cat_counters_cache.feed_id = id AND
2445 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2447 while ($line = db_fetch_assoc($result)) {
2448 $line["cat_id"] = (int) $line["cat_id"];
2450 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2451 "counter" => $line["unread"]);
2453 array_push($ret_arr, $cv);
2456 /* Special case: NULL category doesn't actually exist in the DB */
2458 $cv = array("id" => 0, "kind" => "cat",
2459 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2461 array_push($ret_arr, $cv);
2466 function getCategoryUnread($link, $cat, $owner_uid = false) {
2468 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2473 $cat_query = "cat_id = '$cat'";
2475 $cat_query = "cat_id IS NULL";
2478 $age_qpart = getMaxAgeSubquery();
2480 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2481 AND owner_uid = " . $owner_uid);
2483 $cat_feeds = array();
2484 while ($line = db_fetch_assoc($result)) {
2485 array_push($cat_feeds, "feed_id = " . $line["id"]);
2488 if (count($cat_feeds) == 0) return 0;
2490 $match_part = implode(" OR ", $cat_feeds);
2492 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2493 FROM ttrss_user_entries,ttrss_entries
2494 WHERE unread = true AND ($match_part) AND id = ref_id
2495 AND $age_qpart AND owner_uid = " . $owner_uid);
2499 # this needs to be rewritten
2500 while ($line = db_fetch_assoc($result)) {
2501 $unread +
= $line["unread"];
2505 } else if ($cat == -1) {
2506 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2507 } else if ($cat == -2) {
2509 $result = db_query($link, "
2510 SELECT COUNT(unread) AS unread FROM
2511 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2512 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2513 ttrss_labels2.owner_uid = '$owner_uid'
2514 AND unread = true AND feed_id = ttrss_feeds.id
2515 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2517 $unread = db_fetch_result($result, 0, "unread");
2524 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2525 if (DB_TYPE
== "pgsql") {
2526 return "ttrss_entries.date_updated >
2527 NOW() - INTERVAL '$days days'";
2529 return "ttrss_entries.date_updated >
2530 DATE_SUB(NOW(), INTERVAL $days DAY)";
2534 function getFeedUnread($link, $feed, $is_cat = false) {
2535 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2538 function getLabelUnread($link, $label_id, $owner_uid = false) {
2539 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2541 $result = db_query($link, "
2542 SELECT COUNT(unread) AS unread FROM
2543 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2544 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2545 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2546 AND unread = true AND feed_id = ttrss_feeds.id
2547 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2549 if (db_num_rows($result) != 0) {
2550 return db_fetch_result($result, 0, "unread");
2556 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2557 $owner_uid = false) {
2559 $n_feed = (int) $feed;
2561 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2564 $unread_qpart = "unread = true";
2566 $unread_qpart = "true";
2569 $age_qpart = getMaxAgeSubquery();
2572 return getCategoryUnread($link, $n_feed, $owner_uid);
2573 } if ($feed != "0" && $n_feed == 0) {
2575 $feed = db_escape_string($feed);
2577 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2578 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2579 AND ref_id = id AND $age_qpart
2580 AND $unread_qpart)) AS count FROM ttrss_tags
2581 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2582 return db_fetch_result($result, 0, "count");
2584 } else if ($n_feed == -1) {
2585 $match_part = "marked = true";
2586 } else if ($n_feed == -2) {
2587 $match_part = "published = true";
2588 } else if ($n_feed == -3) {
2589 $match_part = "unread = true AND score >= 0";
2591 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2593 if (DB_TYPE
== "pgsql") {
2594 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2596 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2598 } else if ($n_feed == -4) {
2599 $match_part = "true";
2600 } else if ($n_feed >= 0) {
2603 $match_part = "feed_id = '$n_feed'";
2605 $match_part = "feed_id IS NULL";
2608 } else if ($feed < -10) {
2610 $label_id = -$feed - 11;
2612 return getLabelUnread($link, $label_id, $owner_uid);
2619 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2620 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2622 $from_qpart = "ttrss_user_entries,ttrss_entries";
2626 $query = "SELECT count(int_id) AS unread
2627 FROM $from_qpart WHERE
2628 ttrss_user_entries.ref_id = ttrss_entries.id AND
2631 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2633 $result = db_query($link, $query);
2637 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2638 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2639 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2640 AND $unread_qpart AND $age_qpart AND
2641 ttrss_tags.owner_uid = " . $owner_uid);
2644 $unread = db_fetch_result($result, 0, "unread");
2649 function getGlobalUnread($link, $user_id = false) {
2652 $user_id = $_SESSION["uid"];
2655 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2656 WHERE owner_uid = '$user_id' AND feed_id > 0");
2658 $c_id = db_fetch_result($result, 0, "c_id");
2663 function getGlobalCounters($link, $global_unread = -1) {
2666 if ($global_unread == -1) {
2667 $global_unread = getGlobalUnread($link);
2670 $cv = array("id" => "global-unread",
2671 "counter" => $global_unread);
2673 array_push($ret_arr, $cv);
2675 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2676 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2678 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2680 $cv = array("id" => "subscribed-feeds",
2681 "counter" => $subscribed_feeds);
2683 array_push($ret_arr, $cv);
2688 function getSubscribedFeeds($link) {
2689 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2690 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2692 return db_fetch_result($result, 0, "fn");
2695 function getTagCounters($link) {
2699 $age_qpart = getMaxAgeSubquery();
2701 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2702 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2703 AND ref_id = id AND $age_qpart
2704 AND unread = true)) AS count FROM ttrss_tags
2705 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2706 ORDER BY count DESC LIMIT 55");
2710 while ($line = db_fetch_assoc($result)) {
2711 $tags[$line["tag_name"]] +
= $line["count"];
2714 foreach (array_keys($tags) as $tag) {
2715 $unread = $tags[$tag];
2716 $tag = htmlspecialchars($tag);
2718 $cv = array("id" => $tag,
2720 "counter" => $unread);
2722 array_push($ret_arr, $cv);
2728 function getVirtCounters($link) {
2732 for ($i = 0; $i >= -4; $i--) {
2734 $count = getFeedUnread($link, $i);
2736 $cv = array("id" => $i,
2737 "counter" => $count);
2739 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2740 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2742 array_push($ret_arr, $cv);
2748 function getLabelCounters($link, $descriptions = false) {
2752 $age_qpart = getMaxAgeSubquery();
2754 $owner_uid = $_SESSION["uid"];
2756 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2757 WHERE owner_uid = '$owner_uid'");
2759 while ($line = db_fetch_assoc($result)) {
2761 $id = -$line["id"] - 11;
2763 $label_name = $line["caption"];
2764 $count = getFeedUnread($link, $id);
2766 $cv = array("id" => $id,
2767 "counter" => $count);
2770 $cv["description"] = $label_name;
2772 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2773 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2775 array_push($ret_arr, $cv);
2781 function getFeedCounters($link, $active_feed = false) {
2785 $age_qpart = getMaxAgeSubquery();
2787 $query = "SELECT ttrss_feeds.id,
2789 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2790 last_error, value AS count
2791 FROM ttrss_feeds, ttrss_counters_cache
2792 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2793 AND ttrss_counters_cache.feed_id = id";
2795 $result = db_query($link, $query);
2796 $fctrs_modified = false;
2798 while ($line = db_fetch_assoc($result)) {
2801 $count = $line["count"];
2802 $last_error = htmlspecialchars($line["last_error"]);
2804 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2806 $has_img = feed_has_icon($id);
2808 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2811 $cv = array("id" => $id,
2812 "updated" => $last_updated,
2813 "counter" => $count,
2814 "has_img" => (int) $has_img);
2817 $cv["error"] = $last_error;
2819 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2820 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2822 if ($active_feed && $id == $active_feed)
2823 $cv["title"] = truncate_string($line["title"], 30);
2825 array_push($ret_arr, $cv);
2832 function get_pgsql_version($link) {
2833 $result = db_query($link, "SELECT version() AS version");
2834 $version = split(" ", db_fetch_result($result, 0, "version"));
2839 * Subscribes the user to the given feed
2841 * @param resource $link Database connection
2842 * @param string $url Feed URL to subscribe to
2843 * @param integer $cat_id Category ID the feed shall be added to
2844 * @param string $auth_login (optional) Feed username
2845 * @param string $auth_pass (optional) Feed password
2847 * @return integer Status code:
2848 * 0 - OK, Feed already exists
2849 * 1 - OK, Feed added
2851 * 3 - URL content is HTML, no feeds available
2852 * 4 - URL content is HTML which contains multiple feeds.
2853 * Here you should call extractfeedurls in rpc-backend
2854 * to get all possible feeds.
2855 * 5 - Couldn't download the URL content.
2857 function subscribe_to_feed($link, $url, $cat_id = 0,
2858 $auth_login = '', $auth_pass = '') {
2860 $url = fix_url($url);
2862 if (!$url ||
!validate_feed_url($url)) return 2;
2866 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
2867 WHERE id = ".$_SESSION['uid']);
2869 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2871 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
2872 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
2874 if (url_is_html($url, $auth_login, $auth_pass)) {
2875 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
2876 if (count($feedUrls) == 0) {
2878 } else if (count($feedUrls) > 1) {
2881 //use feed url as new URL
2882 $url = key($feedUrls);
2886 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
2891 if ($cat_id == "0" ||
!$cat_id) {
2892 $cat_qpart = "NULL";
2894 $cat_qpart = "'$cat_id'";
2897 $result = db_query($link,
2898 "SELECT id FROM ttrss_feeds
2899 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2901 if (db_num_rows($result) == 0) {
2902 $result = db_query($link,
2903 "INSERT INTO ttrss_feeds
2904 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2905 VALUES ('".$_SESSION["uid"]."', '$url',
2906 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
2908 $result = db_query($link,
2909 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2910 AND owner_uid = " . $_SESSION["uid"]);
2912 $feed_id = db_fetch_result($result, 0, "id");
2915 update_rss_feed($link, $feed_id, true);
2924 function print_feed_select($link, $id, $default_id = "",
2925 $attributes = "", $include_all_feeds = true) {
2927 print "<select id=\"$id\" name=\"$id\" $attributes>";
2928 if ($include_all_feeds) {
2929 print "<option value=\"0\">".__('All feeds')."</option>";
2932 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2933 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2935 if (db_num_rows($result) > 0 && $include_all_feeds) {
2936 print "<option disabled>--------</option>";
2939 while ($line = db_fetch_assoc($result)) {
2940 if ($line["id"] == $default_id) {
2941 $is_selected = "selected=\"1\"";
2946 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2948 printf("<option $is_selected value='%d'>%s</option>",
2949 $line["id"], $title);
2955 function print_feed_cat_select($link, $id, $default_id = "",
2956 $attributes = "", $include_all_cats = true) {
2958 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
2960 if ($include_all_cats) {
2961 print "<option value=\"0\">".__('Uncategorized')."</option>";
2964 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2965 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2967 if (db_num_rows($result) > 0 && $include_all_cats) {
2968 print "<option disabled=\"1\">--------</option>";
2971 while ($line = db_fetch_assoc($result)) {
2972 if ($line["id"] == $default_id) {
2973 $is_selected = "selected=\"1\"";
2979 printf("<option $is_selected value='%d'>%s</option>",
2980 $line["id"], htmlspecialchars($line["title"]));
2983 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
2988 function checkbox_to_sql_bool($val) {
2989 return ($val == "on") ?
"true" : "false";
2992 function getFeedCatTitle($link, $id) {
2994 return __("Special");
2995 } else if ($id < -10) {
2996 return __("Labels");
2997 } else if ($id > 0) {
2998 $result = db_query($link, "SELECT ttrss_feed_categories.title
2999 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3000 cat_id = ttrss_feed_categories.id");
3001 if (db_num_rows($result) == 1) {
3002 return db_fetch_result($result, 0, "title");
3004 return __("Uncategorized");
3007 return "getFeedCatTitle($id) failed";
3012 function getFeedIcon($id) {
3015 return "images/archive.png";
3018 return "images/mark_set.png";
3021 return "images/pub_set.png";
3024 return "images/fresh.png";
3027 return "images/tag.png";
3031 return "images/label.png";
3033 if (file_exists(ICONS_DIR
. "/$id.ico"))
3034 return ICONS_URL
. "/$id.ico";
3040 function getFeedTitle($link, $id) {
3042 return __("Starred articles");
3043 } else if ($id == -2) {
3044 return __("Published articles");
3045 } else if ($id == -3) {
3046 return __("Fresh articles");
3047 } else if ($id == -4) {
3048 return __("All articles");
3049 } else if ($id === 0 ||
$id === "0") {
3050 return __("Archived articles");
3051 } else if ($id < -10) {
3052 $label_id = -$id - 11;
3053 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3054 if (db_num_rows($result) == 1) {
3055 return db_fetch_result($result, 0, "caption");
3057 return "Unknown label ($label_id)";
3060 } else if ($id > 0) {
3061 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3062 if (db_num_rows($result) == 1) {
3063 return db_fetch_result($result, 0, "title");
3065 return "Unknown feed ($id)";
3072 function get_session_cookie_name() {
3073 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3076 function make_init_params($link) {
3079 $params["theme"] = get_user_theme($link);
3080 $params["theme_options"] = get_user_theme_options($link);
3081 $params["daemon_enabled"] = ENABLE_UPDATE_DAEMON
;
3083 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3084 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3085 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3086 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3088 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3089 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3090 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3091 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3093 $params[strtolower($param)] = (int) get_pref($link, $param);
3096 $params["icons_url"] = ICONS_URL
;
3097 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3098 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3099 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3100 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3101 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3103 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3104 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3106 $max_feed_id = db_fetch_result($result, 0, "mid");
3107 $num_feeds = db_fetch_result($result, 0, "nf");
3109 $params["max_feed_id"] = (int) $max_feed_id;
3110 $params["num_feeds"] = (int) $num_feeds;
3112 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3117 function print_runtime_info($link) {
3118 print "<runtime-info><![CDATA[";
3119 print json_encode(make_runtime_info($link));
3120 print "]]></runtime-info>";
3123 function make_runtime_info($link) {
3126 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3127 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3129 $max_feed_id = db_fetch_result($result, 0, "mid");
3130 $num_feeds = db_fetch_result($result, 0, "nf");
3132 $data["max_feed_id"] = (int) $max_feed_id;
3133 $data["num_feeds"] = (int) $num_feeds;
3135 $data['last_article_id'] = getLastArticleId($link);
3136 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3138 if (ENABLE_UPDATE_DAEMON
) {
3140 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3142 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3144 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3147 $stamp_delta = time() - $stamp;
3149 if ($stamp_delta > 1800) {
3153 $_SESSION["daemon_stamp_check"] = time();
3156 $data['daemon_stamp_ok'] = $stamp_check;
3158 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3160 $data['daemon_stamp'] = $stamp_fmt;
3165 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3166 $new_version_details = @check_for_update
($link);
3168 $data['new_version_available'] = (int) ($new_version_details != false);
3170 $_SESSION["last_version_check"] = time();
3176 function getSearchSql($link, $search, $match_on) {
3178 $search_query_part = "";
3180 $keywords = split(" ", $search);
3181 $query_keywords = array();
3183 foreach ($keywords as $k) {
3184 if (strpos($k, "-") === 0) {
3191 if (strpos($k, "@") === 0) {
3193 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3194 $orig_ts = strtotime(substr($k, 1));
3196 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3198 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3199 } else if ($match_on == "both") {
3200 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3201 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3202 } else if ($match_on == "title") {
3203 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3204 } else if ($match_on == "content") {
3205 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3209 $search_query_part = implode("AND", $query_keywords);
3211 return $search_query_part;
3214 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3216 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3218 $ext_tables_part = "";
3222 if (SPHINX_ENABLED
) {
3223 $ids = join(",", @sphinx_search
($search, 0, 500));
3226 $search_query_part = "ref_id IN ($ids) AND ";
3228 $search_query_part = "ref_id = -1 AND ";
3231 $search_query_part = getSearchSql($link, $search, $match_on);
3232 $search_query_part .= " AND ";
3236 $search_query_part = "";
3239 $view_query_part = "";
3241 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3243 $view_query_part = " ";
3244 } else if ($feed != -1) {
3245 $unread = getFeedUnread($link, $feed, $cat_view);
3247 $view_query_part = " unread = true AND ";
3252 if ($view_mode == "marked") {
3253 $view_query_part = " marked = true AND ";
3256 if ($view_mode == "published") {
3257 $view_query_part = " published = true AND ";
3260 if ($view_mode == "unread") {
3261 $view_query_part = " unread = true AND ";
3264 if ($view_mode == "updated") {
3265 $view_query_part = " (last_read is null and unread = false) AND ";
3269 $limit_query_part = "LIMIT " . $limit;
3272 $vfeed_query_part = "";
3274 // override query strategy and enable feed display when searching globally
3275 if ($search && $search_mode == "all_feeds") {
3276 $query_strategy_part = "ttrss_entries.id > 0";
3277 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3279 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3280 $query_strategy_part = "ttrss_entries.id > 0";
3281 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3282 id = feed_id) as feed_title,";
3283 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3287 $tmp_result = false;
3290 $tmp_result = db_query($link, "SELECT id
3291 FROM ttrss_feeds WHERE cat_id = '$feed'");
3293 $tmp_result = db_query($link, "SELECT id
3294 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3295 WHERE id = '$feed') AND id != '$feed'");
3298 $cat_siblings = array();
3300 if (db_num_rows($tmp_result) > 0) {
3301 while ($p = db_fetch_assoc($tmp_result)) {
3302 array_push($cat_siblings, "feed_id = " . $p["id"]);
3305 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3306 $feed, implode(" OR ", $cat_siblings));
3309 $query_strategy_part = "ttrss_entries.id > 0";
3312 } else if ($feed > 0) {
3317 $query_strategy_part = "cat_id = '$feed'";
3319 $query_strategy_part = "cat_id IS NULL";
3322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3325 $query_strategy_part = "feed_id = '$feed'";
3327 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3328 $query_strategy_part = "feed_id IS NULL";
3329 } else if ($feed == 0 && $cat_view) { // uncategorized
3330 $query_strategy_part = "cat_id IS NULL";
3331 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3332 } else if ($feed == -1) { // starred virtual feed
3333 $query_strategy_part = "marked = true";
3334 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3335 } else if ($feed == -2) { // published virtual feed OR labels category
3338 $query_strategy_part = "published = true";
3339 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3341 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3343 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3345 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3346 ttrss_user_labels2.article_id = ref_id";
3350 } else if ($feed == -3) { // fresh virtual feed
3351 $query_strategy_part = "unread = true AND score >= 0";
3353 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3355 if (DB_TYPE
== "pgsql") {
3356 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3358 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3361 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3362 } else if ($feed == -4) { // all articles virtual feed
3363 $query_strategy_part = "true";
3364 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3365 } else if ($feed <= -10) { // labels
3366 $label_id = -$feed - 11;
3368 $query_strategy_part = "label_id = '$label_id' AND
3369 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3370 ttrss_user_labels2.article_id = ref_id";
3372 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3373 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3376 $query_strategy_part = "id > 0"; // dumb
3379 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3380 $date_sort_field = "updated";
3382 $date_sort_field = "date_entered";
3385 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3386 $order_by = "$date_sort_field";
3388 $order_by = "$date_sort_field DESC";
3391 if ($view_mode != "noscores") {
3392 $order_by = "score DESC, $order_by";
3395 if ($override_order) {
3396 $order_by = $override_order;
3402 $feed_title = "Search results";
3405 $feed_title = getCategoryTitle($link, $feed);
3407 if ((int)$feed == $feed && $feed > 0) {
3408 $result = db_query($link, "SELECT title,site_url,last_error
3409 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3411 $feed_title = db_fetch_result($result, 0, "title");
3412 $feed_site_url = db_fetch_result($result, 0, "site_url");
3413 $last_error = db_fetch_result($result, 0, "last_error");
3415 $feed_title = getFeedTitle($link, $feed);
3420 $content_query_part = "content as content_preview,";
3422 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3425 $feed_kind = "Feeds";
3427 $feed_kind = "Labels";
3430 if ($limit_query_part) {
3431 $offset_query_part = "OFFSET $offset";
3434 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3435 if (!$override_order) {
3436 $order_by = "ttrss_feeds.title, $order_by";
3441 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3442 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3445 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3446 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3449 $query = "SELECT DISTINCT
3452 ttrss_entries.id,ttrss_entries.title,
3455 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3456 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3459 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3465 ttrss_user_entries.ref_id = ttrss_entries.id AND
3466 ttrss_user_entries.owner_uid = '$owner_uid' AND
3469 $query_strategy_part ORDER BY $order_by
3470 $limit_query_part $offset_query_part";
3472 if ($_REQUEST["debug"]) print $query;
3474 $result = db_query($link, $query);
3479 $feed_kind = "Tags";
3481 $result = db_query($link, "SELECT DISTINCT
3485 ttrss_entries.id as id,title,
3487 unread,feed_id,orig_feed_id,
3488 marked,link,last_read,
3489 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3492 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3495 ttrss_entries,ttrss_user_entries,ttrss_tags
3497 ref_id = ttrss_entries.id AND
3498 ttrss_user_entries.owner_uid = '$owner_uid' AND
3499 post_int_id = int_id AND tag_name = '$feed' AND
3502 $query_strategy_part ORDER BY $order_by
3503 $limit_query_part");
3506 return array($result, $feed_title, $feed_site_url, $last_error);
3510 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3511 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3513 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3514 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3515 "margin-bottom : 1em; color : #9a8c59;";
3517 if (!$limit) $limit = 30;
3519 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3520 $date_sort_field = "updated";
3522 $date_sort_field = "date_entered";
3525 $qfh_ret = queryFeedHeadlines($link, $feed,
3526 $limit, $view_mode, $is_cat, $search, $search_mode,
3527 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3529 $result = $qfh_ret[0];
3530 $feed_title = htmlspecialchars($qfh_ret[1]);
3531 $feed_site_url = $qfh_ret[2];
3532 $last_error = $qfh_ret[3];
3534 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3536 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3537 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3538 <rss version=\"2.0\">
3540 <title>$feed_title</title>
3541 <link>$feed_site_url</link>
3542 <description>Feed generated by Tiny Tiny RSS</description>";
3544 while ($line = db_fetch_assoc($result)) {
3546 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3547 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3549 $tags = get_article_tags($link, $line["id"], $owner_uid);
3551 foreach ($tags as $tag) {
3552 print "<category>" . htmlspecialchars($tag) . "</category>";
3555 $rfc822_date = date('r', strtotime($line["updated"]));
3557 print "<pubDate>$rfc822_date</pubDate>";
3559 if ($line["author"]) {
3560 print "<author>" . htmlspecialchars($line["author"]) . "</author>";
3563 print "<title><![CDATA[" .
3564 htmlspecialchars($line["title"]) . "]]></title>";
3566 print "<description><![CDATA[";
3568 if ($line["note"]) {
3569 print "<div style='$note_style'>";
3570 print $line["note"];
3574 print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3575 print "]]></description>";
3577 $enclosures = get_article_enclosures($link, $line["id"]);
3579 foreach ($enclosures as $e) {
3580 $type = htmlspecialchars($e['content_type']);
3581 $url = htmlspecialchars($e['content_url']);
3582 $length = $e['duration'];
3583 print "<enclosure url=\"$url\" type=\"$type\" length=\"$length\"/>";
3589 print "</channel></rss>";
3593 function getCategoryTitle($link, $cat_id) {
3595 if ($cat_id == -1) {
3596 return __("Special");
3597 } else if ($cat_id == -2) {
3598 return __("Labels");
3601 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3604 if (db_num_rows($result) == 1) {
3605 return db_fetch_result($result, 0, "title");
3607 return "Uncategorized";
3612 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3615 if (!$owner) $owner = $_SESSION["uid"];
3617 $res = trim($str); if (!$res) return '';
3619 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) ||
$force_strip_tags) {
3620 $res = $purifier->purify($res);
3623 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3624 $res = preg_replace('/<img[^>]+>/is', '', $res);
3627 if (strpos($res, "href=") === false)
3628 $res = rewrite_urls($res);
3630 $charset_hack = '<head>
3631 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3634 $res = trim($res); if (!$res) return '';
3636 libxml_use_internal_errors(true);
3638 $doc = new DOMDocument();
3639 $doc->loadHTML($charset_hack . $res);
3640 $xpath = new DOMXPath($doc);
3642 $entries = $xpath->query('(//a[@href]|//img[@src])');
3645 foreach ($entries as $entry) {
3649 if ($entry->hasAttribute('href'))
3650 $entry->setAttribute('href',
3651 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3653 if ($entry->hasAttribute('src'))
3654 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3655 $entry->setAttribute('src',
3656 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3659 if (strtolower($entry->nodeName
) == "a") {
3660 $entry->setAttribute("target", "_blank");
3663 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3664 $br = $doc->createElement("br");
3666 if ($entry->parentNode
->nextSibling
) {
3667 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3674 $node = $doc->getElementsByTagName('body')->item(0);
3676 return $doc->saveXML($node);
3680 * Send by mail a digest of last articles.
3682 * @param mixed $link The database connection.
3683 * @param integer $limit The maximum number of articles by digest.
3684 * @return boolean Return false if digests are not enabled.
3686 function send_headlines_digests($link, $limit = 100) {
3688 if (!DIGEST_ENABLE
) return false;
3690 $user_limit = DIGEST_EMAIL_LIMIT
;
3693 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3695 if (DB_TYPE
== "pgsql") {
3696 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3697 } else if (DB_TYPE
== "mysql") {
3698 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3701 $result = db_query($link, "SELECT id,email FROM ttrss_users
3702 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3704 while ($line = db_fetch_assoc($result)) {
3706 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3707 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3709 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3711 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3712 $digest = $tuple[0];
3713 $headlines_count = $tuple[1];
3714 $affected_ids = $tuple[2];
3715 $digest_text = $tuple[3];
3717 if ($headlines_count > 0) {
3719 $mail = new PHPMailer();
3721 $mail->PluginDir
= "lib/phpmailer/";
3722 $mail->SetLanguage("en", "lib/phpmailer/language/");
3724 $mail->CharSet
= "UTF-8";
3726 $mail->From
= DIGEST_FROM_ADDRESS
;
3727 $mail->FromName
= DIGEST_FROM_NAME
;
3728 $mail->AddAddress($line["email"], $line["login"]);
3730 if (DIGEST_SMTP_HOST
) {
3731 $mail->Host
= DIGEST_SMTP_HOST
;
3732 $mail->Mailer
= "smtp";
3733 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3734 $mail->Username
= DIGEST_SMTP_LOGIN
;
3735 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3738 $mail->IsHTML(true);
3739 $mail->Subject
= DIGEST_SUBJECT
;
3740 $mail->Body
= $digest;
3741 $mail->AltBody
= $digest_text;
3743 $rc = $mail->Send();
3745 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3749 if ($rc && $do_catchup) {
3750 print "Marking affected articles as read...\n";
3751 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3754 print "No headlines\n";
3757 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3758 WHERE id = " . $line["id"]);
3762 print "All done.\n";
3766 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3768 require_once "lib/MiniTemplator.class.php";
3770 $tpl = new MiniTemplator
;
3771 $tpl_t = new MiniTemplator
;
3773 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3774 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3776 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3777 $tpl->setVariable('CUR_TIME', date('G:i'));
3779 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3780 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3782 $affected_ids = array();
3784 if (DB_TYPE
== "pgsql") {
3785 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3786 } else if (DB_TYPE
== "mysql") {
3787 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3790 $result = db_query($link, "SELECT ttrss_entries.title,
3791 ttrss_feeds.title AS feed_title,
3793 ttrss_user_entries.ref_id,
3795 SUBSTRING(content, 1, 120) AS excerpt,
3796 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3798 ttrss_user_entries,ttrss_entries,ttrss_feeds
3800 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3801 AND include_in_digest = true
3803 AND ttrss_user_entries.owner_uid = $user_id
3805 ORDER BY ttrss_feeds.title, date_updated DESC
3808 $cur_feed_title = "";
3810 $headlines_count = db_num_rows($result);
3812 $headlines = array();
3814 while ($line = db_fetch_assoc($result)) {
3815 array_push($headlines, $line);
3818 for ($i = 0; $i < sizeof($headlines); $i++
) {
3820 $line = $headlines[$i];
3822 array_push($affected_ids, $line["ref_id"]);
3824 $updated = make_local_datetime($link, $line['last_updated'], false,
3827 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3828 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3829 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3830 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3831 $tpl->setVariable('ARTICLE_EXCERPT',
3832 truncate_string(strip_tags($line["excerpt"]), 100));
3834 $tpl->addBlock('article');
3836 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3837 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3838 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3839 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3840 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3841 // truncate_string(strip_tags($line["excerpt"]), 100));
3843 $tpl_t->addBlock('article');
3845 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3846 $tpl->addBlock('feed');
3847 $tpl_t->addBlock('feed');
3852 $tpl->addBlock('digest');
3853 $tpl->generateOutputToString($tmp);
3855 $tpl_t->addBlock('digest');
3856 $tpl_t->generateOutputToString($tmp_t);
3858 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3861 function check_for_update($link) {
3862 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
3863 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
3865 $version_data = @fetch_file_contents
($version_url);
3867 if ($version_data) {
3868 $version_data = json_decode($version_data, true);
3869 if ($version_data && $version_data['version']) {
3871 if (version_compare(VERSION
, $version_data['version']) == -1) {
3872 return $version_data;
3880 function markArticlesById($link, $ids, $cmode) {
3884 foreach ($ids as $id) {
3885 array_push($tmp_ids, "ref_id = '$id'");
3888 $ids_qpart = join(" OR ", $tmp_ids);
3891 db_query($link, "UPDATE ttrss_user_entries SET
3892 marked = false,last_read = NOW()
3893 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3894 } else if ($cmode == 1) {
3895 db_query($link, "UPDATE ttrss_user_entries SET
3897 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3899 db_query($link, "UPDATE ttrss_user_entries SET
3900 marked = NOT marked,last_read = NOW()
3901 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3905 function publishArticlesById($link, $ids, $cmode) {
3909 foreach ($ids as $id) {
3910 array_push($tmp_ids, "ref_id = '$id'");
3913 $ids_qpart = join(" OR ", $tmp_ids);
3916 db_query($link, "UPDATE ttrss_user_entries SET
3917 published = false,last_read = NOW()
3918 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3919 } else if ($cmode == 1) {
3920 db_query($link, "UPDATE ttrss_user_entries SET
3922 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3924 db_query($link, "UPDATE ttrss_user_entries SET
3925 published = NOT published,last_read = NOW()
3926 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3930 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3932 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3933 if (count($ids) == 0) return;
3937 foreach ($ids as $id) {
3938 array_push($tmp_ids, "ref_id = '$id'");
3941 $ids_qpart = join(" OR ", $tmp_ids);
3944 db_query($link, "UPDATE ttrss_user_entries SET
3945 unread = false,last_read = NOW()
3946 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3947 } else if ($cmode == 1) {
3948 db_query($link, "UPDATE ttrss_user_entries SET
3950 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3952 db_query($link, "UPDATE ttrss_user_entries SET
3953 unread = NOT unread,last_read = NOW()
3954 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3959 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3960 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3962 while ($line = db_fetch_assoc($result)) {
3963 ccache_update($link, $line["feed_id"], $owner_uid);
3967 function catchupArticleById($link, $id, $cmode) {
3970 db_query($link, "UPDATE ttrss_user_entries SET
3971 unread = false,last_read = NOW()
3972 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3973 } else if ($cmode == 1) {
3974 db_query($link, "UPDATE ttrss_user_entries SET
3976 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3978 db_query($link, "UPDATE ttrss_user_entries SET
3979 unread = NOT unread,last_read = NOW()
3980 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3983 $feed_id = getArticleFeed($link, $id);
3984 ccache_update($link, $feed_id, $_SESSION["uid"]);
3987 function make_guid_from_title($title) {
3988 return preg_replace("/[ \"\',.:;]/", "-",
3989 mb_strtolower(strip_tags($title), 'utf-8'));
3992 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
3993 $feed_id, $is_cat, $search, $match_on,
3994 $search_mode, $view_mode, $error) {
3996 $page_prev_link = "viewFeedGoPage(-1)";
3997 $page_next_link = "viewFeedGoPage(1)";
3998 $page_first_link = "viewFeedGoPage(0)";
4000 $catchup_page_link = "catchupPage()";
4001 $catchup_feed_link = "catchupCurrentFeed()";
4002 $catchup_sel_link = "catchupSelection()";
4004 $archive_sel_link = "archiveSelection()";
4005 $delete_sel_link = "deleteSelection()";
4007 $sel_all_link = "selectArticles('all')";
4008 $sel_unread_link = "selectArticles('unread')";
4009 $sel_none_link = "selectArticles('none')";
4010 $sel_inv_link = "selectArticles('invert')";
4012 $tog_unread_link = "selectionToggleUnread()";
4013 $tog_marked_link = "selectionToggleMarked()";
4014 $tog_published_link = "selectionTogglePublished()";
4016 $reply = "<div id=\"subtoolbar_main\">";
4018 $reply .= __('Select:')."
4019 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4020 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4021 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4022 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4026 $reply .= "<select dojoType=\"dijit.form.Select\"
4027 onchange=\"headlineActionsChange(this)\">";
4028 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4030 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4032 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4033 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4034 <option value=\"$tog_published_link\">".__('Published')."</option>";
4036 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4038 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4040 if ($feed_id != "0") {
4041 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4043 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4044 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4048 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4051 $rss_link = htmlspecialchars(get_self_url_prefix() .
4052 "/backend.php?op=rss&id=$feed_id&is_cat=$is_cat&view_mode=$view_mode$search_q");
4054 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4056 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4058 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4060 $reply .= "</select>";
4064 $reply .= "<div id=\"subtoolbar_ftitle\">";
4066 if ($feed_site_url) {
4067 $target = "target=\"_blank\"";
4068 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4069 truncate_string($feed_title,30)."</a>";
4072 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4076 if ($feed_id < -10) {
4077 $label_id = -11-$feed_id;
4079 $result = db_query($link, "SELECT fg_color, bg_color
4080 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4083 if (db_num_rows($result) != 0) {
4084 $fg_color = db_fetch_result($result, 0, "fg_color");
4085 $bg_color = db_fetch_result($result, 0, "bg_color");
4087 $reply .= "<span style='background : $bg_color; color : $fg_color'>";
4088 $reply .= $feed_title;
4089 $reply .= "</span>";
4091 $reply .= $feed_title;
4095 $reply .= $feed_title;
4100 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4105 // Adaptive doesn't really make any sense for generated feeds
4106 // All Articles is the default, so no need to insert it either
4107 if ($view_mode == "adaptive" ||
$view_mode == "all_articles")
4110 $view_mode = "&view-mode=$view_mode";
4114 title=\"".__("View as RSS feed")."\"
4115 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4116 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4123 function outputFeedList($link, $special = true) {
4125 $feedlist = array();
4127 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4129 $feedlist['identifier'] = 'id';
4130 $feedlist['label'] = 'name';
4131 $feedlist['items'] = array();
4133 $owner_uid = $_SESSION["uid"];
4140 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4141 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4143 $cat['items'] = array();
4146 foreach (array(-4, -3, -1, -2, 0) as $i) {
4147 array_push($cat['items'], feedlist_init_feed($link, $i));
4151 array_push($feedlist['items'], $cat);
4153 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4156 $result = db_query($link, "SELECT * FROM
4157 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4159 if (db_num_rows($result) > 0) {
4161 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4162 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4163 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4165 $cat['items'] = array();
4168 while ($line = db_fetch_assoc($result)) {
4170 $label_id = -$line['id'] - 11;
4171 $count = getFeedUnread($link, $label_id);
4173 $feed = feedlist_init_feed($link, $label_id, false, $count);
4175 $feed['fg_color'] = $line['fg_color'];
4176 $feed['bg_color'] = $line['bg_color'];
4178 array_push($cat['items'], $feed);
4182 array_push($feedlist['items'], $cat);
4184 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4189 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4190 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4191 $order_by_qpart = "order_id,category,unread DESC,title";
4193 $order_by_qpart = "order_id,category,title";
4196 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4197 $order_by_qpart = "unread DESC,title";
4199 $order_by_qpart = "title";
4206 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4207 ttrss_feeds.order_id,title";
4209 $order_by_qpart = "title";
4211 $age_qpart = getMaxAgeSubquery();
4213 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4214 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4216 ttrss_feed_categories.title AS category,
4217 ttrss_feed_categories.collapsed,
4219 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4220 ON (ttrss_feed_categories.id = cat_id)
4221 LEFT JOIN ttrss_counters_cache
4223 (ttrss_feeds.id = feed_id)
4225 ttrss_feeds.owner_uid = '$owner_uid'
4226 ORDER BY $order_by_qpart";
4228 $result = db_query($link, $query);
4230 $actid = $_REQUEST["actid"];
4232 if (db_num_rows($result) > 0) {
4237 $cat['items'] = array();
4241 while ($line = db_fetch_assoc($result)) {
4243 $feed = htmlspecialchars(trim($line["title"]));
4245 if (!$feed) $feed = "[Untitled]";
4247 $feed_id = $line["id"];
4248 $unread = $line["unread"];
4250 $cat_id = $line["cat_id"];
4251 $tmp_category = $line["category"];
4252 if (!$tmp_category) $tmp_category = __("Uncategorized");
4254 if ($category != $tmp_category && $enable_cats) {
4256 $category = $tmp_category;
4258 $collapsed = sql_bool_to_bool($line["collapsed"]);
4260 // workaround for NULL category
4261 if ($category == __("Uncategorized")) {
4262 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4265 if ($cat) array_push($feedlist['items'], $cat);
4267 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4270 $updated = make_local_datetime($link, $line["updated_noms"], false);
4272 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4273 $feed, $unread, $line['last_error'], $updated));
4277 array_push($feedlist['items'], $cat);
4279 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4287 function get_article_tags($link, $id, $owner_uid = 0) {
4291 $a_id = db_escape_string($id);
4293 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4295 $query = "SELECT DISTINCT tag_name,
4296 owner_uid as owner FROM
4297 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4298 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4300 $obj_id = md5("TAGS:$owner_uid:$id");
4303 if ($memcache && $obj = $memcache->get($obj_id)) {
4306 /* check cache first */
4308 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4309 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4311 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4314 $tags = explode(",", $tag_cache);
4317 /* do it the hard way */
4319 $tmp_result = db_query($link, $query);
4321 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4322 array_push($tags, $tmp_line["tag_name"]);
4325 /* update the cache */
4327 $tags_str = db_escape_string(join(",", $tags));
4329 db_query($link, "UPDATE ttrss_user_entries
4330 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4331 AND owner_uid = " . $_SESSION["uid"]);
4334 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4340 function trim_value(&$value) {
4341 $value = trim($value);
4344 function trim_array($array) {
4346 array_walk($tmp, 'trim_value');
4350 function tag_is_valid($tag) {
4351 if ($tag == '') return false;
4352 if (preg_match("/^[0-9]*$/", $tag)) return false;
4353 if (mb_strlen($tag) > 250) return false;
4355 if (function_exists('iconv')) {
4356 $tag = iconv("utf-8", "utf-8", $tag);
4359 if (!$tag) return false;
4364 function render_login_form($link, $mobile = 0) {
4367 require_once "login_form.php";
4370 require_once "mobile/login_form.php";
4373 require_once "mobile/classic/login_form.php";
4377 // from http://developer.apple.com/internet/safari/faq.html
4378 function no_cache_incantation() {
4379 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4380 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4381 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4382 header("Cache-Control: post-check=0, pre-check=0", false);
4383 header("Pragma: no-cache"); // HTTP/1.0
4386 function format_warning($msg, $id = "") {
4388 return "<div class=\"warning\" id=\"$id\">
4389 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4392 function format_notice($msg, $id = "") {
4394 return "<div class=\"notice\" id=\"$id\">
4395 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4398 function format_error($msg, $id = "") {
4400 return "<div class=\"error\" id=\"$id\">
4401 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4404 function print_notice($msg) {
4405 return print format_notice($msg);
4408 function print_warning($msg) {
4409 return print format_warning($msg);
4412 function print_error($msg) {
4413 return print format_error($msg);
4417 function T_sprintf() {
4418 $args = func_get_args();
4419 return vsprintf(__(array_shift($args)), $args);
4422 function format_inline_player($link, $url, $ctype) {
4426 if (strpos($ctype, "audio/") === 0) {
4428 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4429 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4430 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4432 $id = 'AUDIO-' . uniqid();
4434 $entry .= "<audio id=\"$id\"\">
4435 <source src=\"$url\"></source>
4438 $entry .= "<span onclick=\"player(this)\"
4439 title=\"".__("Click to play")."\" status=\"0\"
4440 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4444 $entry .= "<object type=\"application/x-shockwave-flash\"
4445 data=\"extras/button/musicplayer.swf?song_url=$url\"
4446 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4447 <param name=\"movie\"
4448 value=\"extras/button/musicplayer.swf?song_url=$url\" />
4453 $filename = substr($url, strrpos($url, "/")+
1);
4455 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4456 $filename . " (" . $ctype . ")" . "</a>";
4461 function format_article($link, $id, $feed_id, $mark_as_read = true,
4462 $zoom_mode = false) {
4468 /* we can figure out feed_id from article id anyway, why do we
4469 * pass feed_id here? let's ignore the argument :( */
4471 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4472 WHERE ref_id = '$id'");
4474 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4476 $rv['feed_id'] = $feed_id;
4478 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4480 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4481 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4483 if (db_num_rows($result) == 1) {
4484 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4485 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4487 $rtl_content = false;
4488 $always_display_enclosures = false;
4492 $rtl_tag = "dir=\"RTL\"";
4499 if ($mark_as_read) {
4500 $result = db_query($link, "UPDATE ttrss_user_entries
4501 SET unread = false,last_read = NOW()
4502 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4504 ccache_update($link, $feed_id, $_SESSION["uid"]);
4507 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4508 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4509 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4510 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4515 FROM ttrss_entries,ttrss_user_entries
4516 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4520 $line = db_fetch_assoc($result);
4522 if ($line["icon_url"]) {
4523 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4525 $feed_icon = " ";
4528 $feed_site_url = $line['site_url'];
4530 $num_comments = $line["num_comments"];
4531 $entry_comments = "";
4533 if ($num_comments > 0) {
4534 if ($line["comments"]) {
4535 $comments_url = $line["comments"];
4537 $comments_url = $line["link"];
4539 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4541 if ($line["comments"] && $line["link"] != $line["comments"]) {
4542 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4547 header("Content-Type: text/html");
4548 $rv['content'] .= "<html><head>
4549 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4550 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4551 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4555 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4556 truncate_string(strip_tags($line['title']), 15) . "</div>";
4558 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4560 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4561 class=\"postHeader\" id=\"POSTHDR-$id\">";
4563 $entry_author = $line["author"];
4565 if ($entry_author) {
4566 $entry_author = __(" - ") . $entry_author;
4569 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4572 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4574 if ($line["link"]) {
4575 $rv['content'] .= "<div clear='both'><a target='_blank'
4576 title=\"".htmlspecialchars($line['title'])."\"
4578 $line["link"] . "\">" .
4579 truncate_string($line["title"], 100) .
4580 "<span class='author'>$entry_author</span></a></div>";
4582 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4585 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4587 if (!$entry_comments) $entry_comments = " "; # placeholder
4589 $rv['content'] .= "<div style='float : right'>
4590 <img src='".theme_image($link, 'images/tag.png')."'
4591 class='tagsPic' alt='Tags' title='Tags'> ";
4594 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4595 <a title=\"".__('Edit tags for this article')."\"
4596 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4598 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4599 class='tagsPic' style=\"cursor : pointer\"
4600 onclick=\"postOpenInNewTab(event, $id)\"
4601 alt='Zoom' title='".__('Open article in new tab')."'>";
4603 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4605 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4606 class='tagsPic' style=\"cursor : pointer\"
4607 onclick=\"editArticleNote($id)\"
4608 alt='PubNote' title='".__('Edit article note')."'>";
4610 if (DIGEST_ENABLE
) {
4611 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4612 class='tagsPic' style=\"cursor : pointer\"
4613 onclick=\"emailArticle($id)\"
4614 alt='Zoom' title='".__('Forward by email')."'>";
4617 if (ENABLE_TWEET_BUTTON
) {
4618 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4619 class='tagsPic' style=\"cursor : pointer\"
4620 onclick=\"tweetArticle($id)\"
4621 alt='Zoom' title='".__('Share on Twitter')."'>";
4624 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4625 class='tagsPic' style=\"cursor : pointer\"
4626 onclick=\"closeArticlePanel($id)\"
4627 alt='Zoom' title='".__('Close this panel')."'>";
4630 $tags_str = strip_tags($tags_str);
4631 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4633 $rv['content'] .= "</div>";
4634 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4636 if ($line["orig_feed_id"]) {
4638 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4639 WHERE id = ".$line["orig_feed_id"]);
4641 if (db_num_rows($tmp_result) != 0) {
4643 $rv['content'] .= "<div clear='both'>";
4644 $rv['content'] .= __("Originally from:");
4646 $rv['content'] .= " ";
4648 $tmp_line = db_fetch_assoc($tmp_result);
4650 $rv['content'] .= "<a target='_blank'
4651 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4652 $tmp_line['title'] . "</a>";
4654 $rv['content'] .= " ";
4656 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4657 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4659 $rv['content'] .= "</div>";
4663 $rv['content'] .= "</div>";
4665 $rv['content'] .= "<div class=\"postIcon\">" .
4666 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4667 href=\"".htmlspecialchars($feed_site_url)."\">".
4668 $feed_icon . "</a></div>";
4670 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4671 if ($line['note']) {
4672 $rv['content'] .= format_article_note($id, $line['note']);
4674 $rv['content'] .= "</div>";
4676 $rv['content'] .= "<div class=\"postContent\">";
4678 $article_content = sanitize_rss($link, $line["content"], false, false,
4681 $rv['content'] .= $article_content;
4683 $rv['content'] .= format_article_enclosures($link, $id,
4684 $always_display_enclosures, $article_content);
4686 $rv['content'] .= "</div>";
4688 $rv['content'] .= "</div>";
4694 <div style=\"text-align : center\">
4695 <button onclick=\"return window.close()\">".
4696 __("Close this window")."</button></div>";
4697 $rv['content'] .= "</body></html>";
4704 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4705 $next_unread_feed, $offset, $vgr_last_feed = false,
4706 $override_order = false) {
4708 $disable_cache = false;
4712 $timing_info = getmicrotime();
4714 $topmost_article_ids = array();
4720 if ($subop == "undefined") $subop = "";
4722 $subop_split = split(":", $subop);
4724 if ($subop == "CatchupSelected") {
4725 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4726 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4728 catchupArticlesById($link, $ids, $cmode);
4731 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4732 update_rss_feed($link, $feed, true);
4735 if ($subop == "MarkAllRead") {
4736 catchup_feed($link, $feed, $cat_view);
4738 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4739 if ($next_unread_feed) {
4740 $feed = $next_unread_feed;
4745 if ($subop_split[0] == "MarkAllReadGR") {
4746 catchup_feed($link, $subop_split[1], false);
4749 // FIXME: might break tag display?
4751 if ($feed > 0 && !$cat_view) {
4752 $result = db_query($link,
4753 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4755 if (db_num_rows($result) == 0) {
4756 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4760 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4762 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4763 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4765 if (db_num_rows($result) == 1) {
4766 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4768 $rtl_content = false;
4772 $rtl_tag = "dir=\"RTL\"";
4778 $rtl_content = false;
4781 /// START /////////////////////////////////////////////////////////////////////////////////
4783 @$search = db_escape_string($_REQUEST["query"]);
4786 $disable_cache = true;
4789 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4790 @$match_on = db_escape_string($_REQUEST["match_on"]);
4796 $real_offset = $offset * $limit;
4798 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4800 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4801 $search, $search_mode, $match_on, $override_order, $real_offset);
4803 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4805 $result = $qfh_ret[0];
4806 $feed_title = $qfh_ret[1];
4807 $feed_site_url = $qfh_ret[2];
4808 $last_error = $qfh_ret[3];
4810 $vgroup_last_feed = $vgr_last_feed;
4812 /// STOP //////////////////////////////////////////////////////////////////////////////////
4816 if (db_num_rows($result) > 0) {
4817 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4818 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
4823 $headlines_count = db_num_rows($result);
4825 if (db_num_rows($result) > 0) {
4827 $lnum = $limit*$offset;
4830 $cur_feed_title = '';
4832 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4834 while ($line = db_fetch_assoc($result)) {
4836 $class = ($lnum %
2) ?
"even" : "odd";
4839 $feed_id = $line["feed_id"];
4841 $labels = get_article_labels($link, $id);
4843 $labels_str = "<span id=\"HLLCTR-$id\">";
4844 $labels_str .= format_article_labels($labels, $id);
4845 $labels_str .= "</span>";
4847 if (count($topmost_article_ids) < 3) {
4848 array_push($topmost_article_ids, $id);
4851 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4853 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4854 theme_image($link, 'images/updated.png')."\"
4857 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4861 if (sql_bool_to_bool($line["unread"]) &&
4862 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4864 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4865 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
4868 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4869 $class .= " Unread";
4876 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4877 $marked_pic = "<img id=\"FMPIC-$id\"
4878 src=\"".theme_image($link, 'images/mark_set.png')."\"
4879 class=\"markedPic\" alt=\"Unstar article\"
4880 onclick='javascript:tMark($id)'>";
4882 $marked_pic = "<img id=\"FMPIC-$id\"
4883 src=\"".theme_image($link, 'images/mark_unset.png')."\"
4884 class=\"markedPic\" alt=\"Star article\"
4885 onclick='javascript:tMark($id)'>";
4888 if ($line["published"] == "t" ||
$line["published"] == "1") {
4889 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4890 'images/pub_set.png')."\"
4892 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4894 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4895 'images/pub_unset.png')."\"
4897 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4900 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4901 # $line["title"] . "</a>";
4903 # $content_link = "<a
4904 # href=\"" . htmlspecialchars($line["link"]) . "\"
4905 # onclick=\"view($id,$feed_id);\">" .
4906 # $line["title"] . "</a>";
4908 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4909 # $line["title"] . "</a>";
4911 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
4913 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4914 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4918 $score = $line["score"];
4920 $score_pic = theme_image($link,
4921 "images/" . get_score_pic($score));
4923 /* $score_title = __("(Click to change)");
4924 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4925 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4927 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
4932 } else if ($score < -100) {
4938 $entry_author = $line["author"];
4940 if ($entry_author) {
4941 $entry_author = " - $entry_author";
4944 $has_feed_icon = feed_has_icon($feed_id);
4946 if ($has_feed_icon) {
4947 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
4949 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
4952 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4954 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4955 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4957 $cur_feed_title = $line["feed_title"];
4958 $vgroup_last_feed = $feed_id;
4960 $cur_feed_title = htmlspecialchars($cur_feed_title);
4962 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
4964 $reply['content'] .= "<div class='cdmFeedTitle'>".
4965 "<div style=\"float : right\">$feed_icon_img</div>".
4966 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
4967 $line["feed_title"]."</a> $vf_catchup_link</div>";
4972 $mouseover_attrs = "onmouseover='postMouseIn($id)'
4973 onmouseout='postMouseOut($id)'";
4975 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
4977 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
4979 $reply['content'] .= "<div class='hlLeft'>";
4981 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
4984 $reply['content'] .= "$marked_pic";
4985 $reply['content'] .= "$published_pic";
4987 $reply['content'] .= "</div>";
4989 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
4990 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
4991 $reply['content'] .= "<a id=\"RTITLE-$id\"
4992 href=\"" . htmlspecialchars($line["link"]) . "\"
4993 onclick=\"return false;\">" .
4996 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4997 if ($content_preview) {
4998 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5002 $reply['content'] .= "</a></span>";
5004 $reply['content'] .= $labels_str;
5006 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5007 if (@$line["feed_title"]) {
5008 print "<span class=\"hlFeed\">
5009 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5010 $line["feed_title"]."</a>)
5015 $reply['content'] .= "</div>";
5017 $reply['content'] .= "<div class=\"hlRight\">";
5018 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5019 $reply['content'] .= $score_pic;
5021 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5023 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5024 title=\"".htmlspecialchars($line['feed_title'])."\">
5025 $feed_icon_img<span>";
5028 $reply['content'] .= "</div>";
5029 $reply['content'] .= "</div>";
5033 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5034 if ($feed_id != $vgroup_last_feed) {
5036 $cur_feed_title = $line["feed_title"];
5037 $vgroup_last_feed = $feed_id;
5039 $cur_feed_title = htmlspecialchars($cur_feed_title);
5041 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5043 $has_feed_icon = feed_has_icon($feed_id);
5045 if ($has_feed_icon) {
5046 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5048 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5051 $reply['content'] .= "<div class='cdmFeedTitle'>".
5052 "<div style=\"float : right\">$feed_icon_img</div>".
5053 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5054 $line["feed_title"]."</a> $vf_catchup_link</div>";
5058 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5060 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5061 onmouseout='postMouseOut($id)'";
5063 $reply['content'] .= "<div class=\"$class\"
5064 id=\"RROW-$id\" $mouseover_attrs'>";
5066 $reply['content'] .= "<div class=\"cdmHeader\">";
5068 $reply['content'] .= "<div style='float : right'>";
5069 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5070 $reply['content'] .= "$score_pic";
5072 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5073 $reply['content'] .= "<span style=\"cursor : pointer\"
5074 title=\"".htmlspecialchars($line["feed_title"])."\"
5075 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5077 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5079 $reply['content'] .= "</div>";
5081 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5082 'RROW-$id')\" id=\"RCHK-$id\"/>";
5084 $reply['content'] .= "$marked_pic";
5085 $reply['content'] .= "$published_pic";
5087 $reply['content'] .= "<span id=\"RTITLE-$id\"
5088 onclick=\"return cdmClicked(event, $id);\"
5089 class=\"titleWrap$hlc_suffix\">
5091 title=\"".htmlspecialchars($line['title'])."\"
5092 target=\"_blank\" href=\"".
5093 htmlspecialchars($line["link"])."\">".
5094 truncate_string($line["title"], 100) .
5095 " $entry_author</a>";
5097 $reply['content'] .= $labels_str;
5100 $content_hidden = "style=\"display : none\"";
5102 $excerpt_hidden = "style=\"display : none\"";
5104 $reply['content'] .= "<span $excerpt_hidden
5105 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5107 $reply['content'] .= "</span>";
5109 $reply['content'] .= "</div>";
5111 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5112 onclick=\"return cdmClicked(event, $id);\"
5115 $reply['content'] .= "<div class=\"cdmContentInner\">";
5117 if ($line["orig_feed_id"]) {
5119 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5120 WHERE id = ".$line["orig_feed_id"]);
5122 if (db_num_rows($tmp_result) != 0) {
5124 $reply['content'] .= "<div clear='both'>";
5125 $reply['content'] .= __("Originally from:");
5127 $reply['content'] .= " ";
5129 $tmp_line = db_fetch_assoc($tmp_result);
5131 $reply['content'] .= "<a target='_blank'
5132 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5133 $tmp_line['title'] . "</a>";
5135 $reply['content'] .= " ";
5137 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5138 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5140 $reply['content'] .= "</div>";
5144 // FIXME: make this less of a hack
5146 $feed_site_url = false;
5148 if ($line["feed_id"]) {
5149 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5150 WHERE id = " . $line["feed_id"]);
5152 if (db_num_rows($tmp_result) == 1) {
5153 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5158 $article_content = sanitize_rss($link, $line["content_preview"],
5159 false, false, $feed_site_url);
5161 if (!$article_content) $article_content = " ";
5163 $article_content = '';
5166 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5167 if ($line['note']) {
5168 $reply['content'] .= format_article_note($id, $line['note']);
5170 $reply['content'] .= "</div>";
5172 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5174 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5175 ttrss_feeds WHERE id = ".
5176 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5177 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5179 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5180 0, "always_display_enclosures"));
5182 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5185 $reply['content'] .= "</div>";
5187 $reply['content'] .= "<div class=\"cdmFooter\">";
5189 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5191 $reply['content'] .= "<img src='".theme_image($link,
5192 'images/tag.png')."' alt='Tags' title='Tags'>
5193 <span id=\"ATSTR-$id\">$tags_str</span>
5194 <a title=\"".__('Edit tags for this article')."\"
5195 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5197 $reply['content'] .= "<div style=\"float : right\">";
5199 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5200 onclick=\"zoomToArticle(event, $id)\"
5201 style=\"cursor : pointer\"
5203 title='".__('Open article in new tab')."'>";
5205 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5207 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5208 style=\"cursor : pointer\" style=\"cursor : pointer\"
5209 onclick=\"editArticleNote($id)\"
5210 alt='PubNote' title='".__('Edit article note')."'>";
5212 if (DIGEST_ENABLE
) {
5213 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5214 style=\"cursor : pointer\"
5215 onclick=\"emailArticle($id)\"
5216 alt='Zoom' title='".__('Forward by email')."'>";
5219 if (ENABLE_TWEET_BUTTON
) {
5220 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5221 class='tagsPic' style=\"cursor : pointer\"
5222 onclick=\"tweetArticle($id)\"
5223 alt='Zoom' title='".__('Share on Twitter')."'>";
5226 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5227 style=\"cursor : pointer\" style=\"cursor : pointer\"
5228 onclick=\"dismissArticle($id)\"
5229 alt='Dismiss' title='".__('Dismiss article')."'>";
5231 $reply['content'] .= "</div>";
5232 $reply['content'] .= "</div>";
5234 $reply['content'] .= "</div>";
5236 $reply['content'] .= "</div>";
5246 switch ($view_mode) {
5248 $message = __("No unread articles found to display.");
5251 $message = __("No updated articles found to display.");
5254 $message = __("No starred articles found to display.");
5258 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5260 $message = __("No articles found to display.");
5264 if (!$offset && $message) {
5265 $reply['content'] .= "<div class='whiteBox'>$message";
5267 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5269 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5270 WHERE owner_uid = " . $_SESSION['uid']);
5272 $last_updated = db_fetch_result($result, 0, "last_updated");
5273 $last_updated = make_local_datetime($link, $last_updated, false);
5275 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5277 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5278 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5280 $num_errors = db_fetch_result($result, 0, "num_errors");
5282 if ($num_errors > 0) {
5283 $reply['content'] .= "<br/>";
5284 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5285 __('Some feeds have update errors (click for details)')."</a>";
5287 $reply['content'] .= "</span></p></div>";
5292 # if ($headlines_count > 0) print "</div>";
5296 #print "]]></content>";
5298 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5299 $vgroup_last_feed, $reply['content'], $reply['toolbar']);
5302 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5304 function printTagCloud($link) {
5306 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5307 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5308 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5310 $result = db_query($link, $query);
5314 while ($line = db_fetch_assoc($result)) {
5315 $tags[$line["tag_name"]] = $line["count"];
5320 $max_size = 32; // max font size in pixels
5321 $min_size = 11; // min font size in pixels
5323 // largest and smallest array values
5324 $max_qty = max(array_values($tags));
5325 $min_qty = min(array_values($tags));
5327 // find the range of values
5328 $spread = $max_qty - $min_qty;
5329 if ($spread == 0) { // we don't want to divide by zero
5333 // set the font-size increment
5334 $step = ($max_size - $min_size) / ($spread);
5336 // loop through the tag array
5337 foreach ($tags as $key => $value) {
5338 // calculate font-size
5339 // find the $value in excess of $min_qty
5340 // multiply by the font-size increment ($size)
5341 // and add the $min_size set above
5342 $size = round($min_size +
(($value - $min_qty) * $step));
5344 $key_escaped = str_replace("'", "\\'", $key);
5346 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5347 $size . "px\" title=\"$value articles tagged with " .
5348 $key . '">' . $key . '</a> ';
5352 function print_checkpoint($n, $s) {
5353 $ts = getmicrotime();
5354 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5358 function sanitize_tag($tag) {
5361 $tag = mb_strtolower($tag, 'utf-8');
5363 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5365 // $tag = str_replace('"', "", $tag);
5366 // $tag = str_replace("+", " ", $tag);
5367 $tag = str_replace("technorati tag: ", "", $tag);
5372 function get_self_url_prefix() {
5376 if ($_SERVER['HTTPS'] != "on") {
5377 $url_path = "http://";
5379 $url_path = "https://";
5382 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5387 function opml_publish_url($link){
5389 $url_path = get_self_url_prefix();
5390 $url_path .= "/opml.php?op=publish&key=" .
5391 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5397 * Purge a feed contents, marked articles excepted.
5399 * @param mixed $link The database connection.
5400 * @param integer $id The id of the feed to purge.
5403 function clear_feed_articles($link, $id) {
5406 $result = db_query($link, "DELETE FROM ttrss_user_entries
5407 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5409 $result = db_query($link, "DELETE FROM ttrss_user_entries
5410 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5413 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5414 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5416 ccache_update($link, $id, $_SESSION['uid']);
5417 } // function clear_feed_articles
5420 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5422 * @return string The Mozilla Firefox feed adding URL.
5424 function add_feed_url() {
5425 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5426 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5428 } // function add_feed_url
5431 * Encrypt a password in SHA1.
5433 * @param string $pass The password to encrypt.
5434 * @param string $login A optionnal login.
5435 * @return string The encrypted password.
5437 function encrypt_password($pass, $login = '') {
5439 return "SHA1X:" . sha1("$login:$pass");
5441 return "SHA1:" . sha1($pass);
5443 } // function encrypt_password
5446 * Update a feed batch.
5447 * Used by daemons to update n feeds by run.
5448 * Only update feed needing a update, and not being processed
5449 * by another process.
5451 * @param mixed $link Database link
5452 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5453 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5454 * @param boolean $debug Set to false to disable debug output. Default to true.
5457 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5458 // Process all other feeds using last_updated and interval parameters
5460 // Test if the user has loggued in recently. If not, it does not update its feeds.
5461 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5462 if (DB_TYPE
== "pgsql") {
5463 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5465 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5468 $login_thresh_qpart = "";
5471 // Test if the feed need a update (update interval exceded).
5472 if (DB_TYPE
== "pgsql") {
5473 $update_limit_qpart = "AND ((
5474 ttrss_feeds.update_interval = 0
5475 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5477 ttrss_feeds.update_interval > 0
5478 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5479 ) OR ttrss_feeds.last_updated IS NULL)";
5481 $update_limit_qpart = "AND ((
5482 ttrss_feeds.update_interval = 0
5483 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5485 ttrss_feeds.update_interval > 0
5486 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5487 ) OR ttrss_feeds.last_updated IS NULL)";
5490 // Test if feed is currently being updated by another process.
5491 if (DB_TYPE
== "pgsql") {
5492 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5494 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5497 // Test if there is a limit to number of updated feeds
5499 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5501 $random_qpart = sql_random_function();
5503 // We search for feed needing update.
5504 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5505 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5506 ttrss_feeds.update_interval
5508 ttrss_feeds, ttrss_users, ttrss_user_prefs
5510 ttrss_feeds.owner_uid = ttrss_users.id
5511 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5512 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5513 $login_thresh_qpart $update_limit_qpart
5514 $updstart_thresh_qpart
5515 ORDER BY $random_qpart $query_limit");
5517 $user_prefs_cache = array();
5519 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5521 // Here is a little cache magic in order to minimize risk of double feed updates.
5522 $feeds_to_update = array();
5523 while ($line = db_fetch_assoc($result)) {
5524 $feeds_to_update[$line['id']] = $line;
5527 // We update the feed last update started date before anything else.
5528 // There is no lag due to feed contents downloads
5529 // It prevent an other process to update the same feed.
5530 $feed_ids = array_keys($feeds_to_update);
5532 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5533 WHERE id IN (%s)", implode(',', $feed_ids)));
5536 // For each feed, we call the feed update function.
5537 while ($line = array_pop($feeds_to_update)) {
5539 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5541 update_rss_feed($link, $line["id"], true);
5543 sleep(1); // prevent flood (FIXME make this an option?)
5546 // Send feed digests by email if needed.
5547 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5549 } // function update_daemon_common
5551 function sanitize_article_content($text) {
5552 # we don't support CDATA sections in articles, they break our own escaping
5553 $text = preg_replace("/\[\[CDATA/", "", $text);
5554 $text = preg_replace("/\]\]\>/", "", $text);
5558 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5563 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5565 if ($memcache && $obj = $memcache->get($obj_id)) {
5571 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5573 $result = db_query($link, "SELECT reg_exp,
5574 ttrss_filter_types.name AS name,
5575 ttrss_filter_actions.name AS action,
5579 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5582 owner_uid = $owner_uid AND
5583 ttrss_filter_types.id = filter_type AND
5584 ttrss_filter_actions.id = action_id AND
5585 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5587 while ($line = db_fetch_assoc($result)) {
5588 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5589 $filter["reg_exp"] = $line["reg_exp"];
5590 $filter["action"] = $line["action"];
5591 $filter["action_param"] = $line["action_param"];
5592 $filter["filter_param"] = $line["filter_param"];
5593 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5595 array_push($filters[$line["name"]], $filter);
5598 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5604 function get_score_pic($score) {
5606 return "score_high.png";
5607 } else if ($score > 0) {
5608 return "score_half_high.png";
5609 } else if ($score < -100) {
5610 return "score_low.png";
5611 } else if ($score < 0) {
5612 return "score_half_low.png";
5614 return "score_neutral.png";
5618 function rounded_table_start($classname, $header = " ") {
5619 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5620 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5621 print "<tr><td class='left'> </td><td class='content'>";
5624 function rounded_table_end($footer = " ") {
5625 print "</td><td class='right'> </td></tr>";
5626 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5630 function feed_has_icon($id) {
5631 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5634 function init_connection($link) {
5635 if (DB_TYPE
== "pgsql") {
5636 pg_query($link, "set client_encoding = 'UTF-8'");
5637 pg_set_client_encoding("UNICODE");
5638 pg_query($link, "set datestyle = 'ISO, european'");
5639 pg_query($link, "set TIME ZONE 0");
5641 db_query($link, "SET time_zone = '+0:0'");
5643 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5644 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5645 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5650 function update_feedbrowser_cache($link) {
5652 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5653 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5654 WHERE tf.feed_url = ttrss_feeds.feed_url
5655 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5656 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5658 db_query($link, "BEGIN");
5660 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5664 while ($line = db_fetch_assoc($result)) {
5665 $subscribers = db_escape_string($line["subscribers"]);
5666 $feed_url = db_escape_string($line["feed_url"]);
5667 $title = db_escape_string($line["title"]);
5669 $tmp_result = db_query($link, "SELECT subscribers FROM
5670 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5672 if (db_num_rows($tmp_result) == 0) {
5674 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5675 (feed_url, title, subscribers) VALUES ('$feed_url',
5676 '$title', '$subscribers')");
5684 db_query($link, "COMMIT");
5690 function ccache_zero($link, $feed_id, $owner_uid) {
5691 db_query($link, "UPDATE ttrss_counters_cache SET
5692 value = 0, updated = NOW() WHERE
5693 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5696 function ccache_zero_all($link, $owner_uid) {
5697 db_query($link, "UPDATE ttrss_counters_cache SET
5698 value = 0 WHERE owner_uid = '$owner_uid'");
5700 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5701 value = 0 WHERE owner_uid = '$owner_uid'");
5704 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5707 $table = "ttrss_counters_cache";
5709 $table = "ttrss_cat_counters_cache";
5712 db_query($link, "DELETE FROM $table WHERE
5713 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5717 function ccache_update_all($link, $owner_uid) {
5719 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5721 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5722 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5724 while ($line = db_fetch_assoc($result)) {
5725 ccache_update($link, $line["feed_id"], $owner_uid, true);
5728 /* We have to manually include category 0 */
5730 ccache_update($link, 0, $owner_uid, true);
5733 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5734 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5736 while ($line = db_fetch_assoc($result)) {
5737 print ccache_update($link, $line["feed_id"], $owner_uid);
5744 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5745 $no_update = false) {
5747 if (!is_numeric($feed_id)) return;
5750 $table = "ttrss_counters_cache";
5752 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5753 WHERE id = '$feed_id'");
5754 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5757 $table = "ttrss_cat_counters_cache";
5760 if (DB_TYPE
== "pgsql") {
5761 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5762 } else if (DB_TYPE
== "mysql") {
5763 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5766 $result = db_query($link, "SELECT value FROM $table
5767 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5770 if (db_num_rows($result) == 1) {
5771 return db_fetch_result($result, 0, "value");
5776 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5782 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5783 $update_pcat = true) {
5785 if (!is_numeric($feed_id)) return;
5787 if (!$is_cat && $feed_id > 0) {
5788 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5789 WHERE id = '$feed_id'");
5790 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5793 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5795 /* When updating a label, all we need to do is recalculate feed counters
5796 * because labels are not cached */
5799 ccache_update_all($link, $owner_uid);
5804 $table = "ttrss_counters_cache";
5806 $table = "ttrss_cat_counters_cache";
5809 if ($is_cat && $feed_id >= 0) {
5810 if ($feed_id != 0) {
5811 $cat_qpart = "cat_id = '$feed_id'";
5813 $cat_qpart = "cat_id IS NULL";
5816 /* Recalculate counters for child feeds */
5818 $result = db_query($link, "SELECT id FROM ttrss_feeds
5819 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5821 while ($line = db_fetch_assoc($result)) {
5822 ccache_update($link, $line["id"], $owner_uid, false, false);
5825 $result = db_query($link, "SELECT SUM(value) AS sv
5826 FROM ttrss_counters_cache, ttrss_feeds
5827 WHERE id = feed_id AND $cat_qpart AND
5828 ttrss_feeds.owner_uid = '$owner_uid'");
5830 $unread = (int) db_fetch_result($result, 0, "sv");
5833 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5836 db_query($link, "BEGIN");
5838 $result = db_query($link, "SELECT feed_id FROM $table
5839 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5841 if (db_num_rows($result) == 1) {
5842 db_query($link, "UPDATE $table SET
5843 value = '$unread', updated = NOW() WHERE
5844 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5847 db_query($link, "INSERT INTO $table
5848 (feed_id, value, owner_uid, updated)
5850 ($feed_id, $unread, $owner_uid, NOW())");
5853 db_query($link, "COMMIT");
5855 if ($feed_id > 0 && $prev_unread != $unread) {
5859 /* Update parent category */
5863 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5864 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5866 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5868 ccache_update($link, $cat_id, $owner_uid, true);
5872 } else if ($feed_id < 0) {
5873 ccache_update_all($link, $owner_uid);
5879 function label_find_id($link, $label, $owner_uid) {
5880 $result = db_query($link,
5881 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5882 AND owner_uid = '$owner_uid' LIMIT 1");
5884 if (db_num_rows($result) == 1) {
5885 return db_fetch_result($result, 0, "id");
5891 function get_article_labels($link, $id) {
5894 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
5898 if ($memcache && $obj = $memcache->get($obj_id)) {
5902 $result = db_query($link, "SELECT label_cache FROM
5903 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
5906 $label_cache = db_fetch_result($result, 0, "label_cache");
5910 $label_cache = json_decode($label_cache, true);
5912 if ($label_cache["no-labels"] == 1)
5915 return $label_cache;
5918 $result = db_query($link,
5919 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5920 FROM ttrss_labels2, ttrss_user_labels2
5922 AND article_id = '$id'
5923 AND owner_uid = ".$_SESSION["uid"] . "
5926 while ($line = db_fetch_assoc($result)) {
5927 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5929 array_push($rv, $rk);
5931 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
5934 label_update_cache($link, $id, $rv);
5936 label_update_cache($link, $id, array("no-labels" => 1));
5943 function label_find_caption($link, $label, $owner_uid) {
5944 $result = db_query($link,
5945 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5946 AND owner_uid = '$owner_uid' LIMIT 1");
5948 if (db_num_rows($result) == 1) {
5949 return db_fetch_result($result, 0, "caption");
5955 function label_update_cache($link, $id, $labels = false, $force = false) {
5958 label_clear_cache($link, $id);
5961 $labels = get_article_labels($link, $id);
5963 $labels = db_escape_string(json_encode($labels));
5965 db_query($link, "UPDATE ttrss_user_entries SET
5966 label_cache = '$labels' WHERE ref_id = '$id'");
5970 function label_clear_cache($link, $id) {
5972 db_query($link, "UPDATE ttrss_user_entries SET
5973 label_cache = '' WHERE ref_id = '$id'");
5977 function label_remove_article($link, $id, $label, $owner_uid) {
5979 $label_id = label_find_id($link, $label, $owner_uid);
5981 if (!$label_id) return;
5983 $result = db_query($link,
5984 "DELETE FROM ttrss_user_labels2
5986 label_id = '$label_id' AND
5987 article_id = '$id'");
5989 label_clear_cache($link, $id);
5992 function label_add_article($link, $id, $label, $owner_uid) {
5997 $obj_id = md5("LABELS:$id:$owner_uid");
5998 $memcache->delete($obj_id);
6001 $label_id = label_find_id($link, $label, $owner_uid);
6003 if (!$label_id) return;
6005 $result = db_query($link,
6007 article_id FROM ttrss_labels2, ttrss_user_labels2
6010 label_id = '$label_id' AND
6011 article_id = '$id' AND owner_uid = '$owner_uid'
6014 if (db_num_rows($result) == 0) {
6015 db_query($link, "INSERT INTO ttrss_user_labels2
6016 (label_id, article_id) VALUES ('$label_id', '$id')");
6019 label_clear_cache($link, $id);
6023 function label_remove($link, $id, $owner_uid) {
6026 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6029 $obj_id = md5("LABELS:$id:$owner_uid");
6030 $memcache->delete($obj_id);
6033 db_query($link, "BEGIN");
6035 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6038 $caption = db_fetch_result($result, 0, "caption");
6040 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6041 AND owner_uid = " . $owner_uid);
6043 if (db_affected_rows($link, $result) != 0 && $caption) {
6045 /* Remove access key for the label */
6047 $ext_id = -11 - $id;
6049 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6050 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6052 /* Disable filters that reference label being removed */
6054 db_query($link, "UPDATE ttrss_filters SET
6055 enabled = false WHERE action_param = '$caption'
6057 AND owner_uid = " . $owner_uid);
6059 /* Remove cached data */
6061 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6062 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6066 db_query($link, "COMMIT");
6069 function label_create($link, $caption) {
6071 db_query($link, "BEGIN");
6075 $result = db_query($link, "SELECT id FROM ttrss_labels2
6076 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6078 if (db_num_rows($result) == 0) {
6079 $result = db_query($link,
6080 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6081 VALUES ('$caption', '".$_SESSION["uid"]."')");
6083 $result = db_affected_rows($link, $result) != 0;
6086 db_query($link, "COMMIT");
6091 function print_labels_headlines_dropdown($link, $feed_id) {
6092 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6094 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6095 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6097 while ($line = db_fetch_assoc($result)) {
6099 $label_id = $line["id"];
6100 $label_caption = $line["caption"];
6103 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6104 print "<option id=\"LHDL-$id\"
6105 value=\"selectionRemoveLabel($label_id)\">".
6106 __('Remove:') . " $label_caption</option>";
6108 print "<option id=\"LHDL-$id\"
6109 value=\"selectionAssignLabel($label_id)\">".
6110 __('Assign:') . " $label_caption</option>";
6115 function format_tags_string($tags, $id) {
6118 $tags_nolinks_str = "";
6122 /* if (get_user_theme($link) == "3pane") {
6130 $formatted_tags = array();
6132 foreach ($tags as $tag) {
6134 $tag_escaped = str_replace("'", "\\'", $tag);
6136 if (mb_strlen($tag) > 30) {
6137 $tag = truncate_string($tag, 30);
6140 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6142 array_push($formatted_tags, $tag_str);
6144 $tmp_tags_str = implode(", ", $formatted_tags);
6146 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6151 $tags_str = implode(", ", $formatted_tags);
6153 if ($num_tags < count($tags)) {
6154 $tags_str .= ", …";
6157 if ($num_tags == 0) {
6158 $tags_str = __("no tags");
6165 function format_article_labels($labels, $id) {
6169 foreach ($labels as $l) {
6170 $labels_str .= sprintf("<span class='hlLabelRef'
6171 style='color : %s; background-color : %s'>%s</span>",
6172 $l[2], $l[3], $l[1]);
6179 function format_article_note($id, $note) {
6181 $str = "<div class='articleNote' title=\"".__('edit note')."\"
6182 onclick=\"editArticleNote($id)\">$note</div>";
6187 function toggle_collapse_cat($link, $cat_id, $mode) {
6189 $mode = bool_to_sql_bool($mode);
6191 db_query($link, "UPDATE ttrss_feed_categories SET
6192 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6199 $pref_name = '_COLLAPSED_SPECIAL';
6202 $pref_name = '_COLLAPSED_LABELS';
6205 $pref_name = '_COLLAPSED_UNCAT';
6211 set_pref($link, $pref_name, 'true');
6213 set_pref($link, $pref_name, 'false');
6219 function remove_feed($link, $id, $owner_uid) {
6223 /* save starred articles in Archived feed */
6225 db_query($link, "BEGIN");
6227 /* prepare feed if necessary */
6229 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6232 if (db_num_rows($result) == 0) {
6233 db_query($link, "INSERT INTO ttrss_archived_feeds
6234 (id, owner_uid, title, feed_url, site_url)
6235 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6239 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6240 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6241 marked = true AND owner_uid = $owner_uid");
6243 /* Remove access key for the feed */
6245 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6246 feed_id = '$id' AND owner_uid = $owner_uid");
6248 /* remove the feed */
6250 db_query($link, "DELETE FROM ttrss_feeds
6251 WHERE id = '$id' AND owner_uid = $owner_uid");
6253 db_query($link, "COMMIT");
6255 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6256 unlink(ICONS_DIR . "/$id.ico");
6259 ccache_remove($link, $id, $owner_uid);
6262 label_remove($link, -11-$id, $owner_uid);
6263 ccache_remove($link, -11-$id, $owner_uid);
6267 function add_feed_category($link, $feed_cat) {
6269 if (!$feed_cat) return false;
6271 db_query($link, "BEGIN");
6273 $result = db_query($link,
6274 "SELECT id FROM ttrss_feed_categories
6275 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6277 if (db_num_rows($result) == 0) {
6279 $result = db_query($link,
6280 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6281 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6283 db_query($link, "COMMIT");
6291 function remove_feed_category($link, $id, $owner_uid) {
6293 db_query($link, "DELETE FROM ttrss_feed_categories
6294 WHERE id = '$id' AND owner_uid = $owner_uid");
6296 ccache_remove($link, $id, $owner_uid, true);
6299 function archive_article($link, $id, $owner_uid) {
6300 db_query($link, "BEGIN");
6302 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6303 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6305 if (db_num_rows($result) != 0) {
6307 /* prepare the archived table */
6309 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6312 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6313 WHERE id = '$feed_id'");
6315 if (db_num_rows($result) == 0) {
6316 db_query($link, "INSERT INTO ttrss_archived_feeds
6317 (id, owner_uid, title, feed_url, site_url)
6318 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6319 WHERE id = '$feed_id'");
6322 db_query($link, "UPDATE ttrss_user_entries
6323 SET orig_feed_id = feed_id, feed_id = NULL
6324 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6328 db_query($link, "COMMIT");
6331 function getArticleFeed($link, $id) {
6332 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6333 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6335 if (db_num_rows($result) != 0) {
6336 return db_fetch_result($result, 0, "feed_id");
6342 function make_url_from_parts($parts) {
6343 $url = $parts['scheme'] . '://' . $parts['host'];
6345 if ($parts['path']) $url .= $parts['path'];
6346 if ($parts['query']) $url .= '?' . $parts['query'];
6352 * Fixes incomplete URLs by prepending "http://".
6353 * Also replaces feed:// with http://, and
6354 * prepends a trailing slash if the url is a domain name only.
6356 * @param string $url Possibly incomplete URL
6358 * @return string Fixed URL.
6360 function fix_url($url) {
6361 if (strpos($url, '://') === false) {
6362 $url = 'http://' . $url;
6363 } else if (substr($url, 0, 5) == 'feed:') {
6364 $url = 'http:' . substr($url, 5);
6367 //prepend slash if the URL has no slash in it
6368 // "http://www.example" -> "http://www.example/"
6369 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6373 if ($url != "http:///")
6379 function validate_feed_url($url) {
6380 $parts = parse_url($url);
6382 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6386 function get_article_enclosures($link, $id) {
6390 $query = "SELECT * FROM ttrss_enclosures
6391 WHERE post_id = '$id' AND content_url != ''";
6393 $obj_id = md5("ENCLOSURES:$id");
6397 if ($memcache && $obj = $memcache->get($obj_id)) {
6400 $result = db_query($link, $query);
6402 if (db_num_rows($result) > 0) {
6403 while ($line = db_fetch_assoc($result)) {
6404 array_push($rv, $line);
6406 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6413 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6419 if ($cat_id == -4 ||
$cat_id == -2) {
6420 $counters = getLabelCounters($link, true);
6422 foreach (array_values($counters) as $cv) {
6424 $unread = $cv["counter"];
6426 if ($unread ||
!$unread_only) {
6430 "title" => $cv["description"],
6431 "unread" => $cv["counter"],
6435 array_push($feeds, $row);
6442 if ($cat_id == -4 ||
$cat_id == -1) {
6443 foreach (array(-1, -2, -3, -4, 0) as $i) {
6444 $unread = getFeedUnread($link, $i);
6446 if ($unread ||
!$unread_only) {
6447 $title = getFeedTitle($link, $i);
6452 "unread" => $unread,
6455 array_push($feeds, $row);
6464 $limit_qpart = "LIMIT $limit OFFSET $offset";
6469 if ($cat_id == -4 ||
$cat_id == -3) {
6470 $result = db_query($link, "SELECT
6471 id, feed_url, cat_id, title, ".
6472 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6473 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6474 " ORDER BY cat_id, title " . $limit_qpart);
6478 $cat_qpart = "cat_id = '$cat_id'";
6480 $cat_qpart = "cat_id IS NULL";
6482 $result = db_query($link, "SELECT
6483 id, feed_url, cat_id, title, ".
6484 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6485 FROM ttrss_feeds WHERE
6486 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6487 " ORDER BY cat_id, title " . $limit_qpart);
6490 while ($line = db_fetch_assoc($result)) {
6492 $unread = getFeedUnread($link, $line["id"]);
6494 $has_icon = feed_has_icon($line['id']);
6496 if ($unread ||
!$unread_only) {
6499 "feed_url" => $line["feed_url"],
6500 "title" => $line["title"],
6501 "id" => (int)$line["id"],
6502 "unread" => (int)$unread,
6503 "has_icon" => $has_icon,
6504 "cat_id" => (int)$line["cat_id"],
6505 "last_updated" => strtotime($line["last_updated"])
6508 array_push($feeds, $row);
6515 function api_get_headlines($link, $feed_id, $limit, $offset,
6516 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6518 /* do not rely on params below */
6520 $search = db_escape_string($_REQUEST["search"]);
6521 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6522 $match_on = db_escape_string($_REQUEST["match_on"]);
6524 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6525 $view_mode, $is_cat, $search, $search_mode, $match_on,
6528 $result = $qfh_ret[0];
6529 $feed_title = $qfh_ret[1];
6531 $headlines = array();
6533 while ($line = db_fetch_assoc($result)) {
6534 $is_updated = ($line["last_read"] == "" &&
6535 ($line["unread"] != "t" && $line["unread"] != "1"));
6537 $headline_row = array(
6538 "id" => (int)$line["id"],
6539 "unread" => sql_bool_to_bool($line["unread"]),
6540 "marked" => sql_bool_to_bool($line["marked"]),
6541 "published" => sql_bool_to_bool($line["published"]),
6542 "updated" => strtotime($line["updated"]),
6543 "is_updated" => $is_updated,
6544 "title" => $line["title"],
6545 "link" => $line["link"],
6546 "feed_id" => $line["feed_id"],
6547 "tags" => get_article_tags($link, $line["id"]),
6550 if ($show_excerpt) {
6551 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6552 $headline_row["excerpt"] = $excerpt;
6555 if ($show_content) {
6556 $headline_row["content"] = $line["content_preview"];
6559 array_push($headlines, $headline_row);
6565 function generate_error_feed($link, $error) {
6568 $reply['headlines']['id'] = -6;
6569 $reply['headlines']['is_cat'] = false;
6571 $reply['headlines']['toolbar'] = '';
6572 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6574 $reply['headlines-info'] = array("count" => 0,
6575 "vgroup_last_feed" => '',
6577 "disable_cache" => true);
6583 function generate_dashboard_feed($link) {
6586 $reply['headlines']['id'] = -5;
6587 $reply['headlines']['is_cat'] = false;
6589 $reply['headlines']['toolbar'] = '';
6590 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6592 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6594 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6595 WHERE owner_uid = " . $_SESSION['uid']);
6597 $last_updated = db_fetch_result($result, 0, "last_updated");
6598 $last_updated = make_local_datetime($link, $last_updated, false);
6600 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6602 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6603 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6605 $num_errors = db_fetch_result($result, 0, "num_errors");
6607 if ($num_errors > 0) {
6608 $reply['headlines']['content'] .= "<br/>";
6609 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6610 __('Some feeds have update errors (click for details)')."</a>";
6612 $reply['headlines']['content'] .= "</span></p>";
6614 $reply['headlines-info'] = array("count" => 0,
6615 "vgroup_last_feed" => '',
6617 "disable_cache" => true);
6622 function save_email_address($link, $email) {
6623 // FIXME: implement persistent storage of emails
6625 if (!$_SESSION['stored_emails'])
6626 $_SESSION['stored_emails'] = array();
6628 if (!in_array($email, $_SESSION['stored_emails']))
6629 array_push($_SESSION['stored_emails'], $email);
6632 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6633 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6635 $sql_is_cat = bool_to_sql_bool($is_cat);
6637 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6638 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6639 AND owner_uid = " . $owner_uid);
6641 if (db_num_rows($result) == 1) {
6642 $key = db_escape_string(sha1(uniqid(rand(), true)));
6644 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6645 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6646 AND owner_uid = " . $owner_uid);
6651 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6655 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6657 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6659 $sql_is_cat = bool_to_sql_bool($is_cat);
6661 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6662 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6663 AND owner_uid = " . $owner_uid);
6665 if (db_num_rows($result) == 1) {
6666 return db_fetch_result($result, 0, "access_key");
6668 $key = db_escape_string(sha1(uniqid(rand(), true)));
6670 $result = db_query($link, "INSERT INTO ttrss_access_keys
6671 (access_key, feed_id, is_cat, owner_uid)
6672 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6680 * Extracts RSS/Atom feed URLs from the given HTML URL.
6682 * @param string $url HTML page URL
6684 * @return array Array of feeds. Key is the full URL, value the title
6686 function get_feeds_from_html($url, $login = false, $pass = false)
6688 $url = fix_url($url);
6689 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6691 libxml_use_internal_errors(true);
6693 $content = @fetch_file_contents
($url, false, $login, $pass);
6695 $doc = new DOMDocument();
6696 $doc->loadHTML($content);
6697 $xpath = new DOMXPath($doc);
6698 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6699 $feedUrls = array();
6700 foreach ($entries as $entry) {
6701 if ($entry->hasAttribute('href')) {
6702 $title = $entry->getAttribute('title');
6704 $title = $entry->getAttribute('type');
6706 $feedUrl = rewrite_relative_url(
6707 $baseUrl, $entry->getAttribute('href')
6709 $feedUrls[$feedUrl] = $title;
6716 * Checks if the content behind the given URL is a HTML file
6718 * @param string $url URL to check
6720 * @return boolean True if the URL contains HTML content
6722 function url_is_html($url, $login = false, $pass = false) {
6723 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6725 if (stripos($content, '<html>') === false
6726 && stripos($content, '<html ') === false
6734 function print_label_select($link, $name, $value, $attributes = "") {
6736 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6737 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6739 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6740 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6742 while ($line = db_fetch_assoc($result)) {
6744 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6746 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6747 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6751 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6758 function format_article_enclosures($link, $id, $always_display_enclosures,
6761 $result = get_article_enclosures($link, $id);
6764 if (count($result) > 0) {
6766 $entries_html = array();
6769 foreach ($result as $line) {
6771 $url = $line["content_url"];
6772 $ctype = $line["content_type"];
6774 if (!$ctype) $ctype = __("unknown type");
6776 # $filename = substr($url, strrpos($url, "/")+1);
6778 $entry = format_inline_player($link, $url, $ctype);
6780 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6781 # $filename . " (" . $ctype . ")" . "</a>";
6783 array_push($entries_html, $entry);
6787 $entry["type"] = $ctype;
6788 $entry["filename"] = $filename;
6789 $entry["url"] = $url;
6791 array_push($entries, $entry);
6794 $rv .= "<div class=\"postEnclosures\">";
6796 if (!get_pref($link, "STRIP_IMAGES")) {
6797 if ($always_display_enclosures ||
6798 !preg_match("/<img/i", $article_content)) {
6800 foreach ($entries as $entry) {
6802 if (preg_match("/image/", $entry["type"]) ||
6803 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6806 alt=\"".htmlspecialchars($entry["filename"])."\"
6807 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6813 if (count($entries) == 1) {
6814 $rv .= __("Attachment:") . " ";
6816 $rv .= __("Attachments:") . " ";
6819 $rv .= join(", ", $entries_html);
6827 function getLastArticleId($link) {
6828 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
6829 WHERE owner_uid = " . $_SESSION["uid"]);
6831 if (db_num_rows($result) == 1) {
6832 return db_fetch_result($result, 0, "id");
6838 function build_url($parts) {
6839 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
6843 * Converts a (possibly) relative URL to a absolute one.
6845 * @param string $url Base URL (i.e. from where the document is)
6846 * @param string $rel_url Possibly relative URL in the document
6848 * @return string Absolute URL
6850 function rewrite_relative_url($url, $rel_url) {
6851 if (strpos($rel_url, "://") !== false) {
6853 } else if (strpos($rel_url, "/") === 0)
6855 $parts = parse_url($url);
6856 $parts['path'] = $rel_url;
6858 return build_url($parts);
6861 $parts = parse_url($url);
6862 if (!isset($parts['path'])) {
6863 $parts['path'] = '/';
6865 $dir = $parts['path'];
6866 if (substr($dir, -1) !== '/') {
6867 $dir = dirname($parts['path']);
6868 $dir !== '/' && $dir .= '/';
6870 $parts['path'] = $dir . $rel_url;
6872 return build_url($parts);
6876 function sphinx_search($query, $offset = 0, $limit = 30) {
6877 $sphinxClient = new SphinxClient();
6879 $sphinxClient->SetServer('localhost', 9312);
6880 $sphinxClient->SetConnectTimeout(1);
6882 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
6883 'feed_title' => 20));
6885 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
6886 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
6887 $sphinxClient->SetLimits($offset, $limit, 1000);
6888 $sphinxClient->SetArrayResult(false);
6889 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
6891 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
6895 if (is_array($result['matches'])) {
6896 foreach (array_keys($result['matches']) as $int_id) {
6897 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
6898 array_push($ids, $ref_id);
6905 function cleanup_tags($link, $days = 14, $limit = 1000) {
6907 if (DB_TYPE
== "pgsql") {
6908 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
6909 } else if (DB_TYPE
== "mysql") {
6910 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
6915 while ($limit > 0) {
6918 $query = "SELECT ttrss_tags.id AS id
6919 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
6920 WHERE post_int_id = int_id AND $interval_query AND
6921 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
6923 $result = db_query($link, $query);
6927 while ($line = db_fetch_assoc($result)) {
6928 array_push($ids, $line['id']);
6931 if (count($ids) > 0) {
6932 $ids = join(",", $ids);
6935 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
6936 $tags_deleted +
= db_affected_rows($link, $tmp_result);
6941 $limit -= $limit_part;
6946 return $tags_deleted;
6949 function feedlist_init_cat($link, $cat_id, $hidden = false) {
6951 $cat_id = (int) $cat_id;
6954 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
6955 } else if ($cat_id == 0 ||
$cat_id == -2) {
6956 $cat_unread = getCategoryUnread($link, $cat_id);
6959 $obj['id'] = 'CAT:' . $cat_id;
6960 $obj['items'] = array();
6961 $obj['name'] = getCategoryTitle($link, $cat_id);
6962 $obj['type'] = 'feed';
6963 $obj['unread'] = (int) $cat_unread;
6964 $obj['hidden'] = $hidden;
6965 $obj['bare_id'] = $cat_id;
6970 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
6972 $feed_id = (int) $feed_id;
6975 $title = getFeedTitle($link, $feed_id, false);
6977 if ($unread === false)
6978 $unread = getFeedUnread($link, $feed_id, false);
6980 $obj['id'] = 'FEED:' . $feed_id;
6981 $obj['name'] = $title;
6982 $obj['unread'] = (int) $unread;
6983 $obj['type'] = 'feed';
6984 $obj['error'] = $error;
6985 $obj['updated'] = $updated;
6986 $obj['icon'] = getFeedIcon($feed_id);
6987 $obj['bare_id'] = $feed_id;
6993 function fetch_twitter_rss($link, $url, $owner_uid) {
6994 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
6995 WHERE id = $owner_uid");
6997 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
6998 $url_escaped = db_escape_string($url);
7000 if ($access_token) {
7002 $tmhOAuth = new tmhOAuth(array(
7003 'consumer_key' => CONSUMER_KEY
,
7004 'consumer_secret' => CONSUMER_SECRET
,
7005 'user_token' => $access_token['oauth_token'],
7006 'user_secret' => $access_token['oauth_token_secret'],
7009 $code = $tmhOAuth->request('GET', $url);
7013 $content = $tmhOAuth->response
['response'];
7015 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7016 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7022 db_query($link, "UPDATE ttrss_feeds
7023 SET last_error = 'OAuth authorization failed ($code).'
7024 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7029 db_query($link, "UPDATE ttrss_feeds
7030 SET last_error = 'OAuth information not found.'
7031 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7037 function print_user_stylesheet($link) {
7038 $value = get_pref($link, 'USER_STYLESHEET');
7041 print "<style type=\"text/css\">";
7042 print str_replace("<br/>", "\n", $value);
7048 function rewrite_urls($line) {
7053 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7054 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);