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 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
46 require_once "lib/accept-to-gettext.php";
47 require_once "lib/gettext/gettext.inc";
49 function startup_gettext() {
51 # Get locale from Accept-Language header
52 $lang = al2gt(array_keys(get_translations()), "text/html");
54 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
55 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
58 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
59 $lang = $_COOKIE["ttrss_lang"];
62 /* In login action of mobile version */
63 if ($_POST["language"] && defined('MOBILE_VERSION')) {
64 $lang = $_POST["language"];
65 $_COOKIE["ttrss_lang"] = $lang;
69 if (defined('LC_MESSAGES')) {
70 _setlocale(LC_MESSAGES
, $lang);
71 } else if (defined('LC_ALL')) {
72 _setlocale(LC_ALL
, $lang);
74 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
77 if (defined('MOBILE_VERSION')) {
78 _bindtextdomain("messages", "../locale");
80 _bindtextdomain("messages", "locale");
83 _textdomain("messages");
84 _bind_textdomain_codeset("messages", "UTF-8");
90 } else { // If translations are enabled.
94 function startup_gettext() {
98 } // If translations are enabled.
100 if (defined('MEMCACHE_SERVER')) {
101 $memcache = new Memcache
;
102 $memcache->connect(MEMCACHE_SERVER
, 11211);
105 require_once 'db-prefs.php';
106 require_once 'errors.php';
107 require_once 'version.php';
109 require_once 'lib/phpmailer/class.phpmailer.php';
110 require_once 'lib/sphinxapi.php';
111 require_once 'lib/tmhoauth/tmhOAuth.php';
113 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
114 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
115 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
117 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
118 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
120 ini_set('user_agent', SELF_USER_AGENT
);
122 require_once "lib/simplepie/simplepie.inc";
123 require_once "lib/magpierss/rss_fetch.inc";
124 require_once 'lib/magpierss/rss_utils.inc';
125 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
127 $config = HTMLPurifier_Config
::createDefault();
129 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s";
131 $config->set('HTML', 'Allowed', $allowed);
132 $purifier = new HTMLPurifier($config);
135 * Print a timestamped debug message.
137 * @param string $msg The debug message.
140 function _debug($msg) {
141 $ts = strftime("%H:%M:%S", time());
142 if (function_exists('posix_getpid')) {
143 $ts = "$ts/" . posix_getpid();
145 print "[$ts] $msg\n";
149 * Purge a feed old posts.
151 * @param mixed $link A database connection.
152 * @param mixed $feed_id The id of the purged feed.
153 * @param mixed $purge_interval Olderness of purged posts.
154 * @param boolean $debug Set to True to enable the debug. False by default.
158 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
160 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
164 $result = db_query($link,
165 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
169 if (db_num_rows($result) == 1) {
170 $owner_uid = db_fetch_result($result, 0, "owner_uid");
173 if ($purge_interval == -1 ||
!$purge_interval) {
175 ccache_update($link, $feed_id, $owner_uid);
180 if (!$owner_uid) return;
182 if (FORCE_ARTICLE_PURGE
== 0) {
183 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
186 $purge_unread = true;
187 $purge_interval = FORCE_ARTICLE_PURGE
;
190 if (!$purge_unread) $query_limit = " unread = false AND ";
192 if (DB_TYPE
== "pgsql") {
193 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
194 marked = false AND feed_id = '$feed_id' AND
195 (SELECT date_updated FROM ttrss_entries WHERE
196 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
198 $pg_version = get_pgsql_version($link);
200 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
202 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
203 ttrss_entries.id = ref_id AND
205 feed_id = '$feed_id' AND
207 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
211 $result = db_query($link, "DELETE FROM ttrss_user_entries
213 WHERE ttrss_entries.id = ref_id AND
215 feed_id = '$feed_id' AND
217 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
220 $rows = pg_affected_rows($result);
224 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
225 marked = false AND feed_id = '$feed_id' AND
226 (SELECT date_updated FROM ttrss_entries WHERE
227 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
229 $result = db_query($link, "DELETE FROM ttrss_user_entries
230 USING ttrss_user_entries, ttrss_entries
231 WHERE ttrss_entries.id = ref_id AND
233 feed_id = '$feed_id' AND
235 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
237 $rows = mysql_affected_rows($link);
241 ccache_update($link, $feed_id, $owner_uid);
244 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
246 } // function purge_feed
249 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
251 * @param mixed $link A database connection
252 * @param boolean $do_output Set to true to enable printed output, false by default.
253 * @param integer $limit The maximal number of removed posts.
257 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
259 $random_qpart = sql_random_function();
262 $limit_qpart = "LIMIT $limit";
267 $result = db_query($link,
268 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
269 ORDER BY $random_qpart $limit_qpart");
271 while ($line = db_fetch_assoc($result)) {
273 $feed_id = $line["id"];
274 $purge_interval = $line["purge_interval"];
275 $owner_uid = $line["owner_uid"];
277 if ($purge_interval == 0) {
279 $tmp_result = db_query($link,
280 "SELECT value FROM ttrss_user_prefs WHERE
281 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
283 if (db_num_rows($tmp_result) != 0) {
284 $purge_interval = db_fetch_result($tmp_result, 0, "value");
289 // print "Feed $feed_id: purge interval = $purge_interval\n";
292 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
293 purge_feed($link, $feed_id, $purge_interval, $do_output);
297 purge_orphans($link, $do_output);
299 } // function global_purge_old_posts */
301 function feed_purge_interval($link, $feed_id) {
303 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
304 WHERE id = '$feed_id'");
306 if (db_num_rows($result) == 1) {
307 $purge_interval = db_fetch_result($result, 0, "purge_interval");
308 $owner_uid = db_fetch_result($result, 0, "owner_uid");
310 if ($purge_interval == 0) $purge_interval = get_pref($link,
311 'PURGE_OLD_DAYS', $owner_uid);
313 return $purge_interval;
320 function purge_old_posts($link) {
322 $user_id = $_SESSION["uid"];
324 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
325 WHERE owner_uid = '$user_id'");
327 while ($line = db_fetch_assoc($result)) {
329 $feed_id = $line["id"];
330 $purge_interval = $line["purge_interval"];
332 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
334 if ($purge_interval > 0) {
335 purge_feed($link, $feed_id, $purge_interval);
339 purge_orphans($link);
342 function purge_orphans($link, $do_output = false) {
344 // purge orphaned posts in main content table
345 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
346 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
349 $rows = db_affected_rows($link, $result);
350 _debug("Purged $rows orphaned posts.");
354 function get_feed_update_interval($link, $feed_id) {
355 $result = db_query($link, "SELECT owner_uid, update_interval FROM
356 ttrss_feeds WHERE id = '$feed_id'");
358 if (db_num_rows($result) == 1) {
359 $update_interval = db_fetch_result($result, 0, "update_interval");
360 $owner_uid = db_fetch_result($result, 0, "owner_uid");
362 if ($update_interval != 0) {
363 return $update_interval;
365 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
373 function fetch_file_contents($url, $type = false, $login = false, $pass = false) {
374 $login = urlencode($login);
375 $pass = urlencode($pass);
377 if (function_exists('curl_init')) {
378 $ch = curl_init($url);
380 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
381 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
382 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
383 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
384 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
385 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
386 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
387 curl_setopt($fp, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
390 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
392 $contents = @curl_exec
($ch);
393 if ($contents === false) {
398 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
399 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
402 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
408 if ($login && $pass && $updated != 3) {
409 $url_parts = array();
411 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
413 if ($url_parts[1] && $url_parts[2]) {
414 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
418 return @file_get_contents
($url);
424 * Try to determine the favicon URL for a feed.
425 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
426 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
428 * @param string $url A feed or page URL
430 * @return mixed The favicon URL, or false if none was found.
432 function get_favicon_url($url) {
434 $favicon_url = false;
436 if ($html = @fetch_file_contents
($url)) {
438 libxml_use_internal_errors(true);
440 $doc = new DOMDocument();
441 $doc->loadHTML($html);
442 $xpath = new DOMXPath($doc);
443 $entries = $xpath->query('/html/head/link[@rel="shortcut icon"]');
445 if (count($entries) > 0) {
446 foreach ($entries as $entry) {
447 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
454 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
457 } // function get_favicon_url
459 function check_feed_favicon($site_url, $feed, $link) {
460 $favicon_url = get_favicon_url($site_url);
462 # print "FAVICON [$site_url]: $favicon_url\n";
464 $icon_file = ICONS_DIR
. "/$feed.ico";
466 if ($favicon_url && !file_exists($icon_file)) {
467 $contents = fetch_file_contents($favicon_url, "image");
470 $fp = fopen($icon_file, "w");
473 fwrite($fp, $contents);
475 chmod($icon_file, 0644);
481 function update_rss_feed($link, $feed, $ignore_daemon = false) {
485 /* Update all feeds with the same URL to utilize memcache */
488 $result = db_query($link, "SELECT f1.id
489 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
490 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
492 while ($line = db_fetch_assoc($result)) {
493 update_rss_feed_real($link, $line["id"], $ignore_daemon);
496 update_rss_feed_real($link, $feed, $ignore_daemon);
500 function update_rss_feed_real($link, $feed, $ignore_daemon = false) {
504 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
508 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
509 _debug("update_rss_feed: start");
512 if (!$ignore_daemon) {
514 if (DB_TYPE
== "pgsql") {
515 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
517 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
520 $result = db_query($link, "SELECT id,update_interval,auth_login,
521 auth_pass,cache_images,update_method
522 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
526 $result = db_query($link, "SELECT id,update_interval,auth_login,
527 feed_url,auth_pass,cache_images,update_method,last_updated,
529 FROM ttrss_feeds WHERE id = '$feed'");
533 if (db_num_rows($result) == 0) {
534 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
535 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
540 $update_method = db_fetch_result($result, 0, "update_method");
541 $last_updated = db_fetch_result($result, 0, "last_updated");
542 $owner_uid = db_fetch_result($result, 0, "owner_uid");
544 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
545 WHERE id = '$feed'");
547 $auth_login = db_fetch_result($result, 0, "auth_login");
548 $auth_pass = db_fetch_result($result, 0, "auth_pass");
550 if ($update_method == 0)
551 $update_method = DEFAULT_UPDATE_METHOD +
1;
557 if ($update_method == 2)
558 $use_simplepie = true;
560 $use_simplepie = false;
562 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
563 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
566 if ($update_method == 1) {
567 $auth_login = urlencode($auth_login);
568 $auth_pass = urlencode($auth_pass);
571 $update_interval = db_fetch_result($result, 0, "update_interval");
572 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
573 $fetch_url = db_fetch_result($result, 0, "feed_url");
575 if ($update_interval < 0) { return; }
577 $feed = db_escape_string($feed);
579 if ($auth_login && $auth_pass && $updated != 3) {
580 $url_parts = array();
581 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
583 if ($url_parts[1] && $url_parts[2]) {
584 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
589 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
590 _debug("update_rss_feed: fetching [$fetch_url]...");
593 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
595 if ($memcache && $obj = $memcache->get($obj_id)) {
597 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
598 _debug("update_rss_feed: data found in memcache.");
605 if ($update_method == 3) {
606 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
607 } else if ($update_method == 1) {
608 $rss = @fetch_rss
($fetch_url);
610 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
611 mkdir(SIMPLEPIE_CACHE_DIR
);
614 $rss = new SimplePie();
615 $rss->set_useragent(SELF_USER_AGENT
);
616 # $rss->set_timeout(10);
617 $rss->set_feed_url($fetch_url);
618 $rss->set_output_encoding('UTF-8');
620 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
622 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
623 _debug("enabling image cache");
626 $rss->set_image_handler("image.php", 'i');
629 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
630 _debug("feed update interval (sec): " .
631 get_feed_update_interval($link, $feed)*60);
634 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
635 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
636 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
642 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
647 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
648 _debug("update_rss_feed: fetch done, parsing...");
651 $feed = db_escape_string($feed);
653 if ($update_method == 2) {
654 $fetch_ok = !$rss->error();
661 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
662 _debug("update_rss_feed: processing feed data...");
665 // db_query($link, "BEGIN");
667 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
668 FROM ttrss_feeds WHERE id = '$feed'");
670 $registered_title = db_fetch_result($result, 0, "title");
671 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
672 $orig_site_url = db_fetch_result($result, 0, "site_url");
674 $owner_uid = db_fetch_result($result, 0, "owner_uid");
676 if ($use_simplepie) {
677 $site_url = $rss->get_link();
679 $site_url = $rss->channel
["link"];
682 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
683 _debug("update_rss_feed: checking favicon...");
686 check_feed_favicon($site_url, $feed, $link);
688 if (!$registered_title ||
$registered_title == "[Unknown]") {
690 if ($use_simplepie) {
691 $feed_title = db_escape_string($rss->get_title());
693 $feed_title = db_escape_string($rss->channel
["title"]);
696 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
697 _debug("update_rss_feed: registering title: $feed_title");
700 db_query($link, "UPDATE ttrss_feeds SET
701 title = '$feed_title' WHERE id = '$feed'");
704 // weird, weird Magpie
705 if (!$use_simplepie) {
706 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
709 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
710 db_query($link, "UPDATE ttrss_feeds SET
711 site_url = '$site_url' WHERE id = '$feed'");
714 // print "I: " . $rss->channel["image"]["url"];
716 if (!$use_simplepie) {
717 $icon_url = db_escape_string($rss->image
["url"]);
719 $icon_url = db_escape_string($rss->get_image_url());
722 $icon_url = substr($icon_url, 0, 250);
724 if ($icon_url && $orig_icon_url != $icon_url) {
725 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
728 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
729 _debug("update_rss_feed: loading filters...");
732 $filters = load_filters($link, $feed, $owner_uid);
734 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
738 if ($use_simplepie) {
739 $iterator = $rss->get_items();
741 $iterator = $rss->items
;
742 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
743 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
746 if (!is_array($iterator)) {
747 /* db_query($link, "UPDATE ttrss_feeds
748 SET last_error = 'Parse error: can\'t find any articles.'
749 WHERE id = '$feed'"); */
751 // clear any errors and mark feed as updated if fetched okay
752 // even if it's blank
754 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
755 _debug("update_rss_feed: entry iterator is not an array, no articles?");
758 db_query($link, "UPDATE ttrss_feeds
759 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
761 return; // no articles
764 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
765 _debug("update_rss_feed: processing articles...");
768 foreach ($iterator as $item) {
770 if ($_REQUEST['xdebug'] == 2) {
774 if ($use_simplepie) {
775 $entry_guid = $item->get_id();
776 if (!$entry_guid) $entry_guid = $item->get_link();
777 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
781 $entry_guid = $item["id"];
783 if (!$entry_guid) $entry_guid = $item["guid"];
784 if (!$entry_guid) $entry_guid = $item["about"];
785 if (!$entry_guid) $entry_guid = $item["link"];
786 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
789 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
790 _debug("update_rss_feed: guid $entry_guid");
793 if (!$entry_guid) continue;
795 $entry_timestamp = "";
797 if ($use_simplepie) {
798 $entry_timestamp = strtotime($item->get_date());
800 $rss_2_date = $item['pubdate'];
801 $rss_1_date = $item['dc']['date'];
802 $atom_date = $item['issued'];
803 if (!$atom_date) $atom_date = $item['updated'];
805 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
806 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
807 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
811 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
812 $entry_timestamp = time();
813 $no_orig_date = 'true';
815 $no_orig_date = 'false';
818 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
820 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
821 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
824 if ($use_simplepie) {
825 $entry_title = $item->get_title();
827 $entry_title = trim(strip_tags($item["title"]));
830 if ($use_simplepie) {
831 $entry_link = $item->get_link();
833 // strange Magpie workaround
834 $entry_link = $item["link_"];
835 if (!$entry_link) $entry_link = $item["link"];
838 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
839 _debug("update_rss_feed: title $entry_title");
842 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
844 $entry_link = strip_tags($entry_link);
846 if ($use_simplepie) {
847 $entry_content = $item->get_content();
848 if (!$entry_content) $entry_content = $item->get_description();
850 $entry_content = $item["content:escaped"];
852 if (!$entry_content) $entry_content = $item["content:encoded"];
853 if (!$entry_content) $entry_content = $item["content"]["encoded"];
854 if (!$entry_content) $entry_content = $item["content"];
856 // Magpie bugs are getting ridiculous
857 if (trim($entry_content) == "Array") $entry_content = false;
859 if (!$entry_content) $entry_content = $item["atom_content"];
860 if (!$entry_content) $entry_content = $item["summary"];
862 if (!$entry_content ||
863 strlen($entry_content) < strlen($item["description"])) {
864 $entry_content = $item["description"];
868 if (is_array($entry_content)) {
869 $entry_content = $entry_content["encoded"];
870 if (!$entry_content) $entry_content = $entry_content["escaped"];
874 if ($_REQUEST["xdebug"] == 2) {
875 print "update_rss_feed: content: ";
876 print_r(htmlspecialchars($entry_content));
879 $entry_content_unescaped = $entry_content;
881 if ($use_simplepie) {
882 $entry_comments = strip_tags($item->data
["comments"]);
883 if ($item->get_author()) {
884 $entry_author_item = $item->get_author();
885 $entry_author = $entry_author_item->get_name();
886 if (!$entry_author) $entry_author = $entry_author_item->get_email();
888 $entry_author = db_escape_string($entry_author);
891 $entry_comments = strip_tags($item["comments"]);
893 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
895 if ($item['author']) {
897 if (is_array($item['author'])) {
899 if (!$entry_author) {
900 $entry_author = db_escape_string(strip_tags($item['author']['name']));
903 if (!$entry_author) {
904 $entry_author = db_escape_string(strip_tags($item['author']['email']));
908 if (!$entry_author) {
909 $entry_author = db_escape_string(strip_tags($item['author']));
914 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
916 $entry_guid = db_escape_string(strip_tags($entry_guid));
917 $entry_guid = mb_substr($entry_guid, 0, 250);
919 $result = db_query($link, "SELECT id FROM ttrss_entries
920 WHERE guid = '$entry_guid'");
922 $entry_content = db_escape_string($entry_content, false);
924 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
926 $entry_title = db_escape_string($entry_title);
927 $entry_link = db_escape_string($entry_link);
928 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
929 $entry_author = mb_substr($entry_author, 0, 250);
931 if ($use_simplepie) {
932 $num_comments = 0; #FIXME#
934 $num_comments = db_escape_string($item["slash"]["comments"]);
937 if (!$num_comments) $num_comments = 0;
939 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
940 _debug("update_rss_feed: looking for tags [1]...");
943 // parse <category> entries into tags
945 $additional_tags = array();
947 if ($use_simplepie) {
949 $additional_tags_src = $item->get_categories();
951 if (is_array($additional_tags_src)) {
952 foreach ($additional_tags_src as $tobj) {
953 array_push($additional_tags, $tobj->get_term());
957 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
958 _debug("update_rss_feed: category tags:");
959 print_r($additional_tags);
964 $t_ctr = $item['category#'];
967 $additional_tags = array();
968 } else if ($t_ctr > 0) {
969 $additional_tags = array($item['category']);
971 if ($item['category@term']) {
972 array_push($additional_tags, $item['category@term']);
975 for ($i = 0; $i <= $t_ctr; $i++
) {
976 if ($item["category#$i"]) {
977 array_push($additional_tags, $item["category#$i"]);
980 if ($item["category#$i@term"]) {
981 array_push($additional_tags, $item["category#$i@term"]);
986 // parse <dc:subject> elements
988 $t_ctr = $item['dc']['subject#'];
991 array_push($additional_tags, $item['dc']['subject']);
993 for ($i = 0; $i <= $t_ctr; $i++
) {
994 if ($item['dc']["subject#$i"]) {
995 array_push($additional_tags, $item['dc']["subject#$i"]);
1001 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1002 _debug("update_rss_feed: looking for tags [2]...");
1006 // <a href="..." rel="tag">Xorg</a>, //
1010 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1011 $entry_content_unescaped, $entry_tags);
1013 $entry_tags = $entry_tags[1];
1015 $entry_tags = array_merge($entry_tags, $additional_tags);
1016 $entry_tags = array_unique($entry_tags);
1018 for ($i = 0; $i < count($entry_tags); $i++
)
1019 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1021 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1022 _debug("update_rss_feed: unfiltered tags found:");
1023 print_r($entry_tags);
1028 $entry_content = sanitize_article_content($entry_content);
1029 $entry_title = sanitize_article_content($entry_title);
1031 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1032 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1035 db_query($link, "BEGIN");
1037 if (db_num_rows($result) == 0) {
1039 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1040 _debug("update_rss_feed: base guid not found");
1043 // base post entry does not exist, create it
1045 $result = db_query($link,
1046 "INSERT INTO ttrss_entries
1063 '$entry_timestamp_fmt',
1073 // we keep encountering the entry in feeds, so we need to
1074 // update date_updated column so that we don't get horrible
1075 // dupes when the entry gets purged and reinserted again e.g.
1076 // in the case of SLOW SLOW OMG SLOW updating feeds
1078 $base_entry_id = db_fetch_result($result, 0, "id");
1080 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1081 WHERE id = '$base_entry_id'");
1084 // now it should exist, if not - bad luck then
1086 $result = db_query($link, "SELECT
1087 id,content_hash,no_orig_date,title,
1088 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1089 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1093 WHERE guid = '$entry_guid'");
1098 if (db_num_rows($result) == 1) {
1100 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1101 _debug("update_rss_feed: base guid found, checking for user record");
1104 // this will be used below in update handler
1105 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1106 $orig_title = db_fetch_result($result, 0, "title");
1107 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1108 $orig_date_updated = strtotime(db_fetch_result($result,
1109 0, "date_updated"));
1111 $ref_id = db_fetch_result($result, 0, "id");
1112 $entry_ref_id = $ref_id;
1114 // check for user post link to main table
1116 // do we allow duplicate posts with same GUID in different feeds?
1117 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1118 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1120 $dupcheck_qpart = "";
1123 /* Collect article tags here so we could filter by them: */
1125 $article_filters = get_article_filters($filters, $entry_title,
1126 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1129 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1130 _debug("update_rss_feed: article filters: ");
1131 if (count($article_filters) != 0) {
1132 print_r($article_filters);
1136 if (find_article_filter($article_filters, "filter")) {
1137 db_query($link, "COMMIT"); // close transaction in progress
1141 $score = calculate_article_score($article_filters);
1143 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1144 _debug("update_rss_feed: initial score: $score");
1147 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1148 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1151 // if ($_REQUEST["xdebug"]) print "$query\n";
1153 $result = db_query($link, $query);
1155 // okay it doesn't exist - create user entry
1156 if (db_num_rows($result) == 0) {
1158 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1159 _debug("update_rss_feed: user record not found, creating...");
1162 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1164 $last_read_qpart = 'NULL';
1167 $last_read_qpart = 'NOW()';
1170 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1176 if (find_article_filter($article_filters, 'publish')) {
1177 $published = 'true';
1179 $published = 'false';
1182 $result = db_query($link,
1183 "INSERT INTO ttrss_user_entries
1184 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1185 published, score, tag_cache, label_cache)
1186 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1187 $last_read_qpart, $marked, $published, '$score', '', '')");
1189 $result = db_query($link,
1190 "SELECT int_id FROM ttrss_user_entries WHERE
1191 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1192 feed_id = '$feed' LIMIT 1");
1194 if (db_num_rows($result) == 1) {
1195 $entry_int_id = db_fetch_result($result, 0, "int_id");
1198 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1199 _debug("update_rss_feed: user record FOUND");
1202 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1203 $entry_int_id = db_fetch_result($result, 0, "int_id");
1206 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1207 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1210 $post_needs_update = false;
1212 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1213 ($content_hash != $orig_content_hash)) {
1214 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1215 $post_needs_update = true;
1218 if (db_escape_string($orig_title) != $entry_title) {
1219 $post_needs_update = true;
1222 if ($orig_num_comments != $num_comments) {
1223 $post_needs_update = true;
1226 // this doesn't seem to be very reliable
1228 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1229 // $post_needs_update = true;
1232 // if post needs update, update it and mark all user entries
1233 // linking to this post as updated
1234 if ($post_needs_update) {
1236 if (defined('DAEMON_EXTENDED_DEBUG')) {
1237 _debug("update_rss_feed: post $entry_guid needs update...");
1240 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1242 db_query($link, "UPDATE ttrss_entries
1243 SET title = '$entry_title', content = '$entry_content',
1244 content_hash = '$content_hash',
1245 num_comments = '$num_comments'
1246 WHERE id = '$ref_id'");
1248 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1249 db_query($link, "UPDATE ttrss_user_entries
1250 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1252 db_query($link, "UPDATE ttrss_user_entries
1253 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1259 db_query($link, "COMMIT");
1261 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1262 _debug("update_rss_feed: assigning labels...");
1265 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1268 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1269 _debug("update_rss_feed: looking for enclosures...");
1274 $enclosures = array();
1276 if ($use_simplepie) {
1277 $encs = $item->get_enclosures();
1279 if (is_array($encs)) {
1280 foreach ($encs as $e) {
1282 $e->link
, $e->type
, $e->length
);
1284 array_push($enclosures, $e_item);
1291 $e_ctr = $item['enclosure#'];
1294 $e_item = array($item['enclosure@url'],
1295 $item['enclosure@type'],
1296 $item['enclosure@length']);
1298 array_push($enclosures, $e_item);
1300 for ($i = 0; $i <= $e_ctr; $i++
) {
1302 if ($item["enclosure#$i@url"]) {
1303 $e_item = array($item["enclosure#$i@url"],
1304 $item["enclosure#$i@type"],
1305 $item["enclosure#$i@length"]);
1306 array_push($enclosures, $e_item);
1312 // can there be many of those? yes -fox
1314 $m_ctr = $item['media']['content#'];
1317 $e_item = array($item['media']['content@url'],
1318 $item['media']['content@medium'],
1319 $item['media']['content@length']);
1321 array_push($enclosures, $e_item);
1323 for ($i = 0; $i <= $m_ctr; $i++
) {
1325 if ($item["media"]["content#$i@url"]) {
1326 $e_item = array($item["media"]["content#$i@url"],
1327 $item["media"]["content#$i@medium"],
1328 $item["media"]["content#$i@length"]);
1329 array_push($enclosures, $e_item);
1337 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1338 _debug("update_rss_feed: article enclosures:");
1339 print_r($enclosures);
1342 db_query($link, "BEGIN");
1344 foreach ($enclosures as $enc) {
1345 $enc_url = db_escape_string($enc[0]);
1346 $enc_type = db_escape_string($enc[1]);
1347 $enc_dur = db_escape_string($enc[2]);
1349 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1350 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1352 if (db_num_rows($result) == 0) {
1353 db_query($link, "INSERT INTO ttrss_enclosures
1354 (content_url, content_type, title, duration, post_id) VALUES
1355 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1359 db_query($link, "COMMIT");
1361 // check for manual tags (we have to do it here since they're loaded from filters)
1363 foreach ($article_filters as $f) {
1364 if ($f[0] == "tag") {
1366 $manual_tags = trim_array(split(",", $f[1]));
1368 foreach ($manual_tags as $tag) {
1369 if (tag_is_valid($tag)) {
1370 array_push($entry_tags, $tag);
1378 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1379 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1381 $filtered_tags = array();
1382 $tags_to_cache = array();
1384 if ($entry_tags && is_array($entry_tags)) {
1385 foreach ($entry_tags as $tag) {
1386 if (array_search($tag, $boring_tags) === false) {
1387 array_push($filtered_tags, $tag);
1392 $filtered_tags = array_unique($filtered_tags);
1394 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1395 _debug("update_rss_feed: filtered article tags:");
1396 print_r($filtered_tags);
1399 // Save article tags in the database
1401 if (count($filtered_tags) > 0) {
1403 db_query($link, "BEGIN");
1405 foreach ($filtered_tags as $tag) {
1407 $tag = sanitize_tag($tag);
1408 $tag = db_escape_string($tag);
1410 if (!tag_is_valid($tag)) continue;
1412 $result = db_query($link, "SELECT id FROM ttrss_tags
1413 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1414 owner_uid = '$owner_uid' LIMIT 1");
1416 if ($result && db_num_rows($result) == 0) {
1418 db_query($link, "INSERT INTO ttrss_tags
1419 (owner_uid,tag_name,post_int_id)
1420 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1423 array_push($tags_to_cache, $tag);
1426 /* update the cache */
1428 $tags_to_cache = array_unique($tags_to_cache);
1430 $tags_str = db_escape_string(join(",", $tags_to_cache));
1432 db_query($link, "UPDATE ttrss_user_entries
1433 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1434 AND owner_uid = $owner_uid");
1436 db_query($link, "COMMIT");
1439 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1440 _debug("update_rss_feed: article processed");
1444 if (!$last_updated) {
1445 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1446 _debug("update_rss_feed: new feed, catching it up...");
1448 catchup_feed($link, $feed, false, $owner_uid);
1451 purge_feed($link, $feed, 0);
1453 db_query($link, "UPDATE ttrss_feeds
1454 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1456 // db_query($link, "COMMIT");
1460 if ($use_simplepie) {
1461 $error_msg = mb_substr($rss->error(), 0, 250);
1463 $error_msg = mb_substr(magpie_error(), 0, 250);
1466 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1467 _debug("update_rss_feed: error fetching feed: $error_msg");
1470 $error_msg = db_escape_string($error_msg);
1473 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1474 last_updated = NOW() WHERE id = '$feed'");
1477 if ($use_simplepie) {
1481 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1482 _debug("update_rss_feed: done");
1487 function print_select($id, $default, $values, $attributes = "") {
1488 print "<select name=\"$id\" id=\"$id\" $attributes>";
1489 foreach ($values as $v) {
1491 $sel = "selected=\"1\"";
1495 print "<option value=\"$v\" $sel>$v</option>";
1500 function print_select_hash($id, $default, $values, $attributes = "") {
1501 print "<select name=\"$id\" id='$id' $attributes>";
1502 foreach (array_keys($values) as $v) {
1504 $sel = 'selected="selected"';
1508 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1514 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1517 if ($filters["title"]) {
1518 foreach ($filters["title"] as $filter) {
1519 $reg_exp = $filter["reg_exp"];
1520 $inverse = $filter["inverse"];
1521 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1522 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1524 array_push($matches, array($filter["action"], $filter["action_param"]));
1529 if ($filters["content"]) {
1530 foreach ($filters["content"] as $filter) {
1531 $reg_exp = $filter["reg_exp"];
1532 $inverse = $filter["inverse"];
1534 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1535 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1537 array_push($matches, array($filter["action"], $filter["action_param"]));
1542 if ($filters["both"]) {
1543 foreach ($filters["both"] as $filter) {
1544 $reg_exp = $filter["reg_exp"];
1545 $inverse = $filter["inverse"];
1548 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1549 array_push($matches, array($filter["action"], $filter["action_param"]));
1552 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1553 array_push($matches, array($filter["action"], $filter["action_param"]));
1559 if ($filters["link"]) {
1560 $reg_exp = $filter["reg_exp"];
1561 foreach ($filters["link"] as $filter) {
1562 $reg_exp = $filter["reg_exp"];
1563 $inverse = $filter["inverse"];
1565 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1566 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1568 array_push($matches, array($filter["action"], $filter["action_param"]));
1573 if ($filters["date"]) {
1574 $reg_exp = $filter["reg_exp"];
1575 foreach ($filters["date"] as $filter) {
1576 $date_modifier = $filter["filter_param"];
1577 $inverse = $filter["inverse"];
1578 $check_timestamp = strtotime($filter["reg_exp"]);
1580 # no-op when timestamp doesn't parse to prevent misfires
1582 if ($check_timestamp) {
1585 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1586 $date_modifier == "after" && $timestamp > $check_timestamp) {
1590 if ($inverse) $match_ok = !$match_ok;
1593 array_push($matches, array($filter["action"], $filter["action_param"]));
1599 if ($filters["author"]) {
1600 foreach ($filters["author"] as $filter) {
1601 $reg_exp = $filter["reg_exp"];
1602 $inverse = $filter["inverse"];
1603 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1604 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1606 array_push($matches, array($filter["action"], $filter["action_param"]));
1611 if ($filters["tag"]) {
1613 $tag_string = join(",", $tags);
1615 foreach ($filters["tag"] as $filter) {
1616 $reg_exp = $filter["reg_exp"];
1617 $inverse = $filter["inverse"];
1619 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1620 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1622 array_push($matches, array($filter["action"], $filter["action_param"]));
1631 function find_article_filter($filters, $filter_name) {
1632 foreach ($filters as $f) {
1633 if ($f[0] == $filter_name) {
1640 function calculate_article_score($filters) {
1643 foreach ($filters as $f) {
1644 if ($f[0] == "score") {
1651 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1652 foreach ($filters as $f) {
1653 if ($f[0] == "label") {
1654 label_add_article($link, $id, $f[1], $owner_uid);
1659 function getmicrotime() {
1660 list($usec, $sec) = explode(" ",microtime());
1661 return ((float)$usec +
(float)$sec);
1664 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1665 foreach ($values as $v) {
1672 if ($v == $true_is) {
1673 $sel .= " value=\"1\"";
1675 $sel .= " value=\"0\"";
1678 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1679 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1684 function initialize_user_prefs($link, $uid, $profile = false) {
1686 $uid = db_escape_string($uid);
1690 $profile_qpart = "AND profile IS NULL";
1692 $profile_qpart = "AND profile = '$profile'";
1695 if (get_schema_version($link) < 63) $profile_qpart = "";
1697 db_query($link, "BEGIN");
1699 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1701 $u_result = db_query($link, "SELECT pref_name
1702 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1704 $active_prefs = array();
1706 while ($line = db_fetch_assoc($u_result)) {
1707 array_push($active_prefs, $line["pref_name"]);
1710 while ($line = db_fetch_assoc($result)) {
1711 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1712 // print "adding " . $line["pref_name"] . "<br>";
1714 if (get_schema_version($link) < 63) {
1715 db_query($link, "INSERT INTO ttrss_user_prefs
1716 (owner_uid,pref_name,value) VALUES
1717 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1720 db_query($link, "INSERT INTO ttrss_user_prefs
1721 (owner_uid,pref_name,value, profile) VALUES
1722 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1728 db_query($link, "COMMIT");
1732 function lookup_user_id($link, $user) {
1734 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1737 if (db_num_rows($result) == 1) {
1738 return db_fetch_result($result, 0, "id");
1744 function http_authenticate_user($link) {
1746 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1748 if (!$_SERVER["PHP_AUTH_USER"]) {
1750 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1751 header('HTTP/1.0 401 Unauthorized');
1755 $auth_result = authenticate_user($link,
1756 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1758 if (!$auth_result) {
1759 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1760 header('HTTP/1.0 401 Unauthorized');
1768 function authenticate_user($link, $login, $password, $force_auth = false) {
1770 if (!SINGLE_USER_MODE
) {
1772 $pwd_hash1 = encrypt_password($password);
1773 $pwd_hash2 = encrypt_password($password, $login);
1774 $login = db_escape_string($login);
1776 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1777 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1779 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1781 $query = "SELECT id,login,access_level,pwd_hash
1782 FROM ttrss_users WHERE
1786 $query = "SELECT id,login,access_level,pwd_hash
1787 FROM ttrss_users WHERE
1788 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1789 pwd_hash = '$pwd_hash2')";
1792 $result = db_query($link, $query);
1794 if (db_num_rows($result) == 1) {
1795 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1796 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1797 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1799 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1802 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1803 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1805 $_SESSION["last_version_check"] = time();
1807 initialize_user_prefs($link, $_SESSION["uid"]);
1816 $_SESSION["uid"] = 1;
1817 $_SESSION["name"] = "admin";
1819 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1821 initialize_user_prefs($link, $_SESSION["uid"]);
1827 function make_password($length = 8) {
1830 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1834 while ($i < $length) {
1835 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1837 if (!strstr($password, $char)) {
1845 // this is called after user is created to initialize default feeds, labels
1848 // user preferences are checked on every login, not here
1850 function initialize_user($link, $uid) {
1852 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1853 values ('$uid', 'Tiny Tiny RSS: New Releases',
1854 'http://tt-rss.org/releases.rss')");
1856 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1857 values ('$uid', 'Tiny Tiny RSS: Forum',
1858 'http://tt-rss.org/forum/rss.php')");
1861 function logout_user() {
1863 if (isset($_COOKIE[session_name()])) {
1864 setcookie(session_name(), '', time()-42000, '/');
1868 function get_script_urlpath() {
1869 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1872 function validate_session($link) {
1873 if (SINGLE_USER_MODE
) return true;
1875 $check_ip = $_SESSION['ip_address'];
1877 switch (SESSION_CHECK_ADDRESS
) {
1882 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1885 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1886 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1890 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
1891 $_SESSION["login_error_msg"] =
1892 __("Session failed to validate (incorrect IP)");
1896 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
1899 if ($_SESSION["uid"]) {
1901 $result = db_query($link,
1902 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1904 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1906 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1911 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1913 //print_r($_SESSION);
1915 if (time() > $_SESSION["cookie_lifetime"]) {
1923 function login_sequence($link, $mobile = false) {
1924 if (!SINGLE_USER_MODE
) {
1926 $login_action = $_POST["login_action"];
1928 # try to authenticate user if called from login form
1929 if ($login_action == "do_login") {
1930 $login = $_POST["login"];
1931 $password = $_POST["password"];
1932 $remember_me = $_POST["remember_me"];
1934 if (authenticate_user($link, $login, $password)) {
1935 $_POST["password"] = "";
1937 $_SESSION["language"] = $_POST["language"];
1938 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1939 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1941 if ($_POST["profile"]) {
1943 $profile = db_escape_string($_POST["profile"]);
1945 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
1946 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
1948 if (db_num_rows($result) != 0) {
1949 $_SESSION["profile"] = $profile;
1950 $_SESSION["prefs_cache"] = array();
1954 if ($_REQUEST['return']) {
1955 header("Location: " . $_REQUEST['return']);
1957 header("Location: " . $_SERVER["REQUEST_URI"]);
1964 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1968 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1969 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1970 && $_SERVER["REMOTE_USER"] && defined('AUTO_LOGIN') && AUTO_LOGIN
) {
1971 authenticate_user($link,$_SERVER['REMOTE_USER'],null);
1972 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1974 render_login_form($link, $mobile);
1975 //header("Location: login.php");
1979 /* bump login timestamp */
1980 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1983 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1984 setcookie("ttrss_lang", $_SESSION["language"],
1985 time() + SESSION_COOKIE_LIFETIME
);
1990 return authenticate_user($link, "admin", null);
1994 function truncate_string($str, $max_len, $suffix = '…') {
1995 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1996 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2002 function theme_image($link, $filename) {
2004 $theme_path = get_user_theme_path($link);
2006 if ($theme_path && is_file($theme_path.$filename)) {
2007 return $theme_path.$filename;
2016 function get_user_theme($link) {
2018 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2019 $theme_name = get_pref($link, "_THEME_ID");
2020 if (is_dir("themes/$theme_name")) {
2031 function get_user_theme_path($link) {
2034 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2035 $theme_name = get_pref($link, "_THEME_ID");
2037 if ($theme_name && is_dir("themes/$theme_name")) {
2038 $theme_path = "themes/$theme_name/";
2047 if (is_file("$theme_path/theme.ini")) {
2048 $ini = parse_ini_file("$theme_path/theme.ini", true);
2049 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2057 function get_user_theme_options($link) {
2058 $t = get_user_theme_path($link);
2061 if (is_file("$t/theme.ini")) {
2062 $ini = parse_ini_file("$t/theme.ini", true);
2063 if ($ini['theme']['version']) {
2064 return $ini['theme']['options'];
2071 function print_theme_includes($link) {
2073 $t = get_user_theme_path($link);
2077 print "<link rel=\"stylesheet\" type=\"text/css\"
2078 href=\"$t/theme.css?$time \">";
2079 if (file_exists("$t/theme.js")) {
2080 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2086 function get_all_themes() {
2087 $themes = glob("themes/*");
2093 foreach ($themes as $t) {
2094 if (is_file("$t/theme.ini")) {
2095 $ini = parse_ini_file("$t/theme.ini", true);
2096 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2097 !$ini['theme']['disabled']) {
2099 $entry["path"] = $t;
2100 $entry["base"] = basename($t);
2101 $entry["name"] = $ini['theme']['name'];
2102 $entry["version"] = $ini['theme']['version'];
2103 $entry["author"] = $ini['theme']['author'];
2104 $entry["options"] = $ini['theme']['options'];
2105 array_push($rv, $entry);
2113 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2116 $source_tz = new DateTimeZone($source_tz);
2117 } catch (Exception
$e) {
2118 $source_tz = new DateTimeZone('UTC');
2122 $dest_tz = new DateTimeZone($dest_tz);
2123 } catch (Exception
$e) {
2124 $dest_tz = new DateTimeZone('UTC');
2127 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2128 return $dt->format('U') +
$dest_tz->getOffset($dt);
2131 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2132 $no_smart_dt = false) {
2134 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2135 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2137 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2140 $user_tz = new DateTimeZone($user_tz_string);
2141 } catch (Exception
$e) {
2142 $user_tz = new DateTimeZone('UTC');
2145 # We store date in UTC internally
2146 $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
2147 $user_timestamp = $dt->format('U') +
$user_tz->getOffset($dt);
2149 if (!$no_smart_dt && get_pref($link, 'HEADLINES_SMART_DATE', $owner_uid)) {
2150 return smart_date_time($link, $user_timestamp,
2151 $user_tz->getOffset($dt), $owner_uid);
2154 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2156 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2158 return date($format, $user_timestamp);
2162 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2163 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2165 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2166 return date("G:i", $timestamp);
2167 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2168 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2169 return date($format, $timestamp);
2171 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2172 return date($format, $timestamp);
2176 function smart_date($timestamp) {
2177 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2179 } else if (date("Y", $timestamp) == date("Y")) {
2180 return date("D m", $timestamp);
2182 return date("Y/m/d", $timestamp);
2186 function sql_bool_to_string($s) {
2187 if ($s == "t" ||
$s == "1") {
2194 function sql_bool_to_bool($s) {
2195 if ($s == "t" ||
$s == "1") {
2202 function bool_to_sql_bool($s) {
2210 function toggleEvenOdd($a) {
2217 function get_schema_version($link, $nocache = false) {
2218 if (!$_SESSION["schema_version"] ||
$nocache) {
2219 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2220 $version = db_fetch_result($result, 0, "schema_version");
2221 $_SESSION["schema_version"] = $version;
2224 return $_SESSION["schema_version"];
2228 function sanity_check($link) {
2231 $schema_version = get_schema_version($link);
2233 if ($schema_version != SCHEMA_VERSION
) {
2237 if (DB_TYPE
== "mysql") {
2238 $result = db_query($link, "SELECT true", false);
2239 if (db_num_rows($result) != 1) {
2244 if (db_escape_string("testTEST") != "testTEST") {
2248 if ($error_code != 0) {
2249 print_error_xml($error_code);
2256 function file_is_locked($filename) {
2257 if (function_exists('flock')) {
2258 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2260 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2261 flock($fp, LOCK_UN
);
2271 return true; // consider the file always locked and skip the test
2274 function make_lockfile($filename) {
2275 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2277 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2278 if (function_exists('posix_getpid')) {
2279 fwrite($fp, posix_getpid() . "\n");
2287 function make_stampfile($filename) {
2288 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2290 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2291 fwrite($fp, time() . "\n");
2292 flock($fp, LOCK_UN
);
2300 function sql_random_function() {
2301 if (DB_TYPE
== "mysql") {
2308 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2310 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2312 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2319 $cat_qpart = "cat_id = '$feed'";
2321 $cat_qpart = "cat_id IS NULL";
2324 $tmp_result = db_query($link, "SELECT id
2325 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2327 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2329 $tmp_feed = $tmp_line["id"];
2331 db_query($link, "UPDATE ttrss_user_entries
2332 SET unread = false,last_read = NOW()
2333 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2335 } else if ($feed == -2) {
2338 db_query($link, "UPDATE ttrss_user_entries
2339 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2340 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2341 AND unread = true AND owner_uid = $owner_uid");
2344 } else if ($feed > 0) {
2346 db_query($link, "UPDATE ttrss_user_entries
2347 SET unread = false,last_read = NOW()
2348 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2350 } else if ($feed < 0 && $feed > -10) { // special, like starred
2353 db_query($link, "UPDATE ttrss_user_entries
2354 SET unread = false,last_read = NOW()
2355 WHERE marked = true AND owner_uid = $owner_uid");
2359 db_query($link, "UPDATE ttrss_user_entries
2360 SET unread = false,last_read = NOW()
2361 WHERE published = true AND owner_uid = $owner_uid");
2366 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2368 if (DB_TYPE
== "pgsql") {
2369 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2371 $match_part = "updated > DATE_SUB(NOW(),
2372 INTERVAL $intl HOUR) ";
2375 $result = db_query($link, "SELECT id FROM ttrss_entries,
2376 ttrss_user_entries WHERE $match_part AND
2378 ttrss_user_entries.ref_id = ttrss_entries.id AND
2379 owner_uid = $owner_uid");
2381 $affected_ids = array();
2383 while ($line = db_fetch_assoc($result)) {
2384 array_push($affected_ids, $line["id"]);
2387 catchupArticlesById($link, $affected_ids, 0);
2391 db_query($link, "UPDATE ttrss_user_entries
2392 SET unread = false,last_read = NOW()
2393 WHERE owner_uid = $owner_uid");
2396 } else if ($feed < -10) { // label
2398 $label_id = -$feed - 11;
2400 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2401 SET unread = false, last_read = NOW()
2402 WHERE label_id = '$label_id' AND unread = true
2403 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2407 ccache_update($link, $feed, $owner_uid, $cat_view);
2410 db_query($link, "BEGIN");
2412 $tag_name = db_escape_string($feed);
2414 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2415 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2417 while ($line = db_fetch_assoc($result)) {
2418 db_query($link, "UPDATE ttrss_user_entries SET
2419 unread = false, last_read = NOW()
2420 WHERE int_id = " . $line["post_int_id"]);
2422 db_query($link, "COMMIT");
2426 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2428 if (!$omode) $omode = "flc";
2430 $data = getGlobalCounters($link);
2432 $data = array_merge($data, getVirtCounters($link));
2434 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2435 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2436 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2437 if (strchr($omode, "c")) {
2438 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2439 $data = array_merge($data, getCategoryCounters($link));
2446 function getCategoryCounters($link) {
2449 /* Labels category */
2451 $cv = array("id" => -2, "kind" => "cat",
2452 "counter" => getCategoryUnread($link, -2));
2454 array_push($ret_arr, $cv);
2456 $age_qpart = getMaxAgeSubquery();
2458 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2459 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2460 WHERE ttrss_cat_counters_cache.feed_id = id AND
2461 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2463 while ($line = db_fetch_assoc($result)) {
2464 $line["cat_id"] = (int) $line["cat_id"];
2466 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2467 "counter" => $line["unread"]);
2469 array_push($ret_arr, $cv);
2472 /* Special case: NULL category doesn't actually exist in the DB */
2474 $cv = array("id" => 0, "kind" => "cat",
2475 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2477 array_push($ret_arr, $cv);
2482 function getCategoryUnread($link, $cat, $owner_uid = false) {
2484 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2489 $cat_query = "cat_id = '$cat'";
2491 $cat_query = "cat_id IS NULL";
2494 $age_qpart = getMaxAgeSubquery();
2496 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2497 AND owner_uid = " . $owner_uid);
2499 $cat_feeds = array();
2500 while ($line = db_fetch_assoc($result)) {
2501 array_push($cat_feeds, "feed_id = " . $line["id"]);
2504 if (count($cat_feeds) == 0) return 0;
2506 $match_part = implode(" OR ", $cat_feeds);
2508 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2509 FROM ttrss_user_entries,ttrss_entries
2510 WHERE unread = true AND ($match_part) AND id = ref_id
2511 AND $age_qpart AND owner_uid = " . $owner_uid);
2515 # this needs to be rewritten
2516 while ($line = db_fetch_assoc($result)) {
2517 $unread +
= $line["unread"];
2521 } else if ($cat == -1) {
2522 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2523 } else if ($cat == -2) {
2525 $result = db_query($link, "
2526 SELECT COUNT(unread) AS unread FROM
2527 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2528 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2529 ttrss_labels2.owner_uid = '$owner_uid'
2530 AND unread = true AND feed_id = ttrss_feeds.id
2531 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2533 $unread = db_fetch_result($result, 0, "unread");
2540 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2541 if (DB_TYPE
== "pgsql") {
2542 return "ttrss_entries.date_updated >
2543 NOW() - INTERVAL '$days days'";
2545 return "ttrss_entries.date_updated >
2546 DATE_SUB(NOW(), INTERVAL $days DAY)";
2550 function getFeedUnread($link, $feed, $is_cat = false) {
2551 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2554 function getLabelUnread($link, $label_id, $owner_uid = false) {
2555 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2557 $result = db_query($link, "
2558 SELECT COUNT(unread) AS unread FROM
2559 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2560 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2561 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2562 AND unread = true AND feed_id = ttrss_feeds.id
2563 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2565 if (db_num_rows($result) != 0) {
2566 return db_fetch_result($result, 0, "unread");
2572 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2573 $owner_uid = false) {
2575 $n_feed = (int) $feed;
2577 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2580 $unread_qpart = "unread = true";
2582 $unread_qpart = "true";
2585 $age_qpart = getMaxAgeSubquery();
2588 return getCategoryUnread($link, $n_feed, $owner_uid);
2589 } if ($feed != "0" && $n_feed == 0) {
2591 $feed = db_escape_string($feed);
2593 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2594 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2595 AND ref_id = id AND $age_qpart
2596 AND $unread_qpart)) AS count FROM ttrss_tags
2597 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2598 return db_fetch_result($result, 0, "count");
2600 } else if ($n_feed == -1) {
2601 $match_part = "marked = true";
2602 } else if ($n_feed == -2) {
2603 $match_part = "published = true";
2604 } else if ($n_feed == -3) {
2605 $match_part = "unread = true AND score >= 0";
2607 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2609 if (DB_TYPE
== "pgsql") {
2610 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2612 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2614 } else if ($n_feed == -4) {
2615 $match_part = "true";
2616 } else if ($n_feed >= 0) {
2619 $match_part = "feed_id = '$n_feed'";
2621 $match_part = "feed_id IS NULL";
2624 } else if ($feed < -10) {
2626 $label_id = -$feed - 11;
2628 return getLabelUnread($link, $label_id, $owner_uid);
2635 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2636 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2638 $from_qpart = "ttrss_user_entries,ttrss_entries";
2642 $query = "SELECT count(int_id) AS unread
2643 FROM $from_qpart WHERE
2644 ttrss_user_entries.ref_id = ttrss_entries.id AND
2647 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2649 $result = db_query($link, $query);
2653 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2654 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2655 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2656 AND $unread_qpart AND $age_qpart AND
2657 ttrss_tags.owner_uid = " . $owner_uid);
2660 $unread = db_fetch_result($result, 0, "unread");
2665 function getGlobalUnread($link, $user_id = false) {
2668 $user_id = $_SESSION["uid"];
2671 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2672 WHERE owner_uid = '$user_id' AND feed_id > 0");
2674 $c_id = db_fetch_result($result, 0, "c_id");
2679 function getGlobalCounters($link, $global_unread = -1) {
2682 if ($global_unread == -1) {
2683 $global_unread = getGlobalUnread($link);
2686 $cv = array("id" => "global-unread",
2687 "counter" => $global_unread);
2689 array_push($ret_arr, $cv);
2691 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2692 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2694 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2696 $cv = array("id" => "subscribed-feeds",
2697 "counter" => $subscribed_feeds);
2699 array_push($ret_arr, $cv);
2704 function getSubscribedFeeds($link) {
2705 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2706 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2708 return db_fetch_result($result, 0, "fn");
2711 function getTagCounters($link) {
2715 $age_qpart = getMaxAgeSubquery();
2717 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2718 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2719 AND ref_id = id AND $age_qpart
2720 AND unread = true)) AS count FROM ttrss_tags
2721 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2722 ORDER BY count DESC LIMIT 55");
2726 while ($line = db_fetch_assoc($result)) {
2727 $tags[$line["tag_name"]] +
= $line["count"];
2730 foreach (array_keys($tags) as $tag) {
2731 $unread = $tags[$tag];
2732 $tag = htmlspecialchars($tag);
2734 $cv = array("id" => $tag,
2736 "counter" => $unread);
2738 array_push($ret_arr, $cv);
2744 function getVirtCounters($link) {
2748 for ($i = 0; $i >= -4; $i--) {
2750 $count = getFeedUnread($link, $i);
2752 $cv = array("id" => $i,
2753 "counter" => $count);
2755 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2756 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2758 array_push($ret_arr, $cv);
2764 function getLabelCounters($link, $descriptions = false) {
2768 $age_qpart = getMaxAgeSubquery();
2770 $owner_uid = $_SESSION["uid"];
2772 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2773 WHERE owner_uid = '$owner_uid'");
2775 while ($line = db_fetch_assoc($result)) {
2777 $id = -$line["id"] - 11;
2779 $label_name = $line["caption"];
2780 $count = getFeedUnread($link, $id);
2782 $cv = array("id" => $id,
2783 "counter" => $count);
2786 $cv["description"] = $label_name;
2788 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2789 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2791 array_push($ret_arr, $cv);
2797 function getFeedCounters($link, $active_feed = false) {
2801 $age_qpart = getMaxAgeSubquery();
2803 $query = "SELECT ttrss_feeds.id,
2805 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2806 last_error, value AS count
2807 FROM ttrss_feeds, ttrss_counters_cache
2808 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2809 AND ttrss_counters_cache.feed_id = id";
2811 $result = db_query($link, $query);
2812 $fctrs_modified = false;
2814 while ($line = db_fetch_assoc($result)) {
2817 $count = $line["count"];
2818 $last_error = htmlspecialchars($line["last_error"]);
2820 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2822 $has_img = feed_has_icon($id);
2824 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2827 $cv = array("id" => $id,
2828 "updated" => $last_updated,
2829 "counter" => $count,
2830 "has_img" => (int) $has_img);
2833 $cv["error"] = $last_error;
2835 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2836 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2838 if ($active_feed && $id == $active_feed)
2839 $cv["title"] = truncate_string($line["title"], 30);
2841 array_push($ret_arr, $cv);
2848 function get_pgsql_version($link) {
2849 $result = db_query($link, "SELECT version() AS version");
2850 $version = split(" ", db_fetch_result($result, 0, "version"));
2854 function print_error_xml($code, $add_msg = "") {
2857 $error_msg = $ERRORS[$code];
2860 $error_msg = "$error_msg; $add_msg";
2863 print "<rpc-reply>";
2864 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2865 print "</rpc-reply>";
2869 * Subscribes the user to the given feed
2871 * @param resource $link Database connection
2872 * @param string $url Feed URL to subscribe to
2873 * @param integer $cat_id Category ID the feed shall be added to
2874 * @param string $auth_login (optional) Feed username
2875 * @param string $auth_pass (optional) Feed password
2877 * @return integer Status code:
2878 * 0 - OK, Feed already exists
2879 * 1 - OK, Feed added
2881 * 3 - URL content is HTML, no feeds available
2882 * 4 - URL content is HTML which contains multiple feeds.
2883 * Here you should call extractfeedurls in rpc-backend
2884 * to get all possible feeds.
2885 * 5 - Couldn't download the URL content.
2887 function subscribe_to_feed($link, $url, $cat_id = 0,
2888 $auth_login = '', $auth_pass = '') {
2890 $url = fix_url($url);
2892 if (!$url ||
!validate_feed_url($url)) return 2;
2896 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
2897 WHERE id = ".$_SESSION['uid']);
2899 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2901 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
2902 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
2904 if (url_is_html($url, $auth_login, $auth_pass)) {
2905 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
2906 if (count($feedUrls) == 0) {
2908 } else if (count($feedUrls) > 1) {
2911 //use feed url as new URL
2912 $url = key($feedUrls);
2916 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
2921 if ($cat_id == "0" ||
!$cat_id) {
2922 $cat_qpart = "NULL";
2924 $cat_qpart = "'$cat_id'";
2927 $result = db_query($link,
2928 "SELECT id FROM ttrss_feeds
2929 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2931 if (db_num_rows($result) == 0) {
2932 $result = db_query($link,
2933 "INSERT INTO ttrss_feeds
2934 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2935 VALUES ('".$_SESSION["uid"]."', '$url',
2936 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
2938 $result = db_query($link,
2939 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2940 AND owner_uid = " . $_SESSION["uid"]);
2942 $feed_id = db_fetch_result($result, 0, "id");
2945 update_rss_feed($link, $feed_id, true);
2954 function print_feed_select($link, $id, $default_id = "",
2955 $attributes = "", $include_all_feeds = true) {
2957 print "<select id=\"$id\" name=\"$id\" $attributes>";
2958 if ($include_all_feeds) {
2959 print "<option value=\"0\">".__('All feeds')."</option>";
2962 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2963 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2965 if (db_num_rows($result) > 0 && $include_all_feeds) {
2966 print "<option disabled>--------</option>";
2969 while ($line = db_fetch_assoc($result)) {
2970 if ($line["id"] == $default_id) {
2971 $is_selected = "selected=\"1\"";
2976 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2978 printf("<option $is_selected value='%d'>%s</option>",
2979 $line["id"], $title);
2985 function print_feed_cat_select($link, $id, $default_id = "",
2986 $attributes = "", $include_all_cats = true) {
2988 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
2990 if ($include_all_cats) {
2991 print "<option value=\"0\">".__('Uncategorized')."</option>";
2994 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2995 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2997 if (db_num_rows($result) > 0 && $include_all_cats) {
2998 print "<option disabled=\"1\">--------</option>";
3001 while ($line = db_fetch_assoc($result)) {
3002 if ($line["id"] == $default_id) {
3003 $is_selected = "selected=\"1\"";
3009 printf("<option $is_selected value='%d'>%s</option>",
3010 $line["id"], htmlspecialchars($line["title"]));
3013 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3018 function checkbox_to_sql_bool($val) {
3019 return ($val == "on") ?
"true" : "false";
3022 function getFeedCatTitle($link, $id) {
3024 return __("Special");
3025 } else if ($id < -10) {
3026 return __("Labels");
3027 } else if ($id > 0) {
3028 $result = db_query($link, "SELECT ttrss_feed_categories.title
3029 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3030 cat_id = ttrss_feed_categories.id");
3031 if (db_num_rows($result) == 1) {
3032 return db_fetch_result($result, 0, "title");
3034 return __("Uncategorized");
3037 return "getFeedCatTitle($id) failed";
3042 function getFeedIcon($id) {
3045 return "images/archive.png";
3048 return "images/mark_set.png";
3051 return "images/pub_set.png";
3054 return "images/fresh.png";
3057 return "images/tag.png";
3061 return "images/label.png";
3063 if (file_exists(ICONS_DIR
. "/$id.ico"))
3064 return ICONS_URL
. "/$id.ico";
3070 function getFeedTitle($link, $id) {
3072 return __("Starred articles");
3073 } else if ($id == -2) {
3074 return __("Published articles");
3075 } else if ($id == -3) {
3076 return __("Fresh articles");
3077 } else if ($id == -4) {
3078 return __("All articles");
3079 } else if ($id === 0 ||
$id === "0") {
3080 return __("Archived articles");
3081 } else if ($id < -10) {
3082 $label_id = -$id - 11;
3083 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3084 if (db_num_rows($result) == 1) {
3085 return db_fetch_result($result, 0, "caption");
3087 return "Unknown label ($label_id)";
3090 } else if ($id > 0) {
3091 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3092 if (db_num_rows($result) == 1) {
3093 return db_fetch_result($result, 0, "title");
3095 return "Unknown feed ($id)";
3102 function get_session_cookie_name() {
3103 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3106 function make_init_params($link) {
3109 $params["theme"] = get_user_theme($link);
3110 $params["theme_options"] = get_user_theme_options($link);
3111 $params["daemon_enabled"] = ENABLE_UPDATE_DAEMON
;
3113 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3114 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3115 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3116 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3118 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3119 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3120 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3121 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3123 $params[strtolower($param)] = (int) get_pref($link, $param);
3126 $params["icons_url"] = ICONS_URL
;
3127 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3128 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3129 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3130 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3131 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3133 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3134 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3136 $max_feed_id = db_fetch_result($result, 0, "mid");
3137 $num_feeds = db_fetch_result($result, 0, "nf");
3139 $params["max_feed_id"] = (int) $max_feed_id;
3140 $params["num_feeds"] = (int) $num_feeds;
3142 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3147 function print_runtime_info($link) {
3148 print "<runtime-info><![CDATA[";
3149 print json_encode(make_runtime_info($link));
3150 print "]]></runtime-info>";
3153 function make_runtime_info($link) {
3156 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3157 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3159 $max_feed_id = db_fetch_result($result, 0, "mid");
3160 $num_feeds = db_fetch_result($result, 0, "nf");
3162 $data["max_feed_id"] = (int) $max_feed_id;
3163 $data["num_feeds"] = (int) $num_feeds;
3165 $data['last_article_id'] = getLastArticleId($link);
3166 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3168 if (ENABLE_UPDATE_DAEMON
) {
3170 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3172 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3174 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3177 $stamp_delta = time() - $stamp;
3179 if ($stamp_delta > 1800) {
3183 $_SESSION["daemon_stamp_check"] = time();
3186 $data['daemon_stamp_ok'] = $stamp_check;
3188 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3190 $data['daemon_stamp'] = $stamp_fmt;
3195 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3196 $new_version_details = @check_for_update
($link);
3198 $data['new_version_available'] = (int) ($new_version_details != false);
3200 $_SESSION["last_version_check"] = time();
3206 function getSearchSql($link, $search, $match_on) {
3208 $search_query_part = "";
3210 $keywords = split(" ", $search);
3211 $query_keywords = array();
3213 foreach ($keywords as $k) {
3214 if (strpos($k, "-") === 0) {
3221 if (strpos($k, "@") === 0) {
3223 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3224 $orig_ts = strtotime(substr($k, 1));
3226 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3228 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3229 } else if ($match_on == "both") {
3230 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3231 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3232 } else if ($match_on == "title") {
3233 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3234 } else if ($match_on == "content") {
3235 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3239 $search_query_part = implode("AND", $query_keywords);
3241 return $search_query_part;
3244 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3246 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3248 $ext_tables_part = "";
3252 if (SPHINX_ENABLED
) {
3253 $ids = join(",", @sphinx_search
($search, 0, 500));
3256 $search_query_part = "ref_id IN ($ids) AND ";
3258 $search_query_part = "ref_id = -1 AND ";
3261 $search_query_part = getSearchSql($link, $search, $match_on);
3262 $search_query_part .= " AND ";
3266 $search_query_part = "";
3269 $view_query_part = "";
3271 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3273 $view_query_part = " ";
3274 } else if ($feed != -1) {
3275 $unread = getFeedUnread($link, $feed, $cat_view);
3277 $view_query_part = " unread = true AND ";
3282 if ($view_mode == "marked") {
3283 $view_query_part = " marked = true AND ";
3286 if ($view_mode == "published") {
3287 $view_query_part = " published = true AND ";
3290 if ($view_mode == "unread") {
3291 $view_query_part = " unread = true AND ";
3294 if ($view_mode == "updated") {
3295 $view_query_part = " (last_read is null and unread = false) AND ";
3299 $limit_query_part = "LIMIT " . $limit;
3302 $vfeed_query_part = "";
3304 // override query strategy and enable feed display when searching globally
3305 if ($search && $search_mode == "all_feeds") {
3306 $query_strategy_part = "ttrss_entries.id > 0";
3307 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3309 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3310 $query_strategy_part = "ttrss_entries.id > 0";
3311 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3312 id = feed_id) as feed_title,";
3313 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3315 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3317 $tmp_result = false;
3320 $tmp_result = db_query($link, "SELECT id
3321 FROM ttrss_feeds WHERE cat_id = '$feed'");
3323 $tmp_result = db_query($link, "SELECT id
3324 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3325 WHERE id = '$feed') AND id != '$feed'");
3328 $cat_siblings = array();
3330 if (db_num_rows($tmp_result) > 0) {
3331 while ($p = db_fetch_assoc($tmp_result)) {
3332 array_push($cat_siblings, "feed_id = " . $p["id"]);
3335 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3336 $feed, implode(" OR ", $cat_siblings));
3339 $query_strategy_part = "ttrss_entries.id > 0";
3342 } else if ($feed > 0) {
3347 $query_strategy_part = "cat_id = '$feed'";
3349 $query_strategy_part = "cat_id IS NULL";
3352 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3355 $query_strategy_part = "feed_id = '$feed'";
3357 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3358 $query_strategy_part = "feed_id IS NULL";
3359 } else if ($feed == 0 && $cat_view) { // uncategorized
3360 $query_strategy_part = "cat_id IS NULL";
3361 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3362 } else if ($feed == -1) { // starred virtual feed
3363 $query_strategy_part = "marked = true";
3364 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3365 } else if ($feed == -2) { // published virtual feed OR labels category
3368 $query_strategy_part = "published = true";
3369 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3371 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3373 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3375 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3376 ttrss_user_labels2.article_id = ref_id";
3380 } else if ($feed == -3) { // fresh virtual feed
3381 $query_strategy_part = "unread = true AND score >= 0";
3383 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3385 if (DB_TYPE
== "pgsql") {
3386 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3388 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3391 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3392 } else if ($feed == -4) { // all articles virtual feed
3393 $query_strategy_part = "true";
3394 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3395 } else if ($feed <= -10) { // labels
3396 $label_id = -$feed - 11;
3398 $query_strategy_part = "label_id = '$label_id' AND
3399 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3400 ttrss_user_labels2.article_id = ref_id";
3402 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3403 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3406 $query_strategy_part = "id > 0"; // dumb
3409 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3410 $date_sort_field = "updated";
3412 $date_sort_field = "date_entered";
3415 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3416 $order_by = "$date_sort_field";
3418 $order_by = "$date_sort_field DESC";
3421 if ($view_mode != "noscores") {
3422 $order_by = "score DESC, $order_by";
3425 if ($override_order) {
3426 $order_by = $override_order;
3432 $feed_title = "Search results";
3435 $feed_title = getCategoryTitle($link, $feed);
3437 if ((int)$feed == $feed && $feed > 0) {
3438 $result = db_query($link, "SELECT title,site_url,last_error
3439 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3441 $feed_title = db_fetch_result($result, 0, "title");
3442 $feed_site_url = db_fetch_result($result, 0, "site_url");
3443 $last_error = db_fetch_result($result, 0, "last_error");
3445 $feed_title = getFeedTitle($link, $feed);
3450 $content_query_part = "content as content_preview,";
3452 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3455 $feed_kind = "Feeds";
3457 $feed_kind = "Labels";
3460 if ($limit_query_part) {
3461 $offset_query_part = "OFFSET $offset";
3464 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3465 if (!$override_order) {
3466 $order_by = "ttrss_feeds.title, $order_by";
3471 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3472 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3475 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3476 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3479 $query = "SELECT DISTINCT
3482 ttrss_entries.id,ttrss_entries.title,
3485 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3486 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3489 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3495 ttrss_user_entries.ref_id = ttrss_entries.id AND
3496 ttrss_user_entries.owner_uid = '$owner_uid' AND
3499 $query_strategy_part ORDER BY $order_by
3500 $limit_query_part $offset_query_part";
3502 if ($_REQUEST["debug"]) print $query;
3504 $result = db_query($link, $query);
3509 $feed_kind = "Tags";
3511 $result = db_query($link, "SELECT DISTINCT
3515 ttrss_entries.id as id,title,
3517 unread,feed_id,orig_feed_id,
3518 marked,link,last_read,
3519 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3522 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3525 ttrss_entries,ttrss_user_entries,ttrss_tags
3527 ref_id = ttrss_entries.id AND
3528 ttrss_user_entries.owner_uid = '$owner_uid' AND
3529 post_int_id = int_id AND tag_name = '$feed' AND
3532 $query_strategy_part ORDER BY $order_by
3533 $limit_query_part");
3536 return array($result, $feed_title, $feed_site_url, $last_error);
3540 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3541 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3543 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3544 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3545 "margin-bottom : 1em; color : #9a8c59;";
3547 if (!$limit) $limit = 30;
3549 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3550 $date_sort_field = "updated";
3552 $date_sort_field = "date_entered";
3555 $qfh_ret = queryFeedHeadlines($link, $feed,
3556 $limit, $view_mode, $is_cat, $search, $search_mode,
3557 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3559 $result = $qfh_ret[0];
3560 $feed_title = htmlspecialchars($qfh_ret[1]);
3561 $feed_site_url = $qfh_ret[2];
3562 $last_error = $qfh_ret[3];
3564 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3566 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3567 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3568 <rss version=\"2.0\">
3570 <title>$feed_title</title>
3571 <link>$feed_site_url</link>
3572 <description>Feed generated by Tiny Tiny RSS</description>";
3574 while ($line = db_fetch_assoc($result)) {
3576 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3577 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3579 $tags = get_article_tags($link, $line["id"], $owner_uid);
3581 foreach ($tags as $tag) {
3582 print "<category>" . htmlspecialchars($tag) . "</category>";
3585 $rfc822_date = date('r', strtotime($line["updated"]));
3587 print "<pubDate>$rfc822_date</pubDate>";
3589 if ($line["author"]) {
3590 print "<author>" . htmlspecialchars($line["author"]) . "</author>";
3593 print "<title><![CDATA[" .
3594 htmlspecialchars($line["title"]) . "]]></title>";
3596 print "<description><![CDATA[";
3598 if ($line["note"]) {
3599 print "<div style='$note_style'>";
3600 print $line["note"];
3604 print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3605 print "]]></description>";
3607 $enclosures = get_article_enclosures($link, $line["id"]);
3609 foreach ($enclosures as $e) {
3610 $type = htmlspecialchars($e['content_type']);
3611 $url = htmlspecialchars($e['content_url']);
3612 $length = $e['duration'];
3613 print "<enclosure url=\"$url\" type=\"$type\" length=\"$length\"/>";
3619 print "</channel></rss>";
3623 function getCategoryTitle($link, $cat_id) {
3625 if ($cat_id == -1) {
3626 return __("Special");
3627 } else if ($cat_id == -2) {
3628 return __("Labels");
3631 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3634 if (db_num_rows($result) == 1) {
3635 return db_fetch_result($result, 0, "title");
3637 return "Uncategorized";
3642 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3645 if (!$owner) $owner = $_SESSION["uid"];
3647 $res = trim($str); if (!$res) return '';
3649 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) ||
$force_strip_tags) {
3650 $res = $purifier->purify($res);
3653 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3654 $res = preg_replace('/<img[^>]+>/is', '', $res);
3657 if (strpos($res, "href=") === false)
3658 $res = rewrite_urls($res);
3660 $charset_hack = '<head>
3661 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3664 $res = trim($res); if (!$res) return '';
3666 libxml_use_internal_errors(true);
3668 $doc = new DOMDocument();
3669 $doc->loadHTML($charset_hack . $res);
3670 $xpath = new DOMXPath($doc);
3672 $entries = $xpath->query('(//a[@href]|//img[@src])');
3675 foreach ($entries as $entry) {
3679 if ($entry->hasAttribute('href'))
3680 $entry->setAttribute('href',
3681 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3683 if ($entry->hasAttribute('src'))
3684 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3685 $entry->setAttribute('src',
3686 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3689 if (strtolower($entry->nodeName
) == "a") {
3690 $entry->setAttribute("target", "_blank");
3693 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3694 $br = $doc->createElement("br");
3696 if ($entry->parentNode
->nextSibling
) {
3697 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3704 $node = $doc->getElementsByTagName('body')->item(0);
3706 return $doc->saveXML($node);
3710 * Send by mail a digest of last articles.
3712 * @param mixed $link The database connection.
3713 * @param integer $limit The maximum number of articles by digest.
3714 * @return boolean Return false if digests are not enabled.
3716 function send_headlines_digests($link, $limit = 100) {
3718 if (!DIGEST_ENABLE
) return false;
3720 $user_limit = DIGEST_EMAIL_LIMIT
;
3723 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3725 if (DB_TYPE
== "pgsql") {
3726 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3727 } else if (DB_TYPE
== "mysql") {
3728 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3731 $result = db_query($link, "SELECT id,email FROM ttrss_users
3732 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3734 while ($line = db_fetch_assoc($result)) {
3736 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3737 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3739 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3741 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3742 $digest = $tuple[0];
3743 $headlines_count = $tuple[1];
3744 $affected_ids = $tuple[2];
3745 $digest_text = $tuple[3];
3747 if ($headlines_count > 0) {
3749 $mail = new PHPMailer();
3751 $mail->PluginDir
= "lib/phpmailer/";
3752 $mail->SetLanguage("en", "lib/phpmailer/language/");
3754 $mail->CharSet
= "UTF-8";
3756 $mail->From
= DIGEST_FROM_ADDRESS
;
3757 $mail->FromName
= DIGEST_FROM_NAME
;
3758 $mail->AddAddress($line["email"], $line["login"]);
3760 if (DIGEST_SMTP_HOST
) {
3761 $mail->Host
= DIGEST_SMTP_HOST
;
3762 $mail->Mailer
= "smtp";
3763 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3764 $mail->Username
= DIGEST_SMTP_LOGIN
;
3765 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3768 $mail->IsHTML(true);
3769 $mail->Subject
= DIGEST_SUBJECT
;
3770 $mail->Body
= $digest;
3771 $mail->AltBody
= $digest_text;
3773 $rc = $mail->Send();
3775 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3779 if ($rc && $do_catchup) {
3780 print "Marking affected articles as read...\n";
3781 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3784 print "No headlines\n";
3787 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3788 WHERE id = " . $line["id"]);
3792 print "All done.\n";
3796 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3798 require_once "lib/MiniTemplator.class.php";
3800 $tpl = new MiniTemplator
;
3801 $tpl_t = new MiniTemplator
;
3803 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3804 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3806 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3807 $tpl->setVariable('CUR_TIME', date('G:i'));
3809 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3810 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3812 $affected_ids = array();
3814 if (DB_TYPE
== "pgsql") {
3815 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3816 } else if (DB_TYPE
== "mysql") {
3817 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3820 $result = db_query($link, "SELECT ttrss_entries.title,
3821 ttrss_feeds.title AS feed_title,
3823 ttrss_user_entries.ref_id,
3825 SUBSTRING(content, 1, 120) AS excerpt,
3826 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3828 ttrss_user_entries,ttrss_entries,ttrss_feeds
3830 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3831 AND include_in_digest = true
3833 AND ttrss_user_entries.owner_uid = $user_id
3835 ORDER BY ttrss_feeds.title, date_updated DESC
3838 $cur_feed_title = "";
3840 $headlines_count = db_num_rows($result);
3842 $headlines = array();
3844 while ($line = db_fetch_assoc($result)) {
3845 array_push($headlines, $line);
3848 for ($i = 0; $i < sizeof($headlines); $i++
) {
3850 $line = $headlines[$i];
3852 array_push($affected_ids, $line["ref_id"]);
3854 $updated = make_local_datetime($link, $line['last_updated'], false,
3857 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3858 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3859 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3860 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3861 $tpl->setVariable('ARTICLE_EXCERPT',
3862 truncate_string(strip_tags($line["excerpt"]), 100));
3864 $tpl->addBlock('article');
3866 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3867 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3868 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3869 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3870 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3871 // truncate_string(strip_tags($line["excerpt"]), 100));
3873 $tpl_t->addBlock('article');
3875 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3876 $tpl->addBlock('feed');
3877 $tpl_t->addBlock('feed');
3882 $tpl->addBlock('digest');
3883 $tpl->generateOutputToString($tmp);
3885 $tpl_t->addBlock('digest');
3886 $tpl_t->generateOutputToString($tmp_t);
3888 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3891 function check_for_update($link) {
3892 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
3893 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
3895 $version_data = @fetch_file_contents
($version_url);
3897 if ($version_data) {
3898 $version_data = json_decode($version_data, true);
3899 if ($version_data && $version_data['version']) {
3901 if (version_compare(VERSION
, $version_data['version']) == -1) {
3902 return $version_data;
3910 function markArticlesById($link, $ids, $cmode) {
3914 foreach ($ids as $id) {
3915 array_push($tmp_ids, "ref_id = '$id'");
3918 $ids_qpart = join(" OR ", $tmp_ids);
3921 db_query($link, "UPDATE ttrss_user_entries SET
3922 marked = false,last_read = NOW()
3923 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3924 } else if ($cmode == 1) {
3925 db_query($link, "UPDATE ttrss_user_entries SET
3927 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3929 db_query($link, "UPDATE ttrss_user_entries SET
3930 marked = NOT marked,last_read = NOW()
3931 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3935 function publishArticlesById($link, $ids, $cmode) {
3939 foreach ($ids as $id) {
3940 array_push($tmp_ids, "ref_id = '$id'");
3943 $ids_qpart = join(" OR ", $tmp_ids);
3946 db_query($link, "UPDATE ttrss_user_entries SET
3947 published = false,last_read = NOW()
3948 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3949 } else if ($cmode == 1) {
3950 db_query($link, "UPDATE ttrss_user_entries SET
3952 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3954 db_query($link, "UPDATE ttrss_user_entries SET
3955 published = NOT published,last_read = NOW()
3956 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3960 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3962 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3963 if (count($ids) == 0) return;
3967 foreach ($ids as $id) {
3968 array_push($tmp_ids, "ref_id = '$id'");
3971 $ids_qpart = join(" OR ", $tmp_ids);
3974 db_query($link, "UPDATE ttrss_user_entries SET
3975 unread = false,last_read = NOW()
3976 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3977 } else if ($cmode == 1) {
3978 db_query($link, "UPDATE ttrss_user_entries SET
3980 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3982 db_query($link, "UPDATE ttrss_user_entries SET
3983 unread = NOT unread,last_read = NOW()
3984 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3989 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3990 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3992 while ($line = db_fetch_assoc($result)) {
3993 ccache_update($link, $line["feed_id"], $owner_uid);
3997 function catchupArticleById($link, $id, $cmode) {
4000 db_query($link, "UPDATE ttrss_user_entries SET
4001 unread = false,last_read = NOW()
4002 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4003 } else if ($cmode == 1) {
4004 db_query($link, "UPDATE ttrss_user_entries SET
4006 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4008 db_query($link, "UPDATE ttrss_user_entries SET
4009 unread = NOT unread,last_read = NOW()
4010 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4013 $feed_id = getArticleFeed($link, $id);
4014 ccache_update($link, $feed_id, $_SESSION["uid"]);
4017 function make_guid_from_title($title) {
4018 return preg_replace("/[ \"\',.:;]/", "-",
4019 mb_strtolower(strip_tags($title), 'utf-8'));
4022 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4023 $feed_id, $is_cat, $search, $match_on,
4024 $search_mode, $view_mode, $error) {
4026 $page_prev_link = "viewFeedGoPage(-1)";
4027 $page_next_link = "viewFeedGoPage(1)";
4028 $page_first_link = "viewFeedGoPage(0)";
4030 $catchup_page_link = "catchupPage()";
4031 $catchup_feed_link = "catchupCurrentFeed()";
4032 $catchup_sel_link = "catchupSelection()";
4034 $archive_sel_link = "archiveSelection()";
4035 $delete_sel_link = "deleteSelection()";
4037 $sel_all_link = "selectArticles('all')";
4038 $sel_unread_link = "selectArticles('unread')";
4039 $sel_none_link = "selectArticles('none')";
4040 $sel_inv_link = "selectArticles('invert')";
4042 $tog_unread_link = "selectionToggleUnread()";
4043 $tog_marked_link = "selectionToggleMarked()";
4044 $tog_published_link = "selectionTogglePublished()";
4046 $reply = "<div id=\"subtoolbar_main\">";
4048 $reply .= __('Select:')."
4049 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4050 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4051 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4052 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4056 $reply .= "<select dojoType=\"dijit.form.Select\"
4057 onchange=\"headlineActionsChange(this)\">";
4058 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4060 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4062 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4063 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4064 <option value=\"$tog_published_link\">".__('Published')."</option>";
4066 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4068 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4070 if ($feed_id != "0") {
4071 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4073 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4074 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4078 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4081 $rss_link = htmlspecialchars(get_self_url_prefix() .
4082 "/backend.php?op=rss&id=$feed_id&is_cat=$is_cat&view_mode=$view_mode$search_q");
4084 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4086 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4088 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4090 $reply .= "</select>";
4094 $reply .= "<div id=\"subtoolbar_ftitle\">";
4096 if ($feed_site_url) {
4097 $target = "target=\"_blank\"";
4098 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4099 truncate_string($feed_title,30)."</a>";
4102 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4106 if ($feed_id < -10) {
4107 $label_id = -11-$feed_id;
4109 $result = db_query($link, "SELECT fg_color, bg_color
4110 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4113 if (db_num_rows($result) != 0) {
4114 $fg_color = db_fetch_result($result, 0, "fg_color");
4115 $bg_color = db_fetch_result($result, 0, "bg_color");
4117 $reply .= "<span style='background : $bg_color; color : $fg_color'>";
4118 $reply .= $feed_title;
4119 $reply .= "</span>";
4121 $reply .= $feed_title;
4125 $reply .= $feed_title;
4130 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4135 // Adaptive doesn't really make any sense for generated feeds
4136 // All Articles is the default, so no need to insert it either
4137 if ($view_mode == "adaptive" ||
$view_mode == "all_articles")
4140 $view_mode = "&view-mode=$view_mode";
4144 title=\"".__("View as RSS feed")."\"
4145 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4146 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4153 function outputFeedList($link, $special = true) {
4155 $feedlist = array();
4157 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4159 $feedlist['identifier'] = 'id';
4160 $feedlist['label'] = 'name';
4161 $feedlist['items'] = array();
4163 $owner_uid = $_SESSION["uid"];
4170 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4171 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4173 $cat['items'] = array();
4176 foreach (array(-4, -3, -1, -2, 0) as $i) {
4177 array_push($cat['items'], feedlist_init_feed($link, $i));
4181 array_push($feedlist['items'], $cat);
4183 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4186 $result = db_query($link, "SELECT * FROM
4187 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4189 if (db_num_rows($result) > 0) {
4191 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4192 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4193 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4195 $cat['items'] = array();
4198 while ($line = db_fetch_assoc($result)) {
4200 $label_id = -$line['id'] - 11;
4201 $count = getFeedUnread($link, $label_id);
4203 $feed = feedlist_init_feed($link, $label_id, false, $count);
4205 $feed['fg_color'] = $line['fg_color'];
4206 $feed['bg_color'] = $line['bg_color'];
4208 array_push($cat['items'], $feed);
4212 array_push($feedlist['items'], $cat);
4214 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4219 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4220 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4221 $order_by_qpart = "order_id,category,unread DESC,title";
4223 $order_by_qpart = "order_id,category,title";
4226 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4227 $order_by_qpart = "unread DESC,title";
4229 $order_by_qpart = "title";
4236 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4237 ttrss_feeds.order_id,title";
4239 $order_by_qpart = "title";
4241 $age_qpart = getMaxAgeSubquery();
4243 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4244 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4246 ttrss_feed_categories.title AS category,
4247 ttrss_feed_categories.collapsed,
4249 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4250 ON (ttrss_feed_categories.id = cat_id)
4251 LEFT JOIN ttrss_counters_cache
4253 (ttrss_feeds.id = feed_id)
4255 ttrss_feeds.owner_uid = '$owner_uid'
4256 ORDER BY $order_by_qpart";
4258 $result = db_query($link, $query);
4260 $actid = $_REQUEST["actid"];
4262 if (db_num_rows($result) > 0) {
4267 $cat['items'] = array();
4271 while ($line = db_fetch_assoc($result)) {
4273 $feed = htmlspecialchars(trim($line["title"]));
4275 if (!$feed) $feed = "[Untitled]";
4277 $feed_id = $line["id"];
4278 $unread = $line["unread"];
4280 $cat_id = $line["cat_id"];
4281 $tmp_category = $line["category"];
4282 if (!$tmp_category) $tmp_category = __("Uncategorized");
4284 if ($category != $tmp_category && $enable_cats) {
4286 $category = $tmp_category;
4288 $collapsed = sql_bool_to_bool($line["collapsed"]);
4290 // workaround for NULL category
4291 if ($category == __("Uncategorized")) {
4292 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4295 if ($cat) array_push($feedlist['items'], $cat);
4297 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4300 $updated = make_local_datetime($link, $line["updated_noms"], false);
4302 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4303 $feed, $unread, $line['last_error'], $updated));
4307 array_push($feedlist['items'], $cat);
4309 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4317 function get_article_tags($link, $id, $owner_uid = 0) {
4321 $a_id = db_escape_string($id);
4323 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4325 $query = "SELECT DISTINCT tag_name,
4326 owner_uid as owner FROM
4327 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4328 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4330 $obj_id = md5("TAGS:$owner_uid:$id");
4333 if ($memcache && $obj = $memcache->get($obj_id)) {
4336 /* check cache first */
4338 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4339 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4341 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4344 $tags = explode(",", $tag_cache);
4347 /* do it the hard way */
4349 $tmp_result = db_query($link, $query);
4351 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4352 array_push($tags, $tmp_line["tag_name"]);
4355 /* update the cache */
4357 $tags_str = db_escape_string(join(",", $tags));
4359 db_query($link, "UPDATE ttrss_user_entries
4360 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4361 AND owner_uid = " . $_SESSION["uid"]);
4364 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4370 function trim_value(&$value) {
4371 $value = trim($value);
4374 function trim_array($array) {
4376 array_walk($tmp, 'trim_value');
4380 function tag_is_valid($tag) {
4381 if ($tag == '') return false;
4382 if (preg_match("/^[0-9]*$/", $tag)) return false;
4383 if (mb_strlen($tag) > 250) return false;
4385 if (function_exists('iconv')) {
4386 $tag = iconv("utf-8", "utf-8", $tag);
4389 if (!$tag) return false;
4394 function render_login_form($link, $mobile = 0) {
4397 require_once "login_form.php";
4400 require_once "mobile/login_form.php";
4403 require_once "mobile/classic/login_form.php";
4407 // from http://developer.apple.com/internet/safari/faq.html
4408 function no_cache_incantation() {
4409 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4410 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4411 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4412 header("Cache-Control: post-check=0, pre-check=0", false);
4413 header("Pragma: no-cache"); // HTTP/1.0
4416 function format_warning($msg, $id = "") {
4418 return "<div class=\"warning\" id=\"$id\">
4419 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4422 function format_notice($msg, $id = "") {
4424 return "<div class=\"notice\" id=\"$id\">
4425 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4428 function format_error($msg, $id = "") {
4430 return "<div class=\"error\" id=\"$id\">
4431 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4434 function print_notice($msg) {
4435 return print format_notice($msg);
4438 function print_warning($msg) {
4439 return print format_warning($msg);
4442 function print_error($msg) {
4443 return print format_error($msg);
4447 function T_sprintf() {
4448 $args = func_get_args();
4449 return vsprintf(__(array_shift($args)), $args);
4452 function format_inline_player($link, $url, $ctype) {
4456 if (strpos($ctype, "audio/") === 0) {
4458 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4459 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4460 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4462 $id = 'AUDIO-' . uniqid();
4464 $entry .= "<audio id=\"$id\"\">
4465 <source src=\"$url\"></source>
4468 $entry .= "<span onclick=\"player(this)\"
4469 title=\"".__("Click to play")."\" status=\"0\"
4470 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4474 $entry .= "<object type=\"application/x-shockwave-flash\"
4475 data=\"extras/button/musicplayer.swf?song_url=$url\"
4476 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4477 <param name=\"movie\"
4478 value=\"extras/button/musicplayer.swf?song_url=$url\" />
4483 $filename = substr($url, strrpos($url, "/")+
1);
4485 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4486 $filename . " (" . $ctype . ")" . "</a>";
4491 function format_article($link, $id, $feed_id, $mark_as_read = true,
4492 $zoom_mode = false) {
4498 /* we can figure out feed_id from article id anyway, why do we
4499 * pass feed_id here? let's ignore the argument :( */
4501 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4502 WHERE ref_id = '$id'");
4504 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4506 $rv['feed_id'] = $feed_id;
4508 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4510 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4511 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4513 if (db_num_rows($result) == 1) {
4514 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4515 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4517 $rtl_content = false;
4518 $always_display_enclosures = false;
4522 $rtl_tag = "dir=\"RTL\"";
4529 if ($mark_as_read) {
4530 $result = db_query($link, "UPDATE ttrss_user_entries
4531 SET unread = false,last_read = NOW()
4532 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4534 ccache_update($link, $feed_id, $_SESSION["uid"]);
4537 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4538 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4539 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4540 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4545 FROM ttrss_entries,ttrss_user_entries
4546 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4550 $line = db_fetch_assoc($result);
4552 if ($line["icon_url"]) {
4553 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4555 $feed_icon = " ";
4558 $feed_site_url = $line['site_url'];
4560 $num_comments = $line["num_comments"];
4561 $entry_comments = "";
4563 if ($num_comments > 0) {
4564 if ($line["comments"]) {
4565 $comments_url = $line["comments"];
4567 $comments_url = $line["link"];
4569 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4571 if ($line["comments"] && $line["link"] != $line["comments"]) {
4572 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4577 header("Content-Type: text/html");
4578 $rv['content'] .= "<html><head>
4579 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4580 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4581 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4585 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4586 truncate_string(strip_tags($line['title']), 15) . "</div>";
4588 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4590 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4591 class=\"postHeader\" id=\"POSTHDR-$id\">";
4593 $entry_author = $line["author"];
4595 if ($entry_author) {
4596 $entry_author = __(" - ") . $entry_author;
4599 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4602 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4604 if ($line["link"]) {
4605 $rv['content'] .= "<div clear='both'><a target='_blank'
4606 title=\"".htmlspecialchars($line['title'])."\"
4608 $line["link"] . "\">" .
4609 truncate_string($line["title"], 100) .
4610 "<span class='author'>$entry_author</span></a></div>";
4612 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4615 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4617 if (!$entry_comments) $entry_comments = " "; # placeholder
4619 $rv['content'] .= "<div style='float : right'>
4620 <img src='".theme_image($link, 'images/tag.png')."'
4621 class='tagsPic' alt='Tags' title='Tags'> ";
4624 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4625 <a title=\"".__('Edit tags for this article')."\"
4626 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4628 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4629 class='tagsPic' style=\"cursor : pointer\"
4630 onclick=\"postOpenInNewTab(event, $id)\"
4631 alt='Zoom' title='".__('Open article in new tab')."'>";
4633 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4635 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4636 class='tagsPic' style=\"cursor : pointer\"
4637 onclick=\"editArticleNote($id)\"
4638 alt='PubNote' title='".__('Edit article note')."'>";
4640 if (DIGEST_ENABLE
) {
4641 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4642 class='tagsPic' style=\"cursor : pointer\"
4643 onclick=\"emailArticle($id)\"
4644 alt='Zoom' title='".__('Forward by email')."'>";
4647 if (ENABLE_TWEET_BUTTON
) {
4648 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4649 class='tagsPic' style=\"cursor : pointer\"
4650 onclick=\"tweetArticle($id)\"
4651 alt='Zoom' title='".__('Share on Twitter')."'>";
4654 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4655 class='tagsPic' style=\"cursor : pointer\"
4656 onclick=\"closeArticlePanel($id)\"
4657 alt='Zoom' title='".__('Close this panel')."'>";
4660 $tags_str = strip_tags($tags_str);
4661 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4663 $rv['content'] .= "</div>";
4664 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4666 if ($line["orig_feed_id"]) {
4668 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4669 WHERE id = ".$line["orig_feed_id"]);
4671 if (db_num_rows($tmp_result) != 0) {
4673 $rv['content'] .= "<div clear='both'>";
4674 $rv['content'] .= __("Originally from:");
4676 $rv['content'] .= " ";
4678 $tmp_line = db_fetch_assoc($tmp_result);
4680 $rv['content'] .= "<a target='_blank'
4681 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4682 $tmp_line['title'] . "</a>";
4684 $rv['content'] .= " ";
4686 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4687 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4689 $rv['content'] .= "</div>";
4693 $rv['content'] .= "</div>";
4695 $rv['content'] .= "<div class=\"postIcon\">" .
4696 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4697 href=\"".htmlspecialchars($feed_site_url)."\">".
4698 $feed_icon . "</a></div>";
4700 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4701 if ($line['note']) {
4702 $rv['content'] .= format_article_note($id, $line['note']);
4704 $rv['content'] .= "</div>";
4706 $rv['content'] .= "<div class=\"postContent\">";
4708 $article_content = sanitize_rss($link, $line["content"], false, false,
4711 $rv['content'] .= $article_content;
4713 $rv['content'] .= format_article_enclosures($link, $id,
4714 $always_display_enclosures, $article_content);
4716 $rv['content'] .= "</div>";
4718 $rv['content'] .= "</div>";
4724 <div style=\"text-align : center\">
4725 <button onclick=\"return window.close()\">".
4726 __("Close this window")."</button></div>";
4727 $rv['content'] .= "</body></html>";
4734 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4735 $next_unread_feed, $offset, $vgr_last_feed = false,
4736 $override_order = false) {
4738 $disable_cache = false;
4742 $timing_info = getmicrotime();
4744 $topmost_article_ids = array();
4750 if ($subop == "undefined") $subop = "";
4752 $subop_split = split(":", $subop);
4754 if ($subop == "CatchupSelected") {
4755 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4756 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4758 catchupArticlesById($link, $ids, $cmode);
4761 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4762 update_rss_feed($link, $feed, true);
4765 if ($subop == "MarkAllRead") {
4766 catchup_feed($link, $feed, $cat_view);
4768 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4769 if ($next_unread_feed) {
4770 $feed = $next_unread_feed;
4775 if ($subop_split[0] == "MarkAllReadGR") {
4776 catchup_feed($link, $subop_split[1], false);
4779 // FIXME: might break tag display?
4781 if ($feed > 0 && !$cat_view) {
4782 $result = db_query($link,
4783 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4785 if (db_num_rows($result) == 0) {
4786 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4790 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4792 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4793 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4795 if (db_num_rows($result) == 1) {
4796 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4798 $rtl_content = false;
4802 $rtl_tag = "dir=\"RTL\"";
4808 $rtl_content = false;
4811 /// START /////////////////////////////////////////////////////////////////////////////////
4813 @$search = db_escape_string($_REQUEST["query"]);
4816 $disable_cache = true;
4819 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4820 @$match_on = db_escape_string($_REQUEST["match_on"]);
4826 $real_offset = $offset * $limit;
4828 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4830 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4831 $search, $search_mode, $match_on, $override_order, $real_offset);
4833 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4835 $result = $qfh_ret[0];
4836 $feed_title = $qfh_ret[1];
4837 $feed_site_url = $qfh_ret[2];
4838 $last_error = $qfh_ret[3];
4840 $vgroup_last_feed = $vgr_last_feed;
4842 /// STOP //////////////////////////////////////////////////////////////////////////////////
4846 if (db_num_rows($result) > 0) {
4847 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4848 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
4853 $headlines_count = db_num_rows($result);
4855 if (db_num_rows($result) > 0) {
4857 $lnum = $limit*$offset;
4860 $cur_feed_title = '';
4862 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4864 while ($line = db_fetch_assoc($result)) {
4866 $class = ($lnum %
2) ?
"even" : "odd";
4869 $feed_id = $line["feed_id"];
4871 $labels = get_article_labels($link, $id);
4873 $labels_str = "<span id=\"HLLCTR-$id\">";
4874 $labels_str .= format_article_labels($labels, $id);
4875 $labels_str .= "</span>";
4877 if (count($topmost_article_ids) < 3) {
4878 array_push($topmost_article_ids, $id);
4881 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4883 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4884 theme_image($link, 'images/updated.png')."\"
4887 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4891 if (sql_bool_to_bool($line["unread"]) &&
4892 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4894 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4895 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
4898 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4899 $class .= " Unread";
4906 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4907 $marked_pic = "<img id=\"FMPIC-$id\"
4908 src=\"".theme_image($link, 'images/mark_set.png')."\"
4909 class=\"markedPic\" alt=\"Unstar article\"
4910 onclick='javascript:tMark($id)'>";
4912 $marked_pic = "<img id=\"FMPIC-$id\"
4913 src=\"".theme_image($link, 'images/mark_unset.png')."\"
4914 class=\"markedPic\" alt=\"Star article\"
4915 onclick='javascript:tMark($id)'>";
4918 if ($line["published"] == "t" ||
$line["published"] == "1") {
4919 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4920 'images/pub_set.png')."\"
4922 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4924 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4925 'images/pub_unset.png')."\"
4927 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4930 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4931 # $line["title"] . "</a>";
4933 # $content_link = "<a
4934 # href=\"" . htmlspecialchars($line["link"]) . "\"
4935 # onclick=\"view($id,$feed_id);\">" .
4936 # $line["title"] . "</a>";
4938 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4939 # $line["title"] . "</a>";
4941 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
4943 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4944 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4948 $score = $line["score"];
4950 $score_pic = theme_image($link,
4951 "images/" . get_score_pic($score));
4953 /* $score_title = __("(Click to change)");
4954 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4955 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4957 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
4962 } else if ($score < -100) {
4968 $entry_author = $line["author"];
4970 if ($entry_author) {
4971 $entry_author = " - $entry_author";
4974 $has_feed_icon = feed_has_icon($feed_id);
4976 if ($has_feed_icon) {
4977 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
4979 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
4982 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4984 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4985 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4987 $cur_feed_title = $line["feed_title"];
4988 $vgroup_last_feed = $feed_id;
4990 $cur_feed_title = htmlspecialchars($cur_feed_title);
4992 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
4994 $reply['content'] .= "<div class='cdmFeedTitle'>".
4995 "<div style=\"float : right\">$feed_icon_img</div>".
4996 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
4997 $line["feed_title"]."</a> $vf_catchup_link</div>";
5002 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5003 onmouseout='postMouseOut($id)'";
5005 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5007 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5009 $reply['content'] .= "<div class='hlLeft'>";
5011 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5014 $reply['content'] .= "$marked_pic";
5015 $reply['content'] .= "$published_pic";
5017 $reply['content'] .= "</div>";
5019 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5020 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5021 $reply['content'] .= "<a id=\"RTITLE-$id\"
5022 href=\"" . htmlspecialchars($line["link"]) . "\"
5023 onclick=\"return false;\">" .
5026 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5027 if ($content_preview) {
5028 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5032 $reply['content'] .= "</a></span>";
5034 $reply['content'] .= $labels_str;
5036 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5037 if (@$line["feed_title"]) {
5038 print "<span class=\"hlFeed\">
5039 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5040 $line["feed_title"]."</a>)
5045 $reply['content'] .= "</div>";
5047 $reply['content'] .= "<div class=\"hlRight\">";
5048 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5049 $reply['content'] .= $score_pic;
5051 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5053 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5054 title=\"".htmlspecialchars($line['feed_title'])."\">
5055 $feed_icon_img<span>";
5058 $reply['content'] .= "</div>";
5059 $reply['content'] .= "</div>";
5063 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5064 if ($feed_id != $vgroup_last_feed) {
5066 $cur_feed_title = $line["feed_title"];
5067 $vgroup_last_feed = $feed_id;
5069 $cur_feed_title = htmlspecialchars($cur_feed_title);
5071 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5073 $has_feed_icon = feed_has_icon($feed_id);
5075 if ($has_feed_icon) {
5076 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5078 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5081 $reply['content'] .= "<div class='cdmFeedTitle'>".
5082 "<div style=\"float : right\">$feed_icon_img</div>".
5083 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5084 $line["feed_title"]."</a> $vf_catchup_link</div>";
5088 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5090 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5091 onmouseout='postMouseOut($id)'";
5093 $reply['content'] .= "<div class=\"$class\"
5094 id=\"RROW-$id\" $mouseover_attrs'>";
5096 $reply['content'] .= "<div class=\"cdmHeader\">";
5098 $reply['content'] .= "<div style='float : right'>";
5099 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5100 $reply['content'] .= "$score_pic";
5102 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5103 $reply['content'] .= "<span style=\"cursor : pointer\"
5104 title=\"".htmlspecialchars($line["feed_title"])."\"
5105 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5107 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5109 $reply['content'] .= "</div>";
5111 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5112 'RROW-$id')\" id=\"RCHK-$id\"/>";
5114 $reply['content'] .= "$marked_pic";
5115 $reply['content'] .= "$published_pic";
5117 $reply['content'] .= "<span id=\"RTITLE-$id\"
5118 onclick=\"return cdmClicked(event, $id);\"
5119 class=\"titleWrap$hlc_suffix\">
5121 title=\"".htmlspecialchars($line['title'])."\"
5122 target=\"_blank\" href=\"".
5123 htmlspecialchars($line["link"])."\">".
5124 truncate_string($line["title"], 100) .
5125 " $entry_author</a>";
5127 $reply['content'] .= $labels_str;
5130 $content_hidden = "style=\"display : none\"";
5132 $excerpt_hidden = "style=\"display : none\"";
5134 $reply['content'] .= "<span $excerpt_hidden
5135 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5137 $reply['content'] .= "</span>";
5139 $reply['content'] .= "</div>";
5141 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5142 onclick=\"return cdmClicked(event, $id);\"
5145 $reply['content'] .= "<div class=\"cdmContentInner\">";
5147 if ($line["orig_feed_id"]) {
5149 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5150 WHERE id = ".$line["orig_feed_id"]);
5152 if (db_num_rows($tmp_result) != 0) {
5154 $reply['content'] .= "<div clear='both'>";
5155 $reply['content'] .= __("Originally from:");
5157 $reply['content'] .= " ";
5159 $tmp_line = db_fetch_assoc($tmp_result);
5161 $reply['content'] .= "<a target='_blank'
5162 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5163 $tmp_line['title'] . "</a>";
5165 $reply['content'] .= " ";
5167 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5168 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5170 $reply['content'] .= "</div>";
5174 // FIXME: make this less of a hack
5176 $feed_site_url = false;
5178 if ($line["feed_id"]) {
5179 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5180 WHERE id = " . $line["feed_id"]);
5182 if (db_num_rows($tmp_result) == 1) {
5183 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5188 $article_content = sanitize_rss($link, $line["content_preview"],
5189 false, false, $feed_site_url);
5191 if (!$article_content) $article_content = " ";
5193 $article_content = '';
5196 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5197 if ($line['note']) {
5198 $reply['content'] .= format_article_note($id, $line['note']);
5200 $reply['content'] .= "</div>";
5202 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5204 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5205 ttrss_feeds WHERE id = ".
5206 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5207 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5209 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5210 0, "always_display_enclosures"));
5212 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5215 $reply['content'] .= "</div>";
5217 $reply['content'] .= "<div class=\"cdmFooter\">";
5219 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5221 $reply['content'] .= "<img src='".theme_image($link,
5222 'images/tag.png')."' alt='Tags' title='Tags'>
5223 <span id=\"ATSTR-$id\">$tags_str</span>
5224 <a title=\"".__('Edit tags for this article')."\"
5225 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5227 $reply['content'] .= "<div style=\"float : right\">";
5229 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5230 onclick=\"zoomToArticle(event, $id)\"
5231 style=\"cursor : pointer\"
5233 title='".__('Open article in new tab')."'>";
5235 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5237 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5238 style=\"cursor : pointer\" style=\"cursor : pointer\"
5239 onclick=\"editArticleNote($id)\"
5240 alt='PubNote' title='".__('Edit article note')."'>";
5242 if (DIGEST_ENABLE
) {
5243 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5244 style=\"cursor : pointer\"
5245 onclick=\"emailArticle($id)\"
5246 alt='Zoom' title='".__('Forward by email')."'>";
5249 if (ENABLE_TWEET_BUTTON
) {
5250 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5251 class='tagsPic' style=\"cursor : pointer\"
5252 onclick=\"tweetArticle($id)\"
5253 alt='Zoom' title='".__('Share on Twitter')."'>";
5256 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5257 style=\"cursor : pointer\" style=\"cursor : pointer\"
5258 onclick=\"dismissArticle($id)\"
5259 alt='Dismiss' title='".__('Dismiss article')."'>";
5261 $reply['content'] .= "</div>";
5262 $reply['content'] .= "</div>";
5264 $reply['content'] .= "</div>";
5266 $reply['content'] .= "</div>";
5276 switch ($view_mode) {
5278 $message = __("No unread articles found to display.");
5281 $message = __("No updated articles found to display.");
5284 $message = __("No starred articles found to display.");
5288 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5290 $message = __("No articles found to display.");
5294 if (!$offset && $message) {
5295 $reply['content'] .= "<div class='whiteBox'>$message";
5297 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5299 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5300 WHERE owner_uid = " . $_SESSION['uid']);
5302 $last_updated = db_fetch_result($result, 0, "last_updated");
5303 $last_updated = make_local_datetime($link, $last_updated, false);
5305 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5307 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5308 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5310 $num_errors = db_fetch_result($result, 0, "num_errors");
5312 if ($num_errors > 0) {
5313 $reply['content'] .= "<br/>";
5314 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5315 __('Some feeds have update errors (click for details)')."</a>";
5317 $reply['content'] .= "</span></p></div>";
5322 # if ($headlines_count > 0) print "</div>";
5326 #print "]]></content>";
5328 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5329 $vgroup_last_feed, $reply['content'], $reply['toolbar']);
5332 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5334 function printTagCloud($link) {
5336 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5337 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5338 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5340 $result = db_query($link, $query);
5344 while ($line = db_fetch_assoc($result)) {
5345 $tags[$line["tag_name"]] = $line["count"];
5350 $max_size = 32; // max font size in pixels
5351 $min_size = 11; // min font size in pixels
5353 // largest and smallest array values
5354 $max_qty = max(array_values($tags));
5355 $min_qty = min(array_values($tags));
5357 // find the range of values
5358 $spread = $max_qty - $min_qty;
5359 if ($spread == 0) { // we don't want to divide by zero
5363 // set the font-size increment
5364 $step = ($max_size - $min_size) / ($spread);
5366 // loop through the tag array
5367 foreach ($tags as $key => $value) {
5368 // calculate font-size
5369 // find the $value in excess of $min_qty
5370 // multiply by the font-size increment ($size)
5371 // and add the $min_size set above
5372 $size = round($min_size +
(($value - $min_qty) * $step));
5374 $key_escaped = str_replace("'", "\\'", $key);
5376 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5377 $size . "px\" title=\"$value articles tagged with " .
5378 $key . '">' . $key . '</a> ';
5382 function print_checkpoint($n, $s) {
5383 $ts = getmicrotime();
5384 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5388 function sanitize_tag($tag) {
5391 $tag = mb_strtolower($tag, 'utf-8');
5393 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5395 // $tag = str_replace('"', "", $tag);
5396 // $tag = str_replace("+", " ", $tag);
5397 $tag = str_replace("technorati tag: ", "", $tag);
5402 function get_self_url_prefix() {
5406 if ($_SERVER['HTTPS'] != "on") {
5407 $url_path = "http://";
5409 $url_path = "https://";
5412 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5417 function opml_publish_url($link){
5419 $url_path = get_self_url_prefix();
5420 $url_path .= "/opml.php?op=publish&key=" .
5421 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5427 * Purge a feed contents, marked articles excepted.
5429 * @param mixed $link The database connection.
5430 * @param integer $id The id of the feed to purge.
5433 function clear_feed_articles($link, $id) {
5436 $result = db_query($link, "DELETE FROM ttrss_user_entries
5437 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5439 $result = db_query($link, "DELETE FROM ttrss_user_entries
5440 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5443 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5444 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5446 ccache_update($link, $id, $_SESSION['uid']);
5447 } // function clear_feed_articles
5450 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5452 * @return string The Mozilla Firefox feed adding URL.
5454 function add_feed_url() {
5455 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5456 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5458 } // function add_feed_url
5461 * Encrypt a password in SHA1.
5463 * @param string $pass The password to encrypt.
5464 * @param string $login A optionnal login.
5465 * @return string The encrypted password.
5467 function encrypt_password($pass, $login = '') {
5469 return "SHA1X:" . sha1("$login:$pass");
5471 return "SHA1:" . sha1($pass);
5473 } // function encrypt_password
5476 * Update a feed batch.
5477 * Used by daemons to update n feeds by run.
5478 * Only update feed needing a update, and not being processed
5479 * by another process.
5481 * @param mixed $link Database link
5482 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5483 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5484 * @param boolean $debug Set to false to disable debug output. Default to true.
5487 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5488 // Process all other feeds using last_updated and interval parameters
5490 // Test if the user has loggued in recently. If not, it does not update its feeds.
5491 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5492 if (DB_TYPE
== "pgsql") {
5493 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5495 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5498 $login_thresh_qpart = "";
5501 // Test if the feed need a update (update interval exceded).
5502 if (DB_TYPE
== "pgsql") {
5503 $update_limit_qpart = "AND ((
5504 ttrss_feeds.update_interval = 0
5505 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5507 ttrss_feeds.update_interval > 0
5508 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5509 ) OR ttrss_feeds.last_updated IS NULL)";
5511 $update_limit_qpart = "AND ((
5512 ttrss_feeds.update_interval = 0
5513 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5515 ttrss_feeds.update_interval > 0
5516 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5517 ) OR ttrss_feeds.last_updated IS NULL)";
5520 // Test if feed is currently being updated by another process.
5521 if (DB_TYPE
== "pgsql") {
5522 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5524 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5527 // Test if there is a limit to number of updated feeds
5529 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5531 $random_qpart = sql_random_function();
5533 // We search for feed needing update.
5534 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5535 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5536 ttrss_feeds.update_interval
5538 ttrss_feeds, ttrss_users, ttrss_user_prefs
5540 ttrss_feeds.owner_uid = ttrss_users.id
5541 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5542 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5543 $login_thresh_qpart $update_limit_qpart
5544 $updstart_thresh_qpart
5545 ORDER BY $random_qpart $query_limit");
5547 $user_prefs_cache = array();
5549 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5551 // Here is a little cache magic in order to minimize risk of double feed updates.
5552 $feeds_to_update = array();
5553 while ($line = db_fetch_assoc($result)) {
5554 $feeds_to_update[$line['id']] = $line;
5557 // We update the feed last update started date before anything else.
5558 // There is no lag due to feed contents downloads
5559 // It prevent an other process to update the same feed.
5560 $feed_ids = array_keys($feeds_to_update);
5562 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5563 WHERE id IN (%s)", implode(',', $feed_ids)));
5566 // For each feed, we call the feed update function.
5567 while ($line = array_pop($feeds_to_update)) {
5569 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5571 update_rss_feed($link, $line["id"], true);
5573 sleep(1); // prevent flood (FIXME make this an option?)
5576 // Send feed digests by email if needed.
5577 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5579 } // function update_daemon_common
5581 function sanitize_article_content($text) {
5582 # we don't support CDATA sections in articles, they break our own escaping
5583 $text = preg_replace("/\[\[CDATA/", "", $text);
5584 $text = preg_replace("/\]\]\>/", "", $text);
5588 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5593 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5595 if ($memcache && $obj = $memcache->get($obj_id)) {
5601 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5603 $result = db_query($link, "SELECT reg_exp,
5604 ttrss_filter_types.name AS name,
5605 ttrss_filter_actions.name AS action,
5609 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5612 owner_uid = $owner_uid AND
5613 ttrss_filter_types.id = filter_type AND
5614 ttrss_filter_actions.id = action_id AND
5615 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5617 while ($line = db_fetch_assoc($result)) {
5618 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5619 $filter["reg_exp"] = $line["reg_exp"];
5620 $filter["action"] = $line["action"];
5621 $filter["action_param"] = $line["action_param"];
5622 $filter["filter_param"] = $line["filter_param"];
5623 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5625 array_push($filters[$line["name"]], $filter);
5628 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5634 function get_score_pic($score) {
5636 return "score_high.png";
5637 } else if ($score > 0) {
5638 return "score_half_high.png";
5639 } else if ($score < -100) {
5640 return "score_low.png";
5641 } else if ($score < 0) {
5642 return "score_half_low.png";
5644 return "score_neutral.png";
5648 function rounded_table_start($classname, $header = " ") {
5649 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5650 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5651 print "<tr><td class='left'> </td><td class='content'>";
5654 function rounded_table_end($footer = " ") {
5655 print "</td><td class='right'> </td></tr>";
5656 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5660 function feed_has_icon($id) {
5661 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5664 function init_connection($link) {
5665 if (DB_TYPE
== "pgsql") {
5666 pg_query($link, "set client_encoding = 'UTF-8'");
5667 pg_set_client_encoding("UNICODE");
5668 pg_query($link, "set datestyle = 'ISO, european'");
5669 pg_query($link, "set TIME ZONE 0");
5671 db_query($link, "SET time_zone = '+0:0'");
5673 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5674 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5675 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5680 function update_feedbrowser_cache($link) {
5682 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5683 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5684 WHERE tf.feed_url = ttrss_feeds.feed_url
5685 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5686 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5688 db_query($link, "BEGIN");
5690 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5694 while ($line = db_fetch_assoc($result)) {
5695 $subscribers = db_escape_string($line["subscribers"]);
5696 $feed_url = db_escape_string($line["feed_url"]);
5697 $title = db_escape_string($line["title"]);
5699 $tmp_result = db_query($link, "SELECT subscribers FROM
5700 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5702 if (db_num_rows($tmp_result) == 0) {
5704 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5705 (feed_url, title, subscribers) VALUES ('$feed_url',
5706 '$title', '$subscribers')");
5714 db_query($link, "COMMIT");
5720 function ccache_zero($link, $feed_id, $owner_uid) {
5721 db_query($link, "UPDATE ttrss_counters_cache SET
5722 value = 0, updated = NOW() WHERE
5723 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5726 function ccache_zero_all($link, $owner_uid) {
5727 db_query($link, "UPDATE ttrss_counters_cache SET
5728 value = 0 WHERE owner_uid = '$owner_uid'");
5730 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5731 value = 0 WHERE owner_uid = '$owner_uid'");
5734 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5737 $table = "ttrss_counters_cache";
5739 $table = "ttrss_cat_counters_cache";
5742 db_query($link, "DELETE FROM $table WHERE
5743 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5747 function ccache_update_all($link, $owner_uid) {
5749 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5751 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5752 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5754 while ($line = db_fetch_assoc($result)) {
5755 ccache_update($link, $line["feed_id"], $owner_uid, true);
5758 /* We have to manually include category 0 */
5760 ccache_update($link, 0, $owner_uid, true);
5763 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5764 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5766 while ($line = db_fetch_assoc($result)) {
5767 print ccache_update($link, $line["feed_id"], $owner_uid);
5774 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5775 $no_update = false) {
5777 if (!is_numeric($feed_id)) return;
5780 $table = "ttrss_counters_cache";
5782 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5783 WHERE id = '$feed_id'");
5784 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5787 $table = "ttrss_cat_counters_cache";
5790 if (DB_TYPE
== "pgsql") {
5791 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5792 } else if (DB_TYPE
== "mysql") {
5793 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5796 $result = db_query($link, "SELECT value FROM $table
5797 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5800 if (db_num_rows($result) == 1) {
5801 return db_fetch_result($result, 0, "value");
5806 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5812 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5813 $update_pcat = true) {
5815 if (!is_numeric($feed_id)) return;
5817 if (!$is_cat && $feed_id > 0) {
5818 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5819 WHERE id = '$feed_id'");
5820 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5823 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5825 /* When updating a label, all we need to do is recalculate feed counters
5826 * because labels are not cached */
5829 ccache_update_all($link, $owner_uid);
5834 $table = "ttrss_counters_cache";
5836 $table = "ttrss_cat_counters_cache";
5839 if ($is_cat && $feed_id >= 0) {
5840 if ($feed_id != 0) {
5841 $cat_qpart = "cat_id = '$feed_id'";
5843 $cat_qpart = "cat_id IS NULL";
5846 /* Recalculate counters for child feeds */
5848 $result = db_query($link, "SELECT id FROM ttrss_feeds
5849 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5851 while ($line = db_fetch_assoc($result)) {
5852 ccache_update($link, $line["id"], $owner_uid, false, false);
5855 $result = db_query($link, "SELECT SUM(value) AS sv
5856 FROM ttrss_counters_cache, ttrss_feeds
5857 WHERE id = feed_id AND $cat_qpart AND
5858 ttrss_feeds.owner_uid = '$owner_uid'");
5860 $unread = (int) db_fetch_result($result, 0, "sv");
5863 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5866 db_query($link, "BEGIN");
5868 $result = db_query($link, "SELECT feed_id FROM $table
5869 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5871 if (db_num_rows($result) == 1) {
5872 db_query($link, "UPDATE $table SET
5873 value = '$unread', updated = NOW() WHERE
5874 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5877 db_query($link, "INSERT INTO $table
5878 (feed_id, value, owner_uid, updated)
5880 ($feed_id, $unread, $owner_uid, NOW())");
5883 db_query($link, "COMMIT");
5885 if ($feed_id > 0 && $prev_unread != $unread) {
5889 /* Update parent category */
5893 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5894 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5896 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5898 ccache_update($link, $cat_id, $owner_uid, true);
5902 } else if ($feed_id < 0) {
5903 ccache_update_all($link, $owner_uid);
5909 function label_find_id($link, $label, $owner_uid) {
5910 $result = db_query($link,
5911 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5912 AND owner_uid = '$owner_uid' LIMIT 1");
5914 if (db_num_rows($result) == 1) {
5915 return db_fetch_result($result, 0, "id");
5921 function get_article_labels($link, $id) {
5924 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
5928 if ($memcache && $obj = $memcache->get($obj_id)) {
5932 $result = db_query($link, "SELECT label_cache FROM
5933 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
5936 $label_cache = db_fetch_result($result, 0, "label_cache");
5940 $label_cache = json_decode($label_cache, true);
5942 if ($label_cache["no-labels"] == 1)
5945 return $label_cache;
5948 $result = db_query($link,
5949 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5950 FROM ttrss_labels2, ttrss_user_labels2
5952 AND article_id = '$id'
5953 AND owner_uid = ".$_SESSION["uid"] . "
5956 while ($line = db_fetch_assoc($result)) {
5957 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5959 array_push($rv, $rk);
5961 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
5964 label_update_cache($link, $id, $rv);
5966 label_update_cache($link, $id, array("no-labels" => 1));
5973 function label_find_caption($link, $label, $owner_uid) {
5974 $result = db_query($link,
5975 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5976 AND owner_uid = '$owner_uid' LIMIT 1");
5978 if (db_num_rows($result) == 1) {
5979 return db_fetch_result($result, 0, "caption");
5985 function label_update_cache($link, $id, $labels = false, $force = false) {
5988 label_clear_cache($link, $id);
5991 $labels = get_article_labels($link, $id);
5993 $labels = db_escape_string(json_encode($labels));
5995 db_query($link, "UPDATE ttrss_user_entries SET
5996 label_cache = '$labels' WHERE ref_id = '$id'");
6000 function label_clear_cache($link, $id) {
6002 db_query($link, "UPDATE ttrss_user_entries SET
6003 label_cache = '' WHERE ref_id = '$id'");
6007 function label_remove_article($link, $id, $label, $owner_uid) {
6009 $label_id = label_find_id($link, $label, $owner_uid);
6011 if (!$label_id) return;
6013 $result = db_query($link,
6014 "DELETE FROM ttrss_user_labels2
6016 label_id = '$label_id' AND
6017 article_id = '$id'");
6019 label_clear_cache($link, $id);
6022 function label_add_article($link, $id, $label, $owner_uid) {
6027 $obj_id = md5("LABELS:$id:$owner_uid");
6028 $memcache->delete($obj_id);
6031 $label_id = label_find_id($link, $label, $owner_uid);
6033 if (!$label_id) return;
6035 $result = db_query($link,
6037 article_id FROM ttrss_labels2, ttrss_user_labels2
6040 label_id = '$label_id' AND
6041 article_id = '$id' AND owner_uid = '$owner_uid'
6044 if (db_num_rows($result) == 0) {
6045 db_query($link, "INSERT INTO ttrss_user_labels2
6046 (label_id, article_id) VALUES ('$label_id', '$id')");
6049 label_clear_cache($link, $id);
6053 function label_remove($link, $id, $owner_uid) {
6056 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6059 $obj_id = md5("LABELS:$id:$owner_uid");
6060 $memcache->delete($obj_id);
6063 db_query($link, "BEGIN");
6065 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6068 $caption = db_fetch_result($result, 0, "caption");
6070 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6071 AND owner_uid = " . $owner_uid);
6073 if (db_affected_rows($link, $result) != 0 && $caption) {
6075 /* Remove access key for the label */
6077 $ext_id = -11 - $id;
6079 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6080 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6082 /* Disable filters that reference label being removed */
6084 db_query($link, "UPDATE ttrss_filters SET
6085 enabled = false WHERE action_param = '$caption'
6087 AND owner_uid = " . $owner_uid);
6089 /* Remove cached data */
6091 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6092 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6096 db_query($link, "COMMIT");
6099 function label_create($link, $caption) {
6101 db_query($link, "BEGIN");
6105 $result = db_query($link, "SELECT id FROM ttrss_labels2
6106 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6108 if (db_num_rows($result) == 0) {
6109 $result = db_query($link,
6110 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6111 VALUES ('$caption', '".$_SESSION["uid"]."')");
6113 $result = db_affected_rows($link, $result) != 0;
6116 db_query($link, "COMMIT");
6121 function print_labels_headlines_dropdown($link, $feed_id) {
6122 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6124 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6125 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6127 while ($line = db_fetch_assoc($result)) {
6129 $label_id = $line["id"];
6130 $label_caption = $line["caption"];
6133 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6134 print "<option id=\"LHDL-$id\"
6135 value=\"selectionRemoveLabel($label_id)\">".
6136 __('Remove:') . " $label_caption</option>";
6138 print "<option id=\"LHDL-$id\"
6139 value=\"selectionAssignLabel($label_id)\">".
6140 __('Assign:') . " $label_caption</option>";
6145 function format_tags_string($tags, $id) {
6148 $tags_nolinks_str = "";
6152 /* if (get_user_theme($link) == "3pane") {
6160 $formatted_tags = array();
6162 foreach ($tags as $tag) {
6164 $tag_escaped = str_replace("'", "\\'", $tag);
6166 if (mb_strlen($tag) > 30) {
6167 $tag = truncate_string($tag, 30);
6170 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6172 array_push($formatted_tags, $tag_str);
6174 $tmp_tags_str = implode(", ", $formatted_tags);
6176 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6181 $tags_str = implode(", ", $formatted_tags);
6183 if ($num_tags < count($tags)) {
6184 $tags_str .= ", …";
6187 if ($num_tags == 0) {
6188 $tags_str = __("no tags");
6195 function format_article_labels($labels, $id) {
6199 foreach ($labels as $l) {
6200 $labels_str .= sprintf("<span class='hlLabelRef'
6201 style='color : %s; background-color : %s'>%s</span>",
6202 $l[2], $l[3], $l[1]);
6209 function format_article_note($id, $note) {
6211 $str = "<div class='articleNote' title=\"".__('edit note')."\"
6212 onclick=\"editArticleNote($id)\">$note</div>";
6217 function toggle_collapse_cat($link, $cat_id, $mode) {
6219 $mode = bool_to_sql_bool($mode);
6221 db_query($link, "UPDATE ttrss_feed_categories SET
6222 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6229 $pref_name = '_COLLAPSED_SPECIAL';
6232 $pref_name = '_COLLAPSED_LABELS';
6235 $pref_name = '_COLLAPSED_UNCAT';
6241 set_pref($link, $pref_name, 'true');
6243 set_pref($link, $pref_name, 'false');
6249 function remove_feed($link, $id, $owner_uid) {
6253 /* save starred articles in Archived feed */
6255 db_query($link, "BEGIN");
6257 /* prepare feed if necessary */
6259 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6262 if (db_num_rows($result) == 0) {
6263 db_query($link, "INSERT INTO ttrss_archived_feeds
6264 (id, owner_uid, title, feed_url, site_url)
6265 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6269 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6270 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6271 marked = true AND owner_uid = $owner_uid");
6273 /* Remove access key for the feed */
6275 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6276 feed_id = '$id' AND owner_uid = $owner_uid");
6278 /* remove the feed */
6280 db_query($link, "DELETE FROM ttrss_feeds
6281 WHERE id = '$id' AND owner_uid = $owner_uid");
6283 db_query($link, "COMMIT");
6285 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6286 unlink(ICONS_DIR . "/$id.ico");
6289 ccache_remove($link, $id, $owner_uid);
6292 label_remove($link, -11-$id, $owner_uid);
6293 ccache_remove($link, -11-$id, $owner_uid);
6297 function add_feed_category($link, $feed_cat) {
6299 if (!$feed_cat) return false;
6301 db_query($link, "BEGIN");
6303 $result = db_query($link,
6304 "SELECT id FROM ttrss_feed_categories
6305 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6307 if (db_num_rows($result) == 0) {
6309 $result = db_query($link,
6310 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6311 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6313 db_query($link, "COMMIT");
6321 function remove_feed_category($link, $id, $owner_uid) {
6323 db_query($link, "DELETE FROM ttrss_feed_categories
6324 WHERE id = '$id' AND owner_uid = $owner_uid");
6326 ccache_remove($link, $id, $owner_uid, true);
6329 function archive_article($link, $id, $owner_uid) {
6330 db_query($link, "BEGIN");
6332 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6333 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6335 if (db_num_rows($result) != 0) {
6337 /* prepare the archived table */
6339 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6342 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6343 WHERE id = '$feed_id'");
6345 if (db_num_rows($result) == 0) {
6346 db_query($link, "INSERT INTO ttrss_archived_feeds
6347 (id, owner_uid, title, feed_url, site_url)
6348 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6349 WHERE id = '$feed_id'");
6352 db_query($link, "UPDATE ttrss_user_entries
6353 SET orig_feed_id = feed_id, feed_id = NULL
6354 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6358 db_query($link, "COMMIT");
6361 function getArticleFeed($link, $id) {
6362 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6363 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6365 if (db_num_rows($result) != 0) {
6366 return db_fetch_result($result, 0, "feed_id");
6372 function make_url_from_parts($parts) {
6373 $url = $parts['scheme'] . '://' . $parts['host'];
6375 if ($parts['path']) $url .= $parts['path'];
6376 if ($parts['query']) $url .= '?' . $parts['query'];
6382 * Fixes incomplete URLs by prepending "http://".
6383 * Also replaces feed:// with http://, and
6384 * prepends a trailing slash if the url is a domain name only.
6386 * @param string $url Possibly incomplete URL
6388 * @return string Fixed URL.
6390 function fix_url($url) {
6391 if (strpos($url, '://') === false) {
6392 $url = 'http://' . $url;
6393 } else if (substr($url, 0, 5) == 'feed:') {
6394 $url = 'http:' . substr($url, 5);
6397 //prepend slash if the URL has no slash in it
6398 // "http://www.example" -> "http://www.example/"
6399 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6403 if ($url != "http:///")
6409 function validate_feed_url($url) {
6410 $parts = parse_url($url);
6412 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6416 function get_article_enclosures($link, $id) {
6420 $query = "SELECT * FROM ttrss_enclosures
6421 WHERE post_id = '$id' AND content_url != ''";
6423 $obj_id = md5("ENCLOSURES:$id");
6427 if ($memcache && $obj = $memcache->get($obj_id)) {
6430 $result = db_query($link, $query);
6432 if (db_num_rows($result) > 0) {
6433 while ($line = db_fetch_assoc($result)) {
6434 array_push($rv, $line);
6436 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6443 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6449 if ($cat_id == -4 ||
$cat_id == -2) {
6450 $counters = getLabelCounters($link, true);
6452 foreach (array_values($counters) as $cv) {
6454 $unread = $cv["counter"];
6456 if ($unread ||
!$unread_only) {
6460 "title" => $cv["description"],
6461 "unread" => $cv["counter"],
6465 array_push($feeds, $row);
6472 if ($cat_id == -4 ||
$cat_id == -1) {
6473 foreach (array(-1, -2, -3, -4, 0) as $i) {
6474 $unread = getFeedUnread($link, $i);
6476 if ($unread ||
!$unread_only) {
6477 $title = getFeedTitle($link, $i);
6482 "unread" => $unread,
6485 array_push($feeds, $row);
6494 $limit_qpart = "LIMIT $limit OFFSET $offset";
6499 if ($cat_id == -4 ||
$cat_id == -3) {
6500 $result = db_query($link, "SELECT
6501 id, feed_url, cat_id, title, ".
6502 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6503 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6504 " ORDER BY cat_id, title " . $limit_qpart);
6508 $cat_qpart = "cat_id = '$cat_id'";
6510 $cat_qpart = "cat_id IS NULL";
6512 $result = db_query($link, "SELECT
6513 id, feed_url, cat_id, title, ".
6514 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6515 FROM ttrss_feeds WHERE
6516 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6517 " ORDER BY cat_id, title " . $limit_qpart);
6520 while ($line = db_fetch_assoc($result)) {
6522 $unread = getFeedUnread($link, $line["id"]);
6524 $has_icon = feed_has_icon($line['id']);
6526 if ($unread ||
!$unread_only) {
6529 "feed_url" => $line["feed_url"],
6530 "title" => $line["title"],
6531 "id" => (int)$line["id"],
6532 "unread" => (int)$unread,
6533 "has_icon" => $has_icon,
6534 "cat_id" => (int)$line["cat_id"],
6535 "last_updated" => strtotime($line["last_updated"])
6538 array_push($feeds, $row);
6545 function api_get_headlines($link, $feed_id, $limit, $offset,
6546 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6548 /* do not rely on params below */
6550 $search = db_escape_string($_REQUEST["search"]);
6551 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6552 $match_on = db_escape_string($_REQUEST["match_on"]);
6554 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6555 $view_mode, $is_cat, $search, $search_mode, $match_on,
6558 $result = $qfh_ret[0];
6559 $feed_title = $qfh_ret[1];
6561 $headlines = array();
6563 while ($line = db_fetch_assoc($result)) {
6564 $is_updated = ($line["last_read"] == "" &&
6565 ($line["unread"] != "t" && $line["unread"] != "1"));
6567 $headline_row = array(
6568 "id" => (int)$line["id"],
6569 "unread" => sql_bool_to_bool($line["unread"]),
6570 "marked" => sql_bool_to_bool($line["marked"]),
6571 "published" => sql_bool_to_bool($line["published"]),
6572 "updated" => strtotime($line["updated"]),
6573 "is_updated" => $is_updated,
6574 "title" => $line["title"],
6575 "link" => $line["link"],
6576 "feed_id" => $line["feed_id"],
6577 "tags" => get_article_tags($link, $line["id"]),
6580 if ($show_excerpt) {
6581 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6582 $headline_row["excerpt"] = $excerpt;
6585 if ($show_content) {
6586 $headline_row["content"] = $line["content_preview"];
6589 array_push($headlines, $headline_row);
6595 function generate_error_feed($link, $error) {
6598 $reply['headlines']['id'] = -6;
6599 $reply['headlines']['is_cat'] = false;
6601 $reply['headlines']['toolbar'] = '';
6602 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6604 $reply['headlines-info'] = array("count" => 0,
6605 "vgroup_last_feed" => '',
6607 "disable_cache" => true);
6613 function generate_dashboard_feed($link) {
6616 $reply['headlines']['id'] = -5;
6617 $reply['headlines']['is_cat'] = false;
6619 $reply['headlines']['toolbar'] = '';
6620 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6622 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6624 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6625 WHERE owner_uid = " . $_SESSION['uid']);
6627 $last_updated = db_fetch_result($result, 0, "last_updated");
6628 $last_updated = make_local_datetime($link, $last_updated, false);
6630 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6632 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6633 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6635 $num_errors = db_fetch_result($result, 0, "num_errors");
6637 if ($num_errors > 0) {
6638 $reply['headlines']['content'] .= "<br/>";
6639 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6640 __('Some feeds have update errors (click for details)')."</a>";
6642 $reply['headlines']['content'] .= "</span></p>";
6644 $reply['headlines-info'] = array("count" => 0,
6645 "vgroup_last_feed" => '',
6647 "disable_cache" => true);
6652 function save_email_address($link, $email) {
6653 // FIXME: implement persistent storage of emails
6655 if (!$_SESSION['stored_emails'])
6656 $_SESSION['stored_emails'] = array();
6658 if (!in_array($email, $_SESSION['stored_emails']))
6659 array_push($_SESSION['stored_emails'], $email);
6662 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6663 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6665 $sql_is_cat = bool_to_sql_bool($is_cat);
6667 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6668 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6669 AND owner_uid = " . $owner_uid);
6671 if (db_num_rows($result) == 1) {
6672 $key = db_escape_string(sha1(uniqid(rand(), true)));
6674 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6675 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6676 AND owner_uid = " . $owner_uid);
6681 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6685 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6687 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6689 $sql_is_cat = bool_to_sql_bool($is_cat);
6691 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6692 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6693 AND owner_uid = " . $owner_uid);
6695 if (db_num_rows($result) == 1) {
6696 return db_fetch_result($result, 0, "access_key");
6698 $key = db_escape_string(sha1(uniqid(rand(), true)));
6700 $result = db_query($link, "INSERT INTO ttrss_access_keys
6701 (access_key, feed_id, is_cat, owner_uid)
6702 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6710 * Extracts RSS/Atom feed URLs from the given HTML URL.
6712 * @param string $url HTML page URL
6714 * @return array Array of feeds. Key is the full URL, value the title
6716 function get_feeds_from_html($url, $login = false, $pass = false)
6718 $url = fix_url($url);
6719 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6721 libxml_use_internal_errors(true);
6723 $content = @fetch_file_contents
($url, false, $login, $pass);
6725 $doc = new DOMDocument();
6726 $doc->loadHTML($content);
6727 $xpath = new DOMXPath($doc);
6728 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6729 $feedUrls = array();
6730 foreach ($entries as $entry) {
6731 if ($entry->hasAttribute('href')) {
6732 $title = $entry->getAttribute('title');
6734 $title = $entry->getAttribute('type');
6736 $feedUrl = rewrite_relative_url(
6737 $baseUrl, $entry->getAttribute('href')
6739 $feedUrls[$feedUrl] = $title;
6746 * Checks if the content behind the given URL is a HTML file
6748 * @param string $url URL to check
6750 * @return boolean True if the URL contains HTML content
6752 function url_is_html($url, $login = false, $pass = false) {
6753 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6755 if (stripos($content, '<html>') === false
6756 && stripos($content, '<html ') === false
6764 function print_label_select($link, $name, $value, $attributes = "") {
6766 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6767 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6769 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6770 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6772 while ($line = db_fetch_assoc($result)) {
6774 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6776 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6777 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6781 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6788 function format_article_enclosures($link, $id, $always_display_enclosures,
6791 $result = get_article_enclosures($link, $id);
6794 if (count($result) > 0) {
6796 $entries_html = array();
6799 foreach ($result as $line) {
6801 $url = $line["content_url"];
6802 $ctype = $line["content_type"];
6804 if (!$ctype) $ctype = __("unknown type");
6806 # $filename = substr($url, strrpos($url, "/")+1);
6808 $entry = format_inline_player($link, $url, $ctype);
6810 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6811 # $filename . " (" . $ctype . ")" . "</a>";
6813 array_push($entries_html, $entry);
6817 $entry["type"] = $ctype;
6818 $entry["filename"] = $filename;
6819 $entry["url"] = $url;
6821 array_push($entries, $entry);
6824 $rv .= "<div class=\"postEnclosures\">";
6826 if (!get_pref($link, "STRIP_IMAGES")) {
6827 if ($always_display_enclosures ||
6828 !preg_match("/<img/i", $article_content)) {
6830 foreach ($entries as $entry) {
6832 if (preg_match("/image/", $entry["type"]) ||
6833 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6836 alt=\"".htmlspecialchars($entry["filename"])."\"
6837 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6843 if (count($entries) == 1) {
6844 $rv .= __("Attachment:") . " ";
6846 $rv .= __("Attachments:") . " ";
6849 $rv .= join(", ", $entries_html);
6857 function getLastArticleId($link) {
6858 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
6859 WHERE owner_uid = " . $_SESSION["uid"]);
6861 if (db_num_rows($result) == 1) {
6862 return db_fetch_result($result, 0, "id");
6868 function build_url($parts) {
6869 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
6873 * Converts a (possibly) relative URL to a absolute one.
6875 * @param string $url Base URL (i.e. from where the document is)
6876 * @param string $rel_url Possibly relative URL in the document
6878 * @return string Absolute URL
6880 function rewrite_relative_url($url, $rel_url) {
6881 if (strpos($rel_url, "://") !== false) {
6883 } else if (strpos($rel_url, "/") === 0)
6885 $parts = parse_url($url);
6886 $parts['path'] = $rel_url;
6888 return build_url($parts);
6891 $parts = parse_url($url);
6892 if (!isset($parts['path'])) {
6893 $parts['path'] = '/';
6895 $dir = $parts['path'];
6896 if (substr($dir, -1) !== '/') {
6897 $dir = dirname($parts['path']);
6898 $dir !== '/' && $dir .= '/';
6900 $parts['path'] = $dir . $rel_url;
6902 return build_url($parts);
6906 function sphinx_search($query, $offset = 0, $limit = 30) {
6907 $sphinxClient = new SphinxClient();
6909 $sphinxClient->SetServer('localhost', 9312);
6910 $sphinxClient->SetConnectTimeout(1);
6912 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
6913 'feed_title' => 20));
6915 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
6916 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
6917 $sphinxClient->SetLimits($offset, $limit, 1000);
6918 $sphinxClient->SetArrayResult(false);
6919 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
6921 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
6925 if (is_array($result['matches'])) {
6926 foreach (array_keys($result['matches']) as $int_id) {
6927 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
6928 array_push($ids, $ref_id);
6935 function cleanup_tags($link, $days = 14, $limit = 1000) {
6937 if (DB_TYPE
== "pgsql") {
6938 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
6939 } else if (DB_TYPE
== "mysql") {
6940 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
6945 while ($limit > 0) {
6948 $query = "SELECT ttrss_tags.id AS id
6949 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
6950 WHERE post_int_id = int_id AND $interval_query AND
6951 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
6953 $result = db_query($link, $query);
6957 while ($line = db_fetch_assoc($result)) {
6958 array_push($ids, $line['id']);
6961 if (count($ids) > 0) {
6962 $ids = join(",", $ids);
6965 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
6966 $tags_deleted +
= db_affected_rows($link, $tmp_result);
6971 $limit -= $limit_part;
6976 return $tags_deleted;
6979 function feedlist_init_cat($link, $cat_id, $hidden = false) {
6981 $cat_id = (int) $cat_id;
6984 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
6985 } else if ($cat_id == 0 ||
$cat_id == -2) {
6986 $cat_unread = getCategoryUnread($link, $cat_id);
6989 $obj['id'] = 'CAT:' . $cat_id;
6990 $obj['items'] = array();
6991 $obj['name'] = getCategoryTitle($link, $cat_id);
6992 $obj['type'] = 'feed';
6993 $obj['unread'] = (int) $cat_unread;
6994 $obj['hidden'] = $hidden;
6995 $obj['bare_id'] = $cat_id;
7000 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7002 $feed_id = (int) $feed_id;
7005 $title = getFeedTitle($link, $feed_id, false);
7007 if ($unread === false)
7008 $unread = getFeedUnread($link, $feed_id, false);
7010 $obj['id'] = 'FEED:' . $feed_id;
7011 $obj['name'] = $title;
7012 $obj['unread'] = (int) $unread;
7013 $obj['type'] = 'feed';
7014 $obj['error'] = $error;
7015 $obj['updated'] = $updated;
7016 $obj['icon'] = getFeedIcon($feed_id);
7017 $obj['bare_id'] = $feed_id;
7023 function fetch_twitter_rss($link, $url, $owner_uid) {
7024 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7025 WHERE id = $owner_uid");
7027 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7028 $url_escaped = db_escape_string($url);
7030 if ($access_token) {
7032 $tmhOAuth = new tmhOAuth(array(
7033 'consumer_key' => CONSUMER_KEY
,
7034 'consumer_secret' => CONSUMER_SECRET
,
7035 'user_token' => $access_token['oauth_token'],
7036 'user_secret' => $access_token['oauth_token_secret'],
7039 $code = $tmhOAuth->request('GET', $url);
7043 $content = $tmhOAuth->response
['response'];
7045 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7046 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7052 db_query($link, "UPDATE ttrss_feeds
7053 SET last_error = 'OAuth authorization failed ($code).'
7054 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7059 db_query($link, "UPDATE ttrss_feeds
7060 SET last_error = 'OAuth information not found.'
7061 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7067 function print_user_stylesheet($link) {
7068 $value = get_pref($link, 'USER_STYLESHEET');
7071 print "<style type=\"text/css\">";
7072 print str_replace("<br/>", "\n", $value);
7078 function rewrite_urls($line) {
7083 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7084 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);