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"];
57 if (defined('LC_MESSAGES')) {
58 _setlocale(LC_MESSAGES
, $lang);
59 } else if (defined('LC_ALL')) {
60 _setlocale(LC_ALL
, $lang);
62 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
64 _bindtextdomain("messages", "locale");
65 _textdomain("messages");
66 _bind_textdomain_codeset("messages", "UTF-8");
72 } else { // If translations are enabled.
76 function startup_gettext() {
80 } // If translations are enabled.
82 require_once 'db-prefs.php';
83 require_once 'compat.php';
84 require_once 'errors.php';
85 require_once 'version.php';
87 require_once 'phpmailer/class.phpmailer.php';
89 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
90 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
91 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
93 require_once "simplepie/simplepie.inc";
94 require_once "magpierss/rss_fetch.inc";
95 require_once 'magpierss/rss_utils.inc';
98 * Print a timestamped debug message.
100 * @param string $msg The debug message.
103 function _debug($msg) {
104 $ts = strftime("%H:%M:%S", time());
105 if (function_exists('posix_getpid')) {
106 $ts = "$ts/" . posix_getpid();
108 print "[$ts] $msg\n";
112 * Purge a feed old posts.
114 * @param mixed $link A database connection.
115 * @param mixed $feed_id The id of the purged feed.
116 * @param mixed $purge_interval Olderness of purged posts.
117 * @param boolean $debug Set to True to enable the debug. False by default.
121 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
123 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
127 $result = db_query($link,
128 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
132 if (db_num_rows($result) == 1) {
133 $owner_uid = db_fetch_result($result, 0, "owner_uid");
136 if (!$owner_uid) return;
138 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
141 if (!$purge_unread) $query_limit = " unread = false AND ";
143 if (DB_TYPE
== "pgsql") {
144 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
145 marked = false AND feed_id = '$feed_id' AND
146 (SELECT date_entered FROM ttrss_entries WHERE
147 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
149 $pg_version = get_pgsql_version($link);
151 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
153 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
154 ttrss_entries.id = ref_id AND
156 feed_id = '$feed_id' AND
158 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
162 $result = db_query($link, "DELETE FROM ttrss_user_entries
164 WHERE ttrss_entries.id = ref_id AND
166 feed_id = '$feed_id' AND
168 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
171 $rows = pg_affected_rows($result);
175 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
176 marked = false AND feed_id = '$feed_id' AND
177 (SELECT date_entered FROM ttrss_entries WHERE
178 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
180 $result = db_query($link, "DELETE FROM ttrss_user_entries
181 USING ttrss_user_entries, ttrss_entries
182 WHERE ttrss_entries.id = ref_id AND
184 feed_id = '$feed_id' AND
186 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
188 $rows = mysql_affected_rows($link);
193 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
195 } // function purge_feed
198 * Purge old posts from old feeds.
200 * @param mixed $link A database connection
201 * @param boolean $do_output Set to true to enable printed output, false by default.
202 * @param integer $limit The maximal number of removed posts.
206 function global_purge_old_posts($link, $do_output = false, $limit = false) {
208 $random_qpart = sql_random_function();
211 $limit_qpart = "LIMIT $limit";
216 $result = db_query($link,
217 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
218 ORDER BY $random_qpart $limit_qpart");
220 while ($line = db_fetch_assoc($result)) {
222 $feed_id = $line["id"];
223 $purge_interval = $line["purge_interval"];
224 $owner_uid = $line["owner_uid"];
226 if ($purge_interval == 0) {
228 $tmp_result = db_query($link,
229 "SELECT value FROM ttrss_user_prefs WHERE
230 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
232 if (db_num_rows($tmp_result) != 0) {
233 $purge_interval = db_fetch_result($tmp_result, 0, "value");
238 // print "Feed $feed_id: purge interval = $purge_interval\n";
241 if ($purge_interval > 0) {
242 purge_feed($link, $feed_id, $purge_interval, $do_output);
246 // purge orphaned posts in main content table
247 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
248 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
251 $rows = db_affected_rows($link, $result);
252 _debug("Purged $rows orphaned posts.");
255 } // function global_purge_old_posts
257 function feed_purge_interval($link, $feed_id) {
259 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
260 WHERE id = '$feed_id'");
262 if (db_num_rows($result) == 1) {
263 $purge_interval = db_fetch_result($result, 0, "purge_interval");
264 $owner_uid = db_fetch_result($result, 0, "owner_uid");
266 if ($purge_interval == 0) $purge_interval = get_pref($link,
267 'PURGE_OLD_DAYS', $user_id);
269 return $purge_interval;
276 function purge_old_posts($link) {
278 $user_id = $_SESSION["uid"];
280 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
281 WHERE owner_uid = '$user_id'");
283 while ($line = db_fetch_assoc($result)) {
285 $feed_id = $line["id"];
286 $purge_interval = $line["purge_interval"];
288 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
290 if ($purge_interval > 0) {
291 purge_feed($link, $feed_id, $purge_interval);
295 // purge orphaned posts in main content table
296 db_query($link, "DELETE FROM ttrss_entries WHERE
297 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
300 function get_feed_update_interval($link, $feed_id) {
301 $result = db_query($link, "SELECT owner_uid, update_interval FROM
302 ttrss_feeds WHERE id = '$feed_id'");
304 if (db_num_rows($result) == 1) {
305 $update_interval = db_fetch_result($result, 0, "update_interval");
306 $owner_uid = db_fetch_result($result, 0, "owner_uid");
308 if ($update_interval != 0) {
309 return $update_interval;
311 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
319 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
321 if (WEB_DEMO_MODE
) return;
324 $user_id = $_SESSION["uid"];
325 purge_old_posts($link);
328 // db_query($link, "BEGIN");
330 if (MAX_UPDATE_TIME
> 0) {
331 if (DB_TYPE
== "mysql") {
334 $q_order = "RANDOM()";
337 $q_order = "last_updated DESC";
340 $result = db_query($link, "SELECT feed_url,id,
341 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
342 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
347 while ($line = db_fetch_assoc($result)) {
348 $upd_intl = $line["update_interval"];
350 if (!$upd_intl ||
$upd_intl == 0) {
351 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
355 // Updates for this feed are disabled
359 if ($fetch ||
(!$line["last_updated"] ||
360 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
362 // print "<!-- feed: ".$line["feed_url"]." -->";
364 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
366 $upd_elapsed = time() - $upd_start;
368 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
374 // db_query($link, "COMMIT");
378 function fetch_file_contents($url) {
379 if (USE_CURL_FOR_ICONS
) {
380 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
382 $ch = curl_init($url);
383 $fp = fopen($tmpfile, "w");
386 curl_setopt($ch, CURLOPT_FILE
, $fp);
387 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
388 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
394 $contents = file_get_contents($tmpfile);
400 return file_get_contents($url);
406 * Try to determine the favicon URL for a feed.
407 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
408 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
410 * @param string $url A feed or page URL
412 * @return mixed The favicon URL, or false if none was found.
414 function get_favicon_url($url) {
416 if ($html = @fetch_file_contents
($url)) {
418 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
419 // Attempt to grab a favicon link from their webpage url
420 $linkUrl = html_entity_decode($matches[1]);
422 if (substr($linkUrl, 0, 1) == '/') {
423 $urlParts = parse_url($url);
424 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
425 } else if (substr($linkUrl, 0, 7) == 'http://') {
426 $faviconURL = $linkUrl;
427 } else if (substr($url, -1, 1) == '/') {
428 $faviconURL = $url.$linkUrl;
430 $faviconURL = $url.'/'.$linkUrl;
434 // If unsuccessful, attempt to "guess" the favicon location
435 $urlParts = parse_url($url);
436 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
440 // Run a test to see if what we have attempted to get actually exists.
441 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
446 } // function get_favicon_url
449 * Check if a link is a valid and working URL.
451 * @param mixed $link A URL to check
453 * @return boolean True if the URL is valid, false otherwise.
455 function url_validate($link) {
457 $url_parts = @parse_url
($link);
459 if ( empty( $url_parts["host"] ) )
462 if ( !empty( $url_parts["path"] ) ) {
463 $documentpath = $url_parts["path"];
468 if ( !empty( $url_parts["query"] ) )
469 $documentpath .= "?" . $url_parts["query"];
471 $host = $url_parts["host"];
472 $port = $url_parts["port"];
477 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
482 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
484 $http_response = fgets( $socket, 22 );
486 $responses = "/(200 OK)|(30[0-9] Moved)/";
487 if ( preg_match($responses, $http_response) ) {
494 } // function url_validate
496 function check_feed_favicon($site_url, $feed, $link) {
497 $favicon_url = get_favicon_url($site_url);
499 # print "FAVICON [$site_url]: $favicon_url\n";
503 $icon_file = ICONS_DIR
. "/$feed.ico";
505 if ($favicon_url && !file_exists($icon_file)) {
506 $contents = fetch_file_contents($favicon_url);
508 $fp = fopen($icon_file, "w");
511 fwrite($fp, $contents);
513 chmod($icon_file, 0644);
517 error_reporting(DEFAULT_ERROR_LEVEL
);
521 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
523 if (!$_GET["daemon"] && !$ignore_daemon) {
527 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
528 _debug("update_rss_feed: start");
531 if (!$ignore_daemon) {
533 if (DB_TYPE
== "pgsql") {
534 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
536 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
539 $result = db_query($link, "SELECT id,update_interval,auth_login,
540 auth_pass,cache_images,update_method
541 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
545 $result = db_query($link, "SELECT id,update_interval,auth_login,
546 auth_pass,cache_images,update_method
547 FROM ttrss_feeds WHERE id = '$feed'");
551 if (db_num_rows($result) == 0) {
552 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
553 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
558 $update_method = db_fetch_result($result, 0, "update_method");
560 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
561 WHERE id = '$feed'");
563 $auth_login = db_fetch_result($result, 0, "auth_login");
564 $auth_pass = db_fetch_result($result, 0, "auth_pass");
566 if (ALLOW_SELECT_UPDATE_METHOD
) {
567 if (ENABLE_SIMPLEPIE
) {
568 $use_simplepie = $update_method != 1;
570 $use_simplepie = $update_method == 2;
573 $use_simplepie = ENABLE_SIMPLEPIE
;
576 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
577 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
580 if (!$use_simplepie) {
581 $auth_login = urlencode($auth_login);
582 $auth_pass = urlencode($auth_pass);
585 $update_interval = db_fetch_result($result, 0, "update_interval");
586 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
588 if ($update_interval < 0) { return; }
590 $feed = db_escape_string($feed);
592 $fetch_url = $feed_url;
594 if ($auth_login && $auth_pass) {
595 $url_parts = array();
596 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
598 if ($url_parts[1] && $url_parts[2]) {
599 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
604 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
605 _debug("update_rss_feed: fetching [$fetch_url]...");
608 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
612 if (!$use_simplepie) {
613 $rss = fetch_rss($fetch_url);
615 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
616 mkdir(SIMPLEPIE_CACHE_DIR
);
619 $rss = new SimplePie();
620 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
621 # $rss->set_timeout(10);
622 $rss->set_feed_url($fetch_url);
623 $rss->set_output_encoding('UTF-8');
625 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
626 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
627 _debug("enabling image cache");
630 $rss->set_image_handler('./image.php', 'i');
633 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
634 _debug("feed update interval (sec): " .
635 get_feed_update_interval($link, $feed)*60);
638 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
639 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
640 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
648 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
649 _debug("update_rss_feed: fetch done, parsing...");
651 error_reporting (DEFAULT_ERROR_LEVEL
);
654 $feed = db_escape_string($feed);
656 if ($use_simplepie) {
657 $fetch_ok = !$rss->error();
664 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
665 _debug("update_rss_feed: processing feed data...");
668 // db_query($link, "BEGIN");
670 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
671 FROM ttrss_feeds WHERE id = '$feed'");
673 $registered_title = db_fetch_result($result, 0, "title");
674 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
675 $orig_site_url = db_fetch_result($result, 0, "site_url");
677 $owner_uid = db_fetch_result($result, 0, "owner_uid");
679 if ($use_simplepie) {
680 $site_url = $rss->get_link();
682 $site_url = $rss->channel
["link"];
685 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
686 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
687 _debug("update_rss_feed: checking favicon...");
690 check_feed_favicon($site_url, $feed, $link);
693 if (!$registered_title ||
$registered_title == "[Unknown]") {
695 if ($use_simplepie) {
696 $feed_title = db_escape_string($rss->get_title());
698 $feed_title = db_escape_string($rss->channel
["title"]);
701 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
702 _debug("update_rss_feed: registering title: $feed_title");
705 db_query($link, "UPDATE ttrss_feeds SET
706 title = '$feed_title' WHERE id = '$feed'");
709 // weird, weird Magpie
710 if (!$use_simplepie) {
711 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
714 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
715 db_query($link, "UPDATE ttrss_feeds SET
716 site_url = '$site_url' WHERE id = '$feed'");
719 // print "I: " . $rss->channel["image"]["url"];
721 if (!$use_simplepie) {
722 $icon_url = $rss->image
["url"];
724 $icon_url = $rss->get_image_url();
727 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
728 $icon_url = db_escape_string($icon_url);
729 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
732 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
733 _debug("update_rss_feed: loading filters...");
736 $filters = load_filters($link, $feed, $owner_uid);
738 if ($use_simplepie) {
739 $iterator = $rss->get_items();
741 $iterator = $rss->items
;
742 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
743 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
746 if (!is_array($iterator)) {
747 /* db_query($link, "UPDATE ttrss_feeds
748 SET last_error = 'Parse error: can\'t find any articles.'
749 WHERE id = '$feed'"); */
751 // clear any errors and mark feed as updated if fetched okay
752 // even if it's blank
754 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
755 _debug("update_rss_feed: entry iterator is not an array, no articles?");
758 db_query($link, "UPDATE ttrss_feeds
759 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
761 return; // no articles
764 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
765 _debug("update_rss_feed: processing articles...");
768 foreach ($iterator as $item) {
770 if ($_GET['xdebug']) {
775 if ($use_simplepie) {
776 $entry_guid = $item->get_id();
777 if (!$entry_guid) $entry_guid = $item->get_link();
778 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
782 $entry_guid = $item["id"];
784 if (!$entry_guid) $entry_guid = $item["guid"];
785 if (!$entry_guid) $entry_guid = $item["link"];
786 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
789 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
790 _debug("update_rss_feed: guid $entry_guid");
793 if (!$entry_guid) continue;
795 $entry_timestamp = "";
797 if ($use_simplepie) {
798 $entry_timestamp = strtotime($item->get_date());
800 $rss_2_date = $item['pubdate'];
801 $rss_1_date = $item['dc']['date'];
802 $atom_date = $item['issued'];
803 if (!$atom_date) $atom_date = $item['updated'];
805 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
806 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
807 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
810 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
811 _debug("update_rss_feed: date $entry_timestamp");
814 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
815 $entry_timestamp = time();
816 $no_orig_date = 'true';
818 $no_orig_date = 'false';
821 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
823 if ($use_simplepie) {
824 $entry_title = $item->get_title();
826 $entry_title = trim(strip_tags($item["title"]));
829 if ($use_simplepie) {
830 $entry_link = $item->get_link();
832 // strange Magpie workaround
833 $entry_link = $item["link_"];
834 if (!$entry_link) $entry_link = $item["link"];
837 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
838 _debug("update_rss_feed: title $entry_title");
841 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
843 $entry_link = strip_tags($entry_link);
845 if ($use_simplepie) {
846 $entry_content = $item->get_content();
847 if (!$entry_content) $entry_content = $item->get_description();
849 $entry_content = $item["content:escaped"];
851 if (!$entry_content) $entry_content = $item["content:encoded"];
852 if (!$entry_content) $entry_content = $item["content"]["encoded"];
853 if (!$entry_content) $entry_content = $item["content"];
855 // Magpie bugs are getting ridiculous
856 if (trim($entry_content) == "Array") $entry_content = false;
858 if (!$entry_content) $entry_content = $item["atom_content"];
859 if (!$entry_content) $entry_content = $item["summary"];
861 if (!$entry_content ||
862 strlen($entry_content) < strlen($item["description"])) {
863 $entry_content = $item["description"];
867 if (is_array($entry_content)) {
868 $entry_content = $entry_content["encoded"];
869 if (!$entry_content) $entry_content = $entry_content["escaped"];
873 if ($_GET["xdebug"]) {
874 print "update_rss_feed: content: ";
875 print_r(htmlspecialchars($entry_content));
878 $entry_content_unescaped = $entry_content;
880 if ($use_simplepie) {
881 $entry_comments = strip_tags($item->data
["comments"]);
882 if ($item->get_author()) {
883 $entry_author_item = $item->get_author();
884 $entry_author = $entry_author_item->get_name();
885 if (!$entry_author) $entry_author = $entry_author_item->get_email();
887 $entry_author = db_escape_string($entry_author);
890 $entry_comments = strip_tags($item["comments"]);
892 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
894 if ($item['author']) {
896 if (is_array($item['author'])) {
898 if (!$entry_author) {
899 $entry_author = db_escape_string(strip_tags($item['author']['name']));
902 if (!$entry_author) {
903 $entry_author = db_escape_string(strip_tags($item['author']['email']));
907 if (!$entry_author) {
908 $entry_author = db_escape_string(strip_tags($item['author']));
913 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
915 $entry_guid = db_escape_string(strip_tags($entry_guid));
916 $entry_guid = mb_substr($entry_guid, 0, 250);
918 $result = db_query($link, "SELECT id FROM ttrss_entries
919 WHERE guid = '$entry_guid'");
921 $entry_content = db_escape_string($entry_content);
923 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
925 $entry_title = db_escape_string($entry_title);
926 $entry_link = db_escape_string($entry_link);
927 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
928 $entry_author = mb_substr($entry_author, 0, 250);
930 if ($use_simplepie) {
931 $num_comments = 0; #FIXME#
933 $num_comments = db_escape_string($item["slash"]["comments"]);
936 if (!$num_comments) $num_comments = 0;
938 // parse <category> entries into tags
940 if ($use_simplepie) {
942 $additional_tags = array();
943 $additional_tags_src = $item->get_categories();
945 if (is_array($additional_tags_src)) {
946 foreach ($additional_tags_src as $tobj) {
947 array_push($additional_tags, $tobj->get_term());
951 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
952 _debug("update_rss_feed: category tags:");
953 print_r($additional_tags);
958 $t_ctr = $item['category#'];
960 $additional_tags = false;
963 $additional_tags = false;
964 } else if ($t_ctr > 0) {
965 $additional_tags = array($item['category']);
967 if ($item['category@term']) {
968 array_push($additional_tags, $item['category@term']);
971 for ($i = 0; $i <= $t_ctr; $i++
) {
972 if ($item["category#$i"]) {
973 array_push($additional_tags, $item["category#$i"]);
976 if ($item["category#$i@term"]) {
977 array_push($additional_tags, $item["category#$i@term"]);
982 // parse <dc:subject> elements
984 $t_ctr = $item['dc']['subject#'];
987 $additional_tags = array($item['dc']['subject']);
989 for ($i = 0; $i <= $t_ctr; $i++
) {
990 if ($item['dc']["subject#$i"]) {
991 array_push($additional_tags, $item['dc']["subject#$i"]);
999 $enclosures = array();
1001 if ($use_simplepie) {
1002 $encs = $item->get_enclosures();
1004 if (is_array($encs)) {
1005 foreach ($encs as $e) {
1007 $e->link
, $e->type
, $e->length
);
1009 array_push($enclosures, $e_item);
1016 $e_ctr = $item['enclosure#'];
1019 $e_item = array($item['enclosure@url'],
1020 $item['enclosure@type'],
1021 $item['enclosure@length']);
1023 array_push($enclosures, $e_item);
1025 for ($i = 0; $i <= $e_ctr; $i++
) {
1027 if ($item["enclosure#$i@url"]) {
1028 $e_item = array($item["enclosure#$i@url"],
1029 $item["enclosure#$i@type"],
1030 $item["enclosure#$i@length"]);
1031 array_push($enclosures, $e_item);
1037 // can there be many of those? yes -fox
1039 $m_ctr = $item['media']['content#'];
1042 $e_item = array($item['media']['content@url'],
1043 $item['media']['content@medium'],
1044 $item['media']['content@length']);
1046 array_push($enclosures, $e_item);
1048 for ($i = 0; $i <= $m_ctr; $i++
) {
1050 if ($item["media"]["content#$i@url"]) {
1051 $e_item = array($item["media"]["content#$i@url"],
1052 $item["media"]["content#$i@medium"],
1053 $item["media"]["content#$i@length"]);
1054 array_push($enclosures, $e_item);
1063 $entry_content = sanitize_article_content($entry_content);
1064 $entry_title = sanitize_article_content($entry_title);
1066 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1067 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1070 db_query($link, "BEGIN");
1072 if (db_num_rows($result) == 0) {
1074 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1075 _debug("update_rss_feed: base guid not found");
1078 // base post entry does not exist, create it
1080 $result = db_query($link,
1081 "INSERT INTO ttrss_entries
1097 '$entry_timestamp_fmt',
1106 // we keep encountering the entry in feeds, so we need to
1107 // update date_entered column so that we don't get horrible
1108 // dupes when the entry gets purged and reinserted again e.g.
1109 // in the case of SLOW SLOW OMG SLOW updating feeds
1111 $base_entry_id = db_fetch_result($result, 0, "id");
1113 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1114 WHERE id = '$base_entry_id'");
1117 // now it should exist, if not - bad luck then
1119 $result = db_query($link, "SELECT
1120 id,content_hash,no_orig_date,title,
1121 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1122 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1126 WHERE guid = '$entry_guid'");
1131 if (db_num_rows($result) == 1) {
1133 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1134 _debug("update_rss_feed: base guid found, checking for user record");
1137 // this will be used below in update handler
1138 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1139 $orig_title = db_fetch_result($result, 0, "title");
1140 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1141 $orig_date_entered = strtotime(db_fetch_result($result,
1142 0, "date_entered"));
1144 $ref_id = db_fetch_result($result, 0, "id");
1145 $entry_ref_id = $ref_id;
1147 // check for user post link to main table
1149 // do we allow duplicate posts with same GUID in different feeds?
1150 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1151 $dupcheck_qpart = "AND feed_id = '$feed'";
1153 $dupcheck_qpart = "";
1156 // error_reporting(0);
1158 $article_filters = get_article_filters($filters, $entry_title,
1159 $entry_content, $entry_link);
1161 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1162 _debug("update_rss_feed: article filters: ");
1163 if (count($article_filters) != 0) {
1164 print_r($article_filters);
1168 if (find_article_filter($article_filters, "filter")) {
1169 db_query($link, "COMMIT"); // close transaction in progress
1173 // error_reporting (DEFAULT_ERROR_LEVEL);
1175 $score = calculate_article_score($article_filters);
1177 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1178 _debug("update_rss_feed: initial score: $score");
1181 $result = db_query($link,
1182 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1183 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1186 // okay it doesn't exist - create user entry
1187 if (db_num_rows($result) == 0) {
1189 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1190 _debug("update_rss_feed: user record not found, creating...");
1193 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1195 $last_read_qpart = 'NULL';
1198 $last_read_qpart = 'NOW()';
1201 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1207 if (find_article_filter($article_filters, 'publish')) {
1208 $published = 'true';
1210 $published = 'false';
1213 $result = db_query($link,
1214 "INSERT INTO ttrss_user_entries
1215 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1217 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1218 $last_read_qpart, $marked, $published, '$score')");
1220 $result = db_query($link,
1221 "SELECT int_id FROM ttrss_user_entries WHERE
1222 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1223 feed_id = '$feed' LIMIT 1");
1225 if (db_num_rows($result) == 1) {
1226 $entry_int_id = db_fetch_result($result, 0, "int_id");
1229 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1230 $entry_int_id = db_fetch_result($result, 0, "int_id");
1233 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1234 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1237 $post_needs_update = false;
1239 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1240 ($content_hash != $orig_content_hash)) {
1241 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1242 $post_needs_update = true;
1245 if (db_escape_string($orig_title) != $entry_title) {
1246 $post_needs_update = true;
1249 if ($orig_num_comments != $num_comments) {
1250 $post_needs_update = true;
1253 // this doesn't seem to be very reliable
1255 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1256 // $post_needs_update = true;
1259 // if post needs update, update it and mark all user entries
1260 // linking to this post as updated
1261 if ($post_needs_update) {
1263 if (defined('DAEMON_EXTENDED_DEBUG')) {
1264 _debug("update_rss_feed: post $entry_guid needs update...");
1267 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1269 db_query($link, "UPDATE ttrss_entries
1270 SET title = '$entry_title', content = '$entry_content',
1271 content_hash = '$content_hash',
1272 num_comments = '$num_comments'
1273 WHERE id = '$ref_id'");
1275 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1276 db_query($link, "UPDATE ttrss_user_entries
1277 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1279 db_query($link, "UPDATE ttrss_user_entries
1280 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1286 db_query($link, "COMMIT");
1288 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1289 _debug("update_rss_feed: looking for enclosures...");
1292 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1293 print_r($enclosures);
1296 db_query($link, "BEGIN");
1298 foreach ($enclosures as $enc) {
1299 $enc_url = db_escape_string($enc[0]);
1300 $enc_type = db_escape_string($enc[1]);
1301 $enc_dur = db_escape_string($enc[2]);
1303 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1304 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1306 if (db_num_rows($result) == 0) {
1307 db_query($link, "INSERT INTO ttrss_enclosures
1308 (content_url, content_type, title, duration, post_id) VALUES
1309 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1313 db_query($link, "COMMIT");
1315 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1316 _debug("update_rss_feed: looking for tags...");
1320 // <a href="..." rel="tag">Xorg</a>, //
1324 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1325 $entry_content_unescaped, $entry_tags);
1327 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1328 print_r($entry_tags);
1329 print "<br/></p>"; */
1331 $entry_tags = $entry_tags[1];
1333 # check for manual tags
1335 $tag_filter = find_article_filter($article_filters, "tag");
1339 $manual_tags = trim_array(split(",", $tag_filter[1]));
1341 foreach ($manual_tags as $tag) {
1342 if (tag_is_valid($tag)) {
1343 array_push($entry_tags, $tag);
1348 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1349 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1351 if ($additional_tags && is_array($additional_tags)) {
1352 foreach ($additional_tags as $tag) {
1353 if (tag_is_valid($tag) &&
1354 array_search($tag, $boring_tags) === FALSE) {
1355 array_push($entry_tags, $tag);
1360 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1362 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1363 print_r($entry_tags);
1366 if (count($entry_tags) > 0) {
1368 db_query($link, "BEGIN");
1370 foreach ($entry_tags as $tag) {
1372 $tag = sanitize_tag($tag);
1373 $tag = db_escape_string($tag);
1375 if (!tag_is_valid($tag)) continue;
1377 $result = db_query($link, "SELECT id FROM ttrss_tags
1378 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1379 owner_uid = '$owner_uid' LIMIT 1");
1381 // print db_fetch_result($result, 0, "id");
1383 if ($result && db_num_rows($result) == 0) {
1385 db_query($link, "INSERT INTO ttrss_tags
1386 (owner_uid,tag_name,post_int_id)
1387 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1391 db_query($link, "COMMIT");
1394 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1395 _debug("update_rss_feed: article processed");
1399 db_query($link, "UPDATE ttrss_feeds
1400 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1402 // db_query($link, "COMMIT");
1406 if ($use_simplepie) {
1407 $error_msg = mb_substr($rss->error(), 0, 250);
1409 $error_msg = mb_substr(magpie_error(), 0, 250);
1412 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1413 _debug("update_rss_feed: error fetching feed: $error_msg");
1416 $error_msg = db_escape_string($error_msg);
1419 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1420 last_updated = NOW() WHERE id = '$feed'");
1423 if ($use_simplepie) {
1427 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1428 _debug("update_rss_feed: done");
1433 function print_select($id, $default, $values, $attributes = "") {
1434 print "<select name=\"$id\" id=\"$id\" $attributes>";
1435 foreach ($values as $v) {
1441 print "<option$sel>$v</option>";
1446 function print_select_hash($id, $default, $values, $attributes = "") {
1447 print "<select name=\"$id\" id='$id' $attributes>";
1448 foreach (array_keys($values) as $v) {
1450 $sel = 'selected="selected"';
1454 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1460 function get_article_filters($filters, $title, $content, $link) {
1463 if ($filters["title"]) {
1464 foreach ($filters["title"] as $filter) {
1465 $reg_exp = $filter["reg_exp"];
1466 $inverse = $filter["inverse"];
1467 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1468 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1470 array_push($matches, array($filter["action"], $filter["action_param"]));
1475 if ($filters["content"]) {
1476 foreach ($filters["content"] as $filter) {
1477 $reg_exp = $filter["reg_exp"];
1478 $inverse = $filter["inverse"];
1480 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1481 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1483 array_push($matches, array($filter["action"], $filter["action_param"]));
1488 if ($filters["both"]) {
1489 foreach ($filters["both"] as $filter) {
1490 $reg_exp = $filter["reg_exp"];
1491 $inverse = $filter["inverse"];
1494 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1495 array_push($matches, array($filter["action"], $filter["action_param"]));
1498 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1499 array_push($matches, array($filter["action"], $filter["action_param"]));
1505 if ($filters["link"]) {
1506 $reg_exp = $filter["reg_exp"];
1507 foreach ($filters["link"] as $filter) {
1508 $reg_exp = $filter["reg_exp"];
1509 $inverse = $filter["inverse"];
1511 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1512 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1514 array_push($matches, array($filter["action"], $filter["action_param"]));
1522 function find_article_filter($filters, $filter_name) {
1523 foreach ($filters as $f) {
1524 if ($f[0] == $filter_name) {
1531 function calculate_article_score($filters) {
1534 foreach ($filters as $f) {
1535 if ($f[0] == "score") {
1543 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1544 $rtl_content = false, $last_updated = false, $last_error = false) {
1546 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1547 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1549 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1553 $rtl_tag = "dir=\"rtl\"";
1555 $rtl_tag = "dir=\"ltr\"";
1558 $error_notify_msg = "";
1561 $link_title = "Error: $last_error ($last_updated)";
1562 $error_notify_msg = "(Error)";
1563 } else if ($last_updated) {
1564 $link_title = "Updated: $last_updated";
1567 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1568 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1570 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1571 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1575 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1578 $fctr_class = "class=\"feedCtrHasUnread\"";
1580 $fctr_class = "class=\"feedCtrNoUnread\"";
1583 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1584 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1586 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1587 $total = getFeedArticles($link, $feed_id);
1588 print "<div class=\"feedExtInfo\">
1589 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1596 function getmicrotime() {
1597 list($usec, $sec) = explode(" ",microtime());
1598 return ((float)$usec +
(float)$sec);
1601 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1602 foreach ($values as $v) {
1609 if ($v == $true_is) {
1610 $sel .= " value=\"1\"";
1612 $sel .= " value=\"0\"";
1615 print "<input class=\"noborder\"
1616 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1621 function initialize_user_prefs($link, $uid) {
1623 $uid = db_escape_string($uid);
1625 db_query($link, "BEGIN");
1627 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1629 $u_result = db_query($link, "SELECT pref_name
1630 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1632 $active_prefs = array();
1634 while ($line = db_fetch_assoc($u_result)) {
1635 array_push($active_prefs, $line["pref_name"]);
1638 while ($line = db_fetch_assoc($result)) {
1639 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1640 // print "adding " . $line["pref_name"] . "<br>";
1642 db_query($link, "INSERT INTO ttrss_user_prefs
1643 (owner_uid,pref_name,value) VALUES
1644 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1649 db_query($link, "COMMIT");
1653 function lookup_user_id($link, $user) {
1655 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1658 if (db_num_rows($result) == 1) {
1659 return db_fetch_result($result, 0, "id");
1665 function http_authenticate_user($link) {
1667 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1669 if (!$_SERVER["PHP_AUTH_USER"]) {
1671 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1672 header('HTTP/1.0 401 Unauthorized');
1676 $auth_result = authenticate_user($link,
1677 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1679 if (!$auth_result) {
1680 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1681 header('HTTP/1.0 401 Unauthorized');
1689 function authenticate_user($link, $login, $password, $force_auth = false) {
1691 if (!SINGLE_USER_MODE
) {
1693 $pwd_hash1 = encrypt_password($password);
1694 $pwd_hash2 = encrypt_password($password, $login);
1696 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1697 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1699 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1701 $query = "SELECT id,login,access_level,pwd_hash
1702 FROM ttrss_users WHERE
1706 $query = "SELECT id,login,access_level,pwd_hash
1707 FROM ttrss_users WHERE
1708 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1709 pwd_hash = '$pwd_hash2')";
1712 $result = db_query($link, $query);
1714 if (db_num_rows($result) == 1) {
1715 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1716 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1717 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1719 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1722 $user_theme = get_user_theme_path($link);
1724 $_SESSION["theme"] = $user_theme;
1725 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1726 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1728 initialize_user_prefs($link, $_SESSION["uid"]);
1737 $_SESSION["uid"] = 1;
1738 $_SESSION["name"] = "admin";
1740 $user_theme = get_user_theme_path($link);
1742 $_SESSION["theme"] = $user_theme;
1743 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1745 initialize_user_prefs($link, $_SESSION["uid"]);
1751 function make_password($length = 8) {
1754 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1758 while ($i < $length) {
1759 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1761 if (!strstr($password, $char)) {
1769 // this is called after user is created to initialize default feeds, labels
1772 // user preferences are checked on every login, not here
1774 function initialize_user($link, $uid) {
1776 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1777 values ('$uid','unread = true', 'Unread articles')");
1779 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1780 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1782 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1783 values ('$uid', 'Tiny Tiny RSS: New Releases',
1784 'http://tt-rss.spb.ru/releases.rss')");
1786 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1787 values ('$uid', 'Tiny Tiny RSS: Forum',
1788 'http://tt-rss.spb.ru/forum/rss.php')");
1791 function logout_user() {
1793 if (isset($_COOKIE[session_name()])) {
1794 setcookie(session_name(), '', time()-42000, '/');
1798 function get_script_urlpath() {
1799 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1802 function validate_session($link) {
1803 if (SINGLE_USER_MODE
) {
1807 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1808 if ($_SESSION["ip_address"]) {
1809 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1810 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1816 if ($_SESSION["uid"]) {
1818 $result = db_query($link,
1819 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1821 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1823 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1828 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1830 //print_r($_SESSION);
1832 if (time() > $_SESSION["cookie_lifetime"]) {
1840 function login_sequence($link, $mobile = false) {
1841 if (!SINGLE_USER_MODE
) {
1843 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1844 $swu = db_escape_string($_REQUEST["swu"]);
1846 $_SESSION["prefs_cache"] = false;
1847 return authenticate_user($link, $swu, null, true);
1851 $login_action = $_POST["login_action"];
1853 # try to authenticate user if called from login form
1854 if ($login_action == "do_login") {
1855 $login = $_POST["login"];
1856 $password = $_POST["password"];
1857 $remember_me = $_POST["remember_me"];
1859 if (authenticate_user($link, $login, $password)) {
1860 $_POST["password"] = "";
1862 $_SESSION["language"] = $_POST["language"];
1863 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1865 header("Location: " . $_SERVER["REQUEST_URI"]);
1870 $_SESSION["login_error_msg"] = "Incorrect username or password";
1874 // print session_id();
1875 // print_r($_SESSION);
1877 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1878 render_login_form($link, $mobile);
1881 /* bump login timestamp */
1882 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1885 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1886 setcookie("ttrss_lang", $_SESSION["language"],
1887 time() + SESSION_COOKIE_LIFETIME
);
1890 /* bump counters stamp since we're getting reloaded anyway */
1892 $_SESSION["get_all_counters_stamp"] = time();
1896 return authenticate_user($link, "admin", null);
1900 function truncate_string($str, $max_len) {
1901 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1902 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1908 function get_user_theme_path($link) {
1909 $result = db_query($link, "SELECT theme_path
1911 ttrss_themes,ttrss_users
1912 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1913 if (db_num_rows($result) != 0) {
1914 return db_fetch_result($result, 0, "theme_path");
1920 function smart_date_time($timestamp) {
1921 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1922 return date("G:i", $timestamp);
1923 } else if (date("Y", $timestamp) == date("Y")) {
1924 return date("M d, G:i", $timestamp);
1926 return date("Y/m/d, G:i", $timestamp);
1930 function smart_date($timestamp) {
1931 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1933 } else if (date("Y", $timestamp) == date("Y")) {
1934 return date("D m", $timestamp);
1936 return date("Y/m/d", $timestamp);
1940 function sql_bool_to_string($s) {
1941 if ($s == "t" ||
$s == "1") {
1948 function sql_bool_to_bool($s) {
1949 if ($s == "t" ||
$s == "1") {
1957 function toggleEvenOdd($a) {
1964 function sanity_check($link) {
1969 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1970 $schema_version = db_fetch_result($result, 0, "schema_version");
1972 if ($schema_version != SCHEMA_VERSION
) {
1976 if (DB_TYPE
== "mysql") {
1977 $result = db_query($link, "SELECT true", false);
1978 if (db_num_rows($result) != 1) {
1983 if (db_escape_string("testTEST") != "testTEST") {
1987 error_reporting (DEFAULT_ERROR_LEVEL
);
1989 if ($error_code != 0) {
1990 print_error_xml($error_code);
1997 function file_is_locked($filename) {
1998 if (function_exists('flock')) {
2000 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2001 error_reporting(DEFAULT_ERROR_LEVEL
);
2003 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2004 flock($fp, LOCK_UN
);
2014 return true; // consider the file always locked and skip the test
2017 function make_lockfile($filename) {
2018 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2020 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2027 function make_stampfile($filename) {
2028 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2030 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2031 fwrite($fp, time() . "\n");
2032 flock($fp, LOCK_UN
);
2040 function read_stampfile($filename) {
2043 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2044 error_reporting (DEFAULT_ERROR_LEVEL
);
2047 if (flock($fp, LOCK_EX
)) {
2048 $stamp = fgets($fp);
2049 flock($fp, LOCK_UN
);
2060 function sql_random_function() {
2061 if (DB_TYPE
== "mysql") {
2068 function catchup_feed($link, $feed, $cat_view) {
2070 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2075 $cat_qpart = "cat_id = '$feed'";
2077 $cat_qpart = "cat_id IS NULL";
2080 $tmp_result = db_query($link, "SELECT id
2081 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2084 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2086 $tmp_feed = $tmp_line["id"];
2088 db_query($link, "UPDATE ttrss_user_entries
2089 SET unread = false,last_read = NOW()
2090 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2093 } else if ($feed > 0) {
2095 $tmp_result = db_query($link, "SELECT id
2096 FROM ttrss_feeds WHERE parent_feed = '$feed'
2097 ORDER BY cat_id,title");
2099 $parent_ids = array();
2101 if (db_num_rows($tmp_result) > 0) {
2102 while ($p = db_fetch_assoc($tmp_result)) {
2103 array_push($parent_ids, "feed_id = " . $p["id"]);
2106 $children_qpart = implode(" OR ", $parent_ids);
2108 db_query($link, "UPDATE ttrss_user_entries
2109 SET unread = false,last_read = NOW()
2110 WHERE (feed_id = '$feed' OR $children_qpart)
2111 AND owner_uid = " . $_SESSION["uid"]);
2114 db_query($link, "UPDATE ttrss_user_entries
2115 SET unread = false,last_read = NOW()
2116 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2119 } else if ($feed < 0 && $feed > -10) { // special, like starred
2122 db_query($link, "UPDATE ttrss_user_entries
2123 SET unread = false,last_read = NOW()
2124 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2128 db_query($link, "UPDATE ttrss_user_entries
2129 SET unread = false,last_read = NOW()
2130 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2135 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2137 if (DB_TYPE
== "pgsql") {
2138 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2140 $match_part = "updated > DATE_SUB(NOW(),
2141 INTERVAL $intl HOUR) ";
2144 $result = db_query($link, "SELECT id FROM ttrss_entries,
2145 ttrss_user_entries WHERE $match_part AND
2147 ttrss_user_entries.ref_id = ttrss_entries.id AND
2148 owner_uid = ".$_SESSION["uid"]);
2150 $affected_ids = array();
2152 while ($line = db_fetch_assoc($result)) {
2153 array_push($affected_ids, $line["id"]);
2156 catchupArticlesById($link, $affected_ids, 0);
2159 } else if ($feed < -10) { // label
2161 // TODO make this more efficient
2163 $label_id = -$feed - 11;
2165 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2166 WHERE id = '$label_id'");
2169 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2171 db_query($link, "BEGIN");
2173 $tmp2_result = db_query($link,
2177 ttrss_user_entries,ttrss_entries,ttrss_feeds
2179 ref_id = ttrss_entries.id AND
2180 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2182 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2184 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2185 db_query($link, "UPDATE
2188 unread = false, last_read = NOW()
2190 int_id = " . $tmp_line["int_id"]);
2193 db_query($link, "COMMIT");
2195 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2196 SET unread = false,last_read = NOW()
2199 AND owner_uid = ".$_SESSION["uid"]); */
2203 db_query($link, "BEGIN");
2205 $tag_name = db_escape_string($feed);
2207 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2208 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2210 while ($line = db_fetch_assoc($result)) {
2211 db_query($link, "UPDATE ttrss_user_entries SET
2212 unread = false, last_read = NOW()
2213 WHERE int_id = " . $line["post_int_id"]);
2215 db_query($link, "COMMIT");
2219 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2223 $cat_qpart = "cat_id = '$feed'";
2225 $cat_qpart = "cat_id IS NULL";
2228 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2229 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2231 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2232 $feed_url = $tmp_line["feed_url"];
2233 $feed_id = $tmp_line["id"];
2234 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2238 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2239 WHERE id = '$feed'");
2240 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2241 update_rss_feed($link, $feed_url, $feed, $force_update);
2245 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2247 /* getting all counters is a resource intensive operation, so we
2248 * rate limit it a little bit */
2252 if (get_pref($link, "SYNC_COUNTERS") ||
2253 time() - $_SESSION["get_all_counters_stamp"] > 5) {
2255 if (!$omode) $omode = "flc";
2257 getGlobalCounters($link);
2259 if (strchr($omode, "l")) getLabelCounters($link);
2260 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2261 if (strchr($omode, "t")) getTagCounters($link);
2262 if (strchr($omode, "c")) {
2263 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2264 getCategoryCounters($link);
2268 $_SESSION["get_all_counters_stamp"] = time();
2273 function getCategoryCounters($link) {
2274 # two special categories are -1 and -2 (all virtuals; all labels)
2276 $ctr = getCategoryUnread($link, -1);
2278 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2280 $ctr = getCategoryUnread($link, -2);
2282 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2284 $age_qpart = getMaxAgeSubquery();
2286 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
2287 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2288 AND id = ref_id AND $age_qpart
2289 AND unread = true)) AS unread FROM ttrss_feeds
2291 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2293 while ($line = db_fetch_assoc($result)) {
2294 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2295 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2296 $line["unread"]."\"/>";
2300 function getCategoryUnread($link, $cat) {
2305 $cat_query = "cat_id = '$cat'";
2307 $cat_query = "cat_id IS NULL";
2310 $age_qpart = getMaxAgeSubquery();
2312 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2314 AND owner_uid = " . $_SESSION["uid"]);
2316 $cat_feeds = array();
2317 while ($line = db_fetch_assoc($result)) {
2318 array_push($cat_feeds, "feed_id = " . $line["id"]);
2321 if (count($cat_feeds) == 0) return 0;
2323 $match_part = implode(" OR ", $cat_feeds);
2325 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2326 FROM ttrss_user_entries,ttrss_entries
2327 WHERE unread = true AND ($match_part) AND id = ref_id
2328 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2332 # this needs to be rewritten
2333 while ($line = db_fetch_assoc($result)) {
2334 $unread +
= $line["unread"];
2338 } else if ($cat == -1) {
2339 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2340 } else if ($cat == -2) {
2342 $rv = getLabelCounters($link, false, true);
2345 foreach (array_keys($rv) as $k) {
2347 $ctr +
= $rv[$k]["counter"];
2355 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2356 if (DB_TYPE
== "pgsql") {
2357 return "ttrss_entries.date_entered >
2358 NOW() - INTERVAL '$days days'";
2360 return "ttrss_entries.date_entered >
2361 DATE_SUB(NOW(), INTERVAL $days DAY)";
2365 function getFeedUnread($link, $feed, $is_cat = false) {
2366 return getFeedArticles($link, $feed, $is_cat, true);
2369 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false) {
2370 $n_feed = sprintf("%d", $feed);
2373 $unread_qpart = "unread = true";
2375 $unread_qpart = "true";
2378 $age_qpart = getMaxAgeSubquery();
2381 return getCategoryUnread($link, $n_feed);
2382 } else if ($n_feed == -1) {
2383 $match_part = "marked = true";
2384 } else if ($n_feed == -2) {
2385 $match_part = "published = true";
2386 } else if ($n_feed == -3) {
2387 $match_part = "unread = true";
2389 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2391 if (DB_TYPE
== "pgsql") {
2392 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2394 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2397 } else if ($n_feed > 0) {
2399 $result = db_query($link, "SELECT id FROM ttrss_feeds
2400 WHERE parent_feed = '$n_feed'
2402 AND owner_uid = " . $_SESSION["uid"]);
2404 if (db_num_rows($result) > 0) {
2406 $linked_feeds = array();
2407 while ($line = db_fetch_assoc($result)) {
2408 array_push($linked_feeds, "feed_id = " . $line["id"]);
2411 array_push($linked_feeds, "feed_id = $n_feed");
2413 $match_part = implode(" OR ", $linked_feeds);
2415 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2416 FROM ttrss_user_entries,ttrss_entries
2417 WHERE $unread_qpart AND
2418 ttrss_user_entries.ref_id = ttrss_entries.id AND
2421 owner_uid = " . $_SESSION["uid"]);
2425 # this needs to be rewritten
2426 while ($line = db_fetch_assoc($result)) {
2427 $unread +
= $line["unread"];
2433 $match_part = "feed_id = '$n_feed'";
2435 } else if ($feed < -10) {
2437 $label_id = -$feed - 11;
2439 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2440 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2442 $match_part = db_fetch_result($result, 0, "sql_exp");
2447 $result = db_query($link, "SELECT count(int_id) AS unread
2448 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2449 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2450 ttrss_user_entries.ref_id = ttrss_entries.id AND
2451 ttrss_feeds.hidden = false AND
2453 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2457 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2458 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2459 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2460 AND $unread_qpart AND $age_qpart AND
2461 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2464 $unread = db_fetch_result($result, 0, "unread");
2469 /* FIXME this needs reworking */
2471 function getGlobalUnread($link, $user_id = false) {
2474 $user_id = $_SESSION["uid"];
2477 $age_qpart = getMaxAgeSubquery();
2479 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2480 WHERE unread = true AND
2481 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2482 ttrss_user_entries.ref_id = ttrss_entries.id AND
2485 ttrss_user_entries.owner_uid = '$user_id'");
2486 $c_id = db_fetch_result($result, 0, "c_id");
2490 function getGlobalCounters($link, $global_unread = -1) {
2491 if ($global_unread == -1) {
2492 $global_unread = getGlobalUnread($link);
2494 print "<counter type=\"global\" id='global-unread'
2495 counter='$global_unread'/>";
2497 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2498 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2500 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2502 print "<counter type=\"global\" id='subscribed-feeds'
2503 counter='$subscribed_feeds'/>";
2507 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2510 if (!$_SESSION["tctr_last_value"]) {
2511 $_SESSION["tctr_last_value"] = array();
2515 $old_counters = $_SESSION["tctr_last_value"];
2517 $tctrs_modified = false;
2519 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2520 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2521 ttrss_user_entries.ref_id = ttrss_entries.id AND
2522 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2523 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2525 select tag_name,0 as count FROM ttrss_tags
2526 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2528 $age_qpart = getMaxAgeSubquery();
2530 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2531 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2532 AND ref_id = id AND $age_qpart
2533 AND unread = true)) AS count FROM ttrss_tags
2534 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2535 ORDER BY count DESC LIMIT 55");
2539 while ($line = db_fetch_assoc($result)) {
2540 $tags[$line["tag_name"]] +
= $line["count"];
2543 foreach (array_keys($tags) as $tag) {
2544 $unread = $tags[$tag];
2546 $tag = htmlspecialchars($tag);
2548 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2549 $old_counters[$tag] = $unread;
2550 $tctrs_modified = true;
2551 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2556 if ($smart_mode && $tctrs_modified) {
2557 $_SESSION["tctr_last_value"] = $old_counters;
2562 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2564 $age_qpart = getMaxAgeSubquery();
2567 if (!$_SESSION["lctr_last_value"]) {
2568 $_SESSION["lctr_last_value"] = array();
2574 $old_counters = $_SESSION["lctr_last_value"];
2575 $lctrs_modified = false;
2577 $count = getFeedUnread($link, -1);
2581 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2582 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2587 print "<counter type=\"label\" id=\"-1\" counter=\"$count\" $xmsg_part/>";
2589 $ret_arr["-1"]["counter"] = $count;
2590 $ret_arr["-1"]["description"] = __("Starred articles");
2593 $count = getFeedUnread($link, -2);
2597 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2598 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2603 print "<counter type=\"label\" id=\"-2\" counter=\"$count\" $xmsg_part/>";
2605 $ret_arr["-2"]["counter"] = $count;
2606 $ret_arr["-2"]["description"] = __("Published articles");
2609 $count = getFeedUnread($link, -3);
2613 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2614 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2619 print "<counter type=\"label\" id=\"-3\" counter=\"$count\" $xmsg_part/>";
2621 $ret_arr["-3"]["counter"] = $count;
2622 $ret_arr["-3"]["description"] = __("Fresh articles");
2626 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2627 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2629 while ($line = db_fetch_assoc($result)) {
2631 $id = -$line["id"] - 11;
2633 $label_name = $line["description"];
2635 error_reporting (0);
2637 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2638 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2639 ttrss_feeds.hidden = false AND
2641 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2642 ttrss_user_entries.ref_id = ttrss_entries.id AND
2643 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2645 $count = db_fetch_result($tmp_result, 0, "count");
2647 if (!$smart_mode ||
$old_counters[$id] != $count) {
2648 $old_counters[$id] = $count;
2649 $lctrs_modified = true;
2652 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2653 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2658 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2660 $ret_arr[$id]["counter"] = $count;
2661 $ret_arr[$id]["description"] = $label_name;
2665 error_reporting (DEFAULT_ERROR_LEVEL
);
2668 if ($smart_mode && $lctrs_modified) {
2669 $_SESSION["lctr_last_value"] = $old_counters;
2675 /* function getFeedCounter($link, $id) {
2677 $result = db_query($link, "SELECT
2678 count(id) as count,last_error
2679 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2680 WHERE feed_id = '$id' AND unread = true
2681 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2682 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2684 $count = db_fetch_result($result, 0, "count");
2685 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2687 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2690 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2692 $age_qpart = getMaxAgeSubquery();
2695 if (!$_SESSION["fctr_last_value"]) {
2696 $_SESSION["fctr_last_value"] = array();
2700 $old_counters = $_SESSION["fctr_last_value"];
2702 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2703 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated,
2705 FROM ttrss_entries,ttrss_user_entries
2706 WHERE feed_id = ttrss_feeds.id AND
2707 ttrss_user_entries.ref_id = ttrss_entries.id
2708 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2709 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2710 AND parent_feed IS NULL"); */
2712 $query = "SELECT ttrss_feeds.id,
2714 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2716 COUNT(ttrss_entries.id) AS count
2718 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2719 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2720 AND ttrss_user_entries.unread = true)
2721 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2723 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2724 AND parent_feed IS NULL
2725 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2727 $result = db_query($link, $query);
2728 $fctrs_modified = false;
2730 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2732 while ($line = db_fetch_assoc($result)) {
2735 $count = $line["count"];
2736 $last_error = htmlspecialchars($line["last_error"]);
2738 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2739 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2741 $last_updated = date($short_date, strtotime($line["last_updated"]));
2744 $last_updated = htmlspecialchars($last_updated);
2746 $has_img = feed_has_icon($id);
2748 $tmp_result = db_query($link,
2749 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2750 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2751 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2752 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2753 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2755 if (db_num_rows($tmp_result) > 0) {
2756 while ($l = db_fetch_assoc($tmp_result)) {
2757 $count +
= $l["unread"];
2761 if (!$smart_mode ||
$old_counters[$id] != $count) {
2762 $old_counters[$id] = $count;
2763 $fctrs_modified = true;
2766 $error_part = "error=\"$last_error\"";
2772 $has_img_part = "hi=\"$has_img\"";
2777 if ($active_feed && $id == $active_feed) {
2778 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2780 $has_title_part = "";
2783 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2784 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2787 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2791 if ($smart_mode && $fctrs_modified) {
2792 $_SESSION["fctr_last_value"] = $old_counters;
2796 function get_script_dt_add() {
2797 if (strpos(VERSION
, ".99") === false) {
2804 function get_pgsql_version($link) {
2805 $result = db_query($link, "SELECT version() AS version");
2806 $version = split(" ", db_fetch_result($result, 0, "version"));
2810 function print_error_xml($code, $add_msg = "") {
2813 $error_msg = $ERRORS[$code];
2816 $error_msg = "$error_msg; $add_msg";
2819 print "<rpc-reply>";
2820 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2821 print "</rpc-reply>";
2824 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2825 $auth_login = '', $auth_pass = '') {
2827 # check for feed:http://url
2828 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2830 # check for feed://URL
2831 if (strpos($feed_link, "//") === 0) {
2832 $feed_link = "http:$feed_link";
2835 if ($feed_link == "") return;
2837 if ($cat_id == "0" ||
!$cat_id) {
2838 $cat_qpart = "NULL";
2840 $cat_qpart = "'$cat_id'";
2843 $result = db_query($link,
2844 "SELECT id FROM ttrss_feeds
2845 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2847 if (db_num_rows($result) == 0) {
2849 $result = db_query($link,
2850 "INSERT INTO ttrss_feeds
2851 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2852 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2853 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2855 $result = db_query($link,
2856 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2857 AND owner_uid = " . $_SESSION["uid"]);
2859 $feed_id = db_fetch_result($result, 0, "id");
2862 update_rss_feed($link, $feed_link, $feed_id, true);
2871 function print_feed_select($link, $id, $default_id = "",
2872 $attributes = "", $include_all_feeds = true) {
2874 print "<select id=\"$id\" name=\"$id\" $attributes>";
2875 if ($include_all_feeds) {
2876 print "<option value=\"0\">".__('All feeds')."</option>";
2879 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2880 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2882 if (db_num_rows($result) > 0 && $include_all_feeds) {
2883 print "<option disabled>--------</option>";
2886 while ($line = db_fetch_assoc($result)) {
2887 if ($line["id"] == $default_id) {
2888 $is_selected = "selected";
2892 printf("<option $is_selected value='%d'>%s</option>",
2893 $line["id"], htmlspecialchars($line["title"]));
2899 function print_feed_cat_select($link, $id, $default_id = "",
2900 $attributes = "", $include_all_cats = true) {
2902 print "<select id=\"$id\" name=\"$id\" $attributes>";
2904 if ($include_all_cats) {
2905 print "<option value=\"0\">".__('Uncategorized')."</option>";
2908 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2909 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2911 if (db_num_rows($result) > 0 && $include_all_cats) {
2912 print "<option disabled>--------</option>";
2915 while ($line = db_fetch_assoc($result)) {
2916 if ($line["id"] == $default_id) {
2917 $is_selected = "selected";
2921 printf("<option $is_selected value='%d'>%s</option>",
2922 $line["id"], htmlspecialchars($line["title"]));
2928 function checkbox_to_sql_bool($val) {
2929 return ($val == "on") ?
"true" : "false";
2932 function getFeedCatTitle($link, $id) {
2934 return __("Special");
2935 } else if ($id < -10) {
2936 return __("Labels");
2937 } else if ($id > 0) {
2938 $result = db_query($link, "SELECT ttrss_feed_categories.title
2939 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2940 cat_id = ttrss_feed_categories.id");
2941 if (db_num_rows($result) == 1) {
2942 return db_fetch_result($result, 0, "title");
2944 return __("Uncategorized");
2947 return "getFeedCatTitle($id) failed";
2952 function getFeedTitle($link, $id) {
2954 return __("Starred articles");
2955 } else if ($id == -2) {
2956 return __("Published articles");
2957 } else if ($id == -3) {
2958 return __("Fresh articles");
2959 } else if ($id < -10) {
2960 $label_id = -$id - 11;
2961 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2962 if (db_num_rows($result) == 1) {
2963 return db_fetch_result($result, 0, "description");
2965 return "Unknown label ($label_id)";
2968 } else if ($id > 0) {
2969 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2970 if (db_num_rows($result) == 1) {
2971 return db_fetch_result($result, 0, "title");
2973 return "Unknown feed ($id)";
2976 return "getFeedTitle($id) failed";
2981 function get_session_cookie_name() {
2982 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2985 function print_init_params($link) {
2986 print "<init-params>";
2987 if ($_SESSION["stored-params"]) {
2988 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2990 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2991 print "<param key=\"$key\" value=\"$value\"/>";
2996 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2997 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2998 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2999 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3001 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
3002 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
3004 print "<param key=\"hide_read_feeds\" value=\"" .
3005 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
3007 print "<param key=\"feeds_sort_by_unread\" value=\"" .
3008 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
3010 print "<param key=\"confirm_feed_catchup\" value=\"" .
3011 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3013 print "<param key=\"cdm_auto_catchup\" value=\"" .
3014 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3016 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3018 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3020 print "<param key=\"default_view_mode\" value=\"" .
3021 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3023 print "<param key=\"default_view_limit\" value=\"" .
3024 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3026 print "<param key=\"default_view_order_by\" value=\"" .
3027 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3029 print "<param key=\"prefs_active_tab\" value=\"" .
3030 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3032 print "<param key=\"infobox_disable_overlay\" value=\"" .
3033 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3035 print "<param key=\"icons_location\" value=\"" .
3038 print "<param key=\"hide_read_shows_special\" value=\"" .
3039 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3041 print "<param key=\"hide_feedlist\" value=\"" .
3042 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3044 print "<param key=\"bw_limit\" value=\"".
3045 (int) $_SESSION["bw_limit"]."\"/>";
3047 print "<param key=\"sync_counters\" value=\"" .
3048 (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3050 print "</init-params>";
3053 function print_runtime_info($link) {
3054 print "<runtime-info>";
3056 if (ENABLE_UPDATE_DAEMON
) {
3057 print "<param key=\"daemon_is_running\" value=\"".
3058 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3060 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3062 $stamp = (int)read_stampfile("update_daemon.stamp");
3064 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3067 $stamp_delta = time() - $stamp;
3069 if ($stamp_delta > 1800) {
3073 $_SESSION["daemon_stamp_check"] = time();
3076 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3078 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3080 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3085 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3087 if ($_SESSION["last_version_check"] +
86400 < time()) {
3088 $new_version_details = check_for_update($link);
3090 print "<param key=\"new_version_available\" value=\"".
3091 sprintf("%d", $new_version_details != ""). "\"/>";
3093 $_SESSION["last_version_check"] = time();
3097 // print "<param key=\"new_version_available\" value=\"1\"/>";
3099 print "</runtime-info>";
3102 function getSearchSql($search, $match_on) {
3104 $search_query_part = "";
3106 $keywords = split(" ", $search);
3107 $query_keywords = array();
3109 if ($match_on == "both") {
3111 foreach ($keywords as $k) {
3112 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3113 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3116 $search_query_part = implode("AND", $query_keywords) . " AND ";
3118 } else if ($match_on == "title") {
3120 foreach ($keywords as $k) {
3121 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3124 $search_query_part = implode("AND", $query_keywords) . " AND ";
3126 } else if ($match_on == "content") {
3128 foreach ($keywords as $k) {
3129 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3133 $search_query_part = implode("AND", $query_keywords);
3135 return $search_query_part;
3138 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3140 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3144 $search_query_part = getSearchSql($search, $match_on);
3145 $search_query_part .= " AND ";
3148 $search_query_part = "";
3151 $view_query_part = "";
3153 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3155 $view_query_part = " ";
3156 } else if ($feed != -1) {
3157 $unread = getFeedUnread($link, $feed, $cat_view);
3159 $view_query_part = " unread = true AND ";
3164 if ($view_mode == "marked") {
3165 $view_query_part = " marked = true AND ";
3168 if ($view_mode == "unread") {
3169 $view_query_part = " unread = true AND ";
3173 $limit_query_part = "LIMIT " . $limit;
3176 $vfeed_query_part = "";
3178 // override query strategy and enable feed display when searching globally
3179 if ($search && $search_mode == "all_feeds") {
3180 $query_strategy_part = "ttrss_entries.id > 0";
3181 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3182 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3183 $query_strategy_part = "ttrss_entries.id > 0";
3184 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3185 id = feed_id) as feed_title,";
3186 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3188 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3190 $tmp_result = false;
3193 $tmp_result = db_query($link, "SELECT id
3194 FROM ttrss_feeds WHERE cat_id = '$feed'");
3196 $tmp_result = db_query($link, "SELECT id
3197 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3198 WHERE id = '$feed') AND id != '$feed'");
3201 $cat_siblings = array();
3203 if (db_num_rows($tmp_result) > 0) {
3204 while ($p = db_fetch_assoc($tmp_result)) {
3205 array_push($cat_siblings, "feed_id = " . $p["id"]);
3208 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3209 $feed, implode(" OR ", $cat_siblings));
3212 $query_strategy_part = "ttrss_entries.id > 0";
3215 } else if ($feed >= 0) {
3220 $query_strategy_part = "cat_id = '$feed'";
3222 $query_strategy_part = "cat_id IS NULL";
3225 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3228 $tmp_result = db_query($link, "SELECT id
3229 FROM ttrss_feeds WHERE parent_feed = '$feed'
3230 ORDER BY cat_id,title");
3232 $parent_ids = array();
3234 if (db_num_rows($tmp_result) > 0) {
3235 while ($p = db_fetch_assoc($tmp_result)) {
3236 array_push($parent_ids, "feed_id = " . $p["id"]);
3239 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3240 $feed, implode(" OR ", $parent_ids));
3242 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3244 $query_strategy_part = "feed_id = '$feed'";
3247 } else if ($feed == -1) { // starred virtual feed
3248 $query_strategy_part = "marked = true";
3249 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3250 } else if ($feed == -2) { // published virtual feed
3251 $query_strategy_part = "published = true";
3252 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3253 } else if ($feed == -3) { // fresh virtual feed
3254 $query_strategy_part = "unread = true";
3256 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3258 if (DB_TYPE
== "pgsql") {
3259 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3261 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3264 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3265 } else if ($feed <= -10) { // labels
3266 $label_id = -$feed - 11;
3268 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3269 WHERE id = '$label_id'");
3271 $query_strategy_part = "(" . db_fetch_result($tmp_result, 0, "sql_exp") . ")";
3273 if (!$query_strategy_part) {
3277 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3279 $query_strategy_part = "id > 0"; // dumb
3282 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3283 $order_by = "updated";
3285 $order_by = "updated DESC";
3288 if ($view_mode != "noscores") {
3289 $order_by = "score DESC, $order_by";
3292 if ($override_order) {
3293 $order_by = $override_order;
3298 if ($search && $search_mode == "all_feeds") {
3299 $feed_title = __("Search results")." ($search)";
3300 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3301 $feed_title = __("Search results")." ($search, $feed)";
3302 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3303 $feed_title = $feed;
3304 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3309 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3310 WHERE id = '$feed' AND owner_uid = $owner_uid");
3311 $feed_title = db_fetch_result($result, 0, "title");
3313 $feed_title = __("Uncategorized");
3317 $feed_title = __("Searched for")." $search ($feed_title)";
3322 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3323 WHERE id = '$feed' AND owner_uid = $owner_uid");
3325 $feed_title = db_fetch_result($result, 0, "title");
3326 $feed_site_url = db_fetch_result($result, 0, "site_url");
3327 $last_error = db_fetch_result($result, 0, "last_error");
3330 $feed_title = __("Searched for") . " $search ($feed_title)";
3334 } else if ($feed == -1) {
3335 $feed_title = __("Starred articles");
3336 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3337 } else if ($feed == -2) {
3338 $feed_title = __("Published articles");
3339 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3340 } else if ($feed == -3) {
3341 $feed_title = __("Fresh articles");
3342 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3343 } else if ($feed < -10) {
3344 $label_id = -$feed - 11;
3345 $result = db_query($link, "SELECT description FROM ttrss_labels
3346 WHERE id = '$label_id'");
3347 $feed_title = db_fetch_result($result, 0, "description");
3350 $feed_title = __("Searched for") . " $search ($feed_title)";
3356 if ($feed < -10) error_reporting (0);
3358 $content_query_part = "content as content_preview,";
3360 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3363 $feed_kind = "Feeds";
3365 $feed_kind = "Labels";
3368 if ($limit_query_part) {
3369 $offset_query_part = "OFFSET $offset";
3372 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3373 if (!$override_order) {
3374 $order_by = "ttrss_feeds.title, $order_by";
3377 // Special output for Fresh feed
3379 /* if ($feed == -3) {
3380 $group_limit_part = "(select count(*) from
3381 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3382 t1.ref_id = t2.id and t1.owner_uid = 2 and
3383 t1.feed_id = ttrss_user_entries.feed_id and
3384 t2.updated > ttrss_entries.updated) <= 5 AND";
3390 ttrss_entries.id,ttrss_entries.title,
3392 unread,feed_id,marked,published,link,last_read,
3393 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3396 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3399 ttrss_entries,ttrss_user_entries,ttrss_feeds
3402 ttrss_feeds.hidden = false AND
3403 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3404 ttrss_user_entries.ref_id = ttrss_entries.id AND
3405 ttrss_user_entries.owner_uid = '$owner_uid' AND
3408 $query_strategy_part ORDER BY $order_by
3409 $limit_query_part $offset_query_part";
3411 if ($_GET["debug"]) print $query;
3413 $result = db_query($link, $query);
3418 $feed_kind = "Tags";
3420 $result = db_query($link, "SELECT
3422 ttrss_entries.id as id,title,
3425 marked,link,last_read,
3426 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3429 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3432 ttrss_entries,ttrss_user_entries,ttrss_tags
3434 ref_id = ttrss_entries.id AND
3435 ttrss_user_entries.owner_uid = '$owner_uid' AND
3436 post_int_id = int_id AND tag_name = '$feed' AND
3439 $query_strategy_part ORDER BY $order_by
3440 $limit_query_part");
3443 return array($result, $feed_title, $feed_site_url, $last_error);
3447 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3448 $search, $search_mode, $match_on) {
3450 $qfh_ret = queryFeedHeadlines($link, $feed,
3451 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3454 $result = $qfh_ret[0];
3455 $feed_title = htmlspecialchars($qfh_ret[1]);
3456 $feed_site_url = $qfh_ret[2];
3457 $last_error = $qfh_ret[3];
3459 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3461 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3462 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3463 <rss version=\"2.0\">
3465 <title>$feed_title</title>
3466 <link>$feed_site_url</link>
3467 <description>Feed generated by Tiny Tiny RSS</description>";
3469 while ($line = db_fetch_assoc($result)) {
3471 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3472 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3474 $tags = get_article_tags($link, $line["id"], $owner_uid);
3476 foreach ($tags as $tag) {
3477 print "<category>" . htmlspecialchars($tag) . "</category>";
3480 $rfc822_date = date('r', strtotime($line["updated"]));
3482 print "<pubDate>$rfc822_date</pubDate>";
3485 htmlspecialchars($line["title"]) . "</title>";
3487 print "<description><![CDATA[" .
3488 $line["content_preview"] . "]]></description>";
3493 print "</channel></rss>";
3497 function getCategoryTitle($link, $cat_id) {
3499 if ($cat_id == -1) {
3500 return __("Special");
3501 } else if ($cat_id == -2) {
3502 return __("Labels");
3505 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3508 if (db_num_rows($result) == 1) {
3509 return db_fetch_result($result, 0, "title");
3511 return "Uncategorized";
3516 // http://ru2.php.net/strip-tags
3518 function strip_tags_long($textstring, $allowed){
3519 while($textstring != strip_tags($textstring, $allowed))
3521 while (strlen($textstring) != 0)
3523 if (strlen($textstring) > 1024) {
3526 $otherlen = strlen($textstring);
3528 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3529 $safetext .= $temptext;
3530 $textstring = substr_replace($textstring,'',0,$otherlen);
3532 $textstring = $safetext;
3538 function sanitize_rss($link, $str, $force_strip_tags = false) {
3541 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3543 $res = strip_tags_long($res,
3544 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3546 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3547 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3550 if (get_pref($link, "STRIP_IMAGES")) {
3552 $res = preg_replace('/<img[^>]+>/is', '', $res);
3560 * Send by mail a digest of last articles.
3562 * @param mixed $link The database connection.
3563 * @param integer $limit The maximum number of articles by digest.
3564 * @return boolean Return false if digests are not enabled.
3566 function send_headlines_digests($link, $limit = 100) {
3568 if (!DIGEST_ENABLE
) return false;
3570 $user_limit = DIGEST_EMAIL_LIMIT
;
3573 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3575 if (DB_TYPE
== "pgsql") {
3576 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3577 } else if (DB_TYPE
== "mysql") {
3578 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3581 $result = db_query($link, "SELECT id,email FROM ttrss_users
3582 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3584 while ($line = db_fetch_assoc($result)) {
3586 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3587 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3589 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3591 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3592 $digest = $tuple[0];
3593 $headlines_count = $tuple[1];
3594 $affected_ids = $tuple[2];
3595 $digest_text = $tuple[3];
3597 if ($headlines_count > 0) {
3599 $mail = new PHPMailer();
3601 $mail->PluginDir
= "phpmailer/";
3602 $mail->SetLanguage("en", "phpmailer/language/");
3604 $mail->CharSet
= "UTF-8";
3606 $mail->From
= DIGEST_FROM_ADDRESS
;
3607 $mail->FromName
= DIGEST_FROM_NAME
;
3608 $mail->AddAddress($line["email"], $line["login"]);
3610 if (DIGEST_SMTP_HOST
) {
3611 $mail->Host
= DIGEST_SMTP_HOST
;
3612 $mail->Mailer
= "smtp";
3613 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3614 $mail->Username
= DIGEST_SMTP_LOGIN
;
3615 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3618 $mail->IsHTML(true);
3619 $mail->Subject
= DIGEST_SUBJECT
;
3620 $mail->Body
= $digest;
3621 $mail->AltBody
= $digest_text;
3623 $rc = $mail->Send();
3625 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3629 if ($rc && $do_catchup) {
3630 print "Marking affected articles as read...\n";
3631 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3634 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3635 WHERE id = " . $line["id"]);
3637 print "No headlines\n";
3642 print "All done.\n";
3646 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3648 require_once "MiniTemplator.class.php";
3650 $tpl = new MiniTemplator
;
3651 $tpl_t = new MiniTemplator
;
3653 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3654 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3656 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3657 $tpl->setVariable('CUR_TIME', date('G:i'));
3659 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3660 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3662 $affected_ids = array();
3664 if (DB_TYPE
== "pgsql") {
3665 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3666 } else if (DB_TYPE
== "mysql") {
3667 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3670 $result = db_query($link, "SELECT ttrss_entries.title,
3671 ttrss_feeds.title AS feed_title,
3673 ttrss_user_entries.ref_id,
3675 SUBSTRING(content, 1, 120) AS excerpt,
3676 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3678 ttrss_user_entries,ttrss_entries,ttrss_feeds
3680 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3681 AND include_in_digest = true
3684 AND ttrss_user_entries.owner_uid = $user_id
3686 ORDER BY ttrss_feeds.title, date_entered DESC
3689 $cur_feed_title = "";
3691 $headlines_count = db_num_rows($result);
3693 $headlines = array();
3695 while ($line = db_fetch_assoc($result)) {
3696 array_push($headlines, $line);
3699 for ($i = 0; $i < sizeof($headlines); $i++
) {
3701 $line = $headlines[$i];
3703 array_push($affected_ids, $line["ref_id"]);
3705 $updated = smart_date_time(strtotime($line["last_updated"]));
3707 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3708 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3709 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3710 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3711 $tpl->setVariable('ARTICLE_EXCERPT',
3712 truncate_string(strip_tags($line["excerpt"]), 100));
3714 $tpl->addBlock('article');
3716 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3717 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3718 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3719 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3720 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3721 // truncate_string(strip_tags($line["excerpt"]), 100));
3723 $tpl_t->addBlock('article');
3725 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3726 $tpl->addBlock('feed');
3727 $tpl_t->addBlock('feed');
3732 $tpl->addBlock('digest');
3733 $tpl->generateOutputToString($tmp);
3735 $tpl_t->addBlock('digest');
3736 $tpl_t->generateOutputToString($tmp_t);
3738 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3741 function check_for_update($link, $brief_fmt = true) {
3742 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3744 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3749 if (ENABLE_SIMPLEPIE
) {
3750 $rss = new SimplePie();
3751 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3752 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3753 $rss->set_feed_url($fetch_url);
3754 $rss->set_output_encoding('UTF-8');
3757 $rss = fetch_rss($releases_feed);
3759 error_reporting (DEFAULT_ERROR_LEVEL
);
3763 if (ENABLE_SIMPLEPIE
) {
3764 $items = $rss->get_items();
3766 $items = $rss->items
;
3768 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3769 if (!$items ||
!is_array($items)) $items = $rss;
3772 if (!is_array($items) ||
count($items) == 0) {
3776 $latest_item = $items[0];
3778 if (ENABLE_SIMPLEPIE
) {
3779 $last_title = $latest_item->get_title();
3781 $last_title = $latest_item["title"];
3784 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3786 if (ENABLE_SIMPLEPIE
) {
3787 $release_url = sanitize_rss($link, $latest_item->get_link());
3788 $content = sanitize_rss($link, $latest_item->get_description());
3790 $release_url = sanitize_rss($link, $latest_item["link"]);
3791 $content = sanitize_rss($link, $latest_item["description"]);
3794 if (version_compare(VERSION
, $latest_version) == -1) {
3796 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3797 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3798 <div id=\"milestoneDetails\">$content</div>");
3800 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3801 <div class='milestoneDetails'>$content</div>
3802 Visit <a target=\"_blank\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3803 download and update information.";
3810 function markArticlesById($link, $ids, $cmode) {
3814 foreach ($ids as $id) {
3815 array_push($tmp_ids, "ref_id = '$id'");
3818 $ids_qpart = join(" OR ", $tmp_ids);
3821 db_query($link, "UPDATE ttrss_user_entries SET
3822 marked = false,last_read = NOW()
3823 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3824 } else if ($cmode == 1) {
3825 db_query($link, "UPDATE ttrss_user_entries SET
3827 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3829 db_query($link, "UPDATE ttrss_user_entries SET
3830 marked = NOT marked,last_read = NOW()
3831 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3835 function publishArticlesById($link, $ids, $cmode) {
3839 foreach ($ids as $id) {
3840 array_push($tmp_ids, "ref_id = '$id'");
3843 $ids_qpart = join(" OR ", $tmp_ids);
3846 db_query($link, "UPDATE ttrss_user_entries SET
3847 published = false,last_read = NOW()
3848 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3849 } else if ($cmode == 1) {
3850 db_query($link, "UPDATE ttrss_user_entries SET
3852 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3854 db_query($link, "UPDATE ttrss_user_entries SET
3855 published = NOT published,last_read = NOW()
3856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3860 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3862 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3866 foreach ($ids as $id) {
3867 array_push($tmp_ids, "ref_id = '$id'");
3870 $ids_qpart = join(" OR ", $tmp_ids);
3873 db_query($link, "UPDATE ttrss_user_entries SET
3874 unread = false,last_read = NOW()
3875 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3876 } else if ($cmode == 1) {
3877 db_query($link, "UPDATE ttrss_user_entries SET
3879 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3881 db_query($link, "UPDATE ttrss_user_entries SET
3882 unread = NOT unread,last_read = NOW()
3883 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3887 function catchupArticleById($link, $id, $cmode) {
3890 db_query($link, "UPDATE ttrss_user_entries SET
3891 unread = false,last_read = NOW()
3892 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3893 } else if ($cmode == 1) {
3894 db_query($link, "UPDATE ttrss_user_entries SET
3896 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3898 db_query($link, "UPDATE ttrss_user_entries SET
3899 unread = NOT unread,last_read = NOW()
3900 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3904 function make_guid_from_title($title) {
3905 return preg_replace("/[ \"\',.:;]/", "-",
3906 mb_strtolower(strip_tags($title), 'utf-8'));
3909 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3910 $bottom = false, $rtl_content = false, $feed_id = 0,
3911 $is_cat = false, $search = false, $match_on = false,
3912 $search_mode = false, $offset = 0, $limit = 0,
3913 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3915 $user_page_offset = $offset +
1;
3918 $class = "headlinesSubToolbar";
3919 $tid = "headlineActionsTop";
3921 $class = "headlinesSubToolbar";
3922 $tid = "headlineActionsBottom";
3925 print "<nobr><table class=\"$class\" id=\"$tid\"
3926 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3934 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3935 $page_next_link = "javascript:viewFeedGoPage(1)";
3936 $page_first_link = "javascript:viewFeedGoPage(0)";
3938 $catchup_page_link = "javascript:catchupPage()";
3939 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3940 $catchup_sel_link = "javascript:catchupSelection()";
3942 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3944 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3945 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3946 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3947 $sel_inv_link = "javascript:invertHeadlineSelection()";
3949 $tog_unread_link = "javascript:selectionToggleUnread()";
3950 $tog_marked_link = "javascript:selectionToggleMarked()";
3951 $tog_published_link = "javascript:selectionTogglePublished()";
3955 $sel_all_link = "javascript:cdmSelectArticles('all')";
3956 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3957 $sel_none_link = "javascript:cdmSelectArticles('none')";
3959 $sel_inv_link = "javascript:invertHeadlineSelection()";
3961 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3962 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3963 $tog_published_link = "javascript:selectionTogglePublished(true)";
3967 if (!$dashboard_menu) {
3969 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3971 print "<td class=\"headlineActions$rtl_cpart\">
3972 <ul class=\"headlineDropdownMenu\">
3975 <a href=\"$sel_all_link\">".__('All')."</a>,
3976 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3977 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3978 <a href=\"$sel_none_link\">".__('None')."</a></li>
3979 <li class=\"vsep\"> </li>
3980 <li class=\"top\">".__('Actions...')."<ul>
3981 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
3982 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
3983 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
3984 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
3985 <li><span class=\"insensitive\">--------</span></li>
3986 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
3987 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
3989 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3992 <li onclick=\"catchupRelativeToArticle(0)\"> ".__("Above active article")."</li>
3993 <li onclick=\"catchupRelativeToArticle(1)\"> ".__("Below active article")."</li>";
3996 <li><span class=\"insensitive\"> ".__("Above active article")."</span></li>
3997 <li><span class=\"insensitive\"> ".__("Below active article")."</span></li>";
4001 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4003 print "<li><span class=\"insensitive\">--------</span></li>";
4004 print "<li><span class=\"insensitive\">".__('Other actions:')."</span></li>";
4007 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4009 <li onclick=\"javascript:labelFromSearch('$search', '$search_mode',
4010 '$match_on', '$feed_id', '$is_cat');\">
4011 ".__('Search to label')."</li>";
4013 print "<li><span class=\"insensitive\"> ".__('Search to label')."</li>";
4017 print "</ul></li></ul>";
4021 // old style subtoolbar:
4023 print "<td class=\"headlineActions$rtl_cpart\">".
4025 <a href=\"$sel_all_link\">".__('All')."</a>,
4026 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4027 <a href=\"$sel_none_link\">".__('None')."</a>
4029 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4030 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4032 __('Mark as read:')."
4033 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4034 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4036 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4039 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
4040 '$match_on', '$feed_id', '$is_cat');\">
4041 ".__('Convert to label')."</a>";
4047 } else { // dashboard menu actions
4053 print "<td class=\"headlineTitle$rtl_cpart\">";
4055 print "<span id=\"subtoolbar_search\"
4056 style=\"display : none\"><input
4057 id=\"subtoolbar_search_box\"
4058 onblur=\"javascript:enableHotkeys();\"
4059 onfocus=\"javascript:disableHotkeys();\"
4060 onchange=\"subtoolbarSearch()\"
4061 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4063 print "<span id=\"subtoolbar_ftitle\">";
4065 if ($feed_site_url) {
4067 $target = "target=\"_blank\"";
4069 print "<a $target href=\"$feed_site_url\">".
4070 truncate_string($feed_title,30)."</a>";
4076 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4079 if ($user_page_offset > 1) {
4080 print " [$user_page_offset] ";
4083 if (!$bottom && !$disable_feed) {
4085 <a target=\"_blank\"
4086 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4087 <img class=\"noborder\"
4088 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4090 } else if ($feed_small_icon) {
4091 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4097 print "</tr></table></nobr>";
4101 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4103 $tmp_category = getCategoryTitle($link, $cat_id);
4104 $cat_unread = getCategoryUnread($link, $cat_id);
4107 $holder_style = "display:none;";
4114 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4117 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4118 $inner_title_class = "catTitle";
4120 $browse_cat_link = "";
4121 $inner_title_class = "catTitleNL";
4125 $cat_class = "feedCat";
4127 $cat_class = "virtCat";
4130 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4131 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4132 title=\"".__('Click to collapse category')."\"
4133 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4134 id=\"FCATN-$cat_id\" $browse_cat_link
4135 \">$tmp_category</span>";
4137 print "<span id=\"FCAP-$cat_id\">";
4139 print " <span id=\"FCATCTR-$cat_id\"
4140 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4146 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4150 function outputFeedList($link, $tags = false) {
4152 print "<ul class=\"feedList\" id=\"feedList\">";
4154 $owner_uid = $_SESSION["uid"];
4158 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4160 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4163 $cat_hidden = false;
4166 printCategoryHeader($link, -1, $cat_hidden, false);
4169 if (defined('_ENABLE_DASHBOARD')) {
4170 printFeedEntry(-4, "virt", __("Dashboard"), 0,
4171 "images/tag.png", $link);
4174 $num_starred = getFeedUnread($link, -1);
4175 $num_published = getFeedUnread($link, -2);
4176 $num_fresh = getFeedUnread($link, -3);
4180 if ($num_fresh > 0) $class .= "Unread";
4182 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4183 "images/fresh.png", $link);
4187 if ($num_starred > 0) $class .= "Unread";
4189 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4192 $mark_img_ext = "gif";
4194 $mark_img_ext = "png";
4197 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4198 "images/mark_set.$mark_img_ext", $link);
4202 if ($num_published > 0) $class .= "Unread";
4204 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4205 "images/pub_set.gif", $link);
4207 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4213 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4215 $result = db_query($link, "SELECT id,sql_exp,description FROM
4216 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4218 if (db_num_rows($result) > 0) {
4219 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4221 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4224 $cat_hidden = false;
4227 printCategoryHeader($link, -2, $cat_hidden, false);
4230 print "<li><hr></li>";
4234 while ($line = db_fetch_assoc($result)) {
4236 error_reporting (0);
4238 $label_id = -$line['id'] - 11;
4239 $count = getFeedUnread($link, $label_id);
4247 error_reporting (DEFAULT_ERROR_LEVEL
);
4249 printFeedEntry($label_id,
4250 $class, $line["description"],
4251 $count, "images/label.png", $link);
4255 if (db_num_rows($result) > 0) {
4256 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4263 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4264 print "<li><hr></li>";
4267 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4268 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4269 $order_by_qpart = "order_id,category,unread DESC,title";
4271 $order_by_qpart = "order_id,category,title";
4274 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4275 $order_by_qpart = "unread DESC,title";
4277 $order_by_qpart = "title";
4281 $age_qpart = getMaxAgeSubquery();
4283 $query = "SELECT ttrss_feeds.*,
4284 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4285 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4286 WHERE feed_id = ttrss_feeds.id AND unread = true
4288 AND ttrss_user_entries.ref_id = ttrss_entries.id
4289 AND owner_uid = '$owner_uid') as unread,
4291 ttrss_feed_categories.title AS category,
4292 ttrss_feed_categories.collapsed
4293 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4294 ON (ttrss_feed_categories.id = cat_id)
4296 ttrss_feeds.hidden = false AND
4297 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4298 ORDER BY $order_by_qpart";
4300 $result = db_query($link, $query);
4302 $actid = $_GET["actid"];
4312 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4314 while ($line = db_fetch_assoc($result)) {
4316 $feed = trim($line["title"]);
4318 if (!$feed) $feed = "[Untitled]";
4320 $feed_id = $line["id"];
4322 $subop = $_GET["subop"];
4324 $unread = $line["unread"];
4326 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4327 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4329 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4332 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4335 $rtl_tag = "dir=\"RTL\"";
4340 $tmp_result = db_query($link,
4341 "SELECT id,COUNT(unread) AS unread
4342 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
4343 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
4344 WHERE parent_feed = '$feed_id' AND unread = true
4345 GROUP BY ttrss_feeds.id");
4347 if (db_num_rows($tmp_result) > 0) {
4348 while ($l = db_fetch_assoc($tmp_result)) {
4349 $unread +
= $l["unread"];
4353 $cat_id = $line["cat_id"];
4355 $tmp_category = $line["category"];
4357 if (!$tmp_category) {
4358 $tmp_category = __("Uncategorized");
4361 // $class = ($lnum % 2) ? "even" : "odd";
4363 if ($line["last_error"]) {
4369 if ($unread > 0) $class .= "Unread";
4371 if ($actid == $feed_id) {
4372 $class .= "Selected";
4375 $total_unread +
= $unread;
4377 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4383 $category = $tmp_category;
4385 $collapsed = sql_bool_to_bool($line["collapsed"]);
4387 // workaround for NULL category
4388 if ($category == __("Uncategorized")) {
4389 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4394 $cat_id = sprintf("%d", $cat_id);
4396 printCategoryHeader($link, $cat_id, $collapsed, true);
4400 printFeedEntry($feed_id, $class, $feed, $unread,
4401 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4402 $last_updated, $line["last_error"]);
4407 if (db_num_rows($result) == 0) {
4408 print "<li>".__('No feeds to display.')."</li>";
4415 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4416 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4417 post_int_id = ttrss_user_entries.int_id AND
4418 unread = true AND ref_id = ttrss_entries.id
4419 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4421 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4422 ORDER BY tag_name"); */
4424 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4425 print "<li class=\"feedCat\">".__('Tags')."</li>";
4426 print "<ul class=\"feedCatList\">";
4429 $age_qpart = getMaxAgeSubquery();
4431 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4432 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4433 AND ref_id = id AND $age_qpart
4434 AND unread = true)) AS count FROM ttrss_tags
4435 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4436 ORDER BY count DESC LIMIT 50");
4440 while ($line = db_fetch_assoc($result)) {
4441 $tags[$line["tag_name"]] +
= $line["count"];
4444 foreach (array_keys($tags) as $tag) {
4446 $unread = $tags[$tag];
4454 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4458 if (db_num_rows($result) == 0) {
4459 print "<li>No tags to display.</li>";
4462 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4472 function get_article_tags($link, $id, $owner_uid = 0) {
4474 $a_id = db_escape_string($id);
4476 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4478 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4479 owner_uid as owner FROM
4480 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4481 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4485 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4486 array_push($tags, $tmp_line["tag_name"]);
4492 function trim_value(&$value) {
4493 $value = trim($value);
4496 function trim_array($array) {
4498 array_walk($tmp, 'trim_value');
4502 function tag_is_valid($tag) {
4503 if ($tag == '') return false;
4504 if (preg_match("/^[0-9]*$/", $tag)) return false;
4506 if (function_exists('iconv')) {
4507 $tag = iconv("utf-8", "utf-8", $tag);
4510 if (!$tag) return false;
4515 function render_login_form($link, $mobile = false) {
4517 require_once "login_form.php";
4519 require_once "mobile/login_form.php";
4523 // from http://developer.apple.com/internet/safari/faq.html
4524 function no_cache_incantation() {
4525 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4526 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4527 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4528 header("Cache-Control: post-check=0, pre-check=0", false);
4529 header("Pragma: no-cache"); // HTTP/1.0
4532 function format_warning($msg, $id = "") {
4533 return "<div class=\"warning\" id=\"$id\">
4534 <img src=\"images/sign_excl.gif\">$msg</div>";
4537 function format_notice($msg) {
4538 return "<div class=\"notice\">
4539 <img src=\"images/sign_info.gif\">$msg</div>";
4542 function format_error($msg) {
4543 return "<div class=\"error\">
4544 <img src=\"images/sign_excl.gif\">$msg</div>";
4547 function print_notice($msg) {
4548 return print format_notice($msg);
4551 function print_warning($msg) {
4552 return print format_warning($msg);
4555 function print_error($msg) {
4556 return print format_error($msg);
4560 function T_sprintf() {
4561 $args = func_get_args();
4562 return vsprintf(__(array_shift($args)), $args);
4565 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4566 $zoom_mode = false) {
4568 /* we can figure out feed_id from article id anyway, why do we
4569 * pass feed_id here? */
4571 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4572 WHERE ref_id = '$id'");
4574 $feed_id = db_fetch_result($result, 0, "feed_id");
4576 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4578 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4579 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4581 if (db_num_rows($result) == 1) {
4582 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4584 $rtl_content = false;
4588 $rtl_tag = "dir=\"RTL\"";
4595 if ($mark_as_read) {
4596 $result = db_query($link, "UPDATE ttrss_user_entries
4597 SET unread = false,last_read = NOW()
4598 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4601 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4602 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4603 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4606 FROM ttrss_entries,ttrss_user_entries
4607 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4613 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4614 $link_target = "target=\"_blank\"";
4617 $line = db_fetch_assoc($result);
4619 if ($line["icon_url"]) {
4620 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4622 $feed_icon = " ";
4625 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4626 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4628 $entry_comments = "";
4631 $num_comments = $line["num_comments"];
4632 $entry_comments = "";
4634 if ($num_comments > 0) {
4635 if ($line["comments"]) {
4636 $comments_url = $line["comments"];
4638 $comments_url = $line["link"];
4640 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4642 if ($line["comments"] && $line["link"] != $line["comments"]) {
4643 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4648 header("Content-Type: text/html");
4650 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4651 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4652 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4657 print "<div class=\"postReply\">";
4659 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4660 onmouseout=\"enable_resize(false)\">";
4662 $entry_author = $line["author"];
4664 if ($entry_author) {
4665 $entry_author = __(" - ") . $entry_author;
4668 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4669 strtotime($line["updated"]));
4671 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4673 if ($line["link"]) {
4674 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4675 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4677 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4680 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4681 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4682 ORDER BY tag_name"); */
4684 $tags = get_article_tags($link, $id);
4687 $tags_nolinks_str = "";
4692 if ($_SESSION["theme"] == "3pane") {
4698 foreach ($tags as $tag) {
4700 $tag_escaped = str_replace("'", "\\'", $tag);
4702 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4704 if ($num_tags == $tag_limit) {
4705 $tags_str .= "…";
4706 $tags_nolinks_str .= "…";
4708 } else if ($num_tags < $tag_limit) {
4709 $tags_str .= $tag_str;
4710 $tags_nolinks_str .= "$tag, ";
4712 $f_tags_str .= $tag_str;
4715 $tags_str = preg_replace("/, $/", "", $tags_str);
4716 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4717 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4719 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4720 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4722 if (!$entry_comments) $entry_comments = " "; # placeholder
4724 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4725 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4727 print "<div style='float : right'>
4728 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4732 <a title=\"".__('Edit tags for this article')."\"
4733 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4735 if (defined('_ENABLE_INLINE_VIEW')) {
4737 print "<img src=\"images/art-inline.png\" class='tagsPic'
4738 style=\"cursor : pointer\" style=\"cursor : pointer\"
4739 onclick=\"showOriginalArticleInline($id)\"
4740 alt='Inline' title='".__('Display original article content')."'>";
4744 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4745 style=\"cursor : pointer\" style=\"cursor : pointer\"
4746 onclick=\"zoomToArticle($id)\"
4747 alt='Zoom' title='".__('Show article summary in new window')."'>";
4749 print "$tags_nolinks_str";
4752 print "<div clear='both'>$entry_comments</div>";
4756 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4757 print "<div class=\"postContent\">";
4759 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4761 $article_content = sanitize_rss($link, $line["content"]);
4763 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4764 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4768 print $article_content;
4770 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4771 post_id = '$id' AND content_url != ''");
4773 if (db_num_rows($result) > 0) {
4775 $entries_html = array();
4778 while ($line = db_fetch_assoc($result)) {
4780 $url = $line["content_url"];
4781 $ctype = $line["content_type"];
4783 if (!$ctype) $ctype = __("unknown type");
4785 $filename = substr($url, strrpos($url, "/")+
1);
4789 if (($ctype == __("audio/mpeg")) &&
4790 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4792 $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> ";
4796 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4797 $filename . " (" . $ctype . ")" . "</a>";
4799 array_push($entries_html, $entry);
4803 $entry["type"] = $ctype;
4804 $entry["filename"] = $filename;
4805 $entry["url"] = $url;
4807 array_push($entries, $entry);
4810 print "<div class=\"postEnclosures\">";
4812 if (!preg_match("/img/i", $article_content)) {
4813 foreach ($entries as $entry) {
4814 if (preg_match("/image/", $entry["type"])) {
4816 alt=\"".htmlspecialchars($entry["filename"])."\"
4817 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4822 print "<div class=\"postEnclosures\">";
4824 if (db_num_rows($result) == 1) {
4825 print __("Attachment:") . " ";
4827 print __("Attachments:") . " ";
4830 print join(", ", $entries_html);
4842 print "]]></article>";
4845 <div style=\"text-align : center\">
4846 <input type=\"submit\" onclick=\"return window.close()\"
4847 value=\"".__("Close this window")."\"></div>";
4848 print "</body></html>";
4854 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4855 $next_unread_feed, $offset, $vgr_last_feed = false,
4856 $override_order = false) {
4858 $disable_cache = false;
4860 $timing_info = getmicrotime();
4862 $topmost_article_ids = array();
4868 if ($subop == "undefined") $subop = "";
4870 $subop_split = split(":", $subop);
4872 if ($subop == "CatchupSelected") {
4873 $ids = split(",", db_escape_string($_GET["ids"]));
4874 $cmode = sprintf("%d", $_GET["cmode"]);
4876 catchupArticlesById($link, $ids, $cmode);
4879 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4880 update_generic_feed($link, $feed, $cat_view, true);
4883 if ($subop == "MarkAllRead") {
4884 catchup_feed($link, $feed, $cat_view);
4886 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4887 if ($next_unread_feed) {
4888 $feed = $next_unread_feed;
4893 if ($subop_split[0] == "MarkAllReadGR") {
4894 catchup_feed($link, $subop_split[1], false);
4899 $result = db_query($link,
4900 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4902 if (db_num_rows($result) == 0) {
4903 print "<div align='center'>".__('Feed not found.')."</div>";
4908 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4910 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4911 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4913 if (db_num_rows($result) == 1) {
4914 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4916 $rtl_content = false;
4920 $rtl_tag = "dir=\"RTL\"";
4926 $rtl_content = false;
4929 $script_dt_add = get_script_dt_add();
4931 /// START /////////////////////////////////////////////////////////////////////////////////
4933 $search = db_escape_string($_GET["query"]);
4936 $disable_cache = true;
4939 $search_mode = db_escape_string($_GET["search_mode"]);
4940 $match_on = db_escape_string($_GET["match_on"]);
4946 $real_offset = $offset * $limit;
4948 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4950 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4951 $search, $search_mode, $match_on, $override_order, $real_offset);
4953 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4955 $result = $qfh_ret[0];
4956 $feed_title = $qfh_ret[1];
4957 $feed_site_url = $qfh_ret[2];
4958 $last_error = $qfh_ret[3];
4960 $vgroup_last_feed = $vgr_last_feed;
4963 $feed_site_url = article_publish_url($link);
4966 /// STOP //////////////////////////////////////////////////////////////////////////////////
4969 print "<div id=\"headlinesContainer\" $rtl_tag>";
4972 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4976 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4977 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4980 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4983 $headlines_count = db_num_rows($result);
4985 if (db_num_rows($result) > 0) {
4987 # print "\{$offset}";
4989 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4990 print "<table class=\"headlinesList\" id=\"headlinesList\"
4991 cellspacing=\"0\">";
4994 $lnum = $limit*$offset;
4996 error_reporting (DEFAULT_ERROR_LEVEL
);
4999 $cur_feed_title = '';
5001 while ($line = db_fetch_assoc($result)) {
5003 $class = ($lnum %
2) ?
"even" : "odd";
5006 $feed_id = $line["feed_id"];
5008 if (count($topmost_article_ids) < 5) {
5009 array_push($topmost_article_ids, $id);
5012 if ($line["last_read"] == "" &&
5013 ($line["unread"] != "t" && $line["unread"] != "1")) {
5015 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5018 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5022 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5030 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5033 $mark_img_ext = "gif";
5035 $mark_img_ext = "png";
5038 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5039 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5041 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5043 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5045 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5048 if ($line["published"] == "t" ||
$line["published"] == "1") {
5049 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5051 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5053 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5055 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5058 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5059 # $line["title"] . "</a>";
5061 # $content_link = "<a
5062 # href=\"" . htmlspecialchars($line["link"]) . "\"
5063 # onclick=\"view($id,$feed_id);\">" .
5064 # $line["title"] . "</a>";
5066 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5067 # $line["title"] . "</a>";
5069 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5070 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5072 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5073 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5076 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5077 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5081 $score = $line["score"];
5083 $score_pic = get_score_pic($score);
5085 $score_title = __("(Click to change)");
5087 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5088 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">";
5092 } else if ($score < -100) {
5098 $entry_author = $line["author"];
5100 if ($entry_author) {
5101 $entry_author = " - $entry_author";
5104 $has_feed_icon = feed_has_icon($feed_id);
5106 if ($has_feed_icon) {
5107 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5109 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5110 $feed_icon_img = "";
5113 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5115 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5116 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5118 $cur_feed_title = $line["feed_title"];
5119 $vgroup_last_feed = $feed_id;
5121 $cur_feed_title = htmlspecialchars($cur_feed_title);
5123 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5125 print "<tr class='feedTitle'><td colspan='7'>".
5126 "<div style=\"float : right\">$feed_icon_img</div>".
5127 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5128 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5132 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5133 onmouseout='postMouseOut($id)'";
5135 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5137 print "<td class='hlUpdPic'>$update_pic</td>";
5139 print "<td class='hlSelectRow'>
5140 <input type=\"checkbox\" onclick=\"tSR(this)\"
5144 print "<td class='hlMarkedPic'>$marked_pic</td>";
5145 print "<td class='hlMarkedPic'>$published_pic</td>";
5147 # if ($line["feed_title"]) {
5148 # print "<td class='hlContent'>$content_link</td>";
5149 # print "<td class='hlFeed'>
5150 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5151 # truncate_string($line["feed_title"],30)."</a> </td>";
5154 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5156 print "<a id=\"RTITLE-$id\"
5157 href=\"" . htmlspecialchars($line["link"]) . "\"
5158 onclick=\"return view($id,$feed_id);\">" .
5161 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5162 if ($content_preview) {
5163 print "<span class=\"contentPreview\"> - $content_preview</span>";
5169 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5170 # $line["feed_title"]."</a>
5172 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5173 if ($line["feed_title"]) {
5174 print "<span class=\"hlFeed\">
5175 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5176 $line["feed_title"]."</a>)
5184 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5186 print "<td class='hlMarkedPic'>$score_pic</td>";
5188 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5189 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5196 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5197 if ($feed_id != $vgroup_last_feed) {
5199 $cur_feed_title = $line["feed_title"];
5200 $vgroup_last_feed = $feed_id;
5202 $cur_feed_title = htmlspecialchars($cur_feed_title);
5204 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5206 $has_feed_icon = feed_has_icon($feed_id);
5208 if ($has_feed_icon) {
5209 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5211 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5214 print "<div class='cdmFeedTitle'>".
5215 "<div style=\"float : right\">$feed_icon_img</div>".
5216 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5217 $line["feed_title"]."</a> $vf_catchup_link</div>";
5222 $add_class = "Unread";
5227 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5228 $show_excerpt = false;
5230 if ($expand_cdm && $score >= -100) {
5232 $show_excerpt = false;
5234 $cdm_cstyle = "style=\"display : none\"";
5235 $show_excerpt = true;
5238 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5239 onmouseout='postMouseOut($id)'";
5241 print "<div class=\"cdmArticle$add_class\"
5243 $mouseover_attrs'>";
5245 print "<div class=\"cdmHeader\">";
5247 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5248 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5251 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5254 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5255 onclick=\"javascript:toggleUnread($id, 0)\"
5256 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5259 print $entry_author;
5261 /* if (!$expand_cdm || $score < -100) {
5262 print " <a id=\"CICH-$id\"
5263 href=\"javascript:cdmExpandArticle($id)\">
5264 (".__('Show article').")</a>";
5268 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5269 if ($line["feed_title"]) {
5270 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5274 print "</span></div>";
5276 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5277 $line["content_preview"] = preg_replace("/href=/i",
5278 "target=\"_blank\" href=", $line["content_preview"]);
5281 if ($show_excerpt) {
5282 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5283 onclick=\"cdmExpandArticle($id)\"
5284 title=\"".__('Click to expand article')."\">";
5285 print truncate_string(strip_tags($line["content_preview"]), 100);
5289 print "<div class=\"cdmContent\"
5290 onclick=\"cdmClicked($id)\"
5291 id=\"CICD-$id\" $cdm_cstyle>";
5293 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5295 print sanitize_rss($link, $line["content_preview"]);
5296 $article_content = $line["content_preview"];
5298 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5299 post_id = '$id' AND content_url != ''");
5301 if (db_num_rows($e_result) > 0) {
5303 $entries_html = array();
5306 while ($e_line = db_fetch_assoc($e_result)) {
5308 $url = $e_line["content_url"];
5309 $ctype = $e_line["content_type"];
5310 if (!$ctype) $ctype = __("unknown type");
5312 $filename = substr($url, strrpos($url, "/")+
1);
5316 if (($ctype == __("audio/mpeg")) &&
5317 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5319 $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> ";
5323 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5324 $filename . " (" . $ctype . ")" . "</a>";
5326 array_push($entries_html, $entry);
5330 $entry["type"] = $ctype;
5331 $entry["filename"] = $filename;
5332 $entry["url"] = $url;
5334 array_push($entries, $entry);
5337 if (!preg_match("/img/i", $article_content)) {
5338 foreach ($entries as $entry) {
5339 if (preg_match("/image/", $entry["type"])) {
5341 alt=\"".htmlspecialchars($entry["filename"])."\"
5342 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5347 print "<div class=\"cdmEnclosures\">";
5349 if (db_num_rows($e_result) == 1) {
5350 print __("Attachment:") . " ";
5352 print __("Attachments:") . " ";
5355 print join(", ", $entries_html);
5361 print "<br clear='both'>";
5364 /* if (!$expand_cdm) {
5365 print "<a id=\"CICH-$id\"
5366 href=\"javascript:cdmExpandArticle($id)\">
5372 print "<div class=\"cdmFooter\"><span class='s0'>";
5374 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5376 print __("Select:").
5377 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5378 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5380 print "</span><span class='s1'>$marked_pic</span> ";
5381 print "<span class='s1'>$published_pic</span> ";
5382 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5383 onclick=\"zoomToArticle($id)\"
5384 style=\"cursor : pointer\"
5386 title='".__('Show article summary in new window')."'></span>";
5388 $tags = get_article_tags($link, $id);
5391 $full_tags_str = "";
5394 foreach ($tags as $tag) {
5396 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5397 if ($num_tags < 5) {
5398 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5399 } else if ($num_tags == 5) {
5400 $tags_str .= "…";
5404 $tags_str = preg_replace("/, $/", "", $tags_str);
5405 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5407 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5409 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5412 if ($tags_str == "") $tags_str = "no tags";
5414 // print "<img src='images/tag.png' class='markedPic'>";
5416 print "<span class='s1'>
5417 <img class='tagsPic' src='images/tag.png' alt='Tags'
5418 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5419 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5423 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5424 href=\"javascript:toggleUnread($id)\">
5435 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5439 // print_headline_subtoolbar($link,
5440 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5446 switch ($view_mode) {
5448 $message = __("No unread articles found to display.");
5451 $message = __("No starred articles found to display.");
5454 $message = __("No articles found to display.");
5457 if (!$offset) print "<div class='whiteBox'>$message</div>";
5465 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5468 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5470 function printTagCloud($link) {
5472 /* get first ref_id to count from */
5478 if (DB_TYPE == "pgsql") {
5479 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5480 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5481 AND date_entered > NOW() - INTERVAL '30 days'";
5483 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5484 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5485 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5488 $result = db_query($link, $query);
5489 $first_id = db_fetch_result($result, 0, "id"); */
5491 //AND post_int_id >= '$first_id'
5492 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5493 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5494 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5496 $result = db_query($link, $query);
5500 while ($line = db_fetch_assoc($result)) {
5501 $tags[$line["tag_name"]] = $line["count"];
5506 $max_size = 32; // max font size in pixels
5507 $min_size = 11; // min font size in pixels
5509 // largest and smallest array values
5510 $max_qty = max(array_values($tags));
5511 $min_qty = min(array_values($tags));
5513 // find the range of values
5514 $spread = $max_qty - $min_qty;
5515 if ($spread == 0) { // we don't want to divide by zero
5519 // set the font-size increment
5520 $step = ($max_size - $min_size) / ($spread);
5522 // loop through the tag array
5523 foreach ($tags as $key => $value) {
5524 // calculate font-size
5525 // find the $value in excess of $min_qty
5526 // multiply by the font-size increment ($size)
5527 // and add the $min_size set above
5528 $size = round($min_size +
(($value - $min_qty) * $step));
5530 $key_escaped = str_replace("'", "\\'", $key);
5532 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5533 $size . "px\" title=\"$value articles tagged with " .
5534 $key . '">' . $key . '</a> ';
5538 function print_checkpoint($n, $s) {
5539 $ts = getmicrotime();
5540 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5544 function sanitize_tag($tag) {
5547 $tag = mb_strtolower($tag, 'utf-8');
5549 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5551 // $tag = str_replace('"', "", $tag);
5552 // $tag = str_replace("+", " ", $tag);
5553 $tag = str_replace("technorati tag: ", "", $tag);
5558 function generate_publish_key() {
5559 return sha1(uniqid(rand(), true));
5562 function article_publish_url($link) {
5567 if ($_SERVER['HTTPS'] != "on") {
5568 $url_path = "http://";
5570 $url_path = "https://";
5573 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5574 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5580 * Purge a feed contents, marked articles excepted.
5582 * @param mixed $link The database connection.
5583 * @param integer $id The id of the feed to purge.
5586 function clear_feed_articles($link, $id) {
5587 $result = db_query($link, "DELETE FROM ttrss_user_entries
5588 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5590 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5591 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5592 } // function clear_feed_articles
5595 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5597 * @return string The Mozilla Firefox feed adding URL.
5599 function add_feed_url() {
5600 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5601 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5603 } // function add_feed_url
5606 * Encrypt a password in SHA1.
5608 * @param string $pass The password to encrypt.
5609 * @param string $login A optionnal login.
5610 * @return string The encrypted password.
5612 function encrypt_password($pass, $login = '') {
5614 return "SHA1X:" . sha1("$login:$pass");
5616 return "SHA1:" . sha1($pass);
5618 } // function encrypt_password
5621 * Update a feed batch.
5622 * Used by daemons to update n feeds by run.
5623 * Only update feed needing a update, and not being processed
5624 * by another process.
5626 * @param mixed $link Database link
5627 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5628 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5629 * @param boolean $debug Set to false to disable debug output. Default to true.
5632 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5633 // Process all other feeds using last_updated and interval parameters
5635 // Test if the user has loggued in recently. If not, it does not update its feeds.
5636 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5637 if (DB_TYPE
== "pgsql") {
5638 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5640 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5643 $login_thresh_qpart = "";
5646 // Test if the feed need a update (update interval exceded).
5647 if (DB_TYPE
== "pgsql") {
5648 $update_limit_qpart = "AND ((
5649 ttrss_feeds.update_interval = 0
5650 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5652 ttrss_feeds.update_interval > 0
5653 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5654 ) OR ttrss_feeds.last_updated IS NULL)";
5656 $update_limit_qpart = "AND ((
5657 ttrss_feeds.update_interval = 0
5658 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5660 ttrss_feeds.update_interval > 0
5661 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5662 ) OR ttrss_feeds.last_updated IS NULL)";
5665 // Test if feed is currently being updated by another process.
5666 if (DB_TYPE
== "pgsql") {
5667 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5669 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5672 // Test if there is a limit to number of updated feeds
5674 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5676 $random_qpart = sql_random_function();
5678 // We search for feed needing update.
5679 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5680 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5681 ttrss_feeds.update_interval
5683 ttrss_feeds, ttrss_users, ttrss_user_prefs
5685 ttrss_feeds.owner_uid = ttrss_users.id
5686 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5687 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5688 $login_thresh_qpart $update_limit_qpart
5689 $updstart_thresh_qpart
5690 ORDER BY $random_qpart $query_limit");
5692 $user_prefs_cache = array();
5694 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5696 // Here is a little cache magic in order to minimize risk of double feed updates.
5697 $feeds_to_update = array();
5698 while ($line = db_fetch_assoc($result)) {
5699 $feeds_to_update[$line['id']] = $line;
5702 // We update the feed last update started date before anything else.
5703 // There is no lag due to feed contents downloads
5704 // It prevent an other process to update the same feed.
5705 $feed_ids = array_keys($feeds_to_update);
5707 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5708 WHERE id IN (%s)", implode(',', $feed_ids)));
5711 // For each feed, we call the feed update function.
5712 while ($line = array_pop($feeds_to_update)) {
5714 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5716 // We setup a alarm to alert if the feed take more than 300s to update.
5718 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5719 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5720 // Cancel the alarm (the update went well)
5721 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5723 sleep(1); // prevent flood (FIXME make this an option?)
5726 // Send feed digests by email if needed.
5727 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5729 } // function update_daemon_common
5731 function generate_dashboard_feed($link) {
5733 print "<div id=\"headlinesContainer\">";
5735 print_headline_subtoolbar($link, "", "Dashboard",
5736 false, false, -4, false, false, false,
5737 false, 0, 0, true, true, "tag.png");
5739 print "<div id=\"headlinesInnerContainer\" class=\"dashboard\">";
5740 print "<div>There is <b>666</b> unread articles in <b>666</b> feeds.</div>";
5745 print "]]></headlines>";
5746 print "<headlines-count value=\"0\"/>";
5747 print "<headlines-unread value=\"0\"/>";
5748 print "<disable-cache value=\"1\"/>";
5751 print "</articles>";
5754 function sanitize_article_content($text) {
5755 # we don't support CDATA sections in articles, they break our own escaping
5756 $text = preg_replace("/\[\[CDATA/", "", $text);
5757 $text = preg_replace("/\]\]\>/", "", $text);
5761 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5764 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5766 $result = db_query($link, "SELECT reg_exp,
5767 ttrss_filter_types.name AS name,
5768 ttrss_filter_actions.name AS action,
5771 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5774 owner_uid = $owner_uid AND
5775 ttrss_filter_types.id = filter_type AND
5776 ttrss_filter_actions.id = action_id AND
5777 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5779 while ($line = db_fetch_assoc($result)) {
5780 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5781 $filter["reg_exp"] = $line["reg_exp"];
5782 $filter["action"] = $line["action"];
5783 $filter["action_param"] = $line["action_param"];
5784 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5786 array_push($filters[$line["name"]], $filter);
5792 function get_score_pic($score) {
5794 return "score_high.png";
5795 } else if ($score > 0) {
5796 return "score_half_high.png";
5797 } else if ($score < -100) {
5798 return "score_low.png";
5799 } else if ($score < 0) {
5800 return "score_half_low.png";
5802 return "score_neutral.png";
5806 function rounded_table_start($classname, $header = " ") {
5807 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5808 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5809 print "<tr><td class='left'> </td><td class='content'>";
5812 function rounded_table_end($footer = " ") {
5813 print "</td><td class='right'> </td></tr>";
5814 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5818 function print_label_dlg_common_examples() {
5820 print __("Match ") . " ";
5822 /* print "<select name=\"label_andor\">";
5823 print "<option value=\"and\">AND</option>";
5824 print "<option value=\"or\">OR</option>";
5825 print "</select>"; */
5827 print "<select name=\"label_fields\" onchange=\"labelFieldsCheck(this)\">";
5828 print "<option value=\"unread\">".__("Unread articles")."</option>";
5829 print "<option value=\"updated\">".__("Updated articles")."</option>";
5830 print "<option value=\"kw_title\">".__("Title contains")."</option>";
5831 print "<option value=\"kw_content\">".__("Content contains")."</option>";
5832 print "<option value=\"scoreE\">".__("Score equals")."</option>";
5833 print "<option value=\"scoreG\">".__("Score is greater than")."</option>";
5834 print "<option value=\"scoreL\">".__("Score is less than")."</option>";
5835 print "<option value=\"newerH\">".__("Articles newer than X hours")."</option>";
5836 print "<option value=\"newerD\">".__("Articles newer than X days")."</option>";
5840 print "<input style=\"display : none\" name=\"label_fields_param\"
5843 print " <input type=\"submit\"
5844 onclick=\"return addLabelExample()\"
5845 value=\"".__("Add")."\">";
5848 function feed_has_icon($id) {
5849 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5852 function init_connection($link) {
5853 if (DB_TYPE
== "pgsql") {
5854 pg_query($link, "set client_encoding = 'UTF-8'");
5855 pg_set_client_encoding("UNICODE");
5856 pg_query($link, "set datestyle = 'european'");
5858 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5859 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5860 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);