3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if (!$owner_uid) return;
150 if (FORCE_ARTICLE_PURGE
== 0) {
151 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
154 $purge_unread = true;
155 $purge_interval = FORCE_ARTICLE_PURGE
;
158 if (!$purge_unread) $query_limit = " unread = false AND ";
160 if (DB_TYPE
== "pgsql") {
161 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
162 marked = false AND feed_id = '$feed_id' AND
163 (SELECT date_entered FROM ttrss_entries WHERE
164 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
166 $pg_version = get_pgsql_version($link);
168 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
170 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
171 ttrss_entries.id = ref_id AND
173 feed_id = '$feed_id' AND
175 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
179 $result = db_query($link, "DELETE FROM ttrss_user_entries
181 WHERE ttrss_entries.id = ref_id AND
183 feed_id = '$feed_id' AND
185 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
188 $rows = pg_affected_rows($result);
192 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
193 marked = false AND feed_id = '$feed_id' AND
194 (SELECT date_entered FROM ttrss_entries WHERE
195 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
197 $result = db_query($link, "DELETE FROM ttrss_user_entries
198 USING ttrss_user_entries, ttrss_entries
199 WHERE ttrss_entries.id = ref_id AND
201 feed_id = '$feed_id' AND
203 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
205 $rows = mysql_affected_rows($link);
209 ccache_update($link, $feed_id, $owner_uid);
212 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
214 } // function purge_feed
217 * Purge old posts from old feeds.
219 * @param mixed $link A database connection
220 * @param boolean $do_output Set to true to enable printed output, false by default.
221 * @param integer $limit The maximal number of removed posts.
225 function global_purge_old_posts($link, $do_output = false, $limit = false) {
227 $random_qpart = sql_random_function();
230 $limit_qpart = "LIMIT $limit";
235 $result = db_query($link,
236 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
237 ORDER BY $random_qpart $limit_qpart");
239 while ($line = db_fetch_assoc($result)) {
241 $feed_id = $line["id"];
242 $purge_interval = $line["purge_interval"];
243 $owner_uid = $line["owner_uid"];
245 if ($purge_interval == 0) {
247 $tmp_result = db_query($link,
248 "SELECT value FROM ttrss_user_prefs WHERE
249 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
251 if (db_num_rows($tmp_result) != 0) {
252 $purge_interval = db_fetch_result($tmp_result, 0, "value");
257 // print "Feed $feed_id: purge interval = $purge_interval\n";
260 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
261 purge_feed($link, $feed_id, $purge_interval, $do_output);
265 // purge orphaned posts in main content table
266 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
267 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
270 $rows = db_affected_rows($link, $result);
271 _debug("Purged $rows orphaned posts.");
274 } // function global_purge_old_posts
276 function feed_purge_interval($link, $feed_id) {
278 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
279 WHERE id = '$feed_id'");
281 if (db_num_rows($result) == 1) {
282 $purge_interval = db_fetch_result($result, 0, "purge_interval");
283 $owner_uid = db_fetch_result($result, 0, "owner_uid");
285 if ($purge_interval == 0) $purge_interval = get_pref($link,
286 'PURGE_OLD_DAYS', $owner_uid);
288 return $purge_interval;
295 function purge_old_posts($link) {
297 $user_id = $_SESSION["uid"];
299 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
300 WHERE owner_uid = '$user_id'");
302 while ($line = db_fetch_assoc($result)) {
304 $feed_id = $line["id"];
305 $purge_interval = $line["purge_interval"];
307 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
309 if ($purge_interval > 0) {
310 purge_feed($link, $feed_id, $purge_interval);
314 // purge orphaned posts in main content table
315 db_query($link, "DELETE FROM ttrss_entries WHERE
316 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
319 function get_feed_update_interval($link, $feed_id) {
320 $result = db_query($link, "SELECT owner_uid, update_interval FROM
321 ttrss_feeds WHERE id = '$feed_id'");
323 if (db_num_rows($result) == 1) {
324 $update_interval = db_fetch_result($result, 0, "update_interval");
325 $owner_uid = db_fetch_result($result, 0, "owner_uid");
327 if ($update_interval != 0) {
328 return $update_interval;
330 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
338 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
340 if (WEB_DEMO_MODE
) return;
343 $user_id = $_SESSION["uid"];
344 purge_old_posts($link);
347 // db_query($link, "BEGIN");
349 if (MAX_UPDATE_TIME
> 0) {
350 if (DB_TYPE
== "mysql") {
353 $q_order = "RANDOM()";
356 $q_order = "last_updated DESC";
359 $result = db_query($link, "SELECT feed_url,id,
360 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
361 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
366 while ($line = db_fetch_assoc($result)) {
367 $upd_intl = $line["update_interval"];
369 if (!$upd_intl ||
$upd_intl == 0) {
370 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
374 // Updates for this feed are disabled
378 if ($fetch ||
(!$line["last_updated"] ||
379 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
381 // print "<!-- feed: ".$line["feed_url"]." -->";
383 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
385 $upd_elapsed = time() - $upd_start;
387 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
393 // db_query($link, "COMMIT");
397 function fetch_file_contents($url) {
398 if (USE_CURL_FOR_ICONS
) {
399 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
401 $ch = curl_init($url);
402 $fp = fopen($tmpfile, "w");
405 curl_setopt($ch, CURLOPT_FILE
, $fp);
406 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
407 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
413 $contents = file_get_contents($tmpfile);
419 return file_get_contents($url);
425 * Try to determine the favicon URL for a feed.
426 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
427 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
429 * @param string $url A feed or page URL
431 * @return mixed The favicon URL, or false if none was found.
433 function get_favicon_url($url) {
435 if ($html = @fetch_file_contents
($url)) {
437 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
438 // Attempt to grab a favicon link from their webpage url
439 $linkUrl = html_entity_decode($matches[1]);
441 if (substr($linkUrl, 0, 1) == '/') {
442 $urlParts = parse_url($url);
443 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
444 } else if (substr($linkUrl, 0, 7) == 'http://') {
445 $faviconURL = $linkUrl;
446 } else if (substr($url, -1, 1) == '/') {
447 $faviconURL = $url.$linkUrl;
449 $faviconURL = $url.'/'.$linkUrl;
453 // If unsuccessful, attempt to "guess" the favicon location
454 $urlParts = parse_url($url);
455 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
459 // Run a test to see if what we have attempted to get actually exists.
460 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
465 } // function get_favicon_url
468 * Check if a link is a valid and working URL.
470 * @param mixed $link A URL to check
472 * @return boolean True if the URL is valid, false otherwise.
474 function url_validate($link) {
476 $url_parts = @parse_url
($link);
478 if ( empty( $url_parts["host"] ) )
481 if ( !empty( $url_parts["path"] ) ) {
482 $documentpath = $url_parts["path"];
487 if ( !empty( $url_parts["query"] ) )
488 $documentpath .= "?" . $url_parts["query"];
490 $host = $url_parts["host"];
491 $port = $url_parts["port"];
496 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
501 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
503 $http_response = fgets( $socket, 22 );
505 $responses = "/(200 OK)|(30[0-9] Moved)/";
506 if ( preg_match($responses, $http_response) ) {
513 } // function url_validate
515 function check_feed_favicon($site_url, $feed, $link) {
516 $favicon_url = get_favicon_url($site_url);
518 # print "FAVICON [$site_url]: $favicon_url\n";
522 $icon_file = ICONS_DIR
. "/$feed.ico";
524 if ($favicon_url && !file_exists($icon_file)) {
525 $contents = fetch_file_contents($favicon_url);
527 $fp = fopen($icon_file, "w");
530 fwrite($fp, $contents);
532 chmod($icon_file, 0644);
536 error_reporting(DEFAULT_ERROR_LEVEL
);
540 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
542 if (!$_GET["daemon"] && !$ignore_daemon) {
546 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
547 _debug("update_rss_feed: start");
550 if (!$ignore_daemon) {
552 if (DB_TYPE
== "pgsql") {
553 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
555 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
558 $result = db_query($link, "SELECT id,update_interval,auth_login,
559 auth_pass,cache_images,update_method
560 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
564 $result = db_query($link, "SELECT id,update_interval,auth_login,
565 auth_pass,cache_images,update_method,hidden
566 FROM ttrss_feeds WHERE id = '$feed'");
570 if (db_num_rows($result) == 0) {
571 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
572 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
577 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
578 $update_method = db_fetch_result($result, 0, "update_method");
580 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
581 WHERE id = '$feed'");
583 $auth_login = db_fetch_result($result, 0, "auth_login");
584 $auth_pass = db_fetch_result($result, 0, "auth_pass");
586 if (ALLOW_SELECT_UPDATE_METHOD
) {
587 if (ENABLE_SIMPLEPIE
) {
588 $use_simplepie = $update_method != 1;
590 $use_simplepie = $update_method == 2;
593 $use_simplepie = ENABLE_SIMPLEPIE
;
596 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
597 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
600 if (!$use_simplepie) {
601 $auth_login = urlencode($auth_login);
602 $auth_pass = urlencode($auth_pass);
605 $update_interval = db_fetch_result($result, 0, "update_interval");
606 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
608 if ($update_interval < 0) { return; }
610 $feed = db_escape_string($feed);
612 $fetch_url = $feed_url;
614 if ($auth_login && $auth_pass) {
615 $url_parts = array();
616 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
618 if ($url_parts[1] && $url_parts[2]) {
619 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
624 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
625 _debug("update_rss_feed: fetching [$fetch_url]...");
628 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
632 if (!$use_simplepie) {
633 $rss = fetch_rss($fetch_url);
635 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
636 mkdir(SIMPLEPIE_CACHE_DIR
);
639 $rss = new SimplePie();
640 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
641 # $rss->set_timeout(10);
642 $rss->set_feed_url($fetch_url);
643 $rss->set_output_encoding('UTF-8');
645 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
646 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
647 _debug("enabling image cache");
650 $rss->set_image_handler('./image.php', 'i');
653 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
654 _debug("feed update interval (sec): " .
655 get_feed_update_interval($link, $feed)*60);
658 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
659 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
660 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
668 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
669 _debug("update_rss_feed: fetch done, parsing...");
671 error_reporting (DEFAULT_ERROR_LEVEL
);
674 $feed = db_escape_string($feed);
676 if ($use_simplepie) {
677 $fetch_ok = !$rss->error();
684 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
685 _debug("update_rss_feed: processing feed data...");
688 // db_query($link, "BEGIN");
690 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
691 FROM ttrss_feeds WHERE id = '$feed'");
693 $registered_title = db_fetch_result($result, 0, "title");
694 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
695 $orig_site_url = db_fetch_result($result, 0, "site_url");
697 $owner_uid = db_fetch_result($result, 0, "owner_uid");
699 if ($use_simplepie) {
700 $site_url = $rss->get_link();
702 $site_url = $rss->channel
["link"];
705 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
706 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
707 _debug("update_rss_feed: checking favicon...");
710 check_feed_favicon($site_url, $feed, $link);
713 if (!$registered_title ||
$registered_title == "[Unknown]") {
715 if ($use_simplepie) {
716 $feed_title = db_escape_string($rss->get_title());
718 $feed_title = db_escape_string($rss->channel
["title"]);
721 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
722 _debug("update_rss_feed: registering title: $feed_title");
725 db_query($link, "UPDATE ttrss_feeds SET
726 title = '$feed_title' WHERE id = '$feed'");
729 // weird, weird Magpie
730 if (!$use_simplepie) {
731 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
734 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
735 db_query($link, "UPDATE ttrss_feeds SET
736 site_url = '$site_url' WHERE id = '$feed'");
739 // print "I: " . $rss->channel["image"]["url"];
741 if (!$use_simplepie) {
742 $icon_url = $rss->image
["url"];
744 $icon_url = $rss->get_image_url();
747 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
748 $icon_url = db_escape_string($icon_url);
749 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
752 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
753 _debug("update_rss_feed: loading filters...");
756 $filters = load_filters($link, $feed, $owner_uid);
758 if ($use_simplepie) {
759 $iterator = $rss->get_items();
761 $iterator = $rss->items
;
762 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
763 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
766 if (!is_array($iterator)) {
767 /* db_query($link, "UPDATE ttrss_feeds
768 SET last_error = 'Parse error: can\'t find any articles.'
769 WHERE id = '$feed'"); */
771 // clear any errors and mark feed as updated if fetched okay
772 // even if it's blank
774 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
775 _debug("update_rss_feed: entry iterator is not an array, no articles?");
778 db_query($link, "UPDATE ttrss_feeds
779 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
781 return; // no articles
784 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
785 _debug("update_rss_feed: processing articles...");
788 foreach ($iterator as $item) {
790 if ($_GET['xdebug']) {
795 if ($use_simplepie) {
796 $entry_guid = $item->get_id();
797 if (!$entry_guid) $entry_guid = $item->get_link();
798 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
802 $entry_guid = $item["id"];
804 if (!$entry_guid) $entry_guid = $item["guid"];
805 if (!$entry_guid) $entry_guid = $item["link"];
806 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
809 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
810 _debug("update_rss_feed: guid $entry_guid");
813 if (!$entry_guid) continue;
815 $entry_timestamp = "";
817 if ($use_simplepie) {
818 $entry_timestamp = strtotime($item->get_date());
820 $rss_2_date = $item['pubdate'];
821 $rss_1_date = $item['dc']['date'];
822 $atom_date = $item['issued'];
823 if (!$atom_date) $atom_date = $item['updated'];
825 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
826 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
827 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
830 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
831 $entry_timestamp = time();
832 $no_orig_date = 'true';
834 $no_orig_date = 'false';
837 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
839 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
840 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
843 if ($use_simplepie) {
844 $entry_title = $item->get_title();
846 $entry_title = trim(strip_tags($item["title"]));
849 if ($use_simplepie) {
850 $entry_link = $item->get_link();
852 // strange Magpie workaround
853 $entry_link = $item["link_"];
854 if (!$entry_link) $entry_link = $item["link"];
857 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
858 _debug("update_rss_feed: title $entry_title");
861 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
863 $entry_link = strip_tags($entry_link);
865 if ($use_simplepie) {
866 $entry_content = $item->get_content();
867 if (!$entry_content) $entry_content = $item->get_description();
869 $entry_content = $item["content:escaped"];
871 if (!$entry_content) $entry_content = $item["content:encoded"];
872 if (!$entry_content) $entry_content = $item["content"]["encoded"];
873 if (!$entry_content) $entry_content = $item["content"];
875 // Magpie bugs are getting ridiculous
876 if (trim($entry_content) == "Array") $entry_content = false;
878 if (!$entry_content) $entry_content = $item["atom_content"];
879 if (!$entry_content) $entry_content = $item["summary"];
881 if (!$entry_content ||
882 strlen($entry_content) < strlen($item["description"])) {
883 $entry_content = $item["description"];
887 if (is_array($entry_content)) {
888 $entry_content = $entry_content["encoded"];
889 if (!$entry_content) $entry_content = $entry_content["escaped"];
893 if ($_GET["xdebug"]) {
894 print "update_rss_feed: content: ";
895 print_r(htmlspecialchars($entry_content));
898 $entry_content_unescaped = $entry_content;
900 if ($use_simplepie) {
901 $entry_comments = strip_tags($item->data
["comments"]);
902 if ($item->get_author()) {
903 $entry_author_item = $item->get_author();
904 $entry_author = $entry_author_item->get_name();
905 if (!$entry_author) $entry_author = $entry_author_item->get_email();
907 $entry_author = db_escape_string($entry_author);
910 $entry_comments = strip_tags($item["comments"]);
912 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
914 if ($item['author']) {
916 if (is_array($item['author'])) {
918 if (!$entry_author) {
919 $entry_author = db_escape_string(strip_tags($item['author']['name']));
922 if (!$entry_author) {
923 $entry_author = db_escape_string(strip_tags($item['author']['email']));
927 if (!$entry_author) {
928 $entry_author = db_escape_string(strip_tags($item['author']));
933 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
935 $entry_guid = db_escape_string(strip_tags($entry_guid));
936 $entry_guid = mb_substr($entry_guid, 0, 250);
938 $result = db_query($link, "SELECT id FROM ttrss_entries
939 WHERE guid = '$entry_guid'");
941 $entry_content = db_escape_string($entry_content);
943 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
945 $entry_title = db_escape_string($entry_title);
946 $entry_link = db_escape_string($entry_link);
947 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
948 $entry_author = mb_substr($entry_author, 0, 250);
950 if ($use_simplepie) {
951 $num_comments = 0; #FIXME#
953 $num_comments = db_escape_string($item["slash"]["comments"]);
956 if (!$num_comments) $num_comments = 0;
958 // parse <category> entries into tags
960 if ($use_simplepie) {
962 $additional_tags = array();
963 $additional_tags_src = $item->get_categories();
965 if (is_array($additional_tags_src)) {
966 foreach ($additional_tags_src as $tobj) {
967 array_push($additional_tags, $tobj->get_term());
971 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
972 _debug("update_rss_feed: category tags:");
973 print_r($additional_tags);
978 $t_ctr = $item['category#'];
980 $additional_tags = false;
983 $additional_tags = false;
984 } else if ($t_ctr > 0) {
985 $additional_tags = array($item['category']);
987 if ($item['category@term']) {
988 array_push($additional_tags, $item['category@term']);
991 for ($i = 0; $i <= $t_ctr; $i++
) {
992 if ($item["category#$i"]) {
993 array_push($additional_tags, $item["category#$i"]);
996 if ($item["category#$i@term"]) {
997 array_push($additional_tags, $item["category#$i@term"]);
1002 // parse <dc:subject> elements
1004 $t_ctr = $item['dc']['subject#'];
1007 $additional_tags = array($item['dc']['subject']);
1009 for ($i = 0; $i <= $t_ctr; $i++
) {
1010 if ($item['dc']["subject#$i"]) {
1011 array_push($additional_tags, $item['dc']["subject#$i"]);
1019 $enclosures = array();
1021 if ($use_simplepie) {
1022 $encs = $item->get_enclosures();
1024 if (is_array($encs)) {
1025 foreach ($encs as $e) {
1027 $e->link
, $e->type
, $e->length
);
1029 array_push($enclosures, $e_item);
1036 $e_ctr = $item['enclosure#'];
1039 $e_item = array($item['enclosure@url'],
1040 $item['enclosure@type'],
1041 $item['enclosure@length']);
1043 array_push($enclosures, $e_item);
1045 for ($i = 0; $i <= $e_ctr; $i++
) {
1047 if ($item["enclosure#$i@url"]) {
1048 $e_item = array($item["enclosure#$i@url"],
1049 $item["enclosure#$i@type"],
1050 $item["enclosure#$i@length"]);
1051 array_push($enclosures, $e_item);
1057 // can there be many of those? yes -fox
1059 $m_ctr = $item['media']['content#'];
1062 $e_item = array($item['media']['content@url'],
1063 $item['media']['content@medium'],
1064 $item['media']['content@length']);
1066 array_push($enclosures, $e_item);
1068 for ($i = 0; $i <= $m_ctr; $i++
) {
1070 if ($item["media"]["content#$i@url"]) {
1071 $e_item = array($item["media"]["content#$i@url"],
1072 $item["media"]["content#$i@medium"],
1073 $item["media"]["content#$i@length"]);
1074 array_push($enclosures, $e_item);
1083 $entry_content = sanitize_article_content($entry_content);
1084 $entry_title = sanitize_article_content($entry_title);
1086 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1087 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1090 db_query($link, "BEGIN");
1092 if (db_num_rows($result) == 0) {
1094 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1095 _debug("update_rss_feed: base guid not found");
1098 // base post entry does not exist, create it
1100 $result = db_query($link,
1101 "INSERT INTO ttrss_entries
1117 '$entry_timestamp_fmt',
1126 // we keep encountering the entry in feeds, so we need to
1127 // update date_entered column so that we don't get horrible
1128 // dupes when the entry gets purged and reinserted again e.g.
1129 // in the case of SLOW SLOW OMG SLOW updating feeds
1131 $base_entry_id = db_fetch_result($result, 0, "id");
1133 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1134 WHERE id = '$base_entry_id'");
1137 // now it should exist, if not - bad luck then
1139 $result = db_query($link, "SELECT
1140 id,content_hash,no_orig_date,title,
1141 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1142 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1146 WHERE guid = '$entry_guid'");
1151 if (db_num_rows($result) == 1) {
1153 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1154 _debug("update_rss_feed: base guid found, checking for user record");
1157 // this will be used below in update handler
1158 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1159 $orig_title = db_fetch_result($result, 0, "title");
1160 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1161 $orig_date_entered = strtotime(db_fetch_result($result,
1162 0, "date_entered"));
1164 $ref_id = db_fetch_result($result, 0, "id");
1165 $entry_ref_id = $ref_id;
1167 // check for user post link to main table
1169 // do we allow duplicate posts with same GUID in different feeds?
1170 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1171 $dupcheck_qpart = "AND feed_id = '$feed'";
1173 $dupcheck_qpart = "";
1176 // error_reporting(0);
1178 $article_filters = get_article_filters($filters, $entry_title,
1179 $entry_content, $entry_link, $entry_timestamp);
1181 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1182 _debug("update_rss_feed: article filters: ");
1183 if (count($article_filters) != 0) {
1184 print_r($article_filters);
1188 if (find_article_filter($article_filters, "filter")) {
1189 db_query($link, "COMMIT"); // close transaction in progress
1193 // error_reporting (DEFAULT_ERROR_LEVEL);
1195 $score = calculate_article_score($article_filters);
1197 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1198 _debug("update_rss_feed: initial score: $score");
1201 $result = db_query($link,
1202 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1203 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1206 // okay it doesn't exist - create user entry
1207 if (db_num_rows($result) == 0) {
1209 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1210 _debug("update_rss_feed: user record not found, creating...");
1213 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1215 $last_read_qpart = 'NULL';
1218 $last_read_qpart = 'NOW()';
1221 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1227 if (find_article_filter($article_filters, 'publish')) {
1228 $published = 'true';
1230 $published = 'false';
1233 $result = db_query($link,
1234 "INSERT INTO ttrss_user_entries
1235 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1237 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1238 $last_read_qpart, $marked, $published, '$score')");
1240 $result = db_query($link,
1241 "SELECT int_id FROM ttrss_user_entries WHERE
1242 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1243 feed_id = '$feed' LIMIT 1");
1245 if (db_num_rows($result) == 1) {
1246 $entry_int_id = db_fetch_result($result, 0, "int_id");
1249 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1250 $entry_int_id = db_fetch_result($result, 0, "int_id");
1253 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1254 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1257 $post_needs_update = false;
1259 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1260 ($content_hash != $orig_content_hash)) {
1261 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1262 $post_needs_update = true;
1265 if (db_escape_string($orig_title) != $entry_title) {
1266 $post_needs_update = true;
1269 if ($orig_num_comments != $num_comments) {
1270 $post_needs_update = true;
1273 // this doesn't seem to be very reliable
1275 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1276 // $post_needs_update = true;
1279 // if post needs update, update it and mark all user entries
1280 // linking to this post as updated
1281 if ($post_needs_update) {
1283 if (defined('DAEMON_EXTENDED_DEBUG')) {
1284 _debug("update_rss_feed: post $entry_guid needs update...");
1287 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1289 db_query($link, "UPDATE ttrss_entries
1290 SET title = '$entry_title', content = '$entry_content',
1291 content_hash = '$content_hash',
1292 num_comments = '$num_comments'
1293 WHERE id = '$ref_id'");
1295 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1296 db_query($link, "UPDATE ttrss_user_entries
1297 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1299 db_query($link, "UPDATE ttrss_user_entries
1300 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1306 db_query($link, "COMMIT");
1308 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1309 _debug("update_rss_feed: assigning labels...");
1312 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1315 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1316 _debug("update_rss_feed: looking for enclosures...");
1319 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1320 print_r($enclosures);
1323 db_query($link, "BEGIN");
1325 foreach ($enclosures as $enc) {
1326 $enc_url = db_escape_string($enc[0]);
1327 $enc_type = db_escape_string($enc[1]);
1328 $enc_dur = db_escape_string($enc[2]);
1330 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1331 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1333 if (db_num_rows($result) == 0) {
1334 db_query($link, "INSERT INTO ttrss_enclosures
1335 (content_url, content_type, title, duration, post_id) VALUES
1336 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1340 db_query($link, "COMMIT");
1342 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1343 _debug("update_rss_feed: looking for tags...");
1347 // <a href="..." rel="tag">Xorg</a>, //
1351 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1352 $entry_content_unescaped, $entry_tags);
1354 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1355 print_r($entry_tags);
1356 print "<br/></p>"; */
1358 $entry_tags = $entry_tags[1];
1360 # check for manual tags
1362 $tag_filter = find_article_filter($article_filters, "tag");
1366 $manual_tags = trim_array(split(",", $tag_filter[1]));
1368 foreach ($manual_tags as $tag) {
1369 if (tag_is_valid($tag)) {
1370 array_push($entry_tags, $tag);
1375 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1376 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1378 if ($additional_tags && is_array($additional_tags)) {
1379 foreach ($additional_tags as $tag) {
1380 if (tag_is_valid($tag) &&
1381 array_search($tag, $boring_tags) === FALSE) {
1382 array_push($entry_tags, $tag);
1387 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1389 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1390 print_r($entry_tags);
1393 if (count($entry_tags) > 0) {
1395 db_query($link, "BEGIN");
1397 foreach ($entry_tags as $tag) {
1399 $tag = sanitize_tag($tag);
1400 $tag = db_escape_string($tag);
1402 if (!tag_is_valid($tag)) continue;
1404 $result = db_query($link, "SELECT id FROM ttrss_tags
1405 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1406 owner_uid = '$owner_uid' LIMIT 1");
1408 // print db_fetch_result($result, 0, "id");
1410 if ($result && db_num_rows($result) == 0) {
1412 db_query($link, "INSERT INTO ttrss_tags
1413 (owner_uid,tag_name,post_int_id)
1414 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1418 db_query($link, "COMMIT");
1421 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1422 _debug("update_rss_feed: article processed");
1427 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1428 _debug("update_rss_feed: updating counters cache...");
1431 // disabled, purge_feed() does that...
1432 //ccache_update($link, $feed, $owner_uid);
1435 purge_feed($link, $feed, 0);
1437 db_query($link, "UPDATE ttrss_feeds
1438 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1440 // db_query($link, "COMMIT");
1444 if ($use_simplepie) {
1445 $error_msg = mb_substr($rss->error(), 0, 250);
1447 $error_msg = mb_substr(magpie_error(), 0, 250);
1450 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1451 _debug("update_rss_feed: error fetching feed: $error_msg");
1454 $error_msg = db_escape_string($error_msg);
1457 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1458 last_updated = NOW() WHERE id = '$feed'");
1461 if ($use_simplepie) {
1465 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1466 _debug("update_rss_feed: done");
1471 function print_select($id, $default, $values, $attributes = "") {
1472 print "<select name=\"$id\" id=\"$id\" $attributes>";
1473 foreach ($values as $v) {
1479 print "<option$sel>$v</option>";
1484 function print_select_hash($id, $default, $values, $attributes = "") {
1485 print "<select name=\"$id\" id='$id' $attributes>";
1486 foreach (array_keys($values) as $v) {
1488 $sel = 'selected="selected"';
1492 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1498 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1501 if ($filters["title"]) {
1502 foreach ($filters["title"] as $filter) {
1503 $reg_exp = $filter["reg_exp"];
1504 $inverse = $filter["inverse"];
1505 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1506 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1508 array_push($matches, array($filter["action"], $filter["action_param"]));
1513 if ($filters["content"]) {
1514 foreach ($filters["content"] as $filter) {
1515 $reg_exp = $filter["reg_exp"];
1516 $inverse = $filter["inverse"];
1518 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1519 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1521 array_push($matches, array($filter["action"], $filter["action_param"]));
1526 if ($filters["both"]) {
1527 foreach ($filters["both"] as $filter) {
1528 $reg_exp = $filter["reg_exp"];
1529 $inverse = $filter["inverse"];
1532 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1533 array_push($matches, array($filter["action"], $filter["action_param"]));
1536 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1537 array_push($matches, array($filter["action"], $filter["action_param"]));
1543 if ($filters["link"]) {
1544 $reg_exp = $filter["reg_exp"];
1545 foreach ($filters["link"] as $filter) {
1546 $reg_exp = $filter["reg_exp"];
1547 $inverse = $filter["inverse"];
1549 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1550 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1552 array_push($matches, array($filter["action"], $filter["action_param"]));
1557 if ($filters["date"]) {
1558 $reg_exp = $filter["reg_exp"];
1559 foreach ($filters["date"] as $filter) {
1560 $date_modifier = $filter["filter_param"];
1561 $inverse = $filter["inverse"];
1562 $check_timestamp = strtotime($filter["reg_exp"]);
1564 # no-op when timestamp doesn't parse to prevent misfires
1566 if ($check_timestamp) {
1569 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1570 $date_modifier == "after" && $timestamp > $check_timestamp) {
1574 if ($inverse) $match_ok = !$match_ok;
1577 array_push($matches, array($filter["action"], $filter["action_param"]));
1586 function find_article_filter($filters, $filter_name) {
1587 foreach ($filters as $f) {
1588 if ($f[0] == $filter_name) {
1595 function calculate_article_score($filters) {
1598 foreach ($filters as $f) {
1599 if ($f[0] == "score") {
1606 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1607 foreach ($filters as $f) {
1608 if ($f[0] == "label") {
1609 label_add_article($link, $id, $f[1], $owner_uid);
1614 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1615 $rtl_content = false, $last_updated = false, $last_error = false) {
1617 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1618 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1620 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1624 $rtl_tag = "dir=\"rtl\"";
1626 $rtl_tag = "dir=\"ltr\"";
1629 $error_notify_msg = "";
1632 $link_title = "Error: $last_error ($last_updated)";
1633 $error_notify_msg = "(Error)";
1634 } else if ($last_updated) {
1635 $link_title = "Updated: $last_updated";
1638 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1639 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1641 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1642 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1646 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1649 $fctr_class = "class=\"feedCtrHasUnread\"";
1651 $fctr_class = "class=\"feedCtrNoUnread\"";
1654 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1655 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1657 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1658 $total = getFeedArticles($link, $feed_id);
1659 print "<div class=\"feedExtInfo\">
1660 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1667 function getmicrotime() {
1668 list($usec, $sec) = explode(" ",microtime());
1669 return ((float)$usec +
(float)$sec);
1672 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1673 foreach ($values as $v) {
1680 if ($v == $true_is) {
1681 $sel .= " value=\"1\"";
1683 $sel .= " value=\"0\"";
1686 print "<input class=\"noborder\"
1687 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1692 function initialize_user_prefs($link, $uid) {
1694 $uid = db_escape_string($uid);
1696 db_query($link, "BEGIN");
1698 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1700 $u_result = db_query($link, "SELECT pref_name
1701 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1703 $active_prefs = array();
1705 while ($line = db_fetch_assoc($u_result)) {
1706 array_push($active_prefs, $line["pref_name"]);
1709 while ($line = db_fetch_assoc($result)) {
1710 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1711 // print "adding " . $line["pref_name"] . "<br>";
1713 db_query($link, "INSERT INTO ttrss_user_prefs
1714 (owner_uid,pref_name,value) VALUES
1715 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1720 db_query($link, "COMMIT");
1724 function lookup_user_id($link, $user) {
1726 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1729 if (db_num_rows($result) == 1) {
1730 return db_fetch_result($result, 0, "id");
1736 function http_authenticate_user($link) {
1738 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1740 if (!$_SERVER["PHP_AUTH_USER"]) {
1742 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1743 header('HTTP/1.0 401 Unauthorized');
1747 $auth_result = authenticate_user($link,
1748 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1750 if (!$auth_result) {
1751 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1752 header('HTTP/1.0 401 Unauthorized');
1760 function authenticate_user($link, $login, $password, $force_auth = false) {
1762 if (!SINGLE_USER_MODE
) {
1764 $pwd_hash1 = encrypt_password($password);
1765 $pwd_hash2 = encrypt_password($password, $login);
1767 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1768 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1770 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1772 $query = "SELECT id,login,access_level,pwd_hash
1773 FROM ttrss_users WHERE
1777 $query = "SELECT id,login,access_level,pwd_hash
1778 FROM ttrss_users WHERE
1779 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1780 pwd_hash = '$pwd_hash2')";
1783 $result = db_query($link, $query);
1785 if (db_num_rows($result) == 1) {
1786 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1787 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1788 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1790 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1793 $user_theme = get_user_theme_path($link);
1795 $_SESSION["theme"] = $user_theme;
1796 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1797 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1799 initialize_user_prefs($link, $_SESSION["uid"]);
1808 $_SESSION["uid"] = 1;
1809 $_SESSION["name"] = "admin";
1811 $user_theme = get_user_theme_path($link);
1813 $_SESSION["theme"] = $user_theme;
1814 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1816 initialize_user_prefs($link, $_SESSION["uid"]);
1822 function make_password($length = 8) {
1825 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1829 while ($i < $length) {
1830 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1832 if (!strstr($password, $char)) {
1840 // this is called after user is created to initialize default feeds, labels
1843 // user preferences are checked on every login, not here
1845 function initialize_user($link, $uid) {
1847 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1848 VALUES ('$uid', 'All Articles')");
1850 db_query($link, "INSERT INTO ttrss_filters
1851 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1852 action_id, action_param, filter_param)
1853 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1855 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1856 values ('$uid', 'Tiny Tiny RSS: New Releases',
1857 'http://tt-rss.org/releases.rss')");
1859 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1860 values ('$uid', 'Tiny Tiny RSS: Forum',
1861 'http://tt-rss.org/forum/rss.php')");
1864 function logout_user() {
1866 if (isset($_COOKIE[session_name()])) {
1867 setcookie(session_name(), '', time()-42000, '/');
1871 function get_script_urlpath() {
1872 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1875 function validate_session($link) {
1876 if (SINGLE_USER_MODE
) {
1880 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1881 if ($_SESSION["ip_address"]) {
1882 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1883 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1889 if ($_SESSION["uid"]) {
1891 $result = db_query($link,
1892 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1894 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1896 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1901 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1903 //print_r($_SESSION);
1905 if (time() > $_SESSION["cookie_lifetime"]) {
1913 function login_sequence($link, $mobile = false) {
1914 if (!SINGLE_USER_MODE
) {
1916 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1917 $swu = db_escape_string($_REQUEST["swu"]);
1919 $_SESSION["prefs_cache"] = false;
1920 return authenticate_user($link, $swu, null, true);
1924 $login_action = $_POST["login_action"];
1926 # try to authenticate user if called from login form
1927 if ($login_action == "do_login") {
1928 $login = $_POST["login"];
1929 $password = $_POST["password"];
1930 $remember_me = $_POST["remember_me"];
1932 if (authenticate_user($link, $login, $password)) {
1933 $_POST["password"] = "";
1935 $_SESSION["language"] = $_POST["language"];
1936 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1938 header("Location: " . $_SERVER["REQUEST_URI"]);
1943 $_SESSION["login_error_msg"] = "Incorrect username or password";
1947 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1948 render_login_form($link, $mobile);
1951 /* bump login timestamp */
1952 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1955 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1956 setcookie("ttrss_lang", $_SESSION["language"],
1957 time() + SESSION_COOKIE_LIFETIME
);
1960 /* bump counters stamp since we're getting reloaded anyway */
1962 $_SESSION["get_all_counters_stamp"] = time();
1966 return authenticate_user($link, "admin", null);
1970 function truncate_string($str, $max_len) {
1971 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1972 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1978 function get_user_theme_path($link) {
1979 $result = db_query($link, "SELECT theme_path
1981 ttrss_themes,ttrss_users
1982 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1983 if (db_num_rows($result) != 0) {
1984 return db_fetch_result($result, 0, "theme_path");
1990 function smart_date_time($timestamp) {
1991 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1992 return date("G:i", $timestamp);
1993 } else if (date("Y", $timestamp) == date("Y")) {
1994 return date("M d, G:i", $timestamp);
1996 return date("Y/m/d, G:i", $timestamp);
2000 function smart_date($timestamp) {
2001 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2003 } else if (date("Y", $timestamp) == date("Y")) {
2004 return date("D m", $timestamp);
2006 return date("Y/m/d", $timestamp);
2010 function sql_bool_to_string($s) {
2011 if ($s == "t" ||
$s == "1") {
2018 function sql_bool_to_bool($s) {
2019 if ($s == "t" ||
$s == "1") {
2027 function toggleEvenOdd($a) {
2034 function sanity_check($link) {
2039 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2040 $schema_version = db_fetch_result($result, 0, "schema_version");
2042 if ($schema_version != SCHEMA_VERSION
) {
2046 if (DB_TYPE
== "mysql") {
2047 $result = db_query($link, "SELECT true", false);
2048 if (db_num_rows($result) != 1) {
2053 if (db_escape_string("testTEST") != "testTEST") {
2057 error_reporting (DEFAULT_ERROR_LEVEL
);
2059 if ($error_code != 0) {
2060 print_error_xml($error_code);
2067 function file_is_locked($filename) {
2068 if (function_exists('flock')) {
2070 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2071 error_reporting(DEFAULT_ERROR_LEVEL
);
2073 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2074 flock($fp, LOCK_UN
);
2084 return true; // consider the file always locked and skip the test
2087 function make_lockfile($filename) {
2088 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2090 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2097 function make_stampfile($filename) {
2098 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2100 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2101 fwrite($fp, time() . "\n");
2102 flock($fp, LOCK_UN
);
2110 function read_stampfile($filename) {
2113 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2114 error_reporting (DEFAULT_ERROR_LEVEL
);
2117 if (flock($fp, LOCK_EX
)) {
2118 $stamp = fgets($fp);
2119 flock($fp, LOCK_UN
);
2130 function sql_random_function() {
2131 if (DB_TYPE
== "mysql") {
2138 function catchup_feed($link, $feed, $cat_view) {
2140 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2145 $cat_qpart = "cat_id = '$feed'";
2147 $cat_qpart = "cat_id IS NULL";
2150 $tmp_result = db_query($link, "SELECT id
2151 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2154 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2156 $tmp_feed = $tmp_line["id"];
2158 db_query($link, "UPDATE ttrss_user_entries
2159 SET unread = false,last_read = NOW()
2160 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2163 } else if ($feed > 0) {
2165 $tmp_result = db_query($link, "SELECT id
2166 FROM ttrss_feeds WHERE parent_feed = '$feed'
2167 ORDER BY cat_id,title");
2169 $parent_ids = array();
2171 if (db_num_rows($tmp_result) > 0) {
2172 while ($p = db_fetch_assoc($tmp_result)) {
2173 array_push($parent_ids, "feed_id = " . $p["id"]);
2176 $children_qpart = implode(" OR ", $parent_ids);
2178 db_query($link, "UPDATE ttrss_user_entries
2179 SET unread = false,last_read = NOW()
2180 WHERE (feed_id = '$feed' OR $children_qpart)
2181 AND owner_uid = " . $_SESSION["uid"]);
2184 db_query($link, "UPDATE ttrss_user_entries
2185 SET unread = false,last_read = NOW()
2186 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2189 } else if ($feed < 0 && $feed > -10) { // special, like starred
2192 db_query($link, "UPDATE ttrss_user_entries
2193 SET unread = false,last_read = NOW()
2194 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2198 db_query($link, "UPDATE ttrss_user_entries
2199 SET unread = false,last_read = NOW()
2200 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2205 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2207 if (DB_TYPE
== "pgsql") {
2208 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2210 $match_part = "updated > DATE_SUB(NOW(),
2211 INTERVAL $intl HOUR) ";
2214 $result = db_query($link, "SELECT id FROM ttrss_entries,
2215 ttrss_user_entries WHERE $match_part AND
2217 ttrss_user_entries.ref_id = ttrss_entries.id AND
2218 owner_uid = ".$_SESSION["uid"]);
2220 $affected_ids = array();
2222 while ($line = db_fetch_assoc($result)) {
2223 array_push($affected_ids, $line["id"]);
2226 catchupArticlesById($link, $affected_ids, 0);
2230 db_query($link, "UPDATE ttrss_user_entries
2231 SET unread = false,last_read = NOW()
2232 WHERE owner_uid = ".$_SESSION["uid"]);
2235 } else if ($feed < -10) { // label
2237 $label_id = -$feed - 11;
2239 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2240 SET unread = false WHERE label_id = '$label_id' AND unread = true
2241 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2245 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2248 db_query($link, "BEGIN");
2250 $tag_name = db_escape_string($feed);
2252 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2253 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2255 while ($line = db_fetch_assoc($result)) {
2256 db_query($link, "UPDATE ttrss_user_entries SET
2257 unread = false, last_read = NOW()
2258 WHERE int_id = " . $line["post_int_id"]);
2260 db_query($link, "COMMIT");
2264 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2268 $cat_qpart = "cat_id = '$feed'";
2270 $cat_qpart = "cat_id IS NULL";
2273 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2274 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2276 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2277 $feed_url = $tmp_line["feed_url"];
2278 $feed_id = $tmp_line["id"];
2279 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2283 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2284 WHERE id = '$feed'");
2285 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2286 update_rss_feed($link, $feed_url, $feed, $force_update);
2290 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2292 if (!$omode) $omode = "flc";
2294 getGlobalCounters($link);
2296 if (strchr($omode, "l")) getLabelCounters($link);
2297 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2298 if (strchr($omode, "t")) getTagCounters($link);
2299 if (strchr($omode, "c")) {
2300 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2301 getCategoryCounters($link);
2306 function getCategoryCounters($link) {
2307 # two special categories are -1 and -2 (all virtuals; all labels)
2309 /* $ctr = getCategoryUnread($link, -1);
2311 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2313 $ctr = getCategoryUnread($link, -2);
2315 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2317 $age_qpart = getMaxAgeSubquery();
2319 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2320 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2321 WHERE ttrss_cat_counters_cache.feed_id = id AND
2322 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2324 while ($line = db_fetch_assoc($result)) {
2325 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2327 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2328 $line["unread"]."\"/>";
2331 /* Special case: NULL category doesn't actually exist in the DB */
2333 print "<counter type=\"category\" id=\"0\" counter=\"".
2334 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2338 function getCategoryUnread($link, $cat, $owner_uid = false) {
2340 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2345 $cat_query = "cat_id = '$cat'";
2347 $cat_query = "cat_id IS NULL";
2350 $age_qpart = getMaxAgeSubquery();
2352 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2354 AND owner_uid = " . $owner_uid);
2356 $cat_feeds = array();
2357 while ($line = db_fetch_assoc($result)) {
2358 array_push($cat_feeds, "feed_id = " . $line["id"]);
2361 if (count($cat_feeds) == 0) return 0;
2363 $match_part = implode(" OR ", $cat_feeds);
2365 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2366 FROM ttrss_user_entries,ttrss_entries
2367 WHERE unread = true AND ($match_part) AND id = ref_id
2368 AND $age_qpart AND owner_uid = " . $owner_uid);
2372 # this needs to be rewritten
2373 while ($line = db_fetch_assoc($result)) {
2374 $unread +
= $line["unread"];
2378 } else if ($cat == -1) {
2379 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2380 } else if ($cat == -2) {
2382 $result = db_query($link, "
2383 SELECT COUNT(unread) AS unread FROM
2384 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2385 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2386 ttrss_labels2.owner_uid = '$owner_uid'
2387 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2388 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2390 $unread = db_fetch_result($result, 0, "unread");
2397 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2398 if (DB_TYPE
== "pgsql") {
2399 return "ttrss_entries.date_entered >
2400 NOW() - INTERVAL '$days days'";
2402 return "ttrss_entries.date_entered >
2403 DATE_SUB(NOW(), INTERVAL $days DAY)";
2407 function getFeedUnread($link, $feed, $is_cat = false) {
2408 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2411 function getLabelUnread($link, $label_id, $owner_uid = false) {
2412 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2414 $result = db_query($link, "
2415 SELECT COUNT(unread) AS unread FROM
2416 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2417 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2418 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2419 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2420 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2422 if (db_num_rows($result) != 0) {
2423 return db_fetch_result($result, 0, "unread");
2429 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2430 $owner_uid = false) {
2432 $n_feed = sprintf("%d", $feed);
2434 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2437 $unread_qpart = "unread = true";
2439 $unread_qpart = "true";
2442 $age_qpart = getMaxAgeSubquery();
2445 return getCategoryUnread($link, $n_feed, $owner_uid);
2446 } else if ($n_feed == -1) {
2447 $match_part = "marked = true";
2448 } else if ($n_feed == -2) {
2449 $match_part = "published = true";
2450 } else if ($n_feed == -3) {
2451 $match_part = "unread = true";
2453 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2455 if (DB_TYPE
== "pgsql") {
2456 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2458 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2460 } else if ($n_feed == -4) {
2461 $match_part = "true";
2462 } else if ($n_feed > 0) {
2464 $result = db_query($link, "SELECT id FROM ttrss_feeds
2465 WHERE parent_feed = '$n_feed'
2467 AND owner_uid = " . $owner_uid);
2469 if (db_num_rows($result) > 0) {
2471 $linked_feeds = array();
2472 while ($line = db_fetch_assoc($result)) {
2473 array_push($linked_feeds, "feed_id = " . $line["id"]);
2476 array_push($linked_feeds, "feed_id = $n_feed");
2478 $match_part = implode(" OR ", $linked_feeds);
2480 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2481 FROM ttrss_user_entries,ttrss_entries
2482 WHERE $unread_qpart AND
2483 ttrss_user_entries.ref_id = ttrss_entries.id AND
2486 owner_uid = " . $owner_uid);
2490 # this needs to be rewritten
2491 while ($line = db_fetch_assoc($result)) {
2492 $unread +
= $line["unread"];
2498 $match_part = "feed_id = '$n_feed'";
2500 } else if ($feed < -10) {
2502 $label_id = -$feed - 11;
2504 return getLabelUnread($link, $label_id, $owner_uid);
2510 $result = db_query($link, "SELECT count(int_id) AS unread
2511 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2512 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2513 ttrss_user_entries.ref_id = ttrss_entries.id AND
2514 ttrss_feeds.hidden = false AND
2516 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2520 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2521 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2522 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2523 AND $unread_qpart AND $age_qpart AND
2524 ttrss_tags.owner_uid = " . $owner_uid);
2527 $unread = db_fetch_result($result, 0, "unread");
2532 function getGlobalUnread($link, $user_id = false) {
2535 $user_id = $_SESSION["uid"];
2538 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2539 WHERE owner_uid = '$user_id' AND feed_id > 0");
2541 $c_id = db_fetch_result($result, 0, "c_id");
2546 function getGlobalCounters($link, $global_unread = -1) {
2547 if ($global_unread == -1) {
2548 $global_unread = getGlobalUnread($link);
2550 print "<counter type=\"global\" id='global-unread'
2551 counter='$global_unread'/>";
2553 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2554 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2556 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2558 print "<counter type=\"global\" id='subscribed-feeds'
2559 counter='$subscribed_feeds'/>";
2563 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2566 if (!$_SESSION["tctr_last_value"]) {
2567 $_SESSION["tctr_last_value"] = array();
2571 $old_counters = $_SESSION["tctr_last_value"];
2573 $tctrs_modified = false;
2575 $age_qpart = getMaxAgeSubquery();
2577 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2578 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2579 AND ref_id = id AND $age_qpart
2580 AND unread = true)) AS count FROM ttrss_tags
2581 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2582 ORDER BY count DESC LIMIT 55");
2586 while ($line = db_fetch_assoc($result)) {
2587 $tags[$line["tag_name"]] +
= $line["count"];
2590 foreach (array_keys($tags) as $tag) {
2591 $unread = $tags[$tag];
2593 $tag = htmlspecialchars($tag);
2595 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2596 $old_counters[$tag] = $unread;
2597 $tctrs_modified = true;
2598 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2603 if ($smart_mode && $tctrs_modified) {
2604 $_SESSION["tctr_last_value"] = $old_counters;
2609 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2611 $age_qpart = getMaxAgeSubquery();
2614 if (!$_SESSION["lctr_last_value"]) {
2615 $_SESSION["lctr_last_value"] = array();
2621 for ($i = -1; $i >= -4; $i--) {
2623 $count = getFeedUnread($link, $i);
2627 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2628 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2633 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2635 $ret_arr[$i]["counter"] = $count;
2636 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2641 $old_counters = $_SESSION["lctr_last_value"];
2642 $lctrs_modified = false;
2645 $owner_uid = $_SESSION["uid"];
2647 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2648 WHERE owner_uid = '$owner_uid'");
2650 while ($line = db_fetch_assoc($result)) {
2652 $id = -$line["id"] - 11;
2654 $label_name = $line["caption"];
2655 $count = getFeedUnread($link, $id);
2657 if (!$smart_mode ||
$old_counters[$id] != $count) {
2658 $old_counters[$id] = $count;
2659 $lctrs_modified = true;
2662 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2663 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2668 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2670 $ret_arr[$id]["counter"] = $count;
2671 $ret_arr[$id]["description"] = $label_name;
2675 error_reporting (DEFAULT_ERROR_LEVEL
);
2678 if ($smart_mode && $lctrs_modified) {
2679 $_SESSION["lctr_last_value"] = $old_counters;
2685 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2687 $age_qpart = getMaxAgeSubquery();
2690 if (!$_SESSION["fctr_last_value"]) {
2691 $_SESSION["fctr_last_value"] = array();
2695 $old_counters = $_SESSION["fctr_last_value"];
2697 $query = "SELECT ttrss_feeds.id,
2699 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2700 last_error, value AS count
2701 FROM ttrss_feeds, ttrss_counters_cache
2702 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2703 AND parent_feed IS NULL
2704 AND ttrss_counters_cache.feed_id = id";
2706 $result = db_query($link, $query);
2707 $fctrs_modified = false;
2709 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2711 while ($line = db_fetch_assoc($result)) {
2714 $count = $line["count"];
2715 $last_error = htmlspecialchars($line["last_error"]);
2717 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2718 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2720 $last_updated = date($short_date, strtotime($line["last_updated"]));
2723 $last_updated = htmlspecialchars($last_updated);
2725 $has_img = feed_has_icon($id);
2727 $tmp_result = db_query($link,
2728 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2729 WHERE parent_feed = '$id' AND feed_id = id");
2731 $count +
= db_fetch_result($tmp_result, 0, "unread");
2733 if (!$smart_mode ||
$old_counters[$id] != $count) {
2734 $old_counters[$id] = $count;
2735 $fctrs_modified = true;
2738 $error_part = "error=\"$last_error\"";
2744 $has_img_part = "hi=\"$has_img\"";
2749 if ($active_feed && $id == $active_feed) {
2750 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2752 $has_title_part = "";
2755 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2756 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2759 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2763 if ($smart_mode && $fctrs_modified) {
2764 $_SESSION["fctr_last_value"] = $old_counters;
2768 function get_script_dt_add() {
2769 if (strpos(VERSION
, ".99") === false) {
2776 function get_pgsql_version($link) {
2777 $result = db_query($link, "SELECT version() AS version");
2778 $version = split(" ", db_fetch_result($result, 0, "version"));
2782 function print_error_xml($code, $add_msg = "") {
2785 $error_msg = $ERRORS[$code];
2788 $error_msg = "$error_msg; $add_msg";
2791 print "<rpc-reply>";
2792 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2793 print "</rpc-reply>";
2796 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2797 $auth_login = '', $auth_pass = '') {
2799 # check for feed:http://url
2800 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2802 # check for feed://URL
2803 if (strpos($feed_link, "//") === 0) {
2804 $feed_link = "http:$feed_link";
2807 if ($feed_link == "") return;
2809 if ($cat_id == "0" ||
!$cat_id) {
2810 $cat_qpart = "NULL";
2812 $cat_qpart = "'$cat_id'";
2815 $result = db_query($link,
2816 "SELECT id FROM ttrss_feeds
2817 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2819 if (db_num_rows($result) == 0) {
2821 $result = db_query($link,
2822 "INSERT INTO ttrss_feeds
2823 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2824 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2825 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2827 $result = db_query($link,
2828 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2829 AND owner_uid = " . $_SESSION["uid"]);
2831 $feed_id = db_fetch_result($result, 0, "id");
2834 update_rss_feed($link, $feed_link, $feed_id, true);
2843 function print_feed_select($link, $id, $default_id = "",
2844 $attributes = "", $include_all_feeds = true) {
2846 print "<select id=\"$id\" name=\"$id\" $attributes>";
2847 if ($include_all_feeds) {
2848 print "<option value=\"0\">".__('All feeds')."</option>";
2851 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2852 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2854 if (db_num_rows($result) > 0 && $include_all_feeds) {
2855 print "<option disabled>--------</option>";
2858 while ($line = db_fetch_assoc($result)) {
2859 if ($line["id"] == $default_id) {
2860 $is_selected = "selected";
2864 printf("<option $is_selected value='%d'>%s</option>",
2865 $line["id"], htmlspecialchars($line["title"]));
2871 function print_feed_cat_select($link, $id, $default_id = "",
2872 $attributes = "", $include_all_cats = true) {
2874 print "<select id=\"$id\" name=\"$id\" $attributes>";
2876 if ($include_all_cats) {
2877 print "<option value=\"0\">".__('Uncategorized')."</option>";
2880 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2881 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2883 if (db_num_rows($result) > 0 && $include_all_cats) {
2884 print "<option disabled>--------</option>";
2887 while ($line = db_fetch_assoc($result)) {
2888 if ($line["id"] == $default_id) {
2889 $is_selected = "selected";
2893 printf("<option $is_selected value='%d'>%s</option>",
2894 $line["id"], htmlspecialchars($line["title"]));
2900 function checkbox_to_sql_bool($val) {
2901 return ($val == "on") ?
"true" : "false";
2904 function getFeedCatTitle($link, $id) {
2906 return __("Special");
2907 } else if ($id < -10) {
2908 return __("Labels");
2909 } else if ($id > 0) {
2910 $result = db_query($link, "SELECT ttrss_feed_categories.title
2911 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2912 cat_id = ttrss_feed_categories.id");
2913 if (db_num_rows($result) == 1) {
2914 return db_fetch_result($result, 0, "title");
2916 return __("Uncategorized");
2919 return "getFeedCatTitle($id) failed";
2924 function getFeedTitle($link, $id) {
2926 return __("Starred articles");
2927 } else if ($id == -2) {
2928 return __("Published articles");
2929 } else if ($id == -3) {
2930 return __("Fresh articles");
2931 } else if ($id == -4) {
2932 return __("All articles");
2933 } else if ($id < -10) {
2934 $label_id = -$id - 11;
2935 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2936 if (db_num_rows($result) == 1) {
2937 return db_fetch_result($result, 0, "caption");
2939 return "Unknown label ($label_id)";
2942 } else if ($id > 0) {
2943 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2944 if (db_num_rows($result) == 1) {
2945 return db_fetch_result($result, 0, "title");
2947 return "Unknown feed ($id)";
2950 return "getFeedTitle($id) failed";
2955 function get_session_cookie_name() {
2956 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2959 function print_init_params($link) {
2960 print "<init-params>";
2961 if ($_SESSION["stored-params"]) {
2962 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2964 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2965 print "<param key=\"$key\" value=\"$value\"/>";
2970 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2971 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2972 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2973 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2975 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2976 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2978 print "<param key=\"hide_read_feeds\" value=\"" .
2979 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2981 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2982 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2984 print "<param key=\"confirm_feed_catchup\" value=\"" .
2985 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2987 print "<param key=\"cdm_auto_catchup\" value=\"" .
2988 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2990 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2992 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2994 print "<param key=\"default_view_mode\" value=\"" .
2995 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2997 print "<param key=\"default_view_limit\" value=\"" .
2998 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3000 print "<param key=\"default_view_order_by\" value=\"" .
3001 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3003 print "<param key=\"prefs_active_tab\" value=\"" .
3004 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3006 print "<param key=\"infobox_disable_overlay\" value=\"" .
3007 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3009 print "<param key=\"icons_location\" value=\"" .
3012 print "<param key=\"hide_read_shows_special\" value=\"" .
3013 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3015 print "<param key=\"hide_feedlist\" value=\"" .
3016 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3018 print "<param key=\"bw_limit\" value=\"".
3019 (int) $_SESSION["bw_limit"]."\"/>";
3021 // print "<param key=\"sync_counters\" value=\"" .
3022 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3024 print "<param key=\"sync_counters\" value=\"1\"/>";
3026 print "</init-params>";
3029 function print_runtime_info($link) {
3030 print "<runtime-info>";
3032 if (ENABLE_UPDATE_DAEMON
) {
3033 print "<param key=\"daemon_is_running\" value=\"".
3034 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3036 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3038 $stamp = (int)read_stampfile("update_daemon.stamp");
3040 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3043 $stamp_delta = time() - $stamp;
3045 if ($stamp_delta > 1800) {
3049 $_SESSION["daemon_stamp_check"] = time();
3052 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3054 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3056 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3061 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3063 if ($_SESSION["last_version_check"] +
86400 < time()) {
3064 $new_version_details = check_for_update($link);
3066 print "<param key=\"new_version_available\" value=\"".
3067 sprintf("%d", $new_version_details != ""). "\"/>";
3069 $_SESSION["last_version_check"] = time();
3073 // print "<param key=\"new_version_available\" value=\"1\"/>";
3075 print "</runtime-info>";
3078 function getSearchSql($search, $match_on) {
3080 $search_query_part = "";
3082 $keywords = split(" ", $search);
3083 $query_keywords = array();
3085 if ($match_on == "both") {
3087 foreach ($keywords as $k) {
3088 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3089 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3092 $search_query_part = implode("AND", $query_keywords) . " AND ";
3094 } else if ($match_on == "title") {
3096 foreach ($keywords as $k) {
3097 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3100 $search_query_part = implode("AND", $query_keywords) . " AND ";
3102 } else if ($match_on == "content") {
3104 foreach ($keywords as $k) {
3105 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3109 $search_query_part = implode("AND", $query_keywords);
3111 return $search_query_part;
3114 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3116 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3120 $search_query_part = getSearchSql($search, $match_on);
3121 $search_query_part .= " AND ";
3124 $search_query_part = "";
3127 $view_query_part = "";
3129 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3131 $view_query_part = " ";
3132 } else if ($feed != -1) {
3133 $unread = getFeedUnread($link, $feed, $cat_view);
3135 $view_query_part = " unread = true AND ";
3140 if ($view_mode == "marked") {
3141 $view_query_part = " marked = true AND ";
3144 if ($view_mode == "unread") {
3145 $view_query_part = " unread = true AND ";
3148 if ($view_mode == "updated") {
3149 $view_query_part = " (last_read is null and unread = false) AND ";
3153 $limit_query_part = "LIMIT " . $limit;
3156 $vfeed_query_part = "";
3158 // override query strategy and enable feed display when searching globally
3159 if ($search && $search_mode == "all_feeds") {
3160 $query_strategy_part = "ttrss_entries.id > 0";
3161 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3162 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3163 $query_strategy_part = "ttrss_entries.id > 0";
3164 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3165 id = feed_id) as feed_title,";
3166 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3168 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3170 $tmp_result = false;
3173 $tmp_result = db_query($link, "SELECT id
3174 FROM ttrss_feeds WHERE cat_id = '$feed'");
3176 $tmp_result = db_query($link, "SELECT id
3177 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3178 WHERE id = '$feed') AND id != '$feed'");
3181 $cat_siblings = array();
3183 if (db_num_rows($tmp_result) > 0) {
3184 while ($p = db_fetch_assoc($tmp_result)) {
3185 array_push($cat_siblings, "feed_id = " . $p["id"]);
3188 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3189 $feed, implode(" OR ", $cat_siblings));
3192 $query_strategy_part = "ttrss_entries.id > 0";
3195 } else if ($feed >= 0) {
3200 $query_strategy_part = "cat_id = '$feed'";
3202 $query_strategy_part = "cat_id IS NULL";
3205 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3208 $tmp_result = db_query($link, "SELECT id
3209 FROM ttrss_feeds WHERE parent_feed = '$feed'
3210 ORDER BY cat_id,title");
3212 $parent_ids = array();
3214 if (db_num_rows($tmp_result) > 0) {
3215 while ($p = db_fetch_assoc($tmp_result)) {
3216 array_push($parent_ids, "feed_id = " . $p["id"]);
3219 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3220 $feed, implode(" OR ", $parent_ids));
3222 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3224 $query_strategy_part = "feed_id = '$feed'";
3227 } else if ($feed == -1) { // starred virtual feed
3228 $query_strategy_part = "marked = true";
3229 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3230 } else if ($feed == -2) { // published virtual feed OR labels category
3233 $query_strategy_part = "published = true";
3234 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3236 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3238 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3240 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3241 ttrss_user_labels2.article_id = ref_id";
3245 } else if ($feed == -3) { // fresh virtual feed
3246 $query_strategy_part = "unread = true";
3248 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3250 if (DB_TYPE
== "pgsql") {
3251 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3253 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3256 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3257 } else if ($feed == -4) { // all articles virtual feed
3258 $query_strategy_part = "true";
3259 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3260 } else if ($feed <= -10) { // labels
3261 $label_id = -$feed - 11;
3263 $query_strategy_part = "label_id = '$label_id' AND
3264 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3265 ttrss_user_labels2.article_id = ref_id";
3267 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3268 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3271 $query_strategy_part = "id > 0"; // dumb
3274 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3275 $order_by = "updated";
3277 $order_by = "updated DESC";
3280 if ($view_mode != "noscores") {
3281 $order_by = "score DESC, $order_by";
3284 if ($override_order) {
3285 $order_by = $override_order;
3290 if ($search && $search_mode == "all_feeds") {
3291 $feed_title = __("Search results")." ($search)";
3292 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3293 $feed_title = __("Search results")." ($search, $feed)";
3294 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3295 $feed_title = $feed;
3296 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3301 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3302 WHERE id = '$feed' AND owner_uid = $owner_uid");
3303 $feed_title = db_fetch_result($result, 0, "title");
3305 $feed_title = __("Uncategorized");
3309 $feed_title = __("Searched for")." $search ($feed_title)";
3314 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3315 WHERE id = '$feed' AND owner_uid = $owner_uid");
3317 $feed_title = db_fetch_result($result, 0, "title");
3318 $feed_site_url = db_fetch_result($result, 0, "site_url");
3319 $last_error = db_fetch_result($result, 0, "last_error");
3322 $feed_title = __("Searched for") . " $search ($feed_title)";
3326 } else if ($feed == -1) {
3327 $feed_title = __("Starred articles");
3328 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3329 } else if ($feed == -2) {
3331 $feed_title = __("Published articles");
3332 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3334 $feed_title = __("Labels");
3336 } else if ($feed == -3) {
3337 $feed_title = __("Fresh articles");
3338 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3339 } else if ($feed == -4) {
3340 $feed_title = __("All articles");
3341 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3342 } else if ($feed < -10) {
3343 $label_id = -$feed - 11;
3344 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3345 WHERE id = '$label_id'");
3346 $feed_title = db_fetch_result($result, 0, "caption");
3349 $feed_title = __("Searched for") . " $search ($feed_title)";
3355 if ($feed < -10) error_reporting (0);
3357 $content_query_part = "content as content_preview,";
3359 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3362 $feed_kind = "Feeds";
3364 $feed_kind = "Labels";
3367 if ($limit_query_part) {
3368 $offset_query_part = "OFFSET $offset";
3371 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3372 if (!$override_order) {
3373 $order_by = "ttrss_feeds.title, $order_by";
3376 // Special output for Fresh feed
3378 /* if ($feed == -3) {
3379 $group_limit_part = "(select count(*) from
3380 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3381 t1.ref_id = t2.id and t1.owner_uid = 2 and
3382 t1.feed_id = ttrss_user_entries.feed_id and
3383 t2.updated > ttrss_entries.updated) <= 5 AND";
3387 $query = "SELECT DISTINCT
3389 ttrss_entries.id,ttrss_entries.title,
3391 unread,feed_id,marked,published,link,last_read,
3392 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3395 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3398 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3401 ttrss_feeds.hidden = false AND
3402 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3403 ttrss_user_entries.ref_id = ttrss_entries.id AND
3404 ttrss_user_entries.owner_uid = '$owner_uid' AND
3407 $query_strategy_part ORDER BY $order_by
3408 $limit_query_part $offset_query_part";
3410 if ($_GET["debug"]) print $query;
3412 $result = db_query($link, $query);
3417 $feed_kind = "Tags";
3419 $result = db_query($link, "SELECT
3421 ttrss_entries.id as id,title,
3424 marked,link,last_read,
3425 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3428 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3431 ttrss_entries,ttrss_user_entries,ttrss_tags
3433 ref_id = ttrss_entries.id AND
3434 ttrss_user_entries.owner_uid = '$owner_uid' AND
3435 post_int_id = int_id AND tag_name = '$feed' AND
3438 $query_strategy_part ORDER BY $order_by
3439 $limit_query_part");
3442 return array($result, $feed_title, $feed_site_url, $last_error);
3446 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3447 $limit, $search, $search_mode, $match_on) {
3449 if (!$limit) $limit = 30;
3451 $qfh_ret = queryFeedHeadlines($link, $feed,
3452 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3455 $result = $qfh_ret[0];
3456 $feed_title = htmlspecialchars($qfh_ret[1]);
3457 $feed_site_url = $qfh_ret[2];
3458 $last_error = $qfh_ret[3];
3460 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3462 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3463 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3464 <rss version=\"2.0\">
3466 <title>$feed_title</title>
3467 <link>$feed_site_url</link>
3468 <description>Feed generated by Tiny Tiny RSS</description>";
3470 while ($line = db_fetch_assoc($result)) {
3472 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3473 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3475 $tags = get_article_tags($link, $line["id"], $owner_uid);
3477 foreach ($tags as $tag) {
3478 print "<category>" . htmlspecialchars($tag) . "</category>";
3481 $rfc822_date = date('r', strtotime($line["updated"]));
3483 print "<pubDate>$rfc822_date</pubDate>";
3486 htmlspecialchars($line["title"]) . "</title>";
3488 print "<description><![CDATA[" .
3489 $line["content_preview"] . "]]></description>";
3494 print "</channel></rss>";
3498 function getCategoryTitle($link, $cat_id) {
3500 if ($cat_id == -1) {
3501 return __("Special");
3502 } else if ($cat_id == -2) {
3503 return __("Labels");
3506 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3509 if (db_num_rows($result) == 1) {
3510 return db_fetch_result($result, 0, "title");
3512 return "Uncategorized";
3517 // http://ru2.php.net/strip-tags
3519 function strip_tags_long($textstring, $allowed){
3520 while($textstring != strip_tags($textstring, $allowed))
3522 while (strlen($textstring) != 0)
3524 if (strlen($textstring) > 1024) {
3527 $otherlen = strlen($textstring);
3529 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3530 $safetext .= $temptext;
3531 $textstring = substr_replace($textstring,'',0,$otherlen);
3533 $textstring = $safetext;
3539 function sanitize_rss($link, $str, $force_strip_tags = false) {
3542 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3544 $res = strip_tags_long($res,
3545 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3547 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3548 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3551 if (get_pref($link, "STRIP_IMAGES")) {
3553 $res = preg_replace('/<img[^>]+>/is', '', $res);
3561 * Send by mail a digest of last articles.
3563 * @param mixed $link The database connection.
3564 * @param integer $limit The maximum number of articles by digest.
3565 * @return boolean Return false if digests are not enabled.
3567 function send_headlines_digests($link, $limit = 100) {
3569 if (!DIGEST_ENABLE
) return false;
3571 $user_limit = DIGEST_EMAIL_LIMIT
;
3574 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3576 if (DB_TYPE
== "pgsql") {
3577 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3578 } else if (DB_TYPE
== "mysql") {
3579 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3582 $result = db_query($link, "SELECT id,email FROM ttrss_users
3583 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3585 while ($line = db_fetch_assoc($result)) {
3587 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3588 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3590 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3592 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3593 $digest = $tuple[0];
3594 $headlines_count = $tuple[1];
3595 $affected_ids = $tuple[2];
3596 $digest_text = $tuple[3];
3598 if ($headlines_count > 0) {
3600 $mail = new PHPMailer();
3602 $mail->PluginDir
= "phpmailer/";
3603 $mail->SetLanguage("en", "phpmailer/language/");
3605 $mail->CharSet
= "UTF-8";
3607 $mail->From
= DIGEST_FROM_ADDRESS
;
3608 $mail->FromName
= DIGEST_FROM_NAME
;
3609 $mail->AddAddress($line["email"], $line["login"]);
3611 if (DIGEST_SMTP_HOST
) {
3612 $mail->Host
= DIGEST_SMTP_HOST
;
3613 $mail->Mailer
= "smtp";
3614 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3615 $mail->Username
= DIGEST_SMTP_LOGIN
;
3616 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3619 $mail->IsHTML(true);
3620 $mail->Subject
= DIGEST_SUBJECT
;
3621 $mail->Body
= $digest;
3622 $mail->AltBody
= $digest_text;
3624 $rc = $mail->Send();
3626 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3630 if ($rc && $do_catchup) {
3631 print "Marking affected articles as read...\n";
3632 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3635 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3636 WHERE id = " . $line["id"]);
3638 print "No headlines\n";
3643 print "All done.\n";
3647 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3649 require_once "MiniTemplator.class.php";
3651 $tpl = new MiniTemplator
;
3652 $tpl_t = new MiniTemplator
;
3654 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3655 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3657 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3658 $tpl->setVariable('CUR_TIME', date('G:i'));
3660 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3661 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3663 $affected_ids = array();
3665 if (DB_TYPE
== "pgsql") {
3666 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3667 } else if (DB_TYPE
== "mysql") {
3668 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3671 $result = db_query($link, "SELECT ttrss_entries.title,
3672 ttrss_feeds.title AS feed_title,
3674 ttrss_user_entries.ref_id,
3676 SUBSTRING(content, 1, 120) AS excerpt,
3677 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3679 ttrss_user_entries,ttrss_entries,ttrss_feeds
3681 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3682 AND include_in_digest = true
3685 AND ttrss_user_entries.owner_uid = $user_id
3687 ORDER BY ttrss_feeds.title, date_entered DESC
3690 $cur_feed_title = "";
3692 $headlines_count = db_num_rows($result);
3694 $headlines = array();
3696 while ($line = db_fetch_assoc($result)) {
3697 array_push($headlines, $line);
3700 for ($i = 0; $i < sizeof($headlines); $i++
) {
3702 $line = $headlines[$i];
3704 array_push($affected_ids, $line["ref_id"]);
3706 $updated = smart_date_time(strtotime($line["last_updated"]));
3708 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3709 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3710 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3711 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3712 $tpl->setVariable('ARTICLE_EXCERPT',
3713 truncate_string(strip_tags($line["excerpt"]), 100));
3715 $tpl->addBlock('article');
3717 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3718 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3719 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3720 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3721 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3722 // truncate_string(strip_tags($line["excerpt"]), 100));
3724 $tpl_t->addBlock('article');
3726 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3727 $tpl->addBlock('feed');
3728 $tpl_t->addBlock('feed');
3733 $tpl->addBlock('digest');
3734 $tpl->generateOutputToString($tmp);
3736 $tpl_t->addBlock('digest');
3737 $tpl_t->generateOutputToString($tmp_t);
3739 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3742 function check_for_update($link, $brief_fmt = true) {
3743 $releases_feed = "http://tt-rss.org/releases.rss";
3745 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3750 if (ENABLE_SIMPLEPIE
) {
3751 $rss = new SimplePie();
3752 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3753 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3754 $rss->set_feed_url($fetch_url);
3755 $rss->set_output_encoding('UTF-8');
3758 $rss = fetch_rss($releases_feed);
3760 error_reporting (DEFAULT_ERROR_LEVEL
);
3764 if (ENABLE_SIMPLEPIE
) {
3765 $items = $rss->get_items();
3767 $items = $rss->items
;
3769 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3770 if (!$items ||
!is_array($items)) $items = $rss;
3773 if (!is_array($items) ||
count($items) == 0) {
3777 $latest_item = $items[0];
3779 if (ENABLE_SIMPLEPIE
) {
3780 $last_title = $latest_item->get_title();
3782 $last_title = $latest_item["title"];
3785 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3787 if (ENABLE_SIMPLEPIE
) {
3788 $release_url = sanitize_rss($link, $latest_item->get_link());
3789 $content = sanitize_rss($link, $latest_item->get_description());
3791 $release_url = sanitize_rss($link, $latest_item["link"]);
3792 $content = sanitize_rss($link, $latest_item["description"]);
3795 if (version_compare(VERSION
, $latest_version) == -1) {
3797 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3798 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3799 <div id=\"milestoneDetails\">$content</div>");
3801 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3802 <div class='milestoneDetails'>$content</div>
3803 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3804 download and update information.";
3811 function markArticlesById($link, $ids, $cmode) {
3815 foreach ($ids as $id) {
3816 array_push($tmp_ids, "ref_id = '$id'");
3819 $ids_qpart = join(" OR ", $tmp_ids);
3822 db_query($link, "UPDATE ttrss_user_entries SET
3823 marked = false,last_read = NOW()
3824 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3825 } else if ($cmode == 1) {
3826 db_query($link, "UPDATE ttrss_user_entries SET
3828 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3830 db_query($link, "UPDATE ttrss_user_entries SET
3831 marked = NOT marked,last_read = NOW()
3832 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3836 function publishArticlesById($link, $ids, $cmode) {
3840 foreach ($ids as $id) {
3841 array_push($tmp_ids, "ref_id = '$id'");
3844 $ids_qpart = join(" OR ", $tmp_ids);
3847 db_query($link, "UPDATE ttrss_user_entries SET
3848 published = false,last_read = NOW()
3849 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3850 } else if ($cmode == 1) {
3851 db_query($link, "UPDATE ttrss_user_entries SET
3853 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3855 db_query($link, "UPDATE ttrss_user_entries SET
3856 published = NOT published,last_read = NOW()
3857 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3861 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3863 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3867 foreach ($ids as $id) {
3868 array_push($tmp_ids, "ref_id = '$id'");
3871 $ids_qpart = join(" OR ", $tmp_ids);
3874 db_query($link, "UPDATE ttrss_user_entries SET
3875 unread = false,last_read = NOW()
3876 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3877 } else if ($cmode == 1) {
3878 db_query($link, "UPDATE ttrss_user_entries SET
3880 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3882 db_query($link, "UPDATE ttrss_user_entries SET
3883 unread = NOT unread,last_read = NOW()
3884 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3889 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3890 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3892 while ($line = db_fetch_assoc($result)) {
3893 ccache_update($link, $line["feed_id"], $owner_uid);
3897 function catchupArticleById($link, $id, $cmode) {
3900 db_query($link, "UPDATE ttrss_user_entries SET
3901 unread = false,last_read = NOW()
3902 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3903 } else if ($cmode == 1) {
3904 db_query($link, "UPDATE ttrss_user_entries SET
3906 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3908 db_query($link, "UPDATE ttrss_user_entries SET
3909 unread = NOT unread,last_read = NOW()
3910 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3914 function make_guid_from_title($title) {
3915 return preg_replace("/[ \"\',.:;]/", "-",
3916 mb_strtolower(strip_tags($title), 'utf-8'));
3919 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3920 $bottom = false, $rtl_content = false, $feed_id = 0,
3921 $is_cat = false, $search = false, $match_on = false,
3922 $search_mode = false, $offset = 0, $limit = 0,
3923 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3925 $user_page_offset = $offset +
1;
3928 $class = "headlinesSubToolbar";
3929 $tid = "headlineActionsTop";
3931 $class = "headlinesSubToolbar";
3932 $tid = "headlineActionsBottom";
3935 print "<nobr><table class=\"$class\" id=\"$tid\"
3936 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3944 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3945 $page_next_link = "javascript:viewFeedGoPage(1)";
3946 $page_first_link = "javascript:viewFeedGoPage(0)";
3948 $catchup_page_link = "javascript:catchupPage()";
3949 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3950 $catchup_sel_link = "javascript:catchupSelection()";
3952 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3954 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3955 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3956 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3957 $sel_inv_link = "javascript:invertHeadlineSelection()";
3959 $tog_unread_link = "javascript:selectionToggleUnread()";
3960 $tog_marked_link = "javascript:selectionToggleMarked()";
3961 $tog_published_link = "javascript:selectionTogglePublished()";
3965 $sel_all_link = "javascript:cdmSelectArticles('all')";
3966 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3967 $sel_none_link = "javascript:cdmSelectArticles('none')";
3969 $sel_inv_link = "javascript:invertHeadlineSelection()";
3971 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3972 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3973 $tog_published_link = "javascript:selectionTogglePublished(true)";
3977 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3979 print "<td class=\"headlineActions$rtl_cpart\">
3980 <ul class=\"headlineDropdownMenu\">
3983 <a href=\"$sel_all_link\">".__('All')."</a>,
3984 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3985 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3986 <a href=\"$sel_none_link\">".__('None')."</a></li>
3987 <li class=\"vsep\"> </li>
3988 <li class=\"top\">".__('Actions...')."<ul>
3989 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
3990 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
3991 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
3992 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
3993 <!-- <li><span class=\"insensitive\">--------</span></li> -->
3994 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
3995 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
3997 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4000 <li onclick=\"catchupRelativeToArticle(0)\"> ".__("Above active article")."</li>
4001 <li onclick=\"catchupRelativeToArticle(1)\"> ".__("Below active article")."</li>";
4004 <li><span class=\"insensitive\"> ".__("Above active article")."</span></li>
4005 <li><span class=\"insensitive\"> ".__("Below active article")."</span></li>";
4009 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4011 //print "<li><span class=\"insensitive\">--------</span></li>";
4012 print "<li><span class=\"insensitive\">".__('Assign label:')."</span></li>";
4014 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
4015 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4017 while ($line = db_fetch_assoc($result)) {
4019 $label_id = $line["id"];
4020 $label_caption = $line["caption"];
4022 if ($feed_id < -10 && $feed_id == -11-$label_id) {
4023 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
4024 $label_caption ".__('(remove)')."</li>";
4026 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
4027 $label_caption</li>";
4031 print "</ul></li></ul>";
4035 // old style subtoolbar:
4037 print "<td class=\"headlineActions$rtl_cpart\">".
4039 <a href=\"$sel_all_link\">".__('All')."</a>,
4040 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4041 <a href=\"$sel_none_link\">".__('None')."</a>
4043 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4044 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4046 __('Mark as read:')."
4047 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4048 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4054 print "<td class=\"headlineTitle$rtl_cpart\">";
4056 print "<span id=\"subtoolbar_search\"
4057 style=\"display : none\"><input
4058 id=\"subtoolbar_search_box\"
4059 onblur=\"javascript:enableHotkeys();\"
4060 onfocus=\"javascript:disableHotkeys();\"
4061 onchange=\"subtoolbarSearch()\"
4062 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4064 print "<span id=\"subtoolbar_ftitle\">";
4066 if ($feed_site_url) {
4068 $target = "target=\"_blank\"";
4070 print "<a $target href=\"$feed_site_url\">".
4071 truncate_string($feed_title,30)."</a>";
4077 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4080 if ($user_page_offset > 1) {
4081 print " [$user_page_offset] ";
4084 if (!$bottom && !$disable_feed) {
4086 <a target=\"_blank\"
4087 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4088 <img class=\"noborder\"
4089 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4091 } else if ($feed_small_icon) {
4092 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4098 print "</tr></table></nobr>";
4102 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4104 $tmp_category = getCategoryTitle($link, $cat_id);
4107 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4108 } else if ($cat_id == 0 ||
$cat_id == -2) {
4109 $cat_unread = getCategoryUnread($link, $cat_id);
4113 $holder_style = "display:none;";
4120 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4123 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4124 $inner_title_class = "catTitle";
4126 $browse_cat_link = "";
4127 $inner_title_class = "catTitleNL";
4130 $cat_class = "feedCat";
4132 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4133 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4134 title=\"".__('Click to collapse category')."\"
4135 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4136 id=\"FCATN-$cat_id\" $browse_cat_link
4137 \">$tmp_category</span>";
4139 print "<span id=\"FCAP-$cat_id\">";
4141 print " <span id=\"FCATCTR-$cat_id\"
4142 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4148 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4152 function outputFeedList($link, $tags = false) {
4154 print "<ul class=\"feedList\" id=\"feedList\">";
4156 $owner_uid = $_SESSION["uid"];
4160 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4162 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4165 $cat_hidden = false;
4168 printCategoryHeader($link, -1, $cat_hidden, false);
4171 $num_starred = getFeedUnread($link, -1);
4172 $num_published = getFeedUnread($link, -2);
4173 $num_fresh = getFeedUnread($link, -3);
4174 $num_total = getFeedUnread($link, -4);
4178 if ($num_total > 0) $class .= "Unread";
4180 printFeedEntry(-4, $class, __("All articles"), $num_total,
4181 "images/tag.png", $link);
4185 if ($num_fresh > 0) $class .= "Unread";
4187 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4188 "images/fresh.png", $link);
4192 if ($num_starred > 0) $class .= "Unread";
4194 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4197 $mark_img_ext = "gif";
4199 $mark_img_ext = "png";
4202 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4203 "images/mark_set.$mark_img_ext", $link);
4207 if ($num_published > 0) $class .= "Unread";
4209 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4210 "images/pub_set.gif", $link);
4212 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4219 $result = db_query($link, "SELECT id,caption FROM
4220 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4222 if (db_num_rows($result) > 0) {
4223 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4225 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4228 $cat_hidden = false;
4231 printCategoryHeader($link, -2, $cat_hidden, true);
4234 print "<li><hr></li>";
4238 while ($line = db_fetch_assoc($result)) {
4240 $label_id = -$line['id'] - 11;
4241 $count = getFeedUnread($link, $label_id);
4249 printFeedEntry($label_id,
4250 $class, $line["caption"],
4251 $count, "images/label.png", $link);
4255 if (db_num_rows($result) > 0) {
4256 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4262 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4263 print "<li><hr></li>";
4266 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4267 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4268 $order_by_qpart = "order_id,category,unread DESC,title";
4270 $order_by_qpart = "order_id,category,title";
4273 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4274 $order_by_qpart = "unread DESC,title";
4276 $order_by_qpart = "title";
4280 $age_qpart = getMaxAgeSubquery();
4282 $query = "SELECT ttrss_feeds.*,
4283 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4285 ttrss_feed_categories.title AS category,
4286 ttrss_feed_categories.collapsed,
4288 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4289 ON (ttrss_feed_categories.id = cat_id)
4290 LEFT JOIN ttrss_counters_cache
4292 (ttrss_feeds.id = feed_id)
4294 ttrss_feeds.hidden = false AND
4295 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4296 ORDER BY $order_by_qpart";
4298 $result = db_query($link, $query);
4300 $actid = $_GET["actid"];
4310 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4312 while ($line = db_fetch_assoc($result)) {
4314 $feed = trim($line["title"]);
4316 if (!$feed) $feed = "[Untitled]";
4318 $feed_id = $line["id"];
4319 $unread = $line["unread"];
4321 $subop = $_GET["subop"];
4323 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4324 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4326 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4329 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4332 $rtl_tag = "dir=\"RTL\"";
4337 $tmp_result = db_query($link,
4338 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4339 WHERE parent_feed = '$feed_id' AND feed_id = id");
4341 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4343 $cat_id = $line["cat_id"];
4345 $tmp_category = $line["category"];
4347 if (!$tmp_category) {
4348 $tmp_category = __("Uncategorized");
4351 // $class = ($lnum % 2) ? "even" : "odd";
4353 if ($line["last_error"]) {
4359 if ($unread > 0) $class .= "Unread";
4361 if ($actid == $feed_id) {
4362 $class .= "Selected";
4365 $total_unread +
= $unread;
4367 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4373 $category = $tmp_category;
4375 $collapsed = sql_bool_to_bool($line["collapsed"]);
4377 // workaround for NULL category
4378 if ($category == __("Uncategorized")) {
4379 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4384 $cat_id = sprintf("%d", $cat_id);
4386 printCategoryHeader($link, $cat_id, $collapsed, true);
4390 printFeedEntry($feed_id, $class, $feed, $unread,
4391 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4392 $last_updated, $line["last_error"]);
4397 if (db_num_rows($result) == 0) {
4398 print "<li>".__('No feeds to display.')."</li>";
4405 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4406 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4407 post_int_id = ttrss_user_entries.int_id AND
4408 unread = true AND ref_id = ttrss_entries.id
4409 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4411 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4412 ORDER BY tag_name"); */
4414 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4415 print "<li class=\"feedCat\">".__('Tags')."</li>";
4416 print "<ul class=\"feedCatList\">";
4419 $age_qpart = getMaxAgeSubquery();
4421 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4422 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4423 AND ref_id = id AND $age_qpart
4424 AND unread = true)) AS count FROM ttrss_tags
4425 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4426 ORDER BY count DESC LIMIT 50");
4430 while ($line = db_fetch_assoc($result)) {
4431 $tags[$line["tag_name"]] +
= $line["count"];
4434 foreach (array_keys($tags) as $tag) {
4436 $unread = $tags[$tag];
4444 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4448 if (db_num_rows($result) == 0) {
4449 print "<li>No tags to display.</li>";
4452 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4462 function get_article_tags($link, $id, $owner_uid = 0) {
4464 $a_id = db_escape_string($id);
4466 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4468 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4469 owner_uid as owner FROM
4470 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4471 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4475 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4476 array_push($tags, $tmp_line["tag_name"]);
4482 function trim_value(&$value) {
4483 $value = trim($value);
4486 function trim_array($array) {
4488 array_walk($tmp, 'trim_value');
4492 function tag_is_valid($tag) {
4493 if ($tag == '') return false;
4494 if (preg_match("/^[0-9]*$/", $tag)) return false;
4496 if (function_exists('iconv')) {
4497 $tag = iconv("utf-8", "utf-8", $tag);
4500 if (!$tag) return false;
4505 function render_login_form($link, $mobile = false) {
4507 require_once "login_form.php";
4509 require_once "mobile/login_form.php";
4513 // from http://developer.apple.com/internet/safari/faq.html
4514 function no_cache_incantation() {
4515 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4516 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4517 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4518 header("Cache-Control: post-check=0, pre-check=0", false);
4519 header("Pragma: no-cache"); // HTTP/1.0
4522 function format_warning($msg, $id = "") {
4523 return "<div class=\"warning\" id=\"$id\">
4524 <img src=\"images/sign_excl.gif\">$msg</div>";
4527 function format_notice($msg) {
4528 return "<div class=\"notice\">
4529 <img src=\"images/sign_info.gif\">$msg</div>";
4532 function format_error($msg) {
4533 return "<div class=\"error\">
4534 <img src=\"images/sign_excl.gif\">$msg</div>";
4537 function print_notice($msg) {
4538 return print format_notice($msg);
4541 function print_warning($msg) {
4542 return print format_warning($msg);
4545 function print_error($msg) {
4546 return print format_error($msg);
4550 function T_sprintf() {
4551 $args = func_get_args();
4552 return vsprintf(__(array_shift($args)), $args);
4555 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4556 $zoom_mode = false) {
4558 /* we can figure out feed_id from article id anyway, why do we
4559 * pass feed_id here? */
4561 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4562 WHERE ref_id = '$id'");
4564 $feed_id = db_fetch_result($result, 0, "feed_id");
4566 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4568 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4569 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4571 if (db_num_rows($result) == 1) {
4572 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4574 $rtl_content = false;
4578 $rtl_tag = "dir=\"RTL\"";
4585 if ($mark_as_read) {
4586 $result = db_query($link, "UPDATE ttrss_user_entries
4587 SET unread = false,last_read = NOW()
4588 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4590 ccache_update($link, $feed_id, $_SESSION["uid"]);
4593 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4594 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4595 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4598 FROM ttrss_entries,ttrss_user_entries
4599 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4605 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4606 $link_target = "target=\"_blank\"";
4609 $line = db_fetch_assoc($result);
4611 if ($line["icon_url"]) {
4612 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4614 $feed_icon = " ";
4617 $num_comments = $line["num_comments"];
4618 $entry_comments = "";
4620 if ($num_comments > 0) {
4621 if ($line["comments"]) {
4622 $comments_url = $line["comments"];
4624 $comments_url = $line["link"];
4626 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4628 if ($line["comments"] && $line["link"] != $line["comments"]) {
4629 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4634 header("Content-Type: text/html");
4636 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4637 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4638 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4643 print "<div class=\"postReply\">";
4645 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4646 onmouseout=\"enable_resize(false)\">";
4648 $entry_author = $line["author"];
4650 if ($entry_author) {
4651 $entry_author = __(" - ") . $entry_author;
4654 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4655 strtotime($line["updated"]));
4657 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4659 if ($line["link"]) {
4660 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4661 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4663 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4666 $tags = get_article_tags($link, $id);
4669 $tags_nolinks_str = "";
4674 if ($_SESSION["theme"] == "3pane") {
4680 foreach ($tags as $tag) {
4682 $tag_escaped = str_replace("'", "\\'", $tag);
4684 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4686 if ($num_tags == $tag_limit) {
4687 $tags_str .= "…";
4688 $tags_nolinks_str .= "…";
4690 } else if ($num_tags < $tag_limit) {
4691 $tags_str .= $tag_str;
4692 $tags_nolinks_str .= "$tag, ";
4694 $f_tags_str .= $tag_str;
4697 $tags_str = preg_replace("/, $/", "", $tags_str);
4698 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4699 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4701 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4702 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4704 if (!$entry_comments) $entry_comments = " "; # placeholder
4706 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4707 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4709 print "<div style='float : right'>
4710 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4714 <a title=\"".__('Edit tags for this article')."\"
4715 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4717 if (defined('_ENABLE_INLINE_VIEW')) {
4719 print "<img src=\"images/art-inline.png\" class='tagsPic'
4720 style=\"cursor : pointer\" style=\"cursor : pointer\"
4721 onclick=\"showOriginalArticleInline($id)\"
4722 alt='Inline' title='".__('Display original article content')."'>";
4726 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4727 style=\"cursor : pointer\" style=\"cursor : pointer\"
4728 onclick=\"zoomToArticle($id)\"
4729 alt='Zoom' title='".__('Show article summary in new window')."'>";
4731 print "$tags_nolinks_str";
4734 print "<div clear='both'>$entry_comments</div>";
4738 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4740 print "<div class=\"postContent\">";
4742 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4744 $article_content = sanitize_rss($link, $line["content"]);
4746 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4747 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4751 print $article_content;
4753 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4754 post_id = '$id' AND content_url != ''");
4756 if (db_num_rows($result) > 0) {
4758 $entries_html = array();
4761 while ($line = db_fetch_assoc($result)) {
4763 $url = $line["content_url"];
4764 $ctype = $line["content_type"];
4766 if (!$ctype) $ctype = __("unknown type");
4768 $filename = substr($url, strrpos($url, "/")+
1);
4772 if (($ctype == __("audio/mpeg")) &&
4773 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4775 $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> ";
4779 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4780 $filename . " (" . $ctype . ")" . "</a>";
4782 array_push($entries_html, $entry);
4786 $entry["type"] = $ctype;
4787 $entry["filename"] = $filename;
4788 $entry["url"] = $url;
4790 array_push($entries, $entry);
4793 print "<div class=\"postEnclosures\">";
4795 if (!preg_match("/img/i", $article_content)) {
4796 foreach ($entries as $entry) {
4797 if (preg_match("/image/", $entry["type"])) {
4799 alt=\"".htmlspecialchars($entry["filename"])."\"
4800 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4805 print "<div class=\"postEnclosures\">";
4807 if (db_num_rows($result) == 1) {
4808 print __("Attachment:") . " ";
4810 print __("Attachments:") . " ";
4813 print join(", ", $entries_html);
4825 print "]]></article>";
4828 <div style=\"text-align : center\">
4829 <input type=\"submit\" onclick=\"return window.close()\"
4830 value=\"".__("Close this window")."\"></div>";
4831 print "</body></html>";
4837 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4838 $next_unread_feed, $offset, $vgr_last_feed = false,
4839 $override_order = false) {
4841 $disable_cache = false;
4843 $timing_info = getmicrotime();
4845 $topmost_article_ids = array();
4851 if ($subop == "undefined") $subop = "";
4853 $subop_split = split(":", $subop);
4855 if ($subop == "CatchupSelected") {
4856 $ids = split(",", db_escape_string($_GET["ids"]));
4857 $cmode = sprintf("%d", $_GET["cmode"]);
4859 catchupArticlesById($link, $ids, $cmode);
4862 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4863 update_generic_feed($link, $feed, $cat_view, true);
4866 if ($subop == "MarkAllRead") {
4867 catchup_feed($link, $feed, $cat_view);
4869 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4870 if ($next_unread_feed) {
4871 $feed = $next_unread_feed;
4876 if ($subop_split[0] == "MarkAllReadGR") {
4877 catchup_feed($link, $subop_split[1], false);
4882 $result = db_query($link,
4883 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4885 if (db_num_rows($result) == 0) {
4886 print "<div align='center'>".__('Feed not found.')."</div>";
4891 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4893 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4894 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4896 if (db_num_rows($result) == 1) {
4897 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4899 $rtl_content = false;
4903 $rtl_tag = "dir=\"RTL\"";
4909 $rtl_content = false;
4912 $script_dt_add = get_script_dt_add();
4914 /// START /////////////////////////////////////////////////////////////////////////////////
4916 $search = db_escape_string($_GET["query"]);
4919 $disable_cache = true;
4922 $search_mode = db_escape_string($_GET["search_mode"]);
4923 $match_on = db_escape_string($_GET["match_on"]);
4929 $real_offset = $offset * $limit;
4931 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4933 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4934 $search, $search_mode, $match_on, $override_order, $real_offset);
4936 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4938 $result = $qfh_ret[0];
4939 $feed_title = $qfh_ret[1];
4940 $feed_site_url = $qfh_ret[2];
4941 $last_error = $qfh_ret[3];
4943 $vgroup_last_feed = $vgr_last_feed;
4946 $feed_site_url = article_publish_url($link);
4949 /// STOP //////////////////////////////////////////////////////////////////////////////////
4952 print "<div id=\"headlinesContainer\" $rtl_tag>";
4955 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4959 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4960 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4963 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4966 $headlines_count = db_num_rows($result);
4968 if (db_num_rows($result) > 0) {
4970 # print "\{$offset}";
4972 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4973 print "<table class=\"headlinesList\" id=\"headlinesList\"
4974 cellspacing=\"0\">";
4977 $lnum = $limit*$offset;
4979 error_reporting (DEFAULT_ERROR_LEVEL
);
4982 $cur_feed_title = '';
4984 while ($line = db_fetch_assoc($result)) {
4986 $class = ($lnum %
2) ?
"even" : "odd";
4989 $feed_id = $line["feed_id"];
4991 $labels = get_article_labels($link, $id);
4992 $labels_str = "<span id=\"HLLCTR-$id\">";
4994 foreach ($labels as $l) {
4995 $labels_str .= "<span
4996 class='hlLabelRef'>".
5000 $labels_str .= "</span>";
5002 if (count($topmost_article_ids) < 5) {
5003 array_push($topmost_article_ids, $id);
5006 if ($line["last_read"] == "" &&
5007 ($line["unread"] != "t" && $line["unread"] != "1")) {
5009 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5012 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5016 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5024 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5027 $mark_img_ext = "gif";
5029 $mark_img_ext = "png";
5032 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5033 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5035 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5037 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5039 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5042 if ($line["published"] == "t" ||
$line["published"] == "1") {
5043 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5045 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5047 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5049 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5052 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5053 # $line["title"] . "</a>";
5055 # $content_link = "<a
5056 # href=\"" . htmlspecialchars($line["link"]) . "\"
5057 # onclick=\"view($id,$feed_id);\">" .
5058 # $line["title"] . "</a>";
5060 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5061 # $line["title"] . "</a>";
5063 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5064 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5066 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5067 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5070 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5071 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5075 $score = $line["score"];
5077 $score_pic = get_score_pic($score);
5079 /* $score_title = __("(Click to change)");
5080 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5081 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5083 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5088 } else if ($score < -100) {
5094 $entry_author = $line["author"];
5096 if ($entry_author) {
5097 $entry_author = " - $entry_author";
5100 $has_feed_icon = feed_has_icon($feed_id);
5102 if ($has_feed_icon) {
5103 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5105 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5106 $feed_icon_img = "";
5109 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5111 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5112 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5114 $cur_feed_title = $line["feed_title"];
5115 $vgroup_last_feed = $feed_id;
5117 $cur_feed_title = htmlspecialchars($cur_feed_title);
5119 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5121 print "<tr class='feedTitle'><td colspan='7'>".
5122 "<div style=\"float : right\">$feed_icon_img</div>".
5123 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5124 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5128 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5129 onmouseout='postMouseOut($id)'";
5131 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5133 print "<td class='hlUpdPic'>$update_pic</td>";
5135 print "<td class='hlSelectRow'>
5136 <input type=\"checkbox\" onclick=\"tSR(this)\"
5140 print "<td class='hlMarkedPic'>$marked_pic</td>";
5141 print "<td class='hlMarkedPic'>$published_pic</td>";
5143 # if ($line["feed_title"]) {
5144 # print "<td class='hlContent'>$content_link</td>";
5145 # print "<td class='hlFeed'>
5146 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5147 # truncate_string($line["feed_title"],30)."</a> </td>";
5150 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5152 print "<a id=\"RTITLE-$id\"
5153 href=\"" . htmlspecialchars($line["link"]) . "\"
5154 onclick=\"return view($id,$feed_id);\">" .
5157 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5158 if ($content_preview) {
5159 print "<span class=\"contentPreview\"> - $content_preview</span>";
5167 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5168 # $line["feed_title"]."</a>
5170 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5171 if ($line["feed_title"]) {
5172 print "<span class=\"hlFeed\">
5173 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5174 $line["feed_title"]."</a>)
5182 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5184 print "<td class='hlMarkedPic'>$score_pic</td>";
5186 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5187 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5194 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5195 if ($feed_id != $vgroup_last_feed) {
5197 $cur_feed_title = $line["feed_title"];
5198 $vgroup_last_feed = $feed_id;
5200 $cur_feed_title = htmlspecialchars($cur_feed_title);
5202 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5204 $has_feed_icon = feed_has_icon($feed_id);
5206 if ($has_feed_icon) {
5207 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5209 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5212 print "<div class='cdmFeedTitle'>".
5213 "<div style=\"float : right\">$feed_icon_img</div>".
5214 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5215 $line["feed_title"]."</a> $vf_catchup_link</div>";
5220 $add_class = "Unread";
5225 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5226 $show_excerpt = false;
5228 if ($expand_cdm && $score >= -100) {
5230 $show_excerpt = false;
5232 $cdm_cstyle = "style=\"display : none\"";
5233 $show_excerpt = true;
5236 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5237 onmouseout='postMouseOut($id)'";
5239 print "<div class=\"cdmArticle$add_class\"
5241 $mouseover_attrs'>";
5243 print "<div class=\"cdmHeader\">";
5245 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5246 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5249 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5252 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5253 onclick=\"javascript:toggleUnread($id, 0)\"
5254 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5257 print $entry_author;
5259 /* if (!$expand_cdm || $score < -100) {
5260 print " <a id=\"CICH-$id\"
5261 href=\"javascript:cdmExpandArticle($id)\">
5262 (".__('Show article').")</a>";
5267 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5268 if ($line["feed_title"]) {
5269 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5273 print "</span></div>";
5275 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5276 $line["content_preview"] = preg_replace("/href=/i",
5277 "target=\"_blank\" href=", $line["content_preview"]);
5280 if ($show_excerpt) {
5281 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5282 onclick=\"cdmExpandArticle($id)\"
5283 title=\"".__('Click to expand article')."\">";
5284 print truncate_string(strip_tags($line["content_preview"]), 100);
5288 print "<div class=\"cdmContent\"
5289 onclick=\"cdmClicked($id)\"
5290 id=\"CICD-$id\" $cdm_cstyle>";
5292 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5294 print sanitize_rss($link, $line["content_preview"]);
5295 $article_content = $line["content_preview"];
5297 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5298 post_id = '$id' AND content_url != ''");
5300 if (db_num_rows($e_result) > 0) {
5302 $entries_html = array();
5305 while ($e_line = db_fetch_assoc($e_result)) {
5307 $url = $e_line["content_url"];
5308 $ctype = $e_line["content_type"];
5309 if (!$ctype) $ctype = __("unknown type");
5311 $filename = substr($url, strrpos($url, "/")+
1);
5315 if (($ctype == __("audio/mpeg")) &&
5316 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5318 $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> ";
5322 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5323 $filename . " (" . $ctype . ")" . "</a>";
5325 array_push($entries_html, $entry);
5329 $entry["type"] = $ctype;
5330 $entry["filename"] = $filename;
5331 $entry["url"] = $url;
5333 array_push($entries, $entry);
5336 if (!preg_match("/img/i", $article_content)) {
5337 foreach ($entries as $entry) {
5338 if (preg_match("/image/", $entry["type"])) {
5340 alt=\"".htmlspecialchars($entry["filename"])."\"
5341 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5346 print "<div class=\"cdmEnclosures\">";
5348 if (db_num_rows($e_result) == 1) {
5349 print __("Attachment:") . " ";
5351 print __("Attachments:") . " ";
5354 print join(", ", $entries_html);
5360 print "<br clear='both'>";
5363 /* if (!$expand_cdm) {
5364 print "<a id=\"CICH-$id\"
5365 href=\"javascript:cdmExpandArticle($id)\">
5371 print "<div class=\"cdmFooter\"><span class='s0'>";
5373 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5375 print __("Select:").
5376 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5377 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5379 print "</span><span class='s1'>$marked_pic</span> ";
5380 print "<span class='s1'>$published_pic</span> ";
5381 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5382 onclick=\"zoomToArticle($id)\"
5383 style=\"cursor : pointer\"
5385 title='".__('Show article summary in new window')."'></span>";
5387 $tags = get_article_tags($link, $id);
5390 $full_tags_str = "";
5393 foreach ($tags as $tag) {
5395 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5396 if ($num_tags < 5) {
5397 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5398 } else if ($num_tags == 5) {
5399 $tags_str .= "…";
5403 $tags_str = preg_replace("/, $/", "", $tags_str);
5404 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5406 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5408 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5411 if ($tags_str == "") $tags_str = "no tags";
5413 // print "<img src='images/tag.png' class='markedPic'>";
5415 print "<span class='s1'>
5416 <img class='tagsPic' src='images/tag.png' alt='Tags'
5417 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5418 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5422 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5423 href=\"javascript:toggleUnread($id)\">
5434 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5441 switch ($view_mode) {
5443 $message = __("No unread articles found to display.");
5446 $message = __("No updated articles found to display.");
5449 $message = __("No starred articles found to display.");
5453 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5455 $message = __("No articles found to display.");
5459 if (!$offset) print "<div class='whiteBox'>$message</div>";
5467 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5470 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5472 function printTagCloud($link) {
5474 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5475 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5476 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5478 $result = db_query($link, $query);
5482 while ($line = db_fetch_assoc($result)) {
5483 $tags[$line["tag_name"]] = $line["count"];
5488 $max_size = 32; // max font size in pixels
5489 $min_size = 11; // min font size in pixels
5491 // largest and smallest array values
5492 $max_qty = max(array_values($tags));
5493 $min_qty = min(array_values($tags));
5495 // find the range of values
5496 $spread = $max_qty - $min_qty;
5497 if ($spread == 0) { // we don't want to divide by zero
5501 // set the font-size increment
5502 $step = ($max_size - $min_size) / ($spread);
5504 // loop through the tag array
5505 foreach ($tags as $key => $value) {
5506 // calculate font-size
5507 // find the $value in excess of $min_qty
5508 // multiply by the font-size increment ($size)
5509 // and add the $min_size set above
5510 $size = round($min_size +
(($value - $min_qty) * $step));
5512 $key_escaped = str_replace("'", "\\'", $key);
5514 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5515 $size . "px\" title=\"$value articles tagged with " .
5516 $key . '">' . $key . '</a> ';
5520 function print_checkpoint($n, $s) {
5521 $ts = getmicrotime();
5522 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5526 function sanitize_tag($tag) {
5529 $tag = mb_strtolower($tag, 'utf-8');
5531 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5533 // $tag = str_replace('"', "", $tag);
5534 // $tag = str_replace("+", " ", $tag);
5535 $tag = str_replace("technorati tag: ", "", $tag);
5540 function generate_publish_key() {
5541 return sha1(uniqid(rand(), true));
5544 function article_publish_url($link) {
5549 if ($_SERVER['HTTPS'] != "on") {
5550 $url_path = "http://";
5552 $url_path = "https://";
5555 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5556 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5562 * Purge a feed contents, marked articles excepted.
5564 * @param mixed $link The database connection.
5565 * @param integer $id The id of the feed to purge.
5568 function clear_feed_articles($link, $id) {
5569 $result = db_query($link, "DELETE FROM ttrss_user_entries
5570 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5572 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5573 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5575 ccache_update($link, $id, $_SESSION['uid']);
5576 } // function clear_feed_articles
5579 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5581 * @return string The Mozilla Firefox feed adding URL.
5583 function add_feed_url() {
5584 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5585 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5587 } // function add_feed_url
5590 * Encrypt a password in SHA1.
5592 * @param string $pass The password to encrypt.
5593 * @param string $login A optionnal login.
5594 * @return string The encrypted password.
5596 function encrypt_password($pass, $login = '') {
5598 return "SHA1X:" . sha1("$login:$pass");
5600 return "SHA1:" . sha1($pass);
5602 } // function encrypt_password
5605 * Update a feed batch.
5606 * Used by daemons to update n feeds by run.
5607 * Only update feed needing a update, and not being processed
5608 * by another process.
5610 * @param mixed $link Database link
5611 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5612 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5613 * @param boolean $debug Set to false to disable debug output. Default to true.
5616 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5617 // Process all other feeds using last_updated and interval parameters
5619 // Test if the user has loggued in recently. If not, it does not update its feeds.
5620 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5621 if (DB_TYPE
== "pgsql") {
5622 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5624 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5627 $login_thresh_qpart = "";
5630 // Test if the feed need a update (update interval exceded).
5631 if (DB_TYPE
== "pgsql") {
5632 $update_limit_qpart = "AND ((
5633 ttrss_feeds.update_interval = 0
5634 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5636 ttrss_feeds.update_interval > 0
5637 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5638 ) OR ttrss_feeds.last_updated IS NULL)";
5640 $update_limit_qpart = "AND ((
5641 ttrss_feeds.update_interval = 0
5642 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5644 ttrss_feeds.update_interval > 0
5645 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5646 ) OR ttrss_feeds.last_updated IS NULL)";
5649 // Test if feed is currently being updated by another process.
5650 if (DB_TYPE
== "pgsql") {
5651 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5653 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5656 // Test if there is a limit to number of updated feeds
5658 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5660 $random_qpart = sql_random_function();
5662 // We search for feed needing update.
5663 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5664 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5665 ttrss_feeds.update_interval
5667 ttrss_feeds, ttrss_users, ttrss_user_prefs
5669 ttrss_feeds.owner_uid = ttrss_users.id
5670 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5671 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5672 $login_thresh_qpart $update_limit_qpart
5673 $updstart_thresh_qpart
5674 ORDER BY $random_qpart $query_limit");
5676 $user_prefs_cache = array();
5678 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5680 // Here is a little cache magic in order to minimize risk of double feed updates.
5681 $feeds_to_update = array();
5682 while ($line = db_fetch_assoc($result)) {
5683 $feeds_to_update[$line['id']] = $line;
5686 // We update the feed last update started date before anything else.
5687 // There is no lag due to feed contents downloads
5688 // It prevent an other process to update the same feed.
5689 $feed_ids = array_keys($feeds_to_update);
5691 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5692 WHERE id IN (%s)", implode(',', $feed_ids)));
5695 // For each feed, we call the feed update function.
5696 while ($line = array_pop($feeds_to_update)) {
5698 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5700 // We setup a alarm to alert if the feed take more than 300s to update.
5702 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5703 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5704 // Cancel the alarm (the update went well)
5705 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5707 sleep(1); // prevent flood (FIXME make this an option?)
5710 // Send feed digests by email if needed.
5711 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5713 } // function update_daemon_common
5715 function sanitize_article_content($text) {
5716 # we don't support CDATA sections in articles, they break our own escaping
5717 $text = preg_replace("/\[\[CDATA/", "", $text);
5718 $text = preg_replace("/\]\]\>/", "", $text);
5722 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5725 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5727 $result = db_query($link, "SELECT reg_exp,
5728 ttrss_filter_types.name AS name,
5729 ttrss_filter_actions.name AS action,
5733 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5736 owner_uid = $owner_uid AND
5737 ttrss_filter_types.id = filter_type AND
5738 ttrss_filter_actions.id = action_id AND
5739 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5741 while ($line = db_fetch_assoc($result)) {
5742 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5743 $filter["reg_exp"] = $line["reg_exp"];
5744 $filter["action"] = $line["action"];
5745 $filter["action_param"] = $line["action_param"];
5746 $filter["filter_param"] = $line["filter_param"];
5747 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5749 array_push($filters[$line["name"]], $filter);
5755 function get_score_pic($score) {
5757 return "score_high.png";
5758 } else if ($score > 0) {
5759 return "score_half_high.png";
5760 } else if ($score < -100) {
5761 return "score_low.png";
5762 } else if ($score < 0) {
5763 return "score_half_low.png";
5765 return "score_neutral.png";
5769 function rounded_table_start($classname, $header = " ") {
5770 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5771 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5772 print "<tr><td class='left'> </td><td class='content'>";
5775 function rounded_table_end($footer = " ") {
5776 print "</td><td class='right'> </td></tr>";
5777 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5781 function feed_has_icon($id) {
5782 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5785 function init_connection($link) {
5786 if (DB_TYPE
== "pgsql") {
5787 pg_query($link, "set client_encoding = 'UTF-8'");
5788 pg_set_client_encoding("UNICODE");
5789 pg_query($link, "set datestyle = 'ISO, european'");
5791 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5792 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5793 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5798 function update_feedbrowser_cache($link) {
5800 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5801 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5802 WHERE tf.feed_url = ttrss_feeds.feed_url
5803 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5804 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5806 db_query($link, "BEGIN");
5808 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5812 while ($line = db_fetch_assoc($result)) {
5813 $subscribers = db_escape_string($line["subscribers"]);
5814 $feed_url = db_escape_string($line["feed_url"]);
5815 $title = db_escape_string($line["title"]);
5817 $tmp_result = db_query($link, "SELECT subscribers FROM
5818 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5820 if (db_num_rows($tmp_result) == 0) {
5822 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5823 (feed_url, title, subscribers) VALUES ('$feed_url',
5824 '$title', '$subscribers')");
5832 db_query($link, "COMMIT");
5838 function ccache_zero($link, $feed_id, $owner_uid) {
5839 db_query($link, "UPDATE ttrss_counters_cache SET
5840 value = 0, updated = NOW() WHERE
5841 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5844 function ccache_zero_all($link, $owner_uid) {
5845 db_query($link, "UPDATE ttrss_counters_cache SET
5846 value = 0 WHERE owner_uid = '$owner_uid'");
5848 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5849 value = 0 WHERE owner_uid = '$owner_uid'");
5852 function ccache_update_all($link, $owner_uid) {
5854 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5856 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5857 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5859 while ($line = db_fetch_assoc($result)) {
5860 ccache_update($link, $line["feed_id"], $owner_uid, true);
5863 /* We have to manually include category 0 */
5865 ccache_update($link, 0, $owner_uid, true);
5868 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5869 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5871 while ($line = db_fetch_assoc($result)) {
5872 print ccache_update($link, $line["feed_id"], $owner_uid);
5879 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5880 $no_update = false) {
5883 $table = "ttrss_counters_cache";
5885 $table = "ttrss_cat_counters_cache";
5888 if (DB_TYPE
== "pgsql") {
5889 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5890 } else if (DB_TYPE
== "mysql") {
5891 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5894 $result = db_query($link, "SELECT value FROM $table
5895 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5898 if (db_num_rows($result) == 1) {
5899 return db_fetch_result($result, 0, "value");
5904 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5910 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5911 $update_pcat = true) {
5913 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5915 /* When updating a label, all we need to do is recalculate feed counters
5916 * because labels are not cached */
5919 ccache_update_all($link, $owner_uid);
5924 $table = "ttrss_counters_cache";
5926 $table = "ttrss_cat_counters_cache";
5929 if ($is_cat && $feed_id >= 0) {
5930 if ($feed_id != 0) {
5931 $cat_qpart = "cat_id = '$feed_id'";
5933 $cat_qpart = "cat_id IS NULL";
5936 /* Recalculate counters for child feeds */
5938 $result = db_query($link, "SELECT id FROM ttrss_feeds
5939 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5941 while ($line = db_fetch_assoc($result)) {
5942 ccache_update($link, $line["id"], $owner_uid, false, false);
5945 $result = db_query($link, "SELECT SUM(value) AS sv
5946 FROM ttrss_counters_cache, ttrss_feeds
5947 WHERE id = feed_id AND $cat_qpart AND
5948 ttrss_feeds.owner_uid = '$owner_uid'");
5950 $unread = (int) db_fetch_result($result, 0, "sv");
5953 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5956 $result = db_query($link, "SELECT feed_id FROM $table
5957 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5959 if (db_num_rows($result) == 1) {
5960 db_query($link, "UPDATE $table SET
5961 value = '$unread', updated = NOW() WHERE
5962 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5965 db_query($link, "INSERT INTO $table
5966 (feed_id, value, owner_uid, updated)
5968 ($feed_id, $unread, $owner_uid, NOW())");
5971 if ($feed_id > 0 && $prev_unread != $unread) {
5975 /* Update parent category */
5979 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5980 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5982 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5984 ccache_update($link, $cat_id, $owner_uid, true);
5988 } else if ($feed_id < 0) {
5989 ccache_update_all($link, $owner_uid);
5995 function label_find_id($link, $label, $owner_uid) {
5996 $result = db_query($link,
5997 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5998 AND owner_uid = '$owner_uid' LIMIT 1");
6000 if (db_num_rows($result) == 1) {
6001 return db_fetch_result($result, 0, "id");
6007 function get_article_labels($link, $id) {
6008 $result = db_query($link,
6009 "SELECT DISTINCT label_id,caption
6010 FROM ttrss_labels2, ttrss_user_labels2
6012 AND article_id = '$id'
6013 AND owner_uid = ".$_SESSION["uid"] . "
6018 while ($line = db_fetch_assoc($result)) {
6019 $rk = array($line["label_id"], $line["caption"]);
6020 array_push($rv, $rk);
6027 function label_find_caption($link, $label, $owner_uid) {
6028 $result = db_query($link,
6029 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6030 AND owner_uid = '$owner_uid' LIMIT 1");
6032 if (db_num_rows($result) == 1) {
6033 return db_fetch_result($result, 0, "caption");
6039 function label_remove_article($link, $id, $label, $owner_uid) {
6041 $label_id = label_find_id($link, $label, $owner_uid);
6043 if (!$label_id) return;
6045 $result = db_query($link,
6046 "DELETE FROM ttrss_user_labels2
6048 label_id = '$label_id' AND
6049 article_id = '$id'");
6052 function label_add_article($link, $id, $label, $owner_uid) {
6054 $label_id = label_find_id($link, $label, $owner_uid);
6056 if (!$label_id) return;
6058 $result = db_query($link,
6060 article_id FROM ttrss_labels2, ttrss_user_labels2
6063 label_id = '$label_id' AND
6064 article_id = '$id' AND owner_uid = '$owner_uid'
6067 if (db_num_rows($result) == 0) {
6068 db_query($link, "INSERT INTO ttrss_user_labels2
6069 (label_id, article_id) VALUES ('$label_id', '$id')");
6073 function label_remove($link, $id, $owner_uid) {
6075 db_query($link, "BEGIN");
6077 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6080 $caption = db_fetch_result($result, 0, "caption");
6082 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6083 AND owner_uid = " . $_SESSION["uid"]);
6085 if (db_affected_rows($link, $result) != 0 && $caption) {
6087 /* Disable filters that reference label being removed */
6089 db_query($link, "UPDATE ttrss_filters SET
6090 enabled = false WHERE action_param = '$caption'
6092 AND owner_uid = " . $_SESSION["uid"]);
6095 db_query($link, "COMMIT");