3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if (!$owner_uid) return;
150 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
153 if (!$purge_unread) $query_limit = " unread = false AND ";
155 if (DB_TYPE
== "pgsql") {
156 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
157 marked = false AND feed_id = '$feed_id' AND
158 (SELECT date_entered FROM ttrss_entries WHERE
159 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
161 $pg_version = get_pgsql_version($link);
163 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
165 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
166 ttrss_entries.id = ref_id AND
168 feed_id = '$feed_id' AND
170 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
174 $result = db_query($link, "DELETE FROM ttrss_user_entries
176 WHERE ttrss_entries.id = ref_id AND
178 feed_id = '$feed_id' AND
180 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
183 $rows = pg_affected_rows($result);
187 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
188 marked = false AND feed_id = '$feed_id' AND
189 (SELECT date_entered FROM ttrss_entries WHERE
190 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_user_entries, ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
196 feed_id = '$feed_id' AND
198 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
200 $rows = mysql_affected_rows($link);
205 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
207 } // function purge_feed
210 * Purge old posts from old feeds.
212 * @param mixed $link A database connection
213 * @param boolean $do_output Set to true to enable printed output, false by default.
214 * @param integer $limit The maximal number of removed posts.
218 function global_purge_old_posts($link, $do_output = false, $limit = false) {
220 $random_qpart = sql_random_function();
223 $limit_qpart = "LIMIT $limit";
228 $result = db_query($link,
229 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
230 ORDER BY $random_qpart $limit_qpart");
232 while ($line = db_fetch_assoc($result)) {
234 $feed_id = $line["id"];
235 $purge_interval = $line["purge_interval"];
236 $owner_uid = $line["owner_uid"];
238 if ($purge_interval == 0) {
240 $tmp_result = db_query($link,
241 "SELECT value FROM ttrss_user_prefs WHERE
242 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
244 if (db_num_rows($tmp_result) != 0) {
245 $purge_interval = db_fetch_result($tmp_result, 0, "value");
250 // print "Feed $feed_id: purge interval = $purge_interval\n";
253 if ($purge_interval > 0) {
254 purge_feed($link, $feed_id, $purge_interval, $do_output);
258 // purge orphaned posts in main content table
259 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
260 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
263 $rows = db_affected_rows($link, $result);
264 _debug("Purged $rows orphaned posts.");
267 } // function global_purge_old_posts
269 function feed_purge_interval($link, $feed_id) {
271 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
272 WHERE id = '$feed_id'");
274 if (db_num_rows($result) == 1) {
275 $purge_interval = db_fetch_result($result, 0, "purge_interval");
276 $owner_uid = db_fetch_result($result, 0, "owner_uid");
278 if ($purge_interval == 0) $purge_interval = get_pref($link,
279 'PURGE_OLD_DAYS', $user_id);
281 return $purge_interval;
288 function purge_old_posts($link) {
290 $user_id = $_SESSION["uid"];
292 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
293 WHERE owner_uid = '$user_id'");
295 while ($line = db_fetch_assoc($result)) {
297 $feed_id = $line["id"];
298 $purge_interval = $line["purge_interval"];
300 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
302 if ($purge_interval > 0) {
303 purge_feed($link, $feed_id, $purge_interval);
307 // purge orphaned posts in main content table
308 db_query($link, "DELETE FROM ttrss_entries WHERE
309 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
312 function get_feed_update_interval($link, $feed_id) {
313 $result = db_query($link, "SELECT owner_uid, update_interval FROM
314 ttrss_feeds WHERE id = '$feed_id'");
316 if (db_num_rows($result) == 1) {
317 $update_interval = db_fetch_result($result, 0, "update_interval");
318 $owner_uid = db_fetch_result($result, 0, "owner_uid");
320 if ($update_interval != 0) {
321 return $update_interval;
323 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
331 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
333 if (WEB_DEMO_MODE
) return;
336 $user_id = $_SESSION["uid"];
337 purge_old_posts($link);
340 // db_query($link, "BEGIN");
342 if (MAX_UPDATE_TIME
> 0) {
343 if (DB_TYPE
== "mysql") {
346 $q_order = "RANDOM()";
349 $q_order = "last_updated DESC";
352 $result = db_query($link, "SELECT feed_url,id,
353 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
354 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
359 while ($line = db_fetch_assoc($result)) {
360 $upd_intl = $line["update_interval"];
362 if (!$upd_intl ||
$upd_intl == 0) {
363 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
367 // Updates for this feed are disabled
371 if ($fetch ||
(!$line["last_updated"] ||
372 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
374 // print "<!-- feed: ".$line["feed_url"]." -->";
376 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
378 $upd_elapsed = time() - $upd_start;
380 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
386 // db_query($link, "COMMIT");
390 function fetch_file_contents($url) {
391 if (USE_CURL_FOR_ICONS
) {
392 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
394 $ch = curl_init($url);
395 $fp = fopen($tmpfile, "w");
398 curl_setopt($ch, CURLOPT_FILE
, $fp);
399 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
400 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
406 $contents = file_get_contents($tmpfile);
412 return file_get_contents($url);
418 * Try to determine the favicon URL for a feed.
419 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
420 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
422 * @param string $url A feed or page URL
424 * @return mixed The favicon URL, or false if none was found.
426 function get_favicon_url($url) {
428 if ($html = @fetch_file_contents
($url)) {
430 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
431 // Attempt to grab a favicon link from their webpage url
432 $linkUrl = html_entity_decode($matches[1]);
434 if (substr($linkUrl, 0, 1) == '/') {
435 $urlParts = parse_url($url);
436 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
437 } else if (substr($linkUrl, 0, 7) == 'http://') {
438 $faviconURL = $linkUrl;
439 } else if (substr($url, -1, 1) == '/') {
440 $faviconURL = $url.$linkUrl;
442 $faviconURL = $url.'/'.$linkUrl;
446 // If unsuccessful, attempt to "guess" the favicon location
447 $urlParts = parse_url($url);
448 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
452 // Run a test to see if what we have attempted to get actually exists.
453 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
458 } // function get_favicon_url
461 * Check if a link is a valid and working URL.
463 * @param mixed $link A URL to check
465 * @return boolean True if the URL is valid, false otherwise.
467 function url_validate($link) {
469 $url_parts = @parse_url
($link);
471 if ( empty( $url_parts["host"] ) )
474 if ( !empty( $url_parts["path"] ) ) {
475 $documentpath = $url_parts["path"];
480 if ( !empty( $url_parts["query"] ) )
481 $documentpath .= "?" . $url_parts["query"];
483 $host = $url_parts["host"];
484 $port = $url_parts["port"];
489 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
494 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
496 $http_response = fgets( $socket, 22 );
498 $responses = "/(200 OK)|(30[0-9] Moved)/";
499 if ( preg_match($responses, $http_response) ) {
506 } // function url_validate
508 function check_feed_favicon($site_url, $feed, $link) {
509 $favicon_url = get_favicon_url($site_url);
511 # print "FAVICON [$site_url]: $favicon_url\n";
515 $icon_file = ICONS_DIR
. "/$feed.ico";
517 if ($favicon_url && !file_exists($icon_file)) {
518 $contents = fetch_file_contents($favicon_url);
520 $fp = fopen($icon_file, "w");
523 fwrite($fp, $contents);
525 chmod($icon_file, 0644);
529 error_reporting(DEFAULT_ERROR_LEVEL
);
533 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
535 if (!$_GET["daemon"] && !$ignore_daemon) {
539 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
540 _debug("update_rss_feed: start");
543 if (!$ignore_daemon) {
545 if (DB_TYPE
== "pgsql") {
546 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
548 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
551 $result = db_query($link, "SELECT id,update_interval,auth_login,
552 auth_pass,cache_images,update_method
553 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
557 $result = db_query($link, "SELECT id,update_interval,auth_login,
558 auth_pass,cache_images,update_method
559 FROM ttrss_feeds WHERE id = '$feed'");
563 if (db_num_rows($result) == 0) {
564 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
565 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
570 $update_method = db_fetch_result($result, 0, "update_method");
572 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
573 WHERE id = '$feed'");
575 $auth_login = db_fetch_result($result, 0, "auth_login");
576 $auth_pass = db_fetch_result($result, 0, "auth_pass");
578 if (ALLOW_SELECT_UPDATE_METHOD
) {
579 if (ENABLE_SIMPLEPIE
) {
580 $use_simplepie = $update_method != 1;
582 $use_simplepie = $update_method == 2;
585 $use_simplepie = ENABLE_SIMPLEPIE
;
588 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
589 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
592 if (!$use_simplepie) {
593 $auth_login = urlencode($auth_login);
594 $auth_pass = urlencode($auth_pass);
597 $update_interval = db_fetch_result($result, 0, "update_interval");
598 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
600 if ($update_interval < 0) { return; }
602 $feed = db_escape_string($feed);
604 $fetch_url = $feed_url;
606 if ($auth_login && $auth_pass) {
607 $url_parts = array();
608 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
610 if ($url_parts[1] && $url_parts[2]) {
611 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
616 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
617 _debug("update_rss_feed: fetching [$fetch_url]...");
620 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
624 if (!$use_simplepie) {
625 $rss = fetch_rss($fetch_url);
627 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
628 mkdir(SIMPLEPIE_CACHE_DIR
);
631 $rss = new SimplePie();
632 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
633 # $rss->set_timeout(10);
634 $rss->set_feed_url($fetch_url);
635 $rss->set_output_encoding('UTF-8');
637 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
638 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
639 _debug("enabling image cache");
642 $rss->set_image_handler('./image.php', 'i');
645 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
646 _debug("feed update interval (sec): " .
647 get_feed_update_interval($link, $feed)*60);
650 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
651 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
652 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
660 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
661 _debug("update_rss_feed: fetch done, parsing...");
663 error_reporting (DEFAULT_ERROR_LEVEL
);
666 $feed = db_escape_string($feed);
668 if ($use_simplepie) {
669 $fetch_ok = !$rss->error();
676 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
677 _debug("update_rss_feed: processing feed data...");
680 // db_query($link, "BEGIN");
682 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
683 FROM ttrss_feeds WHERE id = '$feed'");
685 $registered_title = db_fetch_result($result, 0, "title");
686 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
687 $orig_site_url = db_fetch_result($result, 0, "site_url");
689 $owner_uid = db_fetch_result($result, 0, "owner_uid");
691 if ($use_simplepie) {
692 $site_url = $rss->get_link();
694 $site_url = $rss->channel
["link"];
697 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
698 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
699 _debug("update_rss_feed: checking favicon...");
702 check_feed_favicon($site_url, $feed, $link);
705 if (!$registered_title ||
$registered_title == "[Unknown]") {
707 if ($use_simplepie) {
708 $feed_title = db_escape_string($rss->get_title());
710 $feed_title = db_escape_string($rss->channel
["title"]);
713 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
714 _debug("update_rss_feed: registering title: $feed_title");
717 db_query($link, "UPDATE ttrss_feeds SET
718 title = '$feed_title' WHERE id = '$feed'");
721 // weird, weird Magpie
722 if (!$use_simplepie) {
723 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
726 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
727 db_query($link, "UPDATE ttrss_feeds SET
728 site_url = '$site_url' WHERE id = '$feed'");
731 // print "I: " . $rss->channel["image"]["url"];
733 if (!$use_simplepie) {
734 $icon_url = $rss->image
["url"];
736 $icon_url = $rss->get_image_url();
739 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
740 $icon_url = db_escape_string($icon_url);
741 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
744 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
745 _debug("update_rss_feed: loading filters...");
748 $filters = load_filters($link, $feed, $owner_uid);
750 if ($use_simplepie) {
751 $iterator = $rss->get_items();
753 $iterator = $rss->items
;
754 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
755 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
758 if (!is_array($iterator)) {
759 /* db_query($link, "UPDATE ttrss_feeds
760 SET last_error = 'Parse error: can\'t find any articles.'
761 WHERE id = '$feed'"); */
763 // clear any errors and mark feed as updated if fetched okay
764 // even if it's blank
766 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
767 _debug("update_rss_feed: entry iterator is not an array, no articles?");
770 db_query($link, "UPDATE ttrss_feeds
771 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
773 return; // no articles
776 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
777 _debug("update_rss_feed: processing articles...");
780 foreach ($iterator as $item) {
782 if ($_GET['xdebug']) {
787 if ($use_simplepie) {
788 $entry_guid = $item->get_id();
789 if (!$entry_guid) $entry_guid = $item->get_link();
790 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
794 $entry_guid = $item["id"];
796 if (!$entry_guid) $entry_guid = $item["guid"];
797 if (!$entry_guid) $entry_guid = $item["link"];
798 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
801 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
802 _debug("update_rss_feed: guid $entry_guid");
805 if (!$entry_guid) continue;
807 $entry_timestamp = "";
809 if ($use_simplepie) {
810 $entry_timestamp = strtotime($item->get_date());
812 $rss_2_date = $item['pubdate'];
813 $rss_1_date = $item['dc']['date'];
814 $atom_date = $item['issued'];
815 if (!$atom_date) $atom_date = $item['updated'];
817 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
818 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
819 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
822 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
823 $entry_timestamp = time();
824 $no_orig_date = 'true';
826 $no_orig_date = 'false';
829 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
831 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
832 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
835 if ($use_simplepie) {
836 $entry_title = $item->get_title();
838 $entry_title = trim(strip_tags($item["title"]));
841 if ($use_simplepie) {
842 $entry_link = $item->get_link();
844 // strange Magpie workaround
845 $entry_link = $item["link_"];
846 if (!$entry_link) $entry_link = $item["link"];
849 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
850 _debug("update_rss_feed: title $entry_title");
853 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
855 $entry_link = strip_tags($entry_link);
857 if ($use_simplepie) {
858 $entry_content = $item->get_content();
859 if (!$entry_content) $entry_content = $item->get_description();
861 $entry_content = $item["content:escaped"];
863 if (!$entry_content) $entry_content = $item["content:encoded"];
864 if (!$entry_content) $entry_content = $item["content"]["encoded"];
865 if (!$entry_content) $entry_content = $item["content"];
867 // Magpie bugs are getting ridiculous
868 if (trim($entry_content) == "Array") $entry_content = false;
870 if (!$entry_content) $entry_content = $item["atom_content"];
871 if (!$entry_content) $entry_content = $item["summary"];
873 if (!$entry_content ||
874 strlen($entry_content) < strlen($item["description"])) {
875 $entry_content = $item["description"];
879 if (is_array($entry_content)) {
880 $entry_content = $entry_content["encoded"];
881 if (!$entry_content) $entry_content = $entry_content["escaped"];
885 if ($_GET["xdebug"]) {
886 print "update_rss_feed: content: ";
887 print_r(htmlspecialchars($entry_content));
890 $entry_content_unescaped = $entry_content;
892 if ($use_simplepie) {
893 $entry_comments = strip_tags($item->data
["comments"]);
894 if ($item->get_author()) {
895 $entry_author_item = $item->get_author();
896 $entry_author = $entry_author_item->get_name();
897 if (!$entry_author) $entry_author = $entry_author_item->get_email();
899 $entry_author = db_escape_string($entry_author);
902 $entry_comments = strip_tags($item["comments"]);
904 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
906 if ($item['author']) {
908 if (is_array($item['author'])) {
910 if (!$entry_author) {
911 $entry_author = db_escape_string(strip_tags($item['author']['name']));
914 if (!$entry_author) {
915 $entry_author = db_escape_string(strip_tags($item['author']['email']));
919 if (!$entry_author) {
920 $entry_author = db_escape_string(strip_tags($item['author']));
925 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
927 $entry_guid = db_escape_string(strip_tags($entry_guid));
928 $entry_guid = mb_substr($entry_guid, 0, 250);
930 $result = db_query($link, "SELECT id FROM ttrss_entries
931 WHERE guid = '$entry_guid'");
933 $entry_content = db_escape_string($entry_content);
935 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
937 $entry_title = db_escape_string($entry_title);
938 $entry_link = db_escape_string($entry_link);
939 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
940 $entry_author = mb_substr($entry_author, 0, 250);
942 if ($use_simplepie) {
943 $num_comments = 0; #FIXME#
945 $num_comments = db_escape_string($item["slash"]["comments"]);
948 if (!$num_comments) $num_comments = 0;
950 // parse <category> entries into tags
952 if ($use_simplepie) {
954 $additional_tags = array();
955 $additional_tags_src = $item->get_categories();
957 if (is_array($additional_tags_src)) {
958 foreach ($additional_tags_src as $tobj) {
959 array_push($additional_tags, $tobj->get_term());
963 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
964 _debug("update_rss_feed: category tags:");
965 print_r($additional_tags);
970 $t_ctr = $item['category#'];
972 $additional_tags = false;
975 $additional_tags = false;
976 } else if ($t_ctr > 0) {
977 $additional_tags = array($item['category']);
979 if ($item['category@term']) {
980 array_push($additional_tags, $item['category@term']);
983 for ($i = 0; $i <= $t_ctr; $i++
) {
984 if ($item["category#$i"]) {
985 array_push($additional_tags, $item["category#$i"]);
988 if ($item["category#$i@term"]) {
989 array_push($additional_tags, $item["category#$i@term"]);
994 // parse <dc:subject> elements
996 $t_ctr = $item['dc']['subject#'];
999 $additional_tags = array($item['dc']['subject']);
1001 for ($i = 0; $i <= $t_ctr; $i++
) {
1002 if ($item['dc']["subject#$i"]) {
1003 array_push($additional_tags, $item['dc']["subject#$i"]);
1011 $enclosures = array();
1013 if ($use_simplepie) {
1014 $encs = $item->get_enclosures();
1016 if (is_array($encs)) {
1017 foreach ($encs as $e) {
1019 $e->link
, $e->type
, $e->length
);
1021 array_push($enclosures, $e_item);
1028 $e_ctr = $item['enclosure#'];
1031 $e_item = array($item['enclosure@url'],
1032 $item['enclosure@type'],
1033 $item['enclosure@length']);
1035 array_push($enclosures, $e_item);
1037 for ($i = 0; $i <= $e_ctr; $i++
) {
1039 if ($item["enclosure#$i@url"]) {
1040 $e_item = array($item["enclosure#$i@url"],
1041 $item["enclosure#$i@type"],
1042 $item["enclosure#$i@length"]);
1043 array_push($enclosures, $e_item);
1049 // can there be many of those? yes -fox
1051 $m_ctr = $item['media']['content#'];
1054 $e_item = array($item['media']['content@url'],
1055 $item['media']['content@medium'],
1056 $item['media']['content@length']);
1058 array_push($enclosures, $e_item);
1060 for ($i = 0; $i <= $m_ctr; $i++
) {
1062 if ($item["media"]["content#$i@url"]) {
1063 $e_item = array($item["media"]["content#$i@url"],
1064 $item["media"]["content#$i@medium"],
1065 $item["media"]["content#$i@length"]);
1066 array_push($enclosures, $e_item);
1075 $entry_content = sanitize_article_content($entry_content);
1076 $entry_title = sanitize_article_content($entry_title);
1078 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1079 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1082 db_query($link, "BEGIN");
1084 if (db_num_rows($result) == 0) {
1086 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1087 _debug("update_rss_feed: base guid not found");
1090 // base post entry does not exist, create it
1092 $result = db_query($link,
1093 "INSERT INTO ttrss_entries
1109 '$entry_timestamp_fmt',
1118 // we keep encountering the entry in feeds, so we need to
1119 // update date_entered column so that we don't get horrible
1120 // dupes when the entry gets purged and reinserted again e.g.
1121 // in the case of SLOW SLOW OMG SLOW updating feeds
1123 $base_entry_id = db_fetch_result($result, 0, "id");
1125 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1126 WHERE id = '$base_entry_id'");
1129 // now it should exist, if not - bad luck then
1131 $result = db_query($link, "SELECT
1132 id,content_hash,no_orig_date,title,
1133 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1134 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1138 WHERE guid = '$entry_guid'");
1143 if (db_num_rows($result) == 1) {
1145 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1146 _debug("update_rss_feed: base guid found, checking for user record");
1149 // this will be used below in update handler
1150 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1151 $orig_title = db_fetch_result($result, 0, "title");
1152 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1153 $orig_date_entered = strtotime(db_fetch_result($result,
1154 0, "date_entered"));
1156 $ref_id = db_fetch_result($result, 0, "id");
1157 $entry_ref_id = $ref_id;
1159 // check for user post link to main table
1161 // do we allow duplicate posts with same GUID in different feeds?
1162 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1163 $dupcheck_qpart = "AND feed_id = '$feed'";
1165 $dupcheck_qpart = "";
1168 // error_reporting(0);
1170 $article_filters = get_article_filters($filters, $entry_title,
1171 $entry_content, $entry_link, $entry_timestamp);
1173 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1174 _debug("update_rss_feed: article filters: ");
1175 if (count($article_filters) != 0) {
1176 print_r($article_filters);
1180 if (find_article_filter($article_filters, "filter")) {
1181 db_query($link, "COMMIT"); // close transaction in progress
1185 // error_reporting (DEFAULT_ERROR_LEVEL);
1187 $score = calculate_article_score($article_filters);
1189 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1190 _debug("update_rss_feed: initial score: $score");
1193 $result = db_query($link,
1194 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1195 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1198 // okay it doesn't exist - create user entry
1199 if (db_num_rows($result) == 0) {
1201 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1202 _debug("update_rss_feed: user record not found, creating...");
1205 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1207 $last_read_qpart = 'NULL';
1210 $last_read_qpart = 'NOW()';
1213 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1219 if (find_article_filter($article_filters, 'publish')) {
1220 $published = 'true';
1222 $published = 'false';
1225 $result = db_query($link,
1226 "INSERT INTO ttrss_user_entries
1227 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1229 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1230 $last_read_qpart, $marked, $published, '$score')");
1232 $result = db_query($link,
1233 "SELECT int_id FROM ttrss_user_entries WHERE
1234 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1235 feed_id = '$feed' LIMIT 1");
1237 if (db_num_rows($result) == 1) {
1238 $entry_int_id = db_fetch_result($result, 0, "int_id");
1241 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1242 $entry_int_id = db_fetch_result($result, 0, "int_id");
1245 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1246 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1249 $post_needs_update = false;
1251 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1252 ($content_hash != $orig_content_hash)) {
1253 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1254 $post_needs_update = true;
1257 if (db_escape_string($orig_title) != $entry_title) {
1258 $post_needs_update = true;
1261 if ($orig_num_comments != $num_comments) {
1262 $post_needs_update = true;
1265 // this doesn't seem to be very reliable
1267 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1268 // $post_needs_update = true;
1271 // if post needs update, update it and mark all user entries
1272 // linking to this post as updated
1273 if ($post_needs_update) {
1275 if (defined('DAEMON_EXTENDED_DEBUG')) {
1276 _debug("update_rss_feed: post $entry_guid needs update...");
1279 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1281 db_query($link, "UPDATE ttrss_entries
1282 SET title = '$entry_title', content = '$entry_content',
1283 content_hash = '$content_hash',
1284 num_comments = '$num_comments'
1285 WHERE id = '$ref_id'");
1287 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1288 db_query($link, "UPDATE ttrss_user_entries
1289 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1291 db_query($link, "UPDATE ttrss_user_entries
1292 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1298 db_query($link, "COMMIT");
1300 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1301 _debug("update_rss_feed: looking for enclosures...");
1304 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1305 print_r($enclosures);
1308 db_query($link, "BEGIN");
1310 foreach ($enclosures as $enc) {
1311 $enc_url = db_escape_string($enc[0]);
1312 $enc_type = db_escape_string($enc[1]);
1313 $enc_dur = db_escape_string($enc[2]);
1315 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1316 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1318 if (db_num_rows($result) == 0) {
1319 db_query($link, "INSERT INTO ttrss_enclosures
1320 (content_url, content_type, title, duration, post_id) VALUES
1321 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1325 db_query($link, "COMMIT");
1327 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1328 _debug("update_rss_feed: looking for tags...");
1332 // <a href="..." rel="tag">Xorg</a>, //
1336 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1337 $entry_content_unescaped, $entry_tags);
1339 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1340 print_r($entry_tags);
1341 print "<br/></p>"; */
1343 $entry_tags = $entry_tags[1];
1345 # check for manual tags
1347 $tag_filter = find_article_filter($article_filters, "tag");
1351 $manual_tags = trim_array(split(",", $tag_filter[1]));
1353 foreach ($manual_tags as $tag) {
1354 if (tag_is_valid($tag)) {
1355 array_push($entry_tags, $tag);
1360 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1361 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1363 if ($additional_tags && is_array($additional_tags)) {
1364 foreach ($additional_tags as $tag) {
1365 if (tag_is_valid($tag) &&
1366 array_search($tag, $boring_tags) === FALSE) {
1367 array_push($entry_tags, $tag);
1372 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1374 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1375 print_r($entry_tags);
1378 if (count($entry_tags) > 0) {
1380 db_query($link, "BEGIN");
1382 foreach ($entry_tags as $tag) {
1384 $tag = sanitize_tag($tag);
1385 $tag = db_escape_string($tag);
1387 if (!tag_is_valid($tag)) continue;
1389 $result = db_query($link, "SELECT id FROM ttrss_tags
1390 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1391 owner_uid = '$owner_uid' LIMIT 1");
1393 // print db_fetch_result($result, 0, "id");
1395 if ($result && db_num_rows($result) == 0) {
1397 db_query($link, "INSERT INTO ttrss_tags
1398 (owner_uid,tag_name,post_int_id)
1399 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1403 db_query($link, "COMMIT");
1406 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1407 _debug("update_rss_feed: article processed");
1411 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1412 _debug("update_rss_feed: updating counters cache...");
1415 ccache_update($link, $feed, $owner_uid);
1417 db_query($link, "UPDATE ttrss_feeds
1418 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1420 // db_query($link, "COMMIT");
1424 if ($use_simplepie) {
1425 $error_msg = mb_substr($rss->error(), 0, 250);
1427 $error_msg = mb_substr(magpie_error(), 0, 250);
1430 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1431 _debug("update_rss_feed: error fetching feed: $error_msg");
1434 $error_msg = db_escape_string($error_msg);
1437 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1438 last_updated = NOW() WHERE id = '$feed'");
1441 if ($use_simplepie) {
1445 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1446 _debug("update_rss_feed: done");
1451 function print_select($id, $default, $values, $attributes = "") {
1452 print "<select name=\"$id\" id=\"$id\" $attributes>";
1453 foreach ($values as $v) {
1459 print "<option$sel>$v</option>";
1464 function print_select_hash($id, $default, $values, $attributes = "") {
1465 print "<select name=\"$id\" id='$id' $attributes>";
1466 foreach (array_keys($values) as $v) {
1468 $sel = 'selected="selected"';
1472 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1478 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1481 if ($filters["title"]) {
1482 foreach ($filters["title"] as $filter) {
1483 $reg_exp = $filter["reg_exp"];
1484 $inverse = $filter["inverse"];
1485 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1486 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1488 array_push($matches, array($filter["action"], $filter["action_param"]));
1493 if ($filters["content"]) {
1494 foreach ($filters["content"] as $filter) {
1495 $reg_exp = $filter["reg_exp"];
1496 $inverse = $filter["inverse"];
1498 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1499 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1501 array_push($matches, array($filter["action"], $filter["action_param"]));
1506 if ($filters["both"]) {
1507 foreach ($filters["both"] as $filter) {
1508 $reg_exp = $filter["reg_exp"];
1509 $inverse = $filter["inverse"];
1512 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1513 array_push($matches, array($filter["action"], $filter["action_param"]));
1516 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1517 array_push($matches, array($filter["action"], $filter["action_param"]));
1523 if ($filters["link"]) {
1524 $reg_exp = $filter["reg_exp"];
1525 foreach ($filters["link"] as $filter) {
1526 $reg_exp = $filter["reg_exp"];
1527 $inverse = $filter["inverse"];
1529 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1530 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1532 array_push($matches, array($filter["action"], $filter["action_param"]));
1537 if ($filters["date"]) {
1538 $reg_exp = $filter["reg_exp"];
1539 foreach ($filters["date"] as $filter) {
1540 $date_modifier = $filter["filter_param"];
1541 $inverse = $filter["inverse"];
1542 $check_timestamp = strtotime($filter["reg_exp"]);
1544 # no-op when timestamp doesn't parse to prevent misfires
1546 if ($check_timestamp) {
1549 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1550 $date_modifier == "after" && $timestamp > $check_timestamp) {
1554 if ($inverse) $match_ok = !$match_ok;
1557 array_push($matches, array($filter["action"], $filter["action_param"]));
1566 function find_article_filter($filters, $filter_name) {
1567 foreach ($filters as $f) {
1568 if ($f[0] == $filter_name) {
1575 function calculate_article_score($filters) {
1578 foreach ($filters as $f) {
1579 if ($f[0] == "score") {
1587 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1588 $rtl_content = false, $last_updated = false, $last_error = false) {
1590 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1591 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1593 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1597 $rtl_tag = "dir=\"rtl\"";
1599 $rtl_tag = "dir=\"ltr\"";
1602 $error_notify_msg = "";
1605 $link_title = "Error: $last_error ($last_updated)";
1606 $error_notify_msg = "(Error)";
1607 } else if ($last_updated) {
1608 $link_title = "Updated: $last_updated";
1611 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1612 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1614 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1615 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1619 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1622 $fctr_class = "class=\"feedCtrHasUnread\"";
1624 $fctr_class = "class=\"feedCtrNoUnread\"";
1627 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1628 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1630 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1631 $total = getFeedArticles($link, $feed_id);
1632 print "<div class=\"feedExtInfo\">
1633 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1640 function getmicrotime() {
1641 list($usec, $sec) = explode(" ",microtime());
1642 return ((float)$usec +
(float)$sec);
1645 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1646 foreach ($values as $v) {
1653 if ($v == $true_is) {
1654 $sel .= " value=\"1\"";
1656 $sel .= " value=\"0\"";
1659 print "<input class=\"noborder\"
1660 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1665 function initialize_user_prefs($link, $uid) {
1667 $uid = db_escape_string($uid);
1669 db_query($link, "BEGIN");
1671 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1673 $u_result = db_query($link, "SELECT pref_name
1674 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1676 $active_prefs = array();
1678 while ($line = db_fetch_assoc($u_result)) {
1679 array_push($active_prefs, $line["pref_name"]);
1682 while ($line = db_fetch_assoc($result)) {
1683 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1684 // print "adding " . $line["pref_name"] . "<br>";
1686 db_query($link, "INSERT INTO ttrss_user_prefs
1687 (owner_uid,pref_name,value) VALUES
1688 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1693 db_query($link, "COMMIT");
1697 function lookup_user_id($link, $user) {
1699 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1702 if (db_num_rows($result) == 1) {
1703 return db_fetch_result($result, 0, "id");
1709 function http_authenticate_user($link) {
1711 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1713 if (!$_SERVER["PHP_AUTH_USER"]) {
1715 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1716 header('HTTP/1.0 401 Unauthorized');
1720 $auth_result = authenticate_user($link,
1721 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1723 if (!$auth_result) {
1724 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1725 header('HTTP/1.0 401 Unauthorized');
1733 function authenticate_user($link, $login, $password, $force_auth = false) {
1735 if (!SINGLE_USER_MODE
) {
1737 $pwd_hash1 = encrypt_password($password);
1738 $pwd_hash2 = encrypt_password($password, $login);
1740 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1741 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1743 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1745 $query = "SELECT id,login,access_level,pwd_hash
1746 FROM ttrss_users WHERE
1750 $query = "SELECT id,login,access_level,pwd_hash
1751 FROM ttrss_users WHERE
1752 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1753 pwd_hash = '$pwd_hash2')";
1756 $result = db_query($link, $query);
1758 if (db_num_rows($result) == 1) {
1759 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1760 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1761 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1763 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1766 $user_theme = get_user_theme_path($link);
1768 $_SESSION["theme"] = $user_theme;
1769 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1770 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1772 initialize_user_prefs($link, $_SESSION["uid"]);
1781 $_SESSION["uid"] = 1;
1782 $_SESSION["name"] = "admin";
1784 $user_theme = get_user_theme_path($link);
1786 $_SESSION["theme"] = $user_theme;
1787 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1789 initialize_user_prefs($link, $_SESSION["uid"]);
1795 function make_password($length = 8) {
1798 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1802 while ($i < $length) {
1803 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1805 if (!strstr($password, $char)) {
1813 // this is called after user is created to initialize default feeds, labels
1816 // user preferences are checked on every login, not here
1818 function initialize_user($link, $uid) {
1820 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1821 values ('$uid','unread = true', 'Unread articles')");
1823 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1824 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1826 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1827 values ('$uid', 'Tiny Tiny RSS: New Releases',
1828 'http://tt-rss.org/releases.rss')");
1830 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1831 values ('$uid', 'Tiny Tiny RSS: Forum',
1832 'http://tt-rss.org/forum/rss.php')");
1835 function logout_user() {
1837 if (isset($_COOKIE[session_name()])) {
1838 setcookie(session_name(), '', time()-42000, '/');
1842 function get_script_urlpath() {
1843 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1846 function validate_session($link) {
1847 if (SINGLE_USER_MODE
) {
1851 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1852 if ($_SESSION["ip_address"]) {
1853 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1854 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1860 if ($_SESSION["uid"]) {
1862 $result = db_query($link,
1863 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1865 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1867 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1872 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1874 //print_r($_SESSION);
1876 if (time() > $_SESSION["cookie_lifetime"]) {
1884 function login_sequence($link, $mobile = false) {
1885 if (!SINGLE_USER_MODE
) {
1887 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1888 $swu = db_escape_string($_REQUEST["swu"]);
1890 $_SESSION["prefs_cache"] = false;
1891 return authenticate_user($link, $swu, null, true);
1895 $login_action = $_POST["login_action"];
1897 # try to authenticate user if called from login form
1898 if ($login_action == "do_login") {
1899 $login = $_POST["login"];
1900 $password = $_POST["password"];
1901 $remember_me = $_POST["remember_me"];
1903 if (authenticate_user($link, $login, $password)) {
1904 $_POST["password"] = "";
1906 $_SESSION["language"] = $_POST["language"];
1907 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1909 header("Location: " . $_SERVER["REQUEST_URI"]);
1914 $_SESSION["login_error_msg"] = "Incorrect username or password";
1918 // print session_id();
1919 // print_r($_SESSION);
1921 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1922 render_login_form($link, $mobile);
1925 /* bump login timestamp */
1926 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1929 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1930 setcookie("ttrss_lang", $_SESSION["language"],
1931 time() + SESSION_COOKIE_LIFETIME
);
1934 /* bump counters stamp since we're getting reloaded anyway */
1936 $_SESSION["get_all_counters_stamp"] = time();
1940 return authenticate_user($link, "admin", null);
1944 function truncate_string($str, $max_len) {
1945 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1946 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1952 function get_user_theme_path($link) {
1953 $result = db_query($link, "SELECT theme_path
1955 ttrss_themes,ttrss_users
1956 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1957 if (db_num_rows($result) != 0) {
1958 return db_fetch_result($result, 0, "theme_path");
1964 function smart_date_time($timestamp) {
1965 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1966 return date("G:i", $timestamp);
1967 } else if (date("Y", $timestamp) == date("Y")) {
1968 return date("M d, G:i", $timestamp);
1970 return date("Y/m/d, G:i", $timestamp);
1974 function smart_date($timestamp) {
1975 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1977 } else if (date("Y", $timestamp) == date("Y")) {
1978 return date("D m", $timestamp);
1980 return date("Y/m/d", $timestamp);
1984 function sql_bool_to_string($s) {
1985 if ($s == "t" ||
$s == "1") {
1992 function sql_bool_to_bool($s) {
1993 if ($s == "t" ||
$s == "1") {
2001 function toggleEvenOdd($a) {
2008 function sanity_check($link) {
2013 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2014 $schema_version = db_fetch_result($result, 0, "schema_version");
2016 if ($schema_version != SCHEMA_VERSION
) {
2020 if (DB_TYPE
== "mysql") {
2021 $result = db_query($link, "SELECT true", false);
2022 if (db_num_rows($result) != 1) {
2027 if (db_escape_string("testTEST") != "testTEST") {
2031 error_reporting (DEFAULT_ERROR_LEVEL
);
2033 if ($error_code != 0) {
2034 print_error_xml($error_code);
2041 function file_is_locked($filename) {
2042 if (function_exists('flock')) {
2044 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2045 error_reporting(DEFAULT_ERROR_LEVEL
);
2047 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2048 flock($fp, LOCK_UN
);
2058 return true; // consider the file always locked and skip the test
2061 function make_lockfile($filename) {
2062 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2064 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2071 function make_stampfile($filename) {
2072 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2074 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2075 fwrite($fp, time() . "\n");
2076 flock($fp, LOCK_UN
);
2084 function read_stampfile($filename) {
2087 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2088 error_reporting (DEFAULT_ERROR_LEVEL
);
2091 if (flock($fp, LOCK_EX
)) {
2092 $stamp = fgets($fp);
2093 flock($fp, LOCK_UN
);
2104 function sql_random_function() {
2105 if (DB_TYPE
== "mysql") {
2112 function catchup_feed($link, $feed, $cat_view) {
2114 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2119 $cat_qpart = "cat_id = '$feed'";
2121 $cat_qpart = "cat_id IS NULL";
2124 $tmp_result = db_query($link, "SELECT id
2125 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2128 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2130 $tmp_feed = $tmp_line["id"];
2132 db_query($link, "UPDATE ttrss_user_entries
2133 SET unread = false,last_read = NOW()
2134 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2137 } else if ($feed > 0) {
2139 $tmp_result = db_query($link, "SELECT id
2140 FROM ttrss_feeds WHERE parent_feed = '$feed'
2141 ORDER BY cat_id,title");
2143 $parent_ids = array();
2145 if (db_num_rows($tmp_result) > 0) {
2146 while ($p = db_fetch_assoc($tmp_result)) {
2147 array_push($parent_ids, "feed_id = " . $p["id"]);
2150 $children_qpart = implode(" OR ", $parent_ids);
2152 db_query($link, "UPDATE ttrss_user_entries
2153 SET unread = false,last_read = NOW()
2154 WHERE (feed_id = '$feed' OR $children_qpart)
2155 AND owner_uid = " . $_SESSION["uid"]);
2158 db_query($link, "UPDATE ttrss_user_entries
2159 SET unread = false,last_read = NOW()
2160 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2163 } else if ($feed < 0 && $feed > -10) { // special, like starred
2166 db_query($link, "UPDATE ttrss_user_entries
2167 SET unread = false,last_read = NOW()
2168 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2172 db_query($link, "UPDATE ttrss_user_entries
2173 SET unread = false,last_read = NOW()
2174 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2179 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2181 if (DB_TYPE
== "pgsql") {
2182 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2184 $match_part = "updated > DATE_SUB(NOW(),
2185 INTERVAL $intl HOUR) ";
2188 $result = db_query($link, "SELECT id FROM ttrss_entries,
2189 ttrss_user_entries WHERE $match_part AND
2191 ttrss_user_entries.ref_id = ttrss_entries.id AND
2192 owner_uid = ".$_SESSION["uid"]);
2194 $affected_ids = array();
2196 while ($line = db_fetch_assoc($result)) {
2197 array_push($affected_ids, $line["id"]);
2200 catchupArticlesById($link, $affected_ids, 0);
2203 } else if ($feed < -10) { // label
2205 // TODO make this more efficient
2207 $label_id = -$feed - 11;
2209 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2210 WHERE id = '$label_id'");
2213 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2215 db_query($link, "BEGIN");
2217 $tmp2_result = db_query($link,
2221 ttrss_user_entries,ttrss_entries,ttrss_feeds
2223 ref_id = ttrss_entries.id AND
2224 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2226 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2228 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2229 db_query($link, "UPDATE
2232 unread = false, last_read = NOW()
2234 int_id = " . $tmp_line["int_id"]);
2237 db_query($link, "COMMIT");
2239 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2240 SET unread = false,last_read = NOW()
2243 AND owner_uid = ".$_SESSION["uid"]); */
2247 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2250 db_query($link, "BEGIN");
2252 $tag_name = db_escape_string($feed);
2254 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2255 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2257 while ($line = db_fetch_assoc($result)) {
2258 db_query($link, "UPDATE ttrss_user_entries SET
2259 unread = false, last_read = NOW()
2260 WHERE int_id = " . $line["post_int_id"]);
2262 db_query($link, "COMMIT");
2266 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2270 $cat_qpart = "cat_id = '$feed'";
2272 $cat_qpart = "cat_id IS NULL";
2275 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2276 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2278 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2279 $feed_url = $tmp_line["feed_url"];
2280 $feed_id = $tmp_line["id"];
2281 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2285 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2286 WHERE id = '$feed'");
2287 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2288 update_rss_feed($link, $feed_url, $feed, $force_update);
2292 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2294 /* getting all counters is a resource intensive operation, so we
2295 * rate limit it a little bit */
2299 // if (get_pref($link, "SYNC_COUNTERS") ||
2300 // time() - $_SESSION["get_all_counters_stamp"] > 5) {
2302 if (!$omode) $omode = "flc";
2304 getGlobalCounters($link);
2306 if (strchr($omode, "l")) getLabelCounters($link);
2307 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2308 if (strchr($omode, "t")) getTagCounters($link);
2309 if (strchr($omode, "c")) {
2310 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2311 getCategoryCounters($link);
2315 $_SESSION["get_all_counters_stamp"] = time();
2320 function getCategoryCounters($link) {
2321 # two special categories are -1 and -2 (all virtuals; all labels)
2323 $ctr = getCategoryUnread($link, -1);
2325 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2327 $ctr = getCategoryUnread($link, -2);
2329 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2331 $age_qpart = getMaxAgeSubquery();
2333 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2334 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2335 WHERE ttrss_cat_counters_cache.feed_id = id AND
2336 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2338 while ($line = db_fetch_assoc($result)) {
2339 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2341 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2342 $line["unread"]."\"/>";
2345 /* Special case: NULL category doesn't actually exist in the DB */
2347 print "<counter type=\"category\" id=\"0\" counter=\"".
2348 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2352 function getCategoryUnread($link, $cat, $owner_uid = false) {
2354 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2359 $cat_query = "cat_id = '$cat'";
2361 $cat_query = "cat_id IS NULL";
2364 $age_qpart = getMaxAgeSubquery();
2366 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2368 AND owner_uid = " . $owner_uid);
2370 $cat_feeds = array();
2371 while ($line = db_fetch_assoc($result)) {
2372 array_push($cat_feeds, "feed_id = " . $line["id"]);
2375 if (count($cat_feeds) == 0) return 0;
2377 $match_part = implode(" OR ", $cat_feeds);
2379 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2380 FROM ttrss_user_entries,ttrss_entries
2381 WHERE unread = true AND ($match_part) AND id = ref_id
2382 AND $age_qpart AND owner_uid = " . $owner_uid);
2386 # this needs to be rewritten
2387 while ($line = db_fetch_assoc($result)) {
2388 $unread +
= $line["unread"];
2392 } else if ($cat == -1) {
2393 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2394 } else if ($cat == -2) {
2396 $rv = getLabelCounters($link, false, true);
2399 foreach (array_keys($rv) as $k) {
2401 $ctr +
= $rv[$k]["counter"];
2409 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2410 if (DB_TYPE
== "pgsql") {
2411 return "ttrss_entries.date_entered >
2412 NOW() - INTERVAL '$days days'";
2414 return "ttrss_entries.date_entered >
2415 DATE_SUB(NOW(), INTERVAL $days DAY)";
2419 function getFeedUnread($link, $feed, $is_cat = false) {
2420 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2423 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2424 $owner_uid = false) {
2426 $n_feed = sprintf("%d", $feed);
2428 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2431 $unread_qpart = "unread = true";
2433 $unread_qpart = "true";
2436 $age_qpart = getMaxAgeSubquery();
2439 return getCategoryUnread($link, $n_feed, $owner_uid);
2440 } else if ($n_feed == -1) {
2441 $match_part = "marked = true";
2442 } else if ($n_feed == -2) {
2443 $match_part = "published = true";
2444 } else if ($n_feed == -3) {
2445 $match_part = "unread = true";
2447 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2449 if (DB_TYPE
== "pgsql") {
2450 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2452 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2455 } else if ($n_feed > 0) {
2457 $result = db_query($link, "SELECT id FROM ttrss_feeds
2458 WHERE parent_feed = '$n_feed'
2460 AND owner_uid = " . $owner_uid);
2462 if (db_num_rows($result) > 0) {
2464 $linked_feeds = array();
2465 while ($line = db_fetch_assoc($result)) {
2466 array_push($linked_feeds, "feed_id = " . $line["id"]);
2469 array_push($linked_feeds, "feed_id = $n_feed");
2471 $match_part = implode(" OR ", $linked_feeds);
2473 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2474 FROM ttrss_user_entries,ttrss_entries
2475 WHERE $unread_qpart AND
2476 ttrss_user_entries.ref_id = ttrss_entries.id AND
2479 owner_uid = " . $owner_uid);
2483 # this needs to be rewritten
2484 while ($line = db_fetch_assoc($result)) {
2485 $unread +
= $line["unread"];
2491 $match_part = "feed_id = '$n_feed'";
2493 } else if ($feed < -10) {
2495 $label_id = -$feed - 11;
2497 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2498 id = '$label_id' AND owner_uid = " . $owner_uid);
2500 $match_part = db_fetch_result($result, 0, "sql_exp");
2505 $result = db_query($link, "SELECT count(int_id) AS unread
2506 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2507 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2508 ttrss_user_entries.ref_id = ttrss_entries.id AND
2509 ttrss_feeds.hidden = false AND
2511 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2515 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2516 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2517 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2518 AND $unread_qpart AND $age_qpart AND
2519 ttrss_tags.owner_uid = " . $owner_uid);
2522 $unread = db_fetch_result($result, 0, "unread");
2527 function getGlobalUnread($link, $user_id = false) {
2530 $user_id = $_SESSION["uid"];
2533 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2534 WHERE owner_uid = '$user_id' AND feed_id > 0");
2536 $c_id = db_fetch_result($result, 0, "c_id");
2541 function getGlobalCounters($link, $global_unread = -1) {
2542 if ($global_unread == -1) {
2543 $global_unread = getGlobalUnread($link);
2545 print "<counter type=\"global\" id='global-unread'
2546 counter='$global_unread'/>";
2548 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2549 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2551 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2553 print "<counter type=\"global\" id='subscribed-feeds'
2554 counter='$subscribed_feeds'/>";
2558 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2561 if (!$_SESSION["tctr_last_value"]) {
2562 $_SESSION["tctr_last_value"] = array();
2566 $old_counters = $_SESSION["tctr_last_value"];
2568 $tctrs_modified = false;
2570 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2571 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2572 ttrss_user_entries.ref_id = ttrss_entries.id AND
2573 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2574 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2576 select tag_name,0 as count FROM ttrss_tags
2577 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2579 $age_qpart = getMaxAgeSubquery();
2581 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2582 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2583 AND ref_id = id AND $age_qpart
2584 AND unread = true)) AS count FROM ttrss_tags
2585 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2586 ORDER BY count DESC LIMIT 55");
2590 while ($line = db_fetch_assoc($result)) {
2591 $tags[$line["tag_name"]] +
= $line["count"];
2594 foreach (array_keys($tags) as $tag) {
2595 $unread = $tags[$tag];
2597 $tag = htmlspecialchars($tag);
2599 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2600 $old_counters[$tag] = $unread;
2601 $tctrs_modified = true;
2602 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2607 if ($smart_mode && $tctrs_modified) {
2608 $_SESSION["tctr_last_value"] = $old_counters;
2613 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2615 $age_qpart = getMaxAgeSubquery();
2618 if (!$_SESSION["lctr_last_value"]) {
2619 $_SESSION["lctr_last_value"] = array();
2625 $old_counters = $_SESSION["lctr_last_value"];
2626 $lctrs_modified = false;
2628 $count = getFeedUnread($link, -1);
2632 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2633 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2638 print "<counter type=\"label\" id=\"-1\" counter=\"$count\" $xmsg_part/>";
2640 $ret_arr["-1"]["counter"] = $count;
2641 $ret_arr["-1"]["description"] = __("Starred articles");
2644 $count = getFeedUnread($link, -2);
2648 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2649 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2654 print "<counter type=\"label\" id=\"-2\" counter=\"$count\" $xmsg_part/>";
2656 $ret_arr["-2"]["counter"] = $count;
2657 $ret_arr["-2"]["description"] = __("Published articles");
2660 $count = getFeedUnread($link, -3);
2664 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2665 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2670 print "<counter type=\"label\" id=\"-3\" counter=\"$count\" $xmsg_part/>";
2672 $ret_arr["-3"]["counter"] = $count;
2673 $ret_arr["-3"]["description"] = __("Fresh articles");
2677 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2678 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2680 while ($line = db_fetch_assoc($result)) {
2682 $id = -$line["id"] - 11;
2684 $label_name = $line["description"];
2686 $count = ccache_find($link, $id, $_SESSION["uid"]);
2688 error_reporting (0);
2690 /* $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2691 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2692 ttrss_feeds.hidden = false AND
2694 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2695 ttrss_user_entries.ref_id = ttrss_entries.id AND
2696 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2698 $count = db_fetch_result($tmp_result, 0, "count");
2700 if (!$smart_mode || $old_counters[$id] != $count) {
2701 $old_counters[$id] = $count;
2702 $lctrs_modified = true;
2705 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2706 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2711 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2713 $ret_arr[$id]["counter"] = $count;
2714 $ret_arr[$id]["description"] = $label_name;
2718 if (!$smart_mode ||
$old_counters[$id] != $count) {
2719 $old_counters[$id] = $count;
2720 $lctrs_modified = true;
2723 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2724 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2729 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2731 $ret_arr[$id]["counter"] = $count;
2732 $ret_arr[$id]["description"] = $label_name;
2737 error_reporting (DEFAULT_ERROR_LEVEL
);
2740 if ($smart_mode && $lctrs_modified) {
2741 $_SESSION["lctr_last_value"] = $old_counters;
2747 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2749 $age_qpart = getMaxAgeSubquery();
2752 if (!$_SESSION["fctr_last_value"]) {
2753 $_SESSION["fctr_last_value"] = array();
2757 $old_counters = $_SESSION["fctr_last_value"];
2759 /* $query = "SELECT ttrss_feeds.id,
2761 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2763 COUNT(ttrss_entries.id) AS count
2765 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2766 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2767 AND ttrss_user_entries.unread = true)
2768 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2770 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2771 AND parent_feed IS NULL
2772 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error"; */
2774 $query = "SELECT ttrss_feeds.id,
2776 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2777 last_error, value AS count
2778 FROM ttrss_feeds, ttrss_counters_cache
2779 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2780 AND parent_feed IS NULL
2781 AND ttrss_counters_cache.feed_id = id";
2783 $result = db_query($link, $query);
2784 $fctrs_modified = false;
2786 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2788 while ($line = db_fetch_assoc($result)) {
2791 $count = $line["count"];
2792 $last_error = htmlspecialchars($line["last_error"]);
2794 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2795 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2797 $last_updated = date($short_date, strtotime($line["last_updated"]));
2800 $last_updated = htmlspecialchars($last_updated);
2802 $has_img = feed_has_icon($id);
2804 /* $tmp_result = db_query($link,
2805 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2806 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2807 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2808 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2809 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id"); */
2811 $tmp_result = db_query($link,
2812 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2813 WHERE parent_feed = '$id' AND feed_id = id");
2815 $count +
= db_fetch_result($tmp_result, 0, "unread");
2817 if (!$smart_mode ||
$old_counters[$id] != $count) {
2818 $old_counters[$id] = $count;
2819 $fctrs_modified = true;
2822 $error_part = "error=\"$last_error\"";
2828 $has_img_part = "hi=\"$has_img\"";
2833 if ($active_feed && $id == $active_feed) {
2834 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2836 $has_title_part = "";
2839 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2840 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2843 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2847 if ($smart_mode && $fctrs_modified) {
2848 $_SESSION["fctr_last_value"] = $old_counters;
2852 function get_script_dt_add() {
2853 if (strpos(VERSION
, ".99") === false) {
2860 function get_pgsql_version($link) {
2861 $result = db_query($link, "SELECT version() AS version");
2862 $version = split(" ", db_fetch_result($result, 0, "version"));
2866 function print_error_xml($code, $add_msg = "") {
2869 $error_msg = $ERRORS[$code];
2872 $error_msg = "$error_msg; $add_msg";
2875 print "<rpc-reply>";
2876 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2877 print "</rpc-reply>";
2880 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2881 $auth_login = '', $auth_pass = '') {
2883 # check for feed:http://url
2884 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2886 # check for feed://URL
2887 if (strpos($feed_link, "//") === 0) {
2888 $feed_link = "http:$feed_link";
2891 if ($feed_link == "") return;
2893 if ($cat_id == "0" ||
!$cat_id) {
2894 $cat_qpart = "NULL";
2896 $cat_qpart = "'$cat_id'";
2899 $result = db_query($link,
2900 "SELECT id FROM ttrss_feeds
2901 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2903 if (db_num_rows($result) == 0) {
2905 $result = db_query($link,
2906 "INSERT INTO ttrss_feeds
2907 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2908 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2909 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2911 $result = db_query($link,
2912 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2913 AND owner_uid = " . $_SESSION["uid"]);
2915 $feed_id = db_fetch_result($result, 0, "id");
2918 update_rss_feed($link, $feed_link, $feed_id, true);
2927 function print_feed_select($link, $id, $default_id = "",
2928 $attributes = "", $include_all_feeds = true) {
2930 print "<select id=\"$id\" name=\"$id\" $attributes>";
2931 if ($include_all_feeds) {
2932 print "<option value=\"0\">".__('All feeds')."</option>";
2935 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2936 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2938 if (db_num_rows($result) > 0 && $include_all_feeds) {
2939 print "<option disabled>--------</option>";
2942 while ($line = db_fetch_assoc($result)) {
2943 if ($line["id"] == $default_id) {
2944 $is_selected = "selected";
2948 printf("<option $is_selected value='%d'>%s</option>",
2949 $line["id"], htmlspecialchars($line["title"]));
2955 function print_feed_cat_select($link, $id, $default_id = "",
2956 $attributes = "", $include_all_cats = true) {
2958 print "<select id=\"$id\" name=\"$id\" $attributes>";
2960 if ($include_all_cats) {
2961 print "<option value=\"0\">".__('Uncategorized')."</option>";
2964 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2965 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2967 if (db_num_rows($result) > 0 && $include_all_cats) {
2968 print "<option disabled>--------</option>";
2971 while ($line = db_fetch_assoc($result)) {
2972 if ($line["id"] == $default_id) {
2973 $is_selected = "selected";
2977 printf("<option $is_selected value='%d'>%s</option>",
2978 $line["id"], htmlspecialchars($line["title"]));
2984 function checkbox_to_sql_bool($val) {
2985 return ($val == "on") ?
"true" : "false";
2988 function getFeedCatTitle($link, $id) {
2990 return __("Special");
2991 } else if ($id < -10) {
2992 return __("Labels");
2993 } else if ($id > 0) {
2994 $result = db_query($link, "SELECT ttrss_feed_categories.title
2995 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2996 cat_id = ttrss_feed_categories.id");
2997 if (db_num_rows($result) == 1) {
2998 return db_fetch_result($result, 0, "title");
3000 return __("Uncategorized");
3003 return "getFeedCatTitle($id) failed";
3008 function getFeedTitle($link, $id) {
3010 return __("Starred articles");
3011 } else if ($id == -2) {
3012 return __("Published articles");
3013 } else if ($id == -3) {
3014 return __("Fresh articles");
3015 } else if ($id < -10) {
3016 $label_id = -$id - 11;
3017 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
3018 if (db_num_rows($result) == 1) {
3019 return db_fetch_result($result, 0, "description");
3021 return "Unknown label ($label_id)";
3024 } else if ($id > 0) {
3025 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3026 if (db_num_rows($result) == 1) {
3027 return db_fetch_result($result, 0, "title");
3029 return "Unknown feed ($id)";
3032 return "getFeedTitle($id) failed";
3037 function get_session_cookie_name() {
3038 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3041 function print_init_params($link) {
3042 print "<init-params>";
3043 if ($_SESSION["stored-params"]) {
3044 foreach (array_keys($_SESSION["stored-params"]) as $key) {
3046 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
3047 print "<param key=\"$key\" value=\"$value\"/>";
3052 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
3053 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
3054 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
3055 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3057 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
3058 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
3060 print "<param key=\"hide_read_feeds\" value=\"" .
3061 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
3063 print "<param key=\"feeds_sort_by_unread\" value=\"" .
3064 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
3066 print "<param key=\"confirm_feed_catchup\" value=\"" .
3067 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3069 print "<param key=\"cdm_auto_catchup\" value=\"" .
3070 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3072 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3074 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3076 print "<param key=\"default_view_mode\" value=\"" .
3077 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3079 print "<param key=\"default_view_limit\" value=\"" .
3080 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3082 print "<param key=\"default_view_order_by\" value=\"" .
3083 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3085 print "<param key=\"prefs_active_tab\" value=\"" .
3086 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3088 print "<param key=\"infobox_disable_overlay\" value=\"" .
3089 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3091 print "<param key=\"icons_location\" value=\"" .
3094 print "<param key=\"hide_read_shows_special\" value=\"" .
3095 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3097 print "<param key=\"hide_feedlist\" value=\"" .
3098 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3100 print "<param key=\"bw_limit\" value=\"".
3101 (int) $_SESSION["bw_limit"]."\"/>";
3103 // print "<param key=\"sync_counters\" value=\"" .
3104 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3106 print "<param key=\"sync_counters\" value=\"1\"/>";
3108 print "</init-params>";
3111 function print_runtime_info($link) {
3112 print "<runtime-info>";
3114 if (ENABLE_UPDATE_DAEMON
) {
3115 print "<param key=\"daemon_is_running\" value=\"".
3116 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3118 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3120 $stamp = (int)read_stampfile("update_daemon.stamp");
3122 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3125 $stamp_delta = time() - $stamp;
3127 if ($stamp_delta > 1800) {
3131 $_SESSION["daemon_stamp_check"] = time();
3134 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3136 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3138 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3143 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3145 if ($_SESSION["last_version_check"] +
86400 < time()) {
3146 $new_version_details = check_for_update($link);
3148 print "<param key=\"new_version_available\" value=\"".
3149 sprintf("%d", $new_version_details != ""). "\"/>";
3151 $_SESSION["last_version_check"] = time();
3155 // print "<param key=\"new_version_available\" value=\"1\"/>";
3157 print "</runtime-info>";
3160 function getSearchSql($search, $match_on) {
3162 $search_query_part = "";
3164 $keywords = split(" ", $search);
3165 $query_keywords = array();
3167 if ($match_on == "both") {
3169 foreach ($keywords as $k) {
3170 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3171 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3174 $search_query_part = implode("AND", $query_keywords) . " AND ";
3176 } else if ($match_on == "title") {
3178 foreach ($keywords as $k) {
3179 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3182 $search_query_part = implode("AND", $query_keywords) . " AND ";
3184 } else if ($match_on == "content") {
3186 foreach ($keywords as $k) {
3187 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3191 $search_query_part = implode("AND", $query_keywords);
3193 return $search_query_part;
3196 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3198 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3202 $search_query_part = getSearchSql($search, $match_on);
3203 $search_query_part .= " AND ";
3206 $search_query_part = "";
3209 $view_query_part = "";
3211 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3213 $view_query_part = " ";
3214 } else if ($feed != -1) {
3215 $unread = getFeedUnread($link, $feed, $cat_view);
3217 $view_query_part = " unread = true AND ";
3222 if ($view_mode == "marked") {
3223 $view_query_part = " marked = true AND ";
3226 if ($view_mode == "unread") {
3227 $view_query_part = " unread = true AND ";
3231 $limit_query_part = "LIMIT " . $limit;
3234 $vfeed_query_part = "";
3236 // override query strategy and enable feed display when searching globally
3237 if ($search && $search_mode == "all_feeds") {
3238 $query_strategy_part = "ttrss_entries.id > 0";
3239 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3240 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3241 $query_strategy_part = "ttrss_entries.id > 0";
3242 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3243 id = feed_id) as feed_title,";
3244 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3246 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3248 $tmp_result = false;
3251 $tmp_result = db_query($link, "SELECT id
3252 FROM ttrss_feeds WHERE cat_id = '$feed'");
3254 $tmp_result = db_query($link, "SELECT id
3255 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3256 WHERE id = '$feed') AND id != '$feed'");
3259 $cat_siblings = array();
3261 if (db_num_rows($tmp_result) > 0) {
3262 while ($p = db_fetch_assoc($tmp_result)) {
3263 array_push($cat_siblings, "feed_id = " . $p["id"]);
3266 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3267 $feed, implode(" OR ", $cat_siblings));
3270 $query_strategy_part = "ttrss_entries.id > 0";
3273 } else if ($feed >= 0) {
3278 $query_strategy_part = "cat_id = '$feed'";
3280 $query_strategy_part = "cat_id IS NULL";
3283 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3286 $tmp_result = db_query($link, "SELECT id
3287 FROM ttrss_feeds WHERE parent_feed = '$feed'
3288 ORDER BY cat_id,title");
3290 $parent_ids = array();
3292 if (db_num_rows($tmp_result) > 0) {
3293 while ($p = db_fetch_assoc($tmp_result)) {
3294 array_push($parent_ids, "feed_id = " . $p["id"]);
3297 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3298 $feed, implode(" OR ", $parent_ids));
3300 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3302 $query_strategy_part = "feed_id = '$feed'";
3305 } else if ($feed == -1) { // starred virtual feed
3306 $query_strategy_part = "marked = true";
3307 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3308 } else if ($feed == -2) { // published virtual feed
3309 $query_strategy_part = "published = true";
3310 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3311 } else if ($feed == -3) { // fresh virtual feed
3312 $query_strategy_part = "unread = true";
3314 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3316 if (DB_TYPE
== "pgsql") {
3317 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3319 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3323 } else if ($feed <= -10) { // labels
3324 $label_id = -$feed - 11;
3326 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3327 WHERE id = '$label_id'");
3329 $query_strategy_part = "(" . db_fetch_result($tmp_result, 0, "sql_exp") . ")";
3331 if (!$query_strategy_part) {
3335 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3337 $query_strategy_part = "id > 0"; // dumb
3340 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3341 $order_by = "updated";
3343 $order_by = "updated DESC";
3346 if ($view_mode != "noscores") {
3347 $order_by = "score DESC, $order_by";
3350 if ($override_order) {
3351 $order_by = $override_order;
3356 if ($search && $search_mode == "all_feeds") {
3357 $feed_title = __("Search results")." ($search)";
3358 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3359 $feed_title = __("Search results")." ($search, $feed)";
3360 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3361 $feed_title = $feed;
3362 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3367 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3368 WHERE id = '$feed' AND owner_uid = $owner_uid");
3369 $feed_title = db_fetch_result($result, 0, "title");
3371 $feed_title = __("Uncategorized");
3375 $feed_title = __("Searched for")." $search ($feed_title)";
3380 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3381 WHERE id = '$feed' AND owner_uid = $owner_uid");
3383 $feed_title = db_fetch_result($result, 0, "title");
3384 $feed_site_url = db_fetch_result($result, 0, "site_url");
3385 $last_error = db_fetch_result($result, 0, "last_error");
3388 $feed_title = __("Searched for") . " $search ($feed_title)";
3392 } else if ($feed == -1) {
3393 $feed_title = __("Starred articles");
3394 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3395 } else if ($feed == -2) {
3396 $feed_title = __("Published articles");
3397 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3398 } else if ($feed == -3) {
3399 $feed_title = __("Fresh articles");
3400 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3401 } else if ($feed < -10) {
3402 $label_id = -$feed - 11;
3403 $result = db_query($link, "SELECT description FROM ttrss_labels
3404 WHERE id = '$label_id'");
3405 $feed_title = db_fetch_result($result, 0, "description");
3408 $feed_title = __("Searched for") . " $search ($feed_title)";
3414 if ($feed < -10) error_reporting (0);
3416 $content_query_part = "content as content_preview,";
3418 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3421 $feed_kind = "Feeds";
3423 $feed_kind = "Labels";
3426 if ($limit_query_part) {
3427 $offset_query_part = "OFFSET $offset";
3430 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3431 if (!$override_order) {
3432 $order_by = "ttrss_feeds.title, $order_by";
3435 // Special output for Fresh feed
3437 /* if ($feed == -3) {
3438 $group_limit_part = "(select count(*) from
3439 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3440 t1.ref_id = t2.id and t1.owner_uid = 2 and
3441 t1.feed_id = ttrss_user_entries.feed_id and
3442 t2.updated > ttrss_entries.updated) <= 5 AND";
3448 ttrss_entries.id,ttrss_entries.title,
3450 unread,feed_id,marked,published,link,last_read,
3451 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3454 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3457 ttrss_entries,ttrss_user_entries,ttrss_feeds
3460 ttrss_feeds.hidden = false AND
3461 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3462 ttrss_user_entries.ref_id = ttrss_entries.id AND
3463 ttrss_user_entries.owner_uid = '$owner_uid' AND
3466 $query_strategy_part ORDER BY $order_by
3467 $limit_query_part $offset_query_part";
3469 if ($_GET["debug"]) print $query;
3471 $result = db_query($link, $query);
3476 $feed_kind = "Tags";
3478 $result = db_query($link, "SELECT
3480 ttrss_entries.id as id,title,
3483 marked,link,last_read,
3484 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3487 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3490 ttrss_entries,ttrss_user_entries,ttrss_tags
3492 ref_id = ttrss_entries.id AND
3493 ttrss_user_entries.owner_uid = '$owner_uid' AND
3494 post_int_id = int_id AND tag_name = '$feed' AND
3497 $query_strategy_part ORDER BY $order_by
3498 $limit_query_part");
3501 return array($result, $feed_title, $feed_site_url, $last_error);
3505 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3506 $limit, $search, $search_mode, $match_on) {
3508 if (!$limit) $limit = 30;
3510 $qfh_ret = queryFeedHeadlines($link, $feed,
3511 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3514 $result = $qfh_ret[0];
3515 $feed_title = htmlspecialchars($qfh_ret[1]);
3516 $feed_site_url = $qfh_ret[2];
3517 $last_error = $qfh_ret[3];
3519 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3521 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3522 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3523 <rss version=\"2.0\">
3525 <title>$feed_title</title>
3526 <link>$feed_site_url</link>
3527 <description>Feed generated by Tiny Tiny RSS</description>";
3529 while ($line = db_fetch_assoc($result)) {
3531 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3532 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3534 $tags = get_article_tags($link, $line["id"], $owner_uid);
3536 foreach ($tags as $tag) {
3537 print "<category>" . htmlspecialchars($tag) . "</category>";
3540 $rfc822_date = date('r', strtotime($line["updated"]));
3542 print "<pubDate>$rfc822_date</pubDate>";
3545 htmlspecialchars($line["title"]) . "</title>";
3547 print "<description><![CDATA[" .
3548 $line["content_preview"] . "]]></description>";
3553 print "</channel></rss>";
3557 function getCategoryTitle($link, $cat_id) {
3559 if ($cat_id == -1) {
3560 return __("Special");
3561 } else if ($cat_id == -2) {
3562 return __("Labels");
3565 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3568 if (db_num_rows($result) == 1) {
3569 return db_fetch_result($result, 0, "title");
3571 return "Uncategorized";
3576 // http://ru2.php.net/strip-tags
3578 function strip_tags_long($textstring, $allowed){
3579 while($textstring != strip_tags($textstring, $allowed))
3581 while (strlen($textstring) != 0)
3583 if (strlen($textstring) > 1024) {
3586 $otherlen = strlen($textstring);
3588 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3589 $safetext .= $temptext;
3590 $textstring = substr_replace($textstring,'',0,$otherlen);
3592 $textstring = $safetext;
3598 function sanitize_rss($link, $str, $force_strip_tags = false) {
3601 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3603 $res = strip_tags_long($res,
3604 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3606 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3607 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3610 if (get_pref($link, "STRIP_IMAGES")) {
3612 $res = preg_replace('/<img[^>]+>/is', '', $res);
3620 * Send by mail a digest of last articles.
3622 * @param mixed $link The database connection.
3623 * @param integer $limit The maximum number of articles by digest.
3624 * @return boolean Return false if digests are not enabled.
3626 function send_headlines_digests($link, $limit = 100) {
3628 if (!DIGEST_ENABLE
) return false;
3630 $user_limit = DIGEST_EMAIL_LIMIT
;
3633 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3635 if (DB_TYPE
== "pgsql") {
3636 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3637 } else if (DB_TYPE
== "mysql") {
3638 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3641 $result = db_query($link, "SELECT id,email FROM ttrss_users
3642 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3644 while ($line = db_fetch_assoc($result)) {
3646 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3647 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3649 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3651 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3652 $digest = $tuple[0];
3653 $headlines_count = $tuple[1];
3654 $affected_ids = $tuple[2];
3655 $digest_text = $tuple[3];
3657 if ($headlines_count > 0) {
3659 $mail = new PHPMailer();
3661 $mail->PluginDir
= "phpmailer/";
3662 $mail->SetLanguage("en", "phpmailer/language/");
3664 $mail->CharSet
= "UTF-8";
3666 $mail->From
= DIGEST_FROM_ADDRESS
;
3667 $mail->FromName
= DIGEST_FROM_NAME
;
3668 $mail->AddAddress($line["email"], $line["login"]);
3670 if (DIGEST_SMTP_HOST
) {
3671 $mail->Host
= DIGEST_SMTP_HOST
;
3672 $mail->Mailer
= "smtp";
3673 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3674 $mail->Username
= DIGEST_SMTP_LOGIN
;
3675 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3678 $mail->IsHTML(true);
3679 $mail->Subject
= DIGEST_SUBJECT
;
3680 $mail->Body
= $digest;
3681 $mail->AltBody
= $digest_text;
3683 $rc = $mail->Send();
3685 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3689 if ($rc && $do_catchup) {
3690 print "Marking affected articles as read...\n";
3691 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3694 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3695 WHERE id = " . $line["id"]);
3697 print "No headlines\n";
3702 print "All done.\n";
3706 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3708 require_once "MiniTemplator.class.php";
3710 $tpl = new MiniTemplator
;
3711 $tpl_t = new MiniTemplator
;
3713 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3714 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3716 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3717 $tpl->setVariable('CUR_TIME', date('G:i'));
3719 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3720 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3722 $affected_ids = array();
3724 if (DB_TYPE
== "pgsql") {
3725 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3726 } else if (DB_TYPE
== "mysql") {
3727 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3730 $result = db_query($link, "SELECT ttrss_entries.title,
3731 ttrss_feeds.title AS feed_title,
3733 ttrss_user_entries.ref_id,
3735 SUBSTRING(content, 1, 120) AS excerpt,
3736 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3738 ttrss_user_entries,ttrss_entries,ttrss_feeds
3740 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3741 AND include_in_digest = true
3744 AND ttrss_user_entries.owner_uid = $user_id
3746 ORDER BY ttrss_feeds.title, date_entered DESC
3749 $cur_feed_title = "";
3751 $headlines_count = db_num_rows($result);
3753 $headlines = array();
3755 while ($line = db_fetch_assoc($result)) {
3756 array_push($headlines, $line);
3759 for ($i = 0; $i < sizeof($headlines); $i++
) {
3761 $line = $headlines[$i];
3763 array_push($affected_ids, $line["ref_id"]);
3765 $updated = smart_date_time(strtotime($line["last_updated"]));
3767 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3768 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3769 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3770 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3771 $tpl->setVariable('ARTICLE_EXCERPT',
3772 truncate_string(strip_tags($line["excerpt"]), 100));
3774 $tpl->addBlock('article');
3776 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3777 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3778 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3779 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3780 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3781 // truncate_string(strip_tags($line["excerpt"]), 100));
3783 $tpl_t->addBlock('article');
3785 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3786 $tpl->addBlock('feed');
3787 $tpl_t->addBlock('feed');
3792 $tpl->addBlock('digest');
3793 $tpl->generateOutputToString($tmp);
3795 $tpl_t->addBlock('digest');
3796 $tpl_t->generateOutputToString($tmp_t);
3798 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3801 function check_for_update($link, $brief_fmt = true) {
3802 $releases_feed = "http://tt-rss.org/releases.rss";
3804 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3809 if (ENABLE_SIMPLEPIE
) {
3810 $rss = new SimplePie();
3811 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3812 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3813 $rss->set_feed_url($fetch_url);
3814 $rss->set_output_encoding('UTF-8');
3817 $rss = fetch_rss($releases_feed);
3819 error_reporting (DEFAULT_ERROR_LEVEL
);
3823 if (ENABLE_SIMPLEPIE
) {
3824 $items = $rss->get_items();
3826 $items = $rss->items
;
3828 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3829 if (!$items ||
!is_array($items)) $items = $rss;
3832 if (!is_array($items) ||
count($items) == 0) {
3836 $latest_item = $items[0];
3838 if (ENABLE_SIMPLEPIE
) {
3839 $last_title = $latest_item->get_title();
3841 $last_title = $latest_item["title"];
3844 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3846 if (ENABLE_SIMPLEPIE
) {
3847 $release_url = sanitize_rss($link, $latest_item->get_link());
3848 $content = sanitize_rss($link, $latest_item->get_description());
3850 $release_url = sanitize_rss($link, $latest_item["link"]);
3851 $content = sanitize_rss($link, $latest_item["description"]);
3854 if (version_compare(VERSION
, $latest_version) == -1) {
3856 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3857 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3858 <div id=\"milestoneDetails\">$content</div>");
3860 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3861 <div class='milestoneDetails'>$content</div>
3862 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3863 download and update information.";
3870 function markArticlesById($link, $ids, $cmode) {
3874 foreach ($ids as $id) {
3875 array_push($tmp_ids, "ref_id = '$id'");
3878 $ids_qpart = join(" OR ", $tmp_ids);
3881 db_query($link, "UPDATE ttrss_user_entries SET
3882 marked = false,last_read = NOW()
3883 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3884 } else if ($cmode == 1) {
3885 db_query($link, "UPDATE ttrss_user_entries SET
3887 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3889 db_query($link, "UPDATE ttrss_user_entries SET
3890 marked = NOT marked,last_read = NOW()
3891 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3895 function publishArticlesById($link, $ids, $cmode) {
3899 foreach ($ids as $id) {
3900 array_push($tmp_ids, "ref_id = '$id'");
3903 $ids_qpart = join(" OR ", $tmp_ids);
3906 db_query($link, "UPDATE ttrss_user_entries SET
3907 published = false,last_read = NOW()
3908 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3909 } else if ($cmode == 1) {
3910 db_query($link, "UPDATE ttrss_user_entries SET
3912 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3914 db_query($link, "UPDATE ttrss_user_entries SET
3915 published = NOT published,last_read = NOW()
3916 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3920 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3922 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3926 foreach ($ids as $id) {
3927 array_push($tmp_ids, "ref_id = '$id'");
3930 $ids_qpart = join(" OR ", $tmp_ids);
3933 db_query($link, "UPDATE ttrss_user_entries SET
3934 unread = false,last_read = NOW()
3935 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3936 } else if ($cmode == 1) {
3937 db_query($link, "UPDATE ttrss_user_entries SET
3939 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3941 db_query($link, "UPDATE ttrss_user_entries SET
3942 unread = NOT unread,last_read = NOW()
3943 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3948 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3949 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3951 while ($line = db_fetch_assoc($result)) {
3952 ccache_update($link, $line["feed_id"], $owner_uid);
3956 function catchupArticleById($link, $id, $cmode) {
3959 db_query($link, "UPDATE ttrss_user_entries SET
3960 unread = false,last_read = NOW()
3961 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3962 } else if ($cmode == 1) {
3963 db_query($link, "UPDATE ttrss_user_entries SET
3965 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3967 db_query($link, "UPDATE ttrss_user_entries SET
3968 unread = NOT unread,last_read = NOW()
3969 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3973 function make_guid_from_title($title) {
3974 return preg_replace("/[ \"\',.:;]/", "-",
3975 mb_strtolower(strip_tags($title), 'utf-8'));
3978 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3979 $bottom = false, $rtl_content = false, $feed_id = 0,
3980 $is_cat = false, $search = false, $match_on = false,
3981 $search_mode = false, $offset = 0, $limit = 0,
3982 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3984 $user_page_offset = $offset +
1;
3987 $class = "headlinesSubToolbar";
3988 $tid = "headlineActionsTop";
3990 $class = "headlinesSubToolbar";
3991 $tid = "headlineActionsBottom";
3994 print "<nobr><table class=\"$class\" id=\"$tid\"
3995 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
4003 $page_prev_link = "javascript:viewFeedGoPage(-1)";
4004 $page_next_link = "javascript:viewFeedGoPage(1)";
4005 $page_first_link = "javascript:viewFeedGoPage(0)";
4007 $catchup_page_link = "javascript:catchupPage()";
4008 $catchup_feed_link = "javascript:catchupCurrentFeed()";
4009 $catchup_sel_link = "javascript:catchupSelection()";
4011 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4013 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
4014 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
4015 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
4016 $sel_inv_link = "javascript:invertHeadlineSelection()";
4018 $tog_unread_link = "javascript:selectionToggleUnread()";
4019 $tog_marked_link = "javascript:selectionToggleMarked()";
4020 $tog_published_link = "javascript:selectionTogglePublished()";
4024 $sel_all_link = "javascript:cdmSelectArticles('all')";
4025 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
4026 $sel_none_link = "javascript:cdmSelectArticles('none')";
4028 $sel_inv_link = "javascript:invertHeadlineSelection()";
4030 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4031 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4032 $tog_published_link = "javascript:selectionTogglePublished(true)";
4036 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
4038 print "<td class=\"headlineActions$rtl_cpart\">
4039 <ul class=\"headlineDropdownMenu\">
4042 <a href=\"$sel_all_link\">".__('All')."</a>,
4043 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4044 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4045 <a href=\"$sel_none_link\">".__('None')."</a></li>
4046 <li class=\"vsep\"> </li>
4047 <li class=\"top\">".__('Actions...')."<ul>
4048 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
4049 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4050 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4051 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4052 <li><span class=\"insensitive\">--------</span></li>
4053 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
4054 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4056 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4059 <li onclick=\"catchupRelativeToArticle(0)\"> ".__("Above active article")."</li>
4060 <li onclick=\"catchupRelativeToArticle(1)\"> ".__("Below active article")."</li>";
4063 <li><span class=\"insensitive\"> ".__("Above active article")."</span></li>
4064 <li><span class=\"insensitive\"> ".__("Below active article")."</span></li>";
4068 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4070 print "<li><span class=\"insensitive\">--------</span></li>";
4071 print "<li><span class=\"insensitive\">".__('Other actions:')."</span></li>";
4074 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4076 <li onclick=\"javascript:labelFromSearch('$search', '$search_mode',
4077 '$match_on', '$feed_id', '$is_cat');\">
4078 ".__('Search to label')."</li>";
4080 print "<li><span class=\"insensitive\"> ".__('Search to label')."</li>";
4084 print "</ul></li></ul>";
4088 // old style subtoolbar:
4090 print "<td class=\"headlineActions$rtl_cpart\">".
4092 <a href=\"$sel_all_link\">".__('All')."</a>,
4093 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4094 <a href=\"$sel_none_link\">".__('None')."</a>
4096 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4097 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4099 __('Mark as read:')."
4100 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4101 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4103 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4106 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
4107 '$match_on', '$feed_id', '$is_cat');\">
4108 ".__('Convert to label')."</a>";
4115 print "<td class=\"headlineTitle$rtl_cpart\">";
4117 print "<span id=\"subtoolbar_search\"
4118 style=\"display : none\"><input
4119 id=\"subtoolbar_search_box\"
4120 onblur=\"javascript:enableHotkeys();\"
4121 onfocus=\"javascript:disableHotkeys();\"
4122 onchange=\"subtoolbarSearch()\"
4123 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4125 print "<span id=\"subtoolbar_ftitle\">";
4127 if ($feed_site_url) {
4129 $target = "target=\"_blank\"";
4131 print "<a $target href=\"$feed_site_url\">".
4132 truncate_string($feed_title,30)."</a>";
4138 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4141 if ($user_page_offset > 1) {
4142 print " [$user_page_offset] ";
4145 if (!$bottom && !$disable_feed) {
4147 <a target=\"_blank\"
4148 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4149 <img class=\"noborder\"
4150 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4152 } else if ($feed_small_icon) {
4153 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4159 print "</tr></table></nobr>";
4163 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4165 $tmp_category = getCategoryTitle($link, $cat_id);
4168 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4170 $cat_unread = getCategoryUnread($link, $cat_id);
4174 $holder_style = "display:none;";
4181 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4184 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4185 $inner_title_class = "catTitle";
4187 $browse_cat_link = "";
4188 $inner_title_class = "catTitleNL";
4192 $cat_class = "feedCat";
4194 $cat_class = "virtCat";
4197 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4198 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4199 title=\"".__('Click to collapse category')."\"
4200 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4201 id=\"FCATN-$cat_id\" $browse_cat_link
4202 \">$tmp_category</span>";
4204 print "<span id=\"FCAP-$cat_id\">";
4206 print " <span id=\"FCATCTR-$cat_id\"
4207 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4213 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4217 function outputFeedList($link, $tags = false) {
4219 print "<ul class=\"feedList\" id=\"feedList\">";
4221 $owner_uid = $_SESSION["uid"];
4225 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4227 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4230 $cat_hidden = false;
4233 printCategoryHeader($link, -1, $cat_hidden, false);
4236 $num_starred = getFeedUnread($link, -1);
4237 $num_published = getFeedUnread($link, -2);
4238 $num_fresh = getFeedUnread($link, -3);
4242 if ($num_fresh > 0) $class .= "Unread";
4244 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4245 "images/fresh.png", $link);
4249 if ($num_starred > 0) $class .= "Unread";
4251 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4254 $mark_img_ext = "gif";
4256 $mark_img_ext = "png";
4259 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4260 "images/mark_set.$mark_img_ext", $link);
4264 if ($num_published > 0) $class .= "Unread";
4266 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4267 "images/pub_set.gif", $link);
4269 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4275 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4277 $result = db_query($link, "SELECT id,sql_exp,description FROM
4278 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4280 if (db_num_rows($result) > 0) {
4281 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4283 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4286 $cat_hidden = false;
4289 printCategoryHeader($link, -2, $cat_hidden, false);
4292 print "<li><hr></li>";
4296 while ($line = db_fetch_assoc($result)) {
4298 error_reporting (0);
4300 $label_id = -$line['id'] - 11;
4301 $count = getFeedUnread($link, $label_id);
4309 error_reporting (DEFAULT_ERROR_LEVEL
);
4311 printFeedEntry($label_id,
4312 $class, $line["description"],
4313 $count, "images/label.png", $link);
4317 if (db_num_rows($result) > 0) {
4318 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4325 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4326 print "<li><hr></li>";
4329 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4330 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4331 $order_by_qpart = "order_id,category,unread DESC,title";
4333 $order_by_qpart = "order_id,category,title";
4336 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4337 $order_by_qpart = "unread DESC,title";
4339 $order_by_qpart = "title";
4343 $age_qpart = getMaxAgeSubquery();
4345 $query = "SELECT ttrss_feeds.*,
4346 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4348 ttrss_feed_categories.title AS category,
4349 ttrss_feed_categories.collapsed
4350 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4351 ON (ttrss_feed_categories.id = cat_id)
4353 ttrss_feeds.hidden = false AND
4354 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4355 ORDER BY $order_by_qpart";
4357 $result = db_query($link, $query);
4359 $actid = $_GET["actid"];
4369 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4371 while ($line = db_fetch_assoc($result)) {
4373 $feed = trim($line["title"]);
4375 if (!$feed) $feed = "[Untitled]";
4377 $feed_id = $line["id"];
4379 $subop = $_GET["subop"];
4381 $unread = ccache_find($link, $feed_id, $_SESSION["uid"]);
4383 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4384 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4386 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4389 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4392 $rtl_tag = "dir=\"RTL\"";
4397 $tmp_result = db_query($link,
4398 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4399 WHERE parent_feed = '$feed_id' AND feed_id = id");
4401 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4403 $cat_id = $line["cat_id"];
4405 $tmp_category = $line["category"];
4407 if (!$tmp_category) {
4408 $tmp_category = __("Uncategorized");
4411 // $class = ($lnum % 2) ? "even" : "odd";
4413 if ($line["last_error"]) {
4419 if ($unread > 0) $class .= "Unread";
4421 if ($actid == $feed_id) {
4422 $class .= "Selected";
4425 $total_unread +
= $unread;
4427 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4433 $category = $tmp_category;
4435 $collapsed = sql_bool_to_bool($line["collapsed"]);
4437 // workaround for NULL category
4438 if ($category == __("Uncategorized")) {
4439 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4444 $cat_id = sprintf("%d", $cat_id);
4446 printCategoryHeader($link, $cat_id, $collapsed, true);
4450 printFeedEntry($feed_id, $class, $feed, $unread,
4451 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4452 $last_updated, $line["last_error"]);
4457 if (db_num_rows($result) == 0) {
4458 print "<li>".__('No feeds to display.')."</li>";
4465 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4466 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4467 post_int_id = ttrss_user_entries.int_id AND
4468 unread = true AND ref_id = ttrss_entries.id
4469 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4471 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4472 ORDER BY tag_name"); */
4474 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4475 print "<li class=\"feedCat\">".__('Tags')."</li>";
4476 print "<ul class=\"feedCatList\">";
4479 $age_qpart = getMaxAgeSubquery();
4481 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4482 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4483 AND ref_id = id AND $age_qpart
4484 AND unread = true)) AS count FROM ttrss_tags
4485 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4486 ORDER BY count DESC LIMIT 50");
4490 while ($line = db_fetch_assoc($result)) {
4491 $tags[$line["tag_name"]] +
= $line["count"];
4494 foreach (array_keys($tags) as $tag) {
4496 $unread = $tags[$tag];
4504 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4508 if (db_num_rows($result) == 0) {
4509 print "<li>No tags to display.</li>";
4512 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4522 function get_article_tags($link, $id, $owner_uid = 0) {
4524 $a_id = db_escape_string($id);
4526 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4528 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4529 owner_uid as owner FROM
4530 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4531 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4535 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4536 array_push($tags, $tmp_line["tag_name"]);
4542 function trim_value(&$value) {
4543 $value = trim($value);
4546 function trim_array($array) {
4548 array_walk($tmp, 'trim_value');
4552 function tag_is_valid($tag) {
4553 if ($tag == '') return false;
4554 if (preg_match("/^[0-9]*$/", $tag)) return false;
4556 if (function_exists('iconv')) {
4557 $tag = iconv("utf-8", "utf-8", $tag);
4560 if (!$tag) return false;
4565 function render_login_form($link, $mobile = false) {
4567 require_once "login_form.php";
4569 require_once "mobile/login_form.php";
4573 // from http://developer.apple.com/internet/safari/faq.html
4574 function no_cache_incantation() {
4575 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4576 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4577 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4578 header("Cache-Control: post-check=0, pre-check=0", false);
4579 header("Pragma: no-cache"); // HTTP/1.0
4582 function format_warning($msg, $id = "") {
4583 return "<div class=\"warning\" id=\"$id\">
4584 <img src=\"images/sign_excl.gif\">$msg</div>";
4587 function format_notice($msg) {
4588 return "<div class=\"notice\">
4589 <img src=\"images/sign_info.gif\">$msg</div>";
4592 function format_error($msg) {
4593 return "<div class=\"error\">
4594 <img src=\"images/sign_excl.gif\">$msg</div>";
4597 function print_notice($msg) {
4598 return print format_notice($msg);
4601 function print_warning($msg) {
4602 return print format_warning($msg);
4605 function print_error($msg) {
4606 return print format_error($msg);
4610 function T_sprintf() {
4611 $args = func_get_args();
4612 return vsprintf(__(array_shift($args)), $args);
4615 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4616 $zoom_mode = false) {
4618 /* we can figure out feed_id from article id anyway, why do we
4619 * pass feed_id here? */
4621 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4622 WHERE ref_id = '$id'");
4624 $feed_id = db_fetch_result($result, 0, "feed_id");
4626 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4628 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4629 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4631 if (db_num_rows($result) == 1) {
4632 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4634 $rtl_content = false;
4638 $rtl_tag = "dir=\"RTL\"";
4645 if ($mark_as_read) {
4646 $result = db_query($link, "UPDATE ttrss_user_entries
4647 SET unread = false,last_read = NOW()
4648 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4650 ccache_update($link, $feed_id, $_SESSION["uid"]);
4653 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4654 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4655 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4658 FROM ttrss_entries,ttrss_user_entries
4659 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4665 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4666 $link_target = "target=\"_blank\"";
4669 $line = db_fetch_assoc($result);
4671 if ($line["icon_url"]) {
4672 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4674 $feed_icon = " ";
4677 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4678 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4680 $entry_comments = "";
4683 $num_comments = $line["num_comments"];
4684 $entry_comments = "";
4686 if ($num_comments > 0) {
4687 if ($line["comments"]) {
4688 $comments_url = $line["comments"];
4690 $comments_url = $line["link"];
4692 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4694 if ($line["comments"] && $line["link"] != $line["comments"]) {
4695 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4700 header("Content-Type: text/html");
4702 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4703 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4704 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4709 print "<div class=\"postReply\">";
4711 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4712 onmouseout=\"enable_resize(false)\">";
4714 $entry_author = $line["author"];
4716 if ($entry_author) {
4717 $entry_author = __(" - ") . $entry_author;
4720 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4721 strtotime($line["updated"]));
4723 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4725 if ($line["link"]) {
4726 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4727 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4729 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4732 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4733 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4734 ORDER BY tag_name"); */
4736 $tags = get_article_tags($link, $id);
4739 $tags_nolinks_str = "";
4744 if ($_SESSION["theme"] == "3pane") {
4750 foreach ($tags as $tag) {
4752 $tag_escaped = str_replace("'", "\\'", $tag);
4754 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4756 if ($num_tags == $tag_limit) {
4757 $tags_str .= "…";
4758 $tags_nolinks_str .= "…";
4760 } else if ($num_tags < $tag_limit) {
4761 $tags_str .= $tag_str;
4762 $tags_nolinks_str .= "$tag, ";
4764 $f_tags_str .= $tag_str;
4767 $tags_str = preg_replace("/, $/", "", $tags_str);
4768 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4769 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4771 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4772 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4774 if (!$entry_comments) $entry_comments = " "; # placeholder
4776 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4777 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4779 print "<div style='float : right'>
4780 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4784 <a title=\"".__('Edit tags for this article')."\"
4785 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4787 if (defined('_ENABLE_INLINE_VIEW')) {
4789 print "<img src=\"images/art-inline.png\" class='tagsPic'
4790 style=\"cursor : pointer\" style=\"cursor : pointer\"
4791 onclick=\"showOriginalArticleInline($id)\"
4792 alt='Inline' title='".__('Display original article content')."'>";
4796 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4797 style=\"cursor : pointer\" style=\"cursor : pointer\"
4798 onclick=\"zoomToArticle($id)\"
4799 alt='Zoom' title='".__('Show article summary in new window')."'>";
4801 print "$tags_nolinks_str";
4804 print "<div clear='both'>$entry_comments</div>";
4808 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4809 print "<div class=\"postContent\">";
4811 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4813 $article_content = sanitize_rss($link, $line["content"]);
4815 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4816 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4820 print $article_content;
4822 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4823 post_id = '$id' AND content_url != ''");
4825 if (db_num_rows($result) > 0) {
4827 $entries_html = array();
4830 while ($line = db_fetch_assoc($result)) {
4832 $url = $line["content_url"];
4833 $ctype = $line["content_type"];
4835 if (!$ctype) $ctype = __("unknown type");
4837 $filename = substr($url, strrpos($url, "/")+
1);
4841 if (($ctype == __("audio/mpeg")) &&
4842 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4844 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
4848 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4849 $filename . " (" . $ctype . ")" . "</a>";
4851 array_push($entries_html, $entry);
4855 $entry["type"] = $ctype;
4856 $entry["filename"] = $filename;
4857 $entry["url"] = $url;
4859 array_push($entries, $entry);
4862 print "<div class=\"postEnclosures\">";
4864 if (!preg_match("/img/i", $article_content)) {
4865 foreach ($entries as $entry) {
4866 if (preg_match("/image/", $entry["type"])) {
4868 alt=\"".htmlspecialchars($entry["filename"])."\"
4869 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4874 print "<div class=\"postEnclosures\">";
4876 if (db_num_rows($result) == 1) {
4877 print __("Attachment:") . " ";
4879 print __("Attachments:") . " ";
4882 print join(", ", $entries_html);
4894 print "]]></article>";
4897 <div style=\"text-align : center\">
4898 <input type=\"submit\" onclick=\"return window.close()\"
4899 value=\"".__("Close this window")."\"></div>";
4900 print "</body></html>";
4906 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4907 $next_unread_feed, $offset, $vgr_last_feed = false,
4908 $override_order = false) {
4910 $disable_cache = false;
4912 $timing_info = getmicrotime();
4914 $topmost_article_ids = array();
4920 if ($subop == "undefined") $subop = "";
4922 $subop_split = split(":", $subop);
4924 if ($subop == "CatchupSelected") {
4925 $ids = split(",", db_escape_string($_GET["ids"]));
4926 $cmode = sprintf("%d", $_GET["cmode"]);
4928 catchupArticlesById($link, $ids, $cmode);
4931 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4932 update_generic_feed($link, $feed, $cat_view, true);
4935 if ($subop == "MarkAllRead") {
4936 catchup_feed($link, $feed, $cat_view);
4938 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4939 if ($next_unread_feed) {
4940 $feed = $next_unread_feed;
4945 if ($subop_split[0] == "MarkAllReadGR") {
4946 catchup_feed($link, $subop_split[1], false);
4951 $result = db_query($link,
4952 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4954 if (db_num_rows($result) == 0) {
4955 print "<div align='center'>".__('Feed not found.')."</div>";
4960 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4962 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4963 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4965 if (db_num_rows($result) == 1) {
4966 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4968 $rtl_content = false;
4972 $rtl_tag = "dir=\"RTL\"";
4978 $rtl_content = false;
4981 $script_dt_add = get_script_dt_add();
4983 /// START /////////////////////////////////////////////////////////////////////////////////
4985 $search = db_escape_string($_GET["query"]);
4988 $disable_cache = true;
4991 $search_mode = db_escape_string($_GET["search_mode"]);
4992 $match_on = db_escape_string($_GET["match_on"]);
4998 $real_offset = $offset * $limit;
5000 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5002 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
5003 $search, $search_mode, $match_on, $override_order, $real_offset);
5005 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5007 $result = $qfh_ret[0];
5008 $feed_title = $qfh_ret[1];
5009 $feed_site_url = $qfh_ret[2];
5010 $last_error = $qfh_ret[3];
5012 $vgroup_last_feed = $vgr_last_feed;
5015 $feed_site_url = article_publish_url($link);
5018 /// STOP //////////////////////////////////////////////////////////////////////////////////
5021 print "<div id=\"headlinesContainer\" $rtl_tag>";
5024 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
5028 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
5029 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
5032 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
5035 $headlines_count = db_num_rows($result);
5037 if (db_num_rows($result) > 0) {
5039 # print "\{$offset}";
5041 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5042 print "<table class=\"headlinesList\" id=\"headlinesList\"
5043 cellspacing=\"0\">";
5046 $lnum = $limit*$offset;
5048 error_reporting (DEFAULT_ERROR_LEVEL
);
5051 $cur_feed_title = '';
5053 while ($line = db_fetch_assoc($result)) {
5055 $class = ($lnum %
2) ?
"even" : "odd";
5058 $feed_id = $line["feed_id"];
5060 if (count($topmost_article_ids) < 5) {
5061 array_push($topmost_article_ids, $id);
5064 if ($line["last_read"] == "" &&
5065 ($line["unread"] != "t" && $line["unread"] != "1")) {
5067 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5070 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5074 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5082 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5085 $mark_img_ext = "gif";
5087 $mark_img_ext = "png";
5090 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5091 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5093 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5095 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5097 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5100 if ($line["published"] == "t" ||
$line["published"] == "1") {
5101 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5103 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5105 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5107 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5110 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5111 # $line["title"] . "</a>";
5113 # $content_link = "<a
5114 # href=\"" . htmlspecialchars($line["link"]) . "\"
5115 # onclick=\"view($id,$feed_id);\">" .
5116 # $line["title"] . "</a>";
5118 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5119 # $line["title"] . "</a>";
5121 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5122 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5124 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5125 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5128 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5129 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5133 $score = $line["score"];
5135 $score_pic = get_score_pic($score);
5137 $score_title = __("(Click to change)");
5139 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5140 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">";
5144 } else if ($score < -100) {
5150 $entry_author = $line["author"];
5152 if ($entry_author) {
5153 $entry_author = " - $entry_author";
5156 $has_feed_icon = feed_has_icon($feed_id);
5158 if ($has_feed_icon) {
5159 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5161 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5162 $feed_icon_img = "";
5165 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5167 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5168 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5170 $cur_feed_title = $line["feed_title"];
5171 $vgroup_last_feed = $feed_id;
5173 $cur_feed_title = htmlspecialchars($cur_feed_title);
5175 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5177 print "<tr class='feedTitle'><td colspan='7'>".
5178 "<div style=\"float : right\">$feed_icon_img</div>".
5179 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5180 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5184 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5185 onmouseout='postMouseOut($id)'";
5187 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5189 print "<td class='hlUpdPic'>$update_pic</td>";
5191 print "<td class='hlSelectRow'>
5192 <input type=\"checkbox\" onclick=\"tSR(this)\"
5196 print "<td class='hlMarkedPic'>$marked_pic</td>";
5197 print "<td class='hlMarkedPic'>$published_pic</td>";
5199 # if ($line["feed_title"]) {
5200 # print "<td class='hlContent'>$content_link</td>";
5201 # print "<td class='hlFeed'>
5202 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5203 # truncate_string($line["feed_title"],30)."</a> </td>";
5206 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5208 print "<a id=\"RTITLE-$id\"
5209 href=\"" . htmlspecialchars($line["link"]) . "\"
5210 onclick=\"return view($id,$feed_id);\">" .
5213 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5214 if ($content_preview) {
5215 print "<span class=\"contentPreview\"> - $content_preview</span>";
5221 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5222 # $line["feed_title"]."</a>
5224 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5225 if ($line["feed_title"]) {
5226 print "<span class=\"hlFeed\">
5227 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5228 $line["feed_title"]."</a>)
5236 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5238 print "<td class='hlMarkedPic'>$score_pic</td>";
5240 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5241 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5248 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5249 if ($feed_id != $vgroup_last_feed) {
5251 $cur_feed_title = $line["feed_title"];
5252 $vgroup_last_feed = $feed_id;
5254 $cur_feed_title = htmlspecialchars($cur_feed_title);
5256 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5258 $has_feed_icon = feed_has_icon($feed_id);
5260 if ($has_feed_icon) {
5261 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5263 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5266 print "<div class='cdmFeedTitle'>".
5267 "<div style=\"float : right\">$feed_icon_img</div>".
5268 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5269 $line["feed_title"]."</a> $vf_catchup_link</div>";
5274 $add_class = "Unread";
5279 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5280 $show_excerpt = false;
5282 if ($expand_cdm && $score >= -100) {
5284 $show_excerpt = false;
5286 $cdm_cstyle = "style=\"display : none\"";
5287 $show_excerpt = true;
5290 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5291 onmouseout='postMouseOut($id)'";
5293 print "<div class=\"cdmArticle$add_class\"
5295 $mouseover_attrs'>";
5297 print "<div class=\"cdmHeader\">";
5299 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5300 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5303 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5306 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5307 onclick=\"javascript:toggleUnread($id, 0)\"
5308 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5311 print $entry_author;
5313 /* if (!$expand_cdm || $score < -100) {
5314 print " <a id=\"CICH-$id\"
5315 href=\"javascript:cdmExpandArticle($id)\">
5316 (".__('Show article').")</a>";
5320 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5321 if ($line["feed_title"]) {
5322 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5326 print "</span></div>";
5328 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5329 $line["content_preview"] = preg_replace("/href=/i",
5330 "target=\"_blank\" href=", $line["content_preview"]);
5333 if ($show_excerpt) {
5334 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5335 onclick=\"cdmExpandArticle($id)\"
5336 title=\"".__('Click to expand article')."\">";
5337 print truncate_string(strip_tags($line["content_preview"]), 100);
5341 print "<div class=\"cdmContent\"
5342 onclick=\"cdmClicked($id)\"
5343 id=\"CICD-$id\" $cdm_cstyle>";
5345 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5347 print sanitize_rss($link, $line["content_preview"]);
5348 $article_content = $line["content_preview"];
5350 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5351 post_id = '$id' AND content_url != ''");
5353 if (db_num_rows($e_result) > 0) {
5355 $entries_html = array();
5358 while ($e_line = db_fetch_assoc($e_result)) {
5360 $url = $e_line["content_url"];
5361 $ctype = $e_line["content_type"];
5362 if (!$ctype) $ctype = __("unknown type");
5364 $filename = substr($url, strrpos($url, "/")+
1);
5368 if (($ctype == __("audio/mpeg")) &&
5369 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5371 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
5375 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5376 $filename . " (" . $ctype . ")" . "</a>";
5378 array_push($entries_html, $entry);
5382 $entry["type"] = $ctype;
5383 $entry["filename"] = $filename;
5384 $entry["url"] = $url;
5386 array_push($entries, $entry);
5389 if (!preg_match("/img/i", $article_content)) {
5390 foreach ($entries as $entry) {
5391 if (preg_match("/image/", $entry["type"])) {
5393 alt=\"".htmlspecialchars($entry["filename"])."\"
5394 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5399 print "<div class=\"cdmEnclosures\">";
5401 if (db_num_rows($e_result) == 1) {
5402 print __("Attachment:") . " ";
5404 print __("Attachments:") . " ";
5407 print join(", ", $entries_html);
5413 print "<br clear='both'>";
5416 /* if (!$expand_cdm) {
5417 print "<a id=\"CICH-$id\"
5418 href=\"javascript:cdmExpandArticle($id)\">
5424 print "<div class=\"cdmFooter\"><span class='s0'>";
5426 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5428 print __("Select:").
5429 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5430 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5432 print "</span><span class='s1'>$marked_pic</span> ";
5433 print "<span class='s1'>$published_pic</span> ";
5434 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5435 onclick=\"zoomToArticle($id)\"
5436 style=\"cursor : pointer\"
5438 title='".__('Show article summary in new window')."'></span>";
5440 $tags = get_article_tags($link, $id);
5443 $full_tags_str = "";
5446 foreach ($tags as $tag) {
5448 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5449 if ($num_tags < 5) {
5450 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5451 } else if ($num_tags == 5) {
5452 $tags_str .= "…";
5456 $tags_str = preg_replace("/, $/", "", $tags_str);
5457 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5459 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5461 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5464 if ($tags_str == "") $tags_str = "no tags";
5466 // print "<img src='images/tag.png' class='markedPic'>";
5468 print "<span class='s1'>
5469 <img class='tagsPic' src='images/tag.png' alt='Tags'
5470 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5471 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5475 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5476 href=\"javascript:toggleUnread($id)\">
5487 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5491 // print_headline_subtoolbar($link,
5492 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5498 switch ($view_mode) {
5500 $message = __("No unread articles found to display.");
5503 $message = __("No starred articles found to display.");
5506 $message = __("No articles found to display.");
5509 if (!$offset) print "<div class='whiteBox'>$message</div>";
5517 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5520 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5522 function printTagCloud($link) {
5524 /* get first ref_id to count from */
5530 if (DB_TYPE == "pgsql") {
5531 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5532 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5533 AND date_entered > NOW() - INTERVAL '30 days'";
5535 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5536 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5537 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5540 $result = db_query($link, $query);
5541 $first_id = db_fetch_result($result, 0, "id"); */
5543 //AND post_int_id >= '$first_id'
5544 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5545 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5546 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5548 $result = db_query($link, $query);
5552 while ($line = db_fetch_assoc($result)) {
5553 $tags[$line["tag_name"]] = $line["count"];
5558 $max_size = 32; // max font size in pixels
5559 $min_size = 11; // min font size in pixels
5561 // largest and smallest array values
5562 $max_qty = max(array_values($tags));
5563 $min_qty = min(array_values($tags));
5565 // find the range of values
5566 $spread = $max_qty - $min_qty;
5567 if ($spread == 0) { // we don't want to divide by zero
5571 // set the font-size increment
5572 $step = ($max_size - $min_size) / ($spread);
5574 // loop through the tag array
5575 foreach ($tags as $key => $value) {
5576 // calculate font-size
5577 // find the $value in excess of $min_qty
5578 // multiply by the font-size increment ($size)
5579 // and add the $min_size set above
5580 $size = round($min_size +
(($value - $min_qty) * $step));
5582 $key_escaped = str_replace("'", "\\'", $key);
5584 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5585 $size . "px\" title=\"$value articles tagged with " .
5586 $key . '">' . $key . '</a> ';
5590 function print_checkpoint($n, $s) {
5591 $ts = getmicrotime();
5592 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5596 function sanitize_tag($tag) {
5599 $tag = mb_strtolower($tag, 'utf-8');
5601 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5603 // $tag = str_replace('"', "", $tag);
5604 // $tag = str_replace("+", " ", $tag);
5605 $tag = str_replace("technorati tag: ", "", $tag);
5610 function generate_publish_key() {
5611 return sha1(uniqid(rand(), true));
5614 function article_publish_url($link) {
5619 if ($_SERVER['HTTPS'] != "on") {
5620 $url_path = "http://";
5622 $url_path = "https://";
5625 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5626 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5632 * Purge a feed contents, marked articles excepted.
5634 * @param mixed $link The database connection.
5635 * @param integer $id The id of the feed to purge.
5638 function clear_feed_articles($link, $id) {
5639 $result = db_query($link, "DELETE FROM ttrss_user_entries
5640 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5642 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5643 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5644 } // function clear_feed_articles
5647 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5649 * @return string The Mozilla Firefox feed adding URL.
5651 function add_feed_url() {
5652 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5653 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5655 } // function add_feed_url
5658 * Encrypt a password in SHA1.
5660 * @param string $pass The password to encrypt.
5661 * @param string $login A optionnal login.
5662 * @return string The encrypted password.
5664 function encrypt_password($pass, $login = '') {
5666 return "SHA1X:" . sha1("$login:$pass");
5668 return "SHA1:" . sha1($pass);
5670 } // function encrypt_password
5673 * Update a feed batch.
5674 * Used by daemons to update n feeds by run.
5675 * Only update feed needing a update, and not being processed
5676 * by another process.
5678 * @param mixed $link Database link
5679 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5680 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5681 * @param boolean $debug Set to false to disable debug output. Default to true.
5684 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5685 // Process all other feeds using last_updated and interval parameters
5687 // Test if the user has loggued in recently. If not, it does not update its feeds.
5688 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5689 if (DB_TYPE
== "pgsql") {
5690 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5692 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5695 $login_thresh_qpart = "";
5698 // Test if the feed need a update (update interval exceded).
5699 if (DB_TYPE
== "pgsql") {
5700 $update_limit_qpart = "AND ((
5701 ttrss_feeds.update_interval = 0
5702 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5704 ttrss_feeds.update_interval > 0
5705 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5706 ) OR ttrss_feeds.last_updated IS NULL)";
5708 $update_limit_qpart = "AND ((
5709 ttrss_feeds.update_interval = 0
5710 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5712 ttrss_feeds.update_interval > 0
5713 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5714 ) OR ttrss_feeds.last_updated IS NULL)";
5717 // Test if feed is currently being updated by another process.
5718 if (DB_TYPE
== "pgsql") {
5719 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5721 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5724 // Test if there is a limit to number of updated feeds
5726 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5728 $random_qpart = sql_random_function();
5730 // We search for feed needing update.
5731 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5732 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5733 ttrss_feeds.update_interval
5735 ttrss_feeds, ttrss_users, ttrss_user_prefs
5737 ttrss_feeds.owner_uid = ttrss_users.id
5738 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5739 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5740 $login_thresh_qpart $update_limit_qpart
5741 $updstart_thresh_qpart
5742 ORDER BY $random_qpart $query_limit");
5744 $user_prefs_cache = array();
5746 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5748 // Here is a little cache magic in order to minimize risk of double feed updates.
5749 $feeds_to_update = array();
5750 while ($line = db_fetch_assoc($result)) {
5751 $feeds_to_update[$line['id']] = $line;
5754 // We update the feed last update started date before anything else.
5755 // There is no lag due to feed contents downloads
5756 // It prevent an other process to update the same feed.
5757 $feed_ids = array_keys($feeds_to_update);
5759 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5760 WHERE id IN (%s)", implode(',', $feed_ids)));
5763 // For each feed, we call the feed update function.
5764 while ($line = array_pop($feeds_to_update)) {
5766 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5768 // We setup a alarm to alert if the feed take more than 300s to update.
5770 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5771 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5772 // Cancel the alarm (the update went well)
5773 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5775 sleep(1); // prevent flood (FIXME make this an option?)
5778 // Send feed digests by email if needed.
5779 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5781 } // function update_daemon_common
5783 function sanitize_article_content($text) {
5784 # we don't support CDATA sections in articles, they break our own escaping
5785 $text = preg_replace("/\[\[CDATA/", "", $text);
5786 $text = preg_replace("/\]\]\>/", "", $text);
5790 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5793 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5795 $result = db_query($link, "SELECT reg_exp,
5796 ttrss_filter_types.name AS name,
5797 ttrss_filter_actions.name AS action,
5801 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5804 owner_uid = $owner_uid AND
5805 ttrss_filter_types.id = filter_type AND
5806 ttrss_filter_actions.id = action_id AND
5807 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5809 while ($line = db_fetch_assoc($result)) {
5810 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5811 $filter["reg_exp"] = $line["reg_exp"];
5812 $filter["action"] = $line["action"];
5813 $filter["action_param"] = $line["action_param"];
5814 $filter["filter_param"] = $line["filter_param"];
5815 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5817 array_push($filters[$line["name"]], $filter);
5823 function get_score_pic($score) {
5825 return "score_high.png";
5826 } else if ($score > 0) {
5827 return "score_half_high.png";
5828 } else if ($score < -100) {
5829 return "score_low.png";
5830 } else if ($score < 0) {
5831 return "score_half_low.png";
5833 return "score_neutral.png";
5837 function rounded_table_start($classname, $header = " ") {
5838 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5839 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5840 print "<tr><td class='left'> </td><td class='content'>";
5843 function rounded_table_end($footer = " ") {
5844 print "</td><td class='right'> </td></tr>";
5845 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5849 function print_label_dlg_common_examples() {
5851 print __("Match ") . " ";
5853 /* print "<select name=\"label_andor\">";
5854 print "<option value=\"and\">AND</option>";
5855 print "<option value=\"or\">OR</option>";
5856 print "</select>"; */
5858 print "<select name=\"label_fields\" onchange=\"labelFieldsCheck(this)\">";
5859 print "<option value=\"unread\">".__("Unread articles")."</option>";
5860 print "<option value=\"updated\">".__("Updated articles")."</option>";
5861 print "<option value=\"kw_title\">".__("Title contains")."</option>";
5862 print "<option value=\"kw_content\">".__("Content contains")."</option>";
5863 print "<option value=\"scoreE\">".__("Score equals")."</option>";
5864 print "<option value=\"scoreG\">".__("Score is greater than")."</option>";
5865 print "<option value=\"scoreL\">".__("Score is less than")."</option>";
5866 print "<option value=\"newerH\">".__("Articles newer than X hours")."</option>";
5867 print "<option value=\"newerD\">".__("Articles newer than X days")."</option>";
5871 print "<input style=\"display : none\" name=\"label_fields_param\"
5874 print " <input type=\"submit\"
5875 onclick=\"return addLabelExample()\"
5876 value=\"".__("Add")."\">";
5879 function feed_has_icon($id) {
5880 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5883 function init_connection($link) {
5884 if (DB_TYPE
== "pgsql") {
5885 pg_query($link, "set client_encoding = 'UTF-8'");
5886 pg_set_client_encoding("UNICODE");
5887 pg_query($link, "set datestyle = 'ISO, european'");
5889 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5890 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5891 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5896 function update_feedbrowser_cache($link) {
5898 $result = db_query($link, "SELECT feed_url,COUNT(id) AS subscribers
5899 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5900 WHERE tf.feed_url = ttrss_feeds.feed_url
5901 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5902 GROUP BY feed_url ORDER BY subscribers DESC LIMIT 200");
5904 db_query($link, "BEGIN");
5906 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5910 while ($line = db_fetch_assoc($result)) {
5911 $subscribers = db_escape_string($line["subscribers"]);
5912 $feed_url = db_escape_string($line["feed_url"]);
5914 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5915 (feed_url, subscribers) VALUES ('$feed_url', '$subscribers')");
5920 db_query($link, "COMMIT");
5926 function ccache_zero($link, $feed_id, $owner_uid) {
5927 db_query($link, "UPDATE ttrss_counters_cache SET
5928 value = 0, updated = NOW() WHERE
5929 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5932 function ccache_zero_all($link, $owner_uid) {
5933 db_query($link, "UPDATE ttrss_counters_cache SET
5934 value = 0 WHERE owner_uid = '$owner_uid'");
5936 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5937 value = 0 WHERE owner_uid = '$owner_uid'");
5940 /* function ccache_invalidate($link, $feed_id, $owner_uid, $is_cat = false) {
5943 $table = "ttrss_counters_cache";
5945 $table = "ttrss_cat_counters_cache";
5948 db_query($link, "DELETE FROM $table
5949 WHERE feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5952 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false) {
5955 $table = "ttrss_counters_cache";
5957 $table = "ttrss_cat_counters_cache";
5960 if (DB_TYPE
== "pgsql") {
5961 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5962 } else if (DB_TYPE
== "mysql") {
5963 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5966 $result = db_query($link, "SELECT value FROM $table
5967 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5970 if (db_num_rows($result) == 1) {
5971 return db_fetch_result($result, 0, "value");
5973 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5978 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false) {
5981 $table = "ttrss_counters_cache";
5983 $table = "ttrss_cat_counters_cache";
5986 if ($is_cat && $feed_id >= 0) {
5987 if ($feed_id != 0) {
5988 $cat_qpart = "cat_id = '$feed_id'";
5990 $cat_qpart = "cat_id IS NULL";
5993 $result = db_query($link, "SELECT SUM(value) AS sv
5994 FROM ttrss_counters_cache, ttrss_feeds
5995 WHERE id = feed_id AND $cat_qpart AND
5996 ttrss_feeds.owner_uid = '$owner_uid'");
5998 $unread = db_fetch_result($result, 0, "sv");
6001 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6004 $result = db_query($link, "SELECT feed_id FROM $table
6005 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6007 if (db_num_rows($result) == 1) {
6008 db_query($link, "UPDATE $table SET
6009 value = '$unread', updated = NOW() WHERE
6010 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6013 db_query($link, "INSERT INTO $table
6014 (feed_id, value, owner_uid, updated)
6016 ($feed_id, $unread, $owner_uid, NOW())");
6024 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6025 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6027 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6029 ccache_update($link, $cat_id, $owner_uid, true);
6031 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
6032 WHERE owner_uid = '$owner_uid' AND feed_id < 0");
6034 while ($line = db_fetch_assoc($result)) {
6035 ccache_update($link, $line["feed_id"], $owner_uid);