3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if (!$owner_uid) return;
150 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
153 if (!$purge_unread) $query_limit = " unread = false AND ";
155 if (DB_TYPE
== "pgsql") {
156 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
157 marked = false AND feed_id = '$feed_id' AND
158 (SELECT date_entered FROM ttrss_entries WHERE
159 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
161 $pg_version = get_pgsql_version($link);
163 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
165 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
166 ttrss_entries.id = ref_id AND
168 feed_id = '$feed_id' AND
170 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
174 $result = db_query($link, "DELETE FROM ttrss_user_entries
176 WHERE ttrss_entries.id = ref_id AND
178 feed_id = '$feed_id' AND
180 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
183 $rows = pg_affected_rows($result);
187 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
188 marked = false AND feed_id = '$feed_id' AND
189 (SELECT date_entered FROM ttrss_entries WHERE
190 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_user_entries, ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
196 feed_id = '$feed_id' AND
198 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
200 $rows = mysql_affected_rows($link);
204 ccache_update($link, $feed_id, $owner_uid);
207 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
209 } // function purge_feed
212 * Purge old posts from old feeds.
214 * @param mixed $link A database connection
215 * @param boolean $do_output Set to true to enable printed output, false by default.
216 * @param integer $limit The maximal number of removed posts.
220 function global_purge_old_posts($link, $do_output = false, $limit = false) {
222 $random_qpart = sql_random_function();
225 $limit_qpart = "LIMIT $limit";
230 $result = db_query($link,
231 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
232 ORDER BY $random_qpart $limit_qpart");
234 while ($line = db_fetch_assoc($result)) {
236 $feed_id = $line["id"];
237 $purge_interval = $line["purge_interval"];
238 $owner_uid = $line["owner_uid"];
240 if ($purge_interval == 0) {
242 $tmp_result = db_query($link,
243 "SELECT value FROM ttrss_user_prefs WHERE
244 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
246 if (db_num_rows($tmp_result) != 0) {
247 $purge_interval = db_fetch_result($tmp_result, 0, "value");
252 // print "Feed $feed_id: purge interval = $purge_interval\n";
255 if ($purge_interval > 0) {
256 purge_feed($link, $feed_id, $purge_interval, $do_output);
260 // purge orphaned posts in main content table
261 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
262 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
265 $rows = db_affected_rows($link, $result);
266 _debug("Purged $rows orphaned posts.");
269 } // function global_purge_old_posts
271 function feed_purge_interval($link, $feed_id) {
273 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
274 WHERE id = '$feed_id'");
276 if (db_num_rows($result) == 1) {
277 $purge_interval = db_fetch_result($result, 0, "purge_interval");
278 $owner_uid = db_fetch_result($result, 0, "owner_uid");
280 if ($purge_interval == 0) $purge_interval = get_pref($link,
281 'PURGE_OLD_DAYS', $user_id);
283 return $purge_interval;
290 function purge_old_posts($link) {
292 $user_id = $_SESSION["uid"];
294 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
295 WHERE owner_uid = '$user_id'");
297 while ($line = db_fetch_assoc($result)) {
299 $feed_id = $line["id"];
300 $purge_interval = $line["purge_interval"];
302 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
304 if ($purge_interval > 0) {
305 purge_feed($link, $feed_id, $purge_interval);
309 // purge orphaned posts in main content table
310 db_query($link, "DELETE FROM ttrss_entries WHERE
311 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
314 function get_feed_update_interval($link, $feed_id) {
315 $result = db_query($link, "SELECT owner_uid, update_interval FROM
316 ttrss_feeds WHERE id = '$feed_id'");
318 if (db_num_rows($result) == 1) {
319 $update_interval = db_fetch_result($result, 0, "update_interval");
320 $owner_uid = db_fetch_result($result, 0, "owner_uid");
322 if ($update_interval != 0) {
323 return $update_interval;
325 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
333 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
335 if (WEB_DEMO_MODE
) return;
338 $user_id = $_SESSION["uid"];
339 purge_old_posts($link);
342 // db_query($link, "BEGIN");
344 if (MAX_UPDATE_TIME
> 0) {
345 if (DB_TYPE
== "mysql") {
348 $q_order = "RANDOM()";
351 $q_order = "last_updated DESC";
354 $result = db_query($link, "SELECT feed_url,id,
355 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
356 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
361 while ($line = db_fetch_assoc($result)) {
362 $upd_intl = $line["update_interval"];
364 if (!$upd_intl ||
$upd_intl == 0) {
365 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
369 // Updates for this feed are disabled
373 if ($fetch ||
(!$line["last_updated"] ||
374 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
376 // print "<!-- feed: ".$line["feed_url"]." -->";
378 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
380 $upd_elapsed = time() - $upd_start;
382 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
388 // db_query($link, "COMMIT");
392 function fetch_file_contents($url) {
393 if (USE_CURL_FOR_ICONS
) {
394 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
396 $ch = curl_init($url);
397 $fp = fopen($tmpfile, "w");
400 curl_setopt($ch, CURLOPT_FILE
, $fp);
401 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
402 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
408 $contents = file_get_contents($tmpfile);
414 return file_get_contents($url);
420 * Try to determine the favicon URL for a feed.
421 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
422 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
424 * @param string $url A feed or page URL
426 * @return mixed The favicon URL, or false if none was found.
428 function get_favicon_url($url) {
430 if ($html = @fetch_file_contents
($url)) {
432 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
433 // Attempt to grab a favicon link from their webpage url
434 $linkUrl = html_entity_decode($matches[1]);
436 if (substr($linkUrl, 0, 1) == '/') {
437 $urlParts = parse_url($url);
438 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
439 } else if (substr($linkUrl, 0, 7) == 'http://') {
440 $faviconURL = $linkUrl;
441 } else if (substr($url, -1, 1) == '/') {
442 $faviconURL = $url.$linkUrl;
444 $faviconURL = $url.'/'.$linkUrl;
448 // If unsuccessful, attempt to "guess" the favicon location
449 $urlParts = parse_url($url);
450 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
454 // Run a test to see if what we have attempted to get actually exists.
455 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
460 } // function get_favicon_url
463 * Check if a link is a valid and working URL.
465 * @param mixed $link A URL to check
467 * @return boolean True if the URL is valid, false otherwise.
469 function url_validate($link) {
471 $url_parts = @parse_url
($link);
473 if ( empty( $url_parts["host"] ) )
476 if ( !empty( $url_parts["path"] ) ) {
477 $documentpath = $url_parts["path"];
482 if ( !empty( $url_parts["query"] ) )
483 $documentpath .= "?" . $url_parts["query"];
485 $host = $url_parts["host"];
486 $port = $url_parts["port"];
491 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
496 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
498 $http_response = fgets( $socket, 22 );
500 $responses = "/(200 OK)|(30[0-9] Moved)/";
501 if ( preg_match($responses, $http_response) ) {
508 } // function url_validate
510 function check_feed_favicon($site_url, $feed, $link) {
511 $favicon_url = get_favicon_url($site_url);
513 # print "FAVICON [$site_url]: $favicon_url\n";
517 $icon_file = ICONS_DIR
. "/$feed.ico";
519 if ($favicon_url && !file_exists($icon_file)) {
520 $contents = fetch_file_contents($favicon_url);
522 $fp = fopen($icon_file, "w");
525 fwrite($fp, $contents);
527 chmod($icon_file, 0644);
531 error_reporting(DEFAULT_ERROR_LEVEL
);
535 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
537 if (!$_GET["daemon"] && !$ignore_daemon) {
541 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
542 _debug("update_rss_feed: start");
545 if (!$ignore_daemon) {
547 if (DB_TYPE
== "pgsql") {
548 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
550 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
553 $result = db_query($link, "SELECT id,update_interval,auth_login,
554 auth_pass,cache_images,update_method
555 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
559 $result = db_query($link, "SELECT id,update_interval,auth_login,
560 auth_pass,cache_images,update_method,hidden
561 FROM ttrss_feeds WHERE id = '$feed'");
565 if (db_num_rows($result) == 0) {
566 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
567 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
572 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
573 $update_method = db_fetch_result($result, 0, "update_method");
575 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
576 WHERE id = '$feed'");
578 $auth_login = db_fetch_result($result, 0, "auth_login");
579 $auth_pass = db_fetch_result($result, 0, "auth_pass");
581 if (ALLOW_SELECT_UPDATE_METHOD
) {
582 if (ENABLE_SIMPLEPIE
) {
583 $use_simplepie = $update_method != 1;
585 $use_simplepie = $update_method == 2;
588 $use_simplepie = ENABLE_SIMPLEPIE
;
591 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
592 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
595 if (!$use_simplepie) {
596 $auth_login = urlencode($auth_login);
597 $auth_pass = urlencode($auth_pass);
600 $update_interval = db_fetch_result($result, 0, "update_interval");
601 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
603 if ($update_interval < 0) { return; }
605 $feed = db_escape_string($feed);
607 $fetch_url = $feed_url;
609 if ($auth_login && $auth_pass) {
610 $url_parts = array();
611 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
613 if ($url_parts[1] && $url_parts[2]) {
614 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
619 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
620 _debug("update_rss_feed: fetching [$fetch_url]...");
623 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
627 if (!$use_simplepie) {
628 $rss = fetch_rss($fetch_url);
630 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
631 mkdir(SIMPLEPIE_CACHE_DIR
);
634 $rss = new SimplePie();
635 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
636 # $rss->set_timeout(10);
637 $rss->set_feed_url($fetch_url);
638 $rss->set_output_encoding('UTF-8');
640 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
641 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
642 _debug("enabling image cache");
645 $rss->set_image_handler('./image.php', 'i');
648 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
649 _debug("feed update interval (sec): " .
650 get_feed_update_interval($link, $feed)*60);
653 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
654 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
655 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
663 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
664 _debug("update_rss_feed: fetch done, parsing...");
666 error_reporting (DEFAULT_ERROR_LEVEL
);
669 $feed = db_escape_string($feed);
671 if ($use_simplepie) {
672 $fetch_ok = !$rss->error();
679 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
680 _debug("update_rss_feed: processing feed data...");
683 // db_query($link, "BEGIN");
685 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
686 FROM ttrss_feeds WHERE id = '$feed'");
688 $registered_title = db_fetch_result($result, 0, "title");
689 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
690 $orig_site_url = db_fetch_result($result, 0, "site_url");
692 $owner_uid = db_fetch_result($result, 0, "owner_uid");
694 if ($use_simplepie) {
695 $site_url = $rss->get_link();
697 $site_url = $rss->channel
["link"];
700 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
701 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
702 _debug("update_rss_feed: checking favicon...");
705 check_feed_favicon($site_url, $feed, $link);
708 if (!$registered_title ||
$registered_title == "[Unknown]") {
710 if ($use_simplepie) {
711 $feed_title = db_escape_string($rss->get_title());
713 $feed_title = db_escape_string($rss->channel
["title"]);
716 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
717 _debug("update_rss_feed: registering title: $feed_title");
720 db_query($link, "UPDATE ttrss_feeds SET
721 title = '$feed_title' WHERE id = '$feed'");
724 // weird, weird Magpie
725 if (!$use_simplepie) {
726 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
729 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
730 db_query($link, "UPDATE ttrss_feeds SET
731 site_url = '$site_url' WHERE id = '$feed'");
734 // print "I: " . $rss->channel["image"]["url"];
736 if (!$use_simplepie) {
737 $icon_url = $rss->image
["url"];
739 $icon_url = $rss->get_image_url();
742 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
743 $icon_url = db_escape_string($icon_url);
744 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
747 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
748 _debug("update_rss_feed: loading filters...");
751 $filters = load_filters($link, $feed, $owner_uid);
753 if ($use_simplepie) {
754 $iterator = $rss->get_items();
756 $iterator = $rss->items
;
757 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
758 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
761 if (!is_array($iterator)) {
762 /* db_query($link, "UPDATE ttrss_feeds
763 SET last_error = 'Parse error: can\'t find any articles.'
764 WHERE id = '$feed'"); */
766 // clear any errors and mark feed as updated if fetched okay
767 // even if it's blank
769 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
770 _debug("update_rss_feed: entry iterator is not an array, no articles?");
773 db_query($link, "UPDATE ttrss_feeds
774 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
776 return; // no articles
779 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
780 _debug("update_rss_feed: processing articles...");
783 foreach ($iterator as $item) {
785 if ($_GET['xdebug']) {
790 if ($use_simplepie) {
791 $entry_guid = $item->get_id();
792 if (!$entry_guid) $entry_guid = $item->get_link();
793 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
797 $entry_guid = $item["id"];
799 if (!$entry_guid) $entry_guid = $item["guid"];
800 if (!$entry_guid) $entry_guid = $item["link"];
801 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
804 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
805 _debug("update_rss_feed: guid $entry_guid");
808 if (!$entry_guid) continue;
810 $entry_timestamp = "";
812 if ($use_simplepie) {
813 $entry_timestamp = strtotime($item->get_date());
815 $rss_2_date = $item['pubdate'];
816 $rss_1_date = $item['dc']['date'];
817 $atom_date = $item['issued'];
818 if (!$atom_date) $atom_date = $item['updated'];
820 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
821 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
822 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
825 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
826 $entry_timestamp = time();
827 $no_orig_date = 'true';
829 $no_orig_date = 'false';
832 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
834 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
835 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
838 if ($use_simplepie) {
839 $entry_title = $item->get_title();
841 $entry_title = trim(strip_tags($item["title"]));
844 if ($use_simplepie) {
845 $entry_link = $item->get_link();
847 // strange Magpie workaround
848 $entry_link = $item["link_"];
849 if (!$entry_link) $entry_link = $item["link"];
852 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
853 _debug("update_rss_feed: title $entry_title");
856 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
858 $entry_link = strip_tags($entry_link);
860 if ($use_simplepie) {
861 $entry_content = $item->get_content();
862 if (!$entry_content) $entry_content = $item->get_description();
864 $entry_content = $item["content:escaped"];
866 if (!$entry_content) $entry_content = $item["content:encoded"];
867 if (!$entry_content) $entry_content = $item["content"]["encoded"];
868 if (!$entry_content) $entry_content = $item["content"];
870 // Magpie bugs are getting ridiculous
871 if (trim($entry_content) == "Array") $entry_content = false;
873 if (!$entry_content) $entry_content = $item["atom_content"];
874 if (!$entry_content) $entry_content = $item["summary"];
876 if (!$entry_content ||
877 strlen($entry_content) < strlen($item["description"])) {
878 $entry_content = $item["description"];
882 if (is_array($entry_content)) {
883 $entry_content = $entry_content["encoded"];
884 if (!$entry_content) $entry_content = $entry_content["escaped"];
888 if ($_GET["xdebug"]) {
889 print "update_rss_feed: content: ";
890 print_r(htmlspecialchars($entry_content));
893 $entry_content_unescaped = $entry_content;
895 if ($use_simplepie) {
896 $entry_comments = strip_tags($item->data
["comments"]);
897 if ($item->get_author()) {
898 $entry_author_item = $item->get_author();
899 $entry_author = $entry_author_item->get_name();
900 if (!$entry_author) $entry_author = $entry_author_item->get_email();
902 $entry_author = db_escape_string($entry_author);
905 $entry_comments = strip_tags($item["comments"]);
907 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
909 if ($item['author']) {
911 if (is_array($item['author'])) {
913 if (!$entry_author) {
914 $entry_author = db_escape_string(strip_tags($item['author']['name']));
917 if (!$entry_author) {
918 $entry_author = db_escape_string(strip_tags($item['author']['email']));
922 if (!$entry_author) {
923 $entry_author = db_escape_string(strip_tags($item['author']));
928 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
930 $entry_guid = db_escape_string(strip_tags($entry_guid));
931 $entry_guid = mb_substr($entry_guid, 0, 250);
933 $result = db_query($link, "SELECT id FROM ttrss_entries
934 WHERE guid = '$entry_guid'");
936 $entry_content = db_escape_string($entry_content);
938 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
940 $entry_title = db_escape_string($entry_title);
941 $entry_link = db_escape_string($entry_link);
942 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
943 $entry_author = mb_substr($entry_author, 0, 250);
945 if ($use_simplepie) {
946 $num_comments = 0; #FIXME#
948 $num_comments = db_escape_string($item["slash"]["comments"]);
951 if (!$num_comments) $num_comments = 0;
953 // parse <category> entries into tags
955 if ($use_simplepie) {
957 $additional_tags = array();
958 $additional_tags_src = $item->get_categories();
960 if (is_array($additional_tags_src)) {
961 foreach ($additional_tags_src as $tobj) {
962 array_push($additional_tags, $tobj->get_term());
966 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
967 _debug("update_rss_feed: category tags:");
968 print_r($additional_tags);
973 $t_ctr = $item['category#'];
975 $additional_tags = false;
978 $additional_tags = false;
979 } else if ($t_ctr > 0) {
980 $additional_tags = array($item['category']);
982 if ($item['category@term']) {
983 array_push($additional_tags, $item['category@term']);
986 for ($i = 0; $i <= $t_ctr; $i++
) {
987 if ($item["category#$i"]) {
988 array_push($additional_tags, $item["category#$i"]);
991 if ($item["category#$i@term"]) {
992 array_push($additional_tags, $item["category#$i@term"]);
997 // parse <dc:subject> elements
999 $t_ctr = $item['dc']['subject#'];
1002 $additional_tags = array($item['dc']['subject']);
1004 for ($i = 0; $i <= $t_ctr; $i++
) {
1005 if ($item['dc']["subject#$i"]) {
1006 array_push($additional_tags, $item['dc']["subject#$i"]);
1014 $enclosures = array();
1016 if ($use_simplepie) {
1017 $encs = $item->get_enclosures();
1019 if (is_array($encs)) {
1020 foreach ($encs as $e) {
1022 $e->link
, $e->type
, $e->length
);
1024 array_push($enclosures, $e_item);
1031 $e_ctr = $item['enclosure#'];
1034 $e_item = array($item['enclosure@url'],
1035 $item['enclosure@type'],
1036 $item['enclosure@length']);
1038 array_push($enclosures, $e_item);
1040 for ($i = 0; $i <= $e_ctr; $i++
) {
1042 if ($item["enclosure#$i@url"]) {
1043 $e_item = array($item["enclosure#$i@url"],
1044 $item["enclosure#$i@type"],
1045 $item["enclosure#$i@length"]);
1046 array_push($enclosures, $e_item);
1052 // can there be many of those? yes -fox
1054 $m_ctr = $item['media']['content#'];
1057 $e_item = array($item['media']['content@url'],
1058 $item['media']['content@medium'],
1059 $item['media']['content@length']);
1061 array_push($enclosures, $e_item);
1063 for ($i = 0; $i <= $m_ctr; $i++
) {
1065 if ($item["media"]["content#$i@url"]) {
1066 $e_item = array($item["media"]["content#$i@url"],
1067 $item["media"]["content#$i@medium"],
1068 $item["media"]["content#$i@length"]);
1069 array_push($enclosures, $e_item);
1078 $entry_content = sanitize_article_content($entry_content);
1079 $entry_title = sanitize_article_content($entry_title);
1081 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1082 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1085 db_query($link, "BEGIN");
1087 if (db_num_rows($result) == 0) {
1089 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1090 _debug("update_rss_feed: base guid not found");
1093 // base post entry does not exist, create it
1095 $result = db_query($link,
1096 "INSERT INTO ttrss_entries
1112 '$entry_timestamp_fmt',
1121 // we keep encountering the entry in feeds, so we need to
1122 // update date_entered column so that we don't get horrible
1123 // dupes when the entry gets purged and reinserted again e.g.
1124 // in the case of SLOW SLOW OMG SLOW updating feeds
1126 $base_entry_id = db_fetch_result($result, 0, "id");
1128 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1129 WHERE id = '$base_entry_id'");
1132 // now it should exist, if not - bad luck then
1134 $result = db_query($link, "SELECT
1135 id,content_hash,no_orig_date,title,
1136 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1137 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1141 WHERE guid = '$entry_guid'");
1146 if (db_num_rows($result) == 1) {
1148 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1149 _debug("update_rss_feed: base guid found, checking for user record");
1152 // this will be used below in update handler
1153 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1154 $orig_title = db_fetch_result($result, 0, "title");
1155 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1156 $orig_date_entered = strtotime(db_fetch_result($result,
1157 0, "date_entered"));
1159 $ref_id = db_fetch_result($result, 0, "id");
1160 $entry_ref_id = $ref_id;
1162 // check for user post link to main table
1164 // do we allow duplicate posts with same GUID in different feeds?
1165 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1166 $dupcheck_qpart = "AND feed_id = '$feed'";
1168 $dupcheck_qpart = "";
1171 // error_reporting(0);
1173 $article_filters = get_article_filters($filters, $entry_title,
1174 $entry_content, $entry_link, $entry_timestamp);
1176 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1177 _debug("update_rss_feed: article filters: ");
1178 if (count($article_filters) != 0) {
1179 print_r($article_filters);
1183 if (find_article_filter($article_filters, "filter")) {
1184 db_query($link, "COMMIT"); // close transaction in progress
1188 // error_reporting (DEFAULT_ERROR_LEVEL);
1190 $score = calculate_article_score($article_filters);
1192 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1193 _debug("update_rss_feed: initial score: $score");
1196 $result = db_query($link,
1197 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1198 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1201 // okay it doesn't exist - create user entry
1202 if (db_num_rows($result) == 0) {
1204 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1205 _debug("update_rss_feed: user record not found, creating...");
1208 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1210 $last_read_qpart = 'NULL';
1213 $last_read_qpart = 'NOW()';
1216 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1222 if (find_article_filter($article_filters, 'publish')) {
1223 $published = 'true';
1225 $published = 'false';
1228 $result = db_query($link,
1229 "INSERT INTO ttrss_user_entries
1230 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1232 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1233 $last_read_qpart, $marked, $published, '$score')");
1235 $result = db_query($link,
1236 "SELECT int_id FROM ttrss_user_entries WHERE
1237 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1238 feed_id = '$feed' LIMIT 1");
1240 if (db_num_rows($result) == 1) {
1241 $entry_int_id = db_fetch_result($result, 0, "int_id");
1244 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1245 $entry_int_id = db_fetch_result($result, 0, "int_id");
1248 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1249 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1252 $post_needs_update = false;
1254 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1255 ($content_hash != $orig_content_hash)) {
1256 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1257 $post_needs_update = true;
1260 if (db_escape_string($orig_title) != $entry_title) {
1261 $post_needs_update = true;
1264 if ($orig_num_comments != $num_comments) {
1265 $post_needs_update = true;
1268 // this doesn't seem to be very reliable
1270 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1271 // $post_needs_update = true;
1274 // if post needs update, update it and mark all user entries
1275 // linking to this post as updated
1276 if ($post_needs_update) {
1278 if (defined('DAEMON_EXTENDED_DEBUG')) {
1279 _debug("update_rss_feed: post $entry_guid needs update...");
1282 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1284 db_query($link, "UPDATE ttrss_entries
1285 SET title = '$entry_title', content = '$entry_content',
1286 content_hash = '$content_hash',
1287 num_comments = '$num_comments'
1288 WHERE id = '$ref_id'");
1290 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1291 db_query($link, "UPDATE ttrss_user_entries
1292 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1294 db_query($link, "UPDATE ttrss_user_entries
1295 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1301 db_query($link, "COMMIT");
1303 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1304 _debug("update_rss_feed: assigning labels...");
1307 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1310 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1311 _debug("update_rss_feed: looking for enclosures...");
1314 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1315 print_r($enclosures);
1318 db_query($link, "BEGIN");
1320 foreach ($enclosures as $enc) {
1321 $enc_url = db_escape_string($enc[0]);
1322 $enc_type = db_escape_string($enc[1]);
1323 $enc_dur = db_escape_string($enc[2]);
1325 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1326 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1328 if (db_num_rows($result) == 0) {
1329 db_query($link, "INSERT INTO ttrss_enclosures
1330 (content_url, content_type, title, duration, post_id) VALUES
1331 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1335 db_query($link, "COMMIT");
1337 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1338 _debug("update_rss_feed: looking for tags...");
1342 // <a href="..." rel="tag">Xorg</a>, //
1346 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1347 $entry_content_unescaped, $entry_tags);
1349 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1350 print_r($entry_tags);
1351 print "<br/></p>"; */
1353 $entry_tags = $entry_tags[1];
1355 # check for manual tags
1357 $tag_filter = find_article_filter($article_filters, "tag");
1361 $manual_tags = trim_array(split(",", $tag_filter[1]));
1363 foreach ($manual_tags as $tag) {
1364 if (tag_is_valid($tag)) {
1365 array_push($entry_tags, $tag);
1370 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1371 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1373 if ($additional_tags && is_array($additional_tags)) {
1374 foreach ($additional_tags as $tag) {
1375 if (tag_is_valid($tag) &&
1376 array_search($tag, $boring_tags) === FALSE) {
1377 array_push($entry_tags, $tag);
1382 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1384 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1385 print_r($entry_tags);
1388 if (count($entry_tags) > 0) {
1390 db_query($link, "BEGIN");
1392 foreach ($entry_tags as $tag) {
1394 $tag = sanitize_tag($tag);
1395 $tag = db_escape_string($tag);
1397 if (!tag_is_valid($tag)) continue;
1399 $result = db_query($link, "SELECT id FROM ttrss_tags
1400 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1401 owner_uid = '$owner_uid' LIMIT 1");
1403 // print db_fetch_result($result, 0, "id");
1405 if ($result && db_num_rows($result) == 0) {
1407 db_query($link, "INSERT INTO ttrss_tags
1408 (owner_uid,tag_name,post_int_id)
1409 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1413 db_query($link, "COMMIT");
1416 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1417 _debug("update_rss_feed: article processed");
1422 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1423 _debug("update_rss_feed: updating counters cache...");
1426 ccache_update($link, $feed, $owner_uid);
1429 db_query($link, "UPDATE ttrss_feeds
1430 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1432 // db_query($link, "COMMIT");
1436 if ($use_simplepie) {
1437 $error_msg = mb_substr($rss->error(), 0, 250);
1439 $error_msg = mb_substr(magpie_error(), 0, 250);
1442 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1443 _debug("update_rss_feed: error fetching feed: $error_msg");
1446 $error_msg = db_escape_string($error_msg);
1449 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1450 last_updated = NOW() WHERE id = '$feed'");
1453 if ($use_simplepie) {
1457 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1458 _debug("update_rss_feed: done");
1463 function print_select($id, $default, $values, $attributes = "") {
1464 print "<select name=\"$id\" id=\"$id\" $attributes>";
1465 foreach ($values as $v) {
1471 print "<option$sel>$v</option>";
1476 function print_select_hash($id, $default, $values, $attributes = "") {
1477 print "<select name=\"$id\" id='$id' $attributes>";
1478 foreach (array_keys($values) as $v) {
1480 $sel = 'selected="selected"';
1484 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1490 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1493 if ($filters["title"]) {
1494 foreach ($filters["title"] as $filter) {
1495 $reg_exp = $filter["reg_exp"];
1496 $inverse = $filter["inverse"];
1497 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1498 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1500 array_push($matches, array($filter["action"], $filter["action_param"]));
1505 if ($filters["content"]) {
1506 foreach ($filters["content"] as $filter) {
1507 $reg_exp = $filter["reg_exp"];
1508 $inverse = $filter["inverse"];
1510 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1511 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1513 array_push($matches, array($filter["action"], $filter["action_param"]));
1518 if ($filters["both"]) {
1519 foreach ($filters["both"] as $filter) {
1520 $reg_exp = $filter["reg_exp"];
1521 $inverse = $filter["inverse"];
1524 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1525 array_push($matches, array($filter["action"], $filter["action_param"]));
1528 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1529 array_push($matches, array($filter["action"], $filter["action_param"]));
1535 if ($filters["link"]) {
1536 $reg_exp = $filter["reg_exp"];
1537 foreach ($filters["link"] as $filter) {
1538 $reg_exp = $filter["reg_exp"];
1539 $inverse = $filter["inverse"];
1541 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1542 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1544 array_push($matches, array($filter["action"], $filter["action_param"]));
1549 if ($filters["date"]) {
1550 $reg_exp = $filter["reg_exp"];
1551 foreach ($filters["date"] as $filter) {
1552 $date_modifier = $filter["filter_param"];
1553 $inverse = $filter["inverse"];
1554 $check_timestamp = strtotime($filter["reg_exp"]);
1556 # no-op when timestamp doesn't parse to prevent misfires
1558 if ($check_timestamp) {
1561 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1562 $date_modifier == "after" && $timestamp > $check_timestamp) {
1566 if ($inverse) $match_ok = !$match_ok;
1569 array_push($matches, array($filter["action"], $filter["action_param"]));
1578 function find_article_filter($filters, $filter_name) {
1579 foreach ($filters as $f) {
1580 if ($f[0] == $filter_name) {
1587 function calculate_article_score($filters) {
1590 foreach ($filters as $f) {
1591 if ($f[0] == "score") {
1598 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1599 foreach ($filters as $f) {
1600 if ($f[0] == "label") {
1601 label_add_article($link, $id, $f[1], $owner_uid);
1606 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1607 $rtl_content = false, $last_updated = false, $last_error = false) {
1609 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1610 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1612 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1616 $rtl_tag = "dir=\"rtl\"";
1618 $rtl_tag = "dir=\"ltr\"";
1621 $error_notify_msg = "";
1624 $link_title = "Error: $last_error ($last_updated)";
1625 $error_notify_msg = "(Error)";
1626 } else if ($last_updated) {
1627 $link_title = "Updated: $last_updated";
1630 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1631 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1633 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1634 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1638 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1641 $fctr_class = "class=\"feedCtrHasUnread\"";
1643 $fctr_class = "class=\"feedCtrNoUnread\"";
1646 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1647 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1649 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1650 $total = getFeedArticles($link, $feed_id);
1651 print "<div class=\"feedExtInfo\">
1652 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1659 function getmicrotime() {
1660 list($usec, $sec) = explode(" ",microtime());
1661 return ((float)$usec +
(float)$sec);
1664 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1665 foreach ($values as $v) {
1672 if ($v == $true_is) {
1673 $sel .= " value=\"1\"";
1675 $sel .= " value=\"0\"";
1678 print "<input class=\"noborder\"
1679 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1684 function initialize_user_prefs($link, $uid) {
1686 $uid = db_escape_string($uid);
1688 db_query($link, "BEGIN");
1690 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1692 $u_result = db_query($link, "SELECT pref_name
1693 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1695 $active_prefs = array();
1697 while ($line = db_fetch_assoc($u_result)) {
1698 array_push($active_prefs, $line["pref_name"]);
1701 while ($line = db_fetch_assoc($result)) {
1702 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1703 // print "adding " . $line["pref_name"] . "<br>";
1705 db_query($link, "INSERT INTO ttrss_user_prefs
1706 (owner_uid,pref_name,value) VALUES
1707 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1712 db_query($link, "COMMIT");
1716 function lookup_user_id($link, $user) {
1718 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1721 if (db_num_rows($result) == 1) {
1722 return db_fetch_result($result, 0, "id");
1728 function http_authenticate_user($link) {
1730 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1732 if (!$_SERVER["PHP_AUTH_USER"]) {
1734 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1735 header('HTTP/1.0 401 Unauthorized');
1739 $auth_result = authenticate_user($link,
1740 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1742 if (!$auth_result) {
1743 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1744 header('HTTP/1.0 401 Unauthorized');
1752 function authenticate_user($link, $login, $password, $force_auth = false) {
1754 if (!SINGLE_USER_MODE
) {
1756 $pwd_hash1 = encrypt_password($password);
1757 $pwd_hash2 = encrypt_password($password, $login);
1759 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1760 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1762 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1764 $query = "SELECT id,login,access_level,pwd_hash
1765 FROM ttrss_users WHERE
1769 $query = "SELECT id,login,access_level,pwd_hash
1770 FROM ttrss_users WHERE
1771 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1772 pwd_hash = '$pwd_hash2')";
1775 $result = db_query($link, $query);
1777 if (db_num_rows($result) == 1) {
1778 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1779 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1780 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1782 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1785 $user_theme = get_user_theme_path($link);
1787 $_SESSION["theme"] = $user_theme;
1788 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1789 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1791 initialize_user_prefs($link, $_SESSION["uid"]);
1800 $_SESSION["uid"] = 1;
1801 $_SESSION["name"] = "admin";
1803 $user_theme = get_user_theme_path($link);
1805 $_SESSION["theme"] = $user_theme;
1806 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1808 initialize_user_prefs($link, $_SESSION["uid"]);
1814 function make_password($length = 8) {
1817 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1821 while ($i < $length) {
1822 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1824 if (!strstr($password, $char)) {
1832 // this is called after user is created to initialize default feeds, labels
1835 // user preferences are checked on every login, not here
1837 function initialize_user($link, $uid) {
1839 /* db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1840 values ('$uid','unread = true', 'Unread articles')");
1842 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1843 values ('$uid','last_read is null and unread = false', 'Updated articles')"); */
1845 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1846 values ('$uid', 'Tiny Tiny RSS: New Releases',
1847 'http://tt-rss.org/releases.rss')");
1849 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1850 values ('$uid', 'Tiny Tiny RSS: Forum',
1851 'http://tt-rss.org/forum/rss.php')");
1854 function logout_user() {
1856 if (isset($_COOKIE[session_name()])) {
1857 setcookie(session_name(), '', time()-42000, '/');
1861 function get_script_urlpath() {
1862 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1865 function validate_session($link) {
1866 if (SINGLE_USER_MODE
) {
1870 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1871 if ($_SESSION["ip_address"]) {
1872 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1873 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1879 if ($_SESSION["uid"]) {
1881 $result = db_query($link,
1882 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1884 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1886 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1891 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1893 //print_r($_SESSION);
1895 if (time() > $_SESSION["cookie_lifetime"]) {
1903 function login_sequence($link, $mobile = false) {
1904 if (!SINGLE_USER_MODE
) {
1906 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1907 $swu = db_escape_string($_REQUEST["swu"]);
1909 $_SESSION["prefs_cache"] = false;
1910 return authenticate_user($link, $swu, null, true);
1914 $login_action = $_POST["login_action"];
1916 # try to authenticate user if called from login form
1917 if ($login_action == "do_login") {
1918 $login = $_POST["login"];
1919 $password = $_POST["password"];
1920 $remember_me = $_POST["remember_me"];
1922 if (authenticate_user($link, $login, $password)) {
1923 $_POST["password"] = "";
1925 $_SESSION["language"] = $_POST["language"];
1926 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1928 header("Location: " . $_SERVER["REQUEST_URI"]);
1933 $_SESSION["login_error_msg"] = "Incorrect username or password";
1937 // print session_id();
1938 // print_r($_SESSION);
1940 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1941 render_login_form($link, $mobile);
1944 /* bump login timestamp */
1945 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1948 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1949 setcookie("ttrss_lang", $_SESSION["language"],
1950 time() + SESSION_COOKIE_LIFETIME
);
1953 /* bump counters stamp since we're getting reloaded anyway */
1955 $_SESSION["get_all_counters_stamp"] = time();
1959 return authenticate_user($link, "admin", null);
1963 function truncate_string($str, $max_len) {
1964 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1965 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1971 function get_user_theme_path($link) {
1972 $result = db_query($link, "SELECT theme_path
1974 ttrss_themes,ttrss_users
1975 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1976 if (db_num_rows($result) != 0) {
1977 return db_fetch_result($result, 0, "theme_path");
1983 function smart_date_time($timestamp) {
1984 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1985 return date("G:i", $timestamp);
1986 } else if (date("Y", $timestamp) == date("Y")) {
1987 return date("M d, G:i", $timestamp);
1989 return date("Y/m/d, G:i", $timestamp);
1993 function smart_date($timestamp) {
1994 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1996 } else if (date("Y", $timestamp) == date("Y")) {
1997 return date("D m", $timestamp);
1999 return date("Y/m/d", $timestamp);
2003 function sql_bool_to_string($s) {
2004 if ($s == "t" ||
$s == "1") {
2011 function sql_bool_to_bool($s) {
2012 if ($s == "t" ||
$s == "1") {
2020 function toggleEvenOdd($a) {
2027 function sanity_check($link) {
2032 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2033 $schema_version = db_fetch_result($result, 0, "schema_version");
2035 if ($schema_version != SCHEMA_VERSION
) {
2039 if (DB_TYPE
== "mysql") {
2040 $result = db_query($link, "SELECT true", false);
2041 if (db_num_rows($result) != 1) {
2046 if (db_escape_string("testTEST") != "testTEST") {
2050 error_reporting (DEFAULT_ERROR_LEVEL
);
2052 if ($error_code != 0) {
2053 print_error_xml($error_code);
2060 function file_is_locked($filename) {
2061 if (function_exists('flock')) {
2063 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2064 error_reporting(DEFAULT_ERROR_LEVEL
);
2066 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2067 flock($fp, LOCK_UN
);
2077 return true; // consider the file always locked and skip the test
2080 function make_lockfile($filename) {
2081 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2083 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2090 function make_stampfile($filename) {
2091 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2093 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2094 fwrite($fp, time() . "\n");
2095 flock($fp, LOCK_UN
);
2103 function read_stampfile($filename) {
2106 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2107 error_reporting (DEFAULT_ERROR_LEVEL
);
2110 if (flock($fp, LOCK_EX
)) {
2111 $stamp = fgets($fp);
2112 flock($fp, LOCK_UN
);
2123 function sql_random_function() {
2124 if (DB_TYPE
== "mysql") {
2131 function catchup_feed($link, $feed, $cat_view) {
2133 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2138 $cat_qpart = "cat_id = '$feed'";
2140 $cat_qpart = "cat_id IS NULL";
2143 $tmp_result = db_query($link, "SELECT id
2144 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2147 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2149 $tmp_feed = $tmp_line["id"];
2151 db_query($link, "UPDATE ttrss_user_entries
2152 SET unread = false,last_read = NOW()
2153 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2156 } else if ($feed > 0) {
2158 $tmp_result = db_query($link, "SELECT id
2159 FROM ttrss_feeds WHERE parent_feed = '$feed'
2160 ORDER BY cat_id,title");
2162 $parent_ids = array();
2164 if (db_num_rows($tmp_result) > 0) {
2165 while ($p = db_fetch_assoc($tmp_result)) {
2166 array_push($parent_ids, "feed_id = " . $p["id"]);
2169 $children_qpart = implode(" OR ", $parent_ids);
2171 db_query($link, "UPDATE ttrss_user_entries
2172 SET unread = false,last_read = NOW()
2173 WHERE (feed_id = '$feed' OR $children_qpart)
2174 AND owner_uid = " . $_SESSION["uid"]);
2177 db_query($link, "UPDATE ttrss_user_entries
2178 SET unread = false,last_read = NOW()
2179 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2182 } else if ($feed < 0 && $feed > -10) { // special, like starred
2185 db_query($link, "UPDATE ttrss_user_entries
2186 SET unread = false,last_read = NOW()
2187 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2191 db_query($link, "UPDATE ttrss_user_entries
2192 SET unread = false,last_read = NOW()
2193 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2198 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2200 if (DB_TYPE
== "pgsql") {
2201 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2203 $match_part = "updated > DATE_SUB(NOW(),
2204 INTERVAL $intl HOUR) ";
2207 $result = db_query($link, "SELECT id FROM ttrss_entries,
2208 ttrss_user_entries WHERE $match_part AND
2210 ttrss_user_entries.ref_id = ttrss_entries.id AND
2211 owner_uid = ".$_SESSION["uid"]);
2213 $affected_ids = array();
2215 while ($line = db_fetch_assoc($result)) {
2216 array_push($affected_ids, $line["id"]);
2219 catchupArticlesById($link, $affected_ids, 0);
2222 } else if ($feed < -10) { // label
2224 // TODO make this more efficient
2226 $label_id = -$feed - 11;
2228 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2229 SET unread = false WHERE label_id = '$label_id'
2230 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2234 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2237 db_query($link, "BEGIN");
2239 $tag_name = db_escape_string($feed);
2241 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2242 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2244 while ($line = db_fetch_assoc($result)) {
2245 db_query($link, "UPDATE ttrss_user_entries SET
2246 unread = false, last_read = NOW()
2247 WHERE int_id = " . $line["post_int_id"]);
2249 db_query($link, "COMMIT");
2253 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2257 $cat_qpart = "cat_id = '$feed'";
2259 $cat_qpart = "cat_id IS NULL";
2262 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2263 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2265 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2266 $feed_url = $tmp_line["feed_url"];
2267 $feed_id = $tmp_line["id"];
2268 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2272 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2273 WHERE id = '$feed'");
2274 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2275 update_rss_feed($link, $feed_url, $feed, $force_update);
2279 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2281 /* getting all counters is a resource intensive operation, so we
2282 * rate limit it a little bit */
2286 // if (get_pref($link, "SYNC_COUNTERS") ||
2287 // time() - $_SESSION["get_all_counters_stamp"] > 5) {
2289 if (!$omode) $omode = "flc";
2291 getGlobalCounters($link);
2293 if (strchr($omode, "l")) getLabelCounters($link);
2294 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2295 if (strchr($omode, "t")) getTagCounters($link);
2296 if (strchr($omode, "c")) {
2297 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2298 getCategoryCounters($link);
2302 $_SESSION["get_all_counters_stamp"] = time();
2307 function getCategoryCounters($link) {
2308 # two special categories are -1 and -2 (all virtuals; all labels)
2310 $ctr = getCategoryUnread($link, -1);
2312 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2314 $ctr = getCategoryUnread($link, -2);
2316 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2318 $age_qpart = getMaxAgeSubquery();
2320 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2321 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2322 WHERE ttrss_cat_counters_cache.feed_id = id AND
2323 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2325 while ($line = db_fetch_assoc($result)) {
2326 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2328 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2329 $line["unread"]."\"/>";
2332 /* Special case: NULL category doesn't actually exist in the DB */
2334 print "<counter type=\"category\" id=\"0\" counter=\"".
2335 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2339 function getCategoryUnread($link, $cat, $owner_uid = false) {
2341 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2346 $cat_query = "cat_id = '$cat'";
2348 $cat_query = "cat_id IS NULL";
2351 $age_qpart = getMaxAgeSubquery();
2353 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2355 AND owner_uid = " . $owner_uid);
2357 $cat_feeds = array();
2358 while ($line = db_fetch_assoc($result)) {
2359 array_push($cat_feeds, "feed_id = " . $line["id"]);
2362 if (count($cat_feeds) == 0) return 0;
2364 $match_part = implode(" OR ", $cat_feeds);
2366 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2367 FROM ttrss_user_entries,ttrss_entries
2368 WHERE unread = true AND ($match_part) AND id = ref_id
2369 AND $age_qpart AND owner_uid = " . $owner_uid);
2373 # this needs to be rewritten
2374 while ($line = db_fetch_assoc($result)) {
2375 $unread +
= $line["unread"];
2379 } else if ($cat == -1) {
2380 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2381 } else if ($cat == -2) {
2383 // FIXME: NEW_LABELS
2385 /* $rv = getLabelCounters($link, false, true);
2388 foreach (array_keys($rv) as $k) {
2390 $ctr += $rv[$k]["counter"];
2398 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2399 if (DB_TYPE
== "pgsql") {
2400 return "ttrss_entries.date_entered >
2401 NOW() - INTERVAL '$days days'";
2403 return "ttrss_entries.date_entered >
2404 DATE_SUB(NOW(), INTERVAL $days DAY)";
2408 function getFeedUnread($link, $feed, $is_cat = false) {
2409 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2412 function getLabelUnread($link, $label_id, $owner_uid = false) {
2413 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2415 $result = db_query($link, "
2416 SELECT SUM(unread) AS unread FROM
2417 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2
2418 WHERE label_id = id AND article_id = ref_id AND
2419 ttrss_labels2.owner_uid = '$owner_uid' AND id = '$label_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) ";
2461 } else if ($n_feed > 0) {
2463 $result = db_query($link, "SELECT id FROM ttrss_feeds
2464 WHERE parent_feed = '$n_feed'
2466 AND owner_uid = " . $owner_uid);
2468 if (db_num_rows($result) > 0) {
2470 $linked_feeds = array();
2471 while ($line = db_fetch_assoc($result)) {
2472 array_push($linked_feeds, "feed_id = " . $line["id"]);
2475 array_push($linked_feeds, "feed_id = $n_feed");
2477 $match_part = implode(" OR ", $linked_feeds);
2479 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2480 FROM ttrss_user_entries,ttrss_entries
2481 WHERE $unread_qpart AND
2482 ttrss_user_entries.ref_id = ttrss_entries.id AND
2485 owner_uid = " . $owner_uid);
2489 # this needs to be rewritten
2490 while ($line = db_fetch_assoc($result)) {
2491 $unread +
= $line["unread"];
2497 $match_part = "feed_id = '$n_feed'";
2499 } else if ($feed < -10) {
2501 $label_id = -$feed - 11;
2503 return getLabelUnread($link, $label_id, $owner_uid);
2509 $result = db_query($link, "SELECT count(int_id) AS unread
2510 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2511 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2512 ttrss_user_entries.ref_id = ttrss_entries.id AND
2513 ttrss_feeds.hidden = false AND
2515 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2519 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2520 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2521 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2522 AND $unread_qpart AND $age_qpart AND
2523 ttrss_tags.owner_uid = " . $owner_uid);
2526 $unread = db_fetch_result($result, 0, "unread");
2531 function getGlobalUnread($link, $user_id = false) {
2534 $user_id = $_SESSION["uid"];
2537 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2538 WHERE owner_uid = '$user_id' AND feed_id > 0");
2540 $c_id = db_fetch_result($result, 0, "c_id");
2545 function getGlobalCounters($link, $global_unread = -1) {
2546 if ($global_unread == -1) {
2547 $global_unread = getGlobalUnread($link);
2549 print "<counter type=\"global\" id='global-unread'
2550 counter='$global_unread'/>";
2552 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2553 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2555 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2557 print "<counter type=\"global\" id='subscribed-feeds'
2558 counter='$subscribed_feeds'/>";
2562 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2565 if (!$_SESSION["tctr_last_value"]) {
2566 $_SESSION["tctr_last_value"] = array();
2570 $old_counters = $_SESSION["tctr_last_value"];
2572 $tctrs_modified = false;
2574 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2575 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2576 ttrss_user_entries.ref_id = ttrss_entries.id AND
2577 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2578 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2580 select tag_name,0 as count FROM ttrss_tags
2581 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2583 $age_qpart = getMaxAgeSubquery();
2585 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2586 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2587 AND ref_id = id AND $age_qpart
2588 AND unread = true)) AS count FROM ttrss_tags
2589 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2590 ORDER BY count DESC LIMIT 55");
2594 while ($line = db_fetch_assoc($result)) {
2595 $tags[$line["tag_name"]] +
= $line["count"];
2598 foreach (array_keys($tags) as $tag) {
2599 $unread = $tags[$tag];
2601 $tag = htmlspecialchars($tag);
2603 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2604 $old_counters[$tag] = $unread;
2605 $tctrs_modified = true;
2606 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2611 if ($smart_mode && $tctrs_modified) {
2612 $_SESSION["tctr_last_value"] = $old_counters;
2617 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2619 $age_qpart = getMaxAgeSubquery();
2622 if (!$_SESSION["lctr_last_value"]) {
2623 $_SESSION["lctr_last_value"] = array();
2629 for ($i = -1; $i >= -3; $i--) {
2631 $count = getFeedUnread($link, $i);
2635 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2636 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2641 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2643 $ret_arr[$i]["counter"] = $count;
2644 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2649 $old_counters = $_SESSION["lctr_last_value"];
2650 $lctrs_modified = false;
2653 $owner_uid = $_SESSION["uid"];
2655 $result = db_query($link,
2656 "SELECT id, caption, SUM(unread) AS unread FROM ttrss_labels2
2657 LEFT JOIN ttrss_user_labels2 ON (label_id = id)
2658 LEFT JOIN ttrss_user_entries ON (ref_id = article_id AND
2659 ttrss_user_entries.owner_uid = '$owner_uid')
2660 WHERE ttrss_labels2.owner_uid = '$owner_uid'
2663 while ($line = db_fetch_assoc($result)) {
2665 $id = -$line["id"] - 11;
2667 $label_name = $line["caption"];
2668 $count = $line["unread"];
2670 if (!$smart_mode ||
$old_counters[$id] != $count) {
2671 $old_counters[$id] = $count;
2672 $lctrs_modified = true;
2675 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2676 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2681 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2683 $ret_arr[$id]["counter"] = $count;
2684 $ret_arr[$id]["description"] = $label_name;
2688 error_reporting (DEFAULT_ERROR_LEVEL
);
2691 if ($smart_mode && $lctrs_modified) {
2692 $_SESSION["lctr_last_value"] = $old_counters;
2698 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2700 $age_qpart = getMaxAgeSubquery();
2703 if (!$_SESSION["fctr_last_value"]) {
2704 $_SESSION["fctr_last_value"] = array();
2708 $old_counters = $_SESSION["fctr_last_value"];
2710 /* $query = "SELECT ttrss_feeds.id,
2712 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2714 COUNT(ttrss_entries.id) AS count
2716 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2717 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2718 AND ttrss_user_entries.unread = true)
2719 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2721 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2722 AND parent_feed IS NULL
2723 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error"; */
2725 $query = "SELECT ttrss_feeds.id,
2727 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2728 last_error, value AS count
2729 FROM ttrss_feeds, ttrss_counters_cache
2730 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2731 AND parent_feed IS NULL
2732 AND ttrss_counters_cache.feed_id = id";
2734 $result = db_query($link, $query);
2735 $fctrs_modified = false;
2737 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2739 while ($line = db_fetch_assoc($result)) {
2742 $count = $line["count"];
2743 $last_error = htmlspecialchars($line["last_error"]);
2745 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2746 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2748 $last_updated = date($short_date, strtotime($line["last_updated"]));
2751 $last_updated = htmlspecialchars($last_updated);
2753 $has_img = feed_has_icon($id);
2755 /* $tmp_result = db_query($link,
2756 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2757 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2758 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2759 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2760 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id"); */
2762 $tmp_result = db_query($link,
2763 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2764 WHERE parent_feed = '$id' AND feed_id = id");
2766 $count +
= db_fetch_result($tmp_result, 0, "unread");
2768 if (!$smart_mode ||
$old_counters[$id] != $count) {
2769 $old_counters[$id] = $count;
2770 $fctrs_modified = true;
2773 $error_part = "error=\"$last_error\"";
2779 $has_img_part = "hi=\"$has_img\"";
2784 if ($active_feed && $id == $active_feed) {
2785 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2787 $has_title_part = "";
2790 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2791 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2794 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2798 if ($smart_mode && $fctrs_modified) {
2799 $_SESSION["fctr_last_value"] = $old_counters;
2803 function get_script_dt_add() {
2804 if (strpos(VERSION
, ".99") === false) {
2811 function get_pgsql_version($link) {
2812 $result = db_query($link, "SELECT version() AS version");
2813 $version = split(" ", db_fetch_result($result, 0, "version"));
2817 function print_error_xml($code, $add_msg = "") {
2820 $error_msg = $ERRORS[$code];
2823 $error_msg = "$error_msg; $add_msg";
2826 print "<rpc-reply>";
2827 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2828 print "</rpc-reply>";
2831 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2832 $auth_login = '', $auth_pass = '') {
2834 # check for feed:http://url
2835 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2837 # check for feed://URL
2838 if (strpos($feed_link, "//") === 0) {
2839 $feed_link = "http:$feed_link";
2842 if ($feed_link == "") return;
2844 if ($cat_id == "0" ||
!$cat_id) {
2845 $cat_qpart = "NULL";
2847 $cat_qpart = "'$cat_id'";
2850 $result = db_query($link,
2851 "SELECT id FROM ttrss_feeds
2852 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2854 if (db_num_rows($result) == 0) {
2856 $result = db_query($link,
2857 "INSERT INTO ttrss_feeds
2858 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2859 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2860 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2862 $result = db_query($link,
2863 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2864 AND owner_uid = " . $_SESSION["uid"]);
2866 $feed_id = db_fetch_result($result, 0, "id");
2869 update_rss_feed($link, $feed_link, $feed_id, true);
2878 function print_feed_select($link, $id, $default_id = "",
2879 $attributes = "", $include_all_feeds = true) {
2881 print "<select id=\"$id\" name=\"$id\" $attributes>";
2882 if ($include_all_feeds) {
2883 print "<option value=\"0\">".__('All feeds')."</option>";
2886 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2887 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2889 if (db_num_rows($result) > 0 && $include_all_feeds) {
2890 print "<option disabled>--------</option>";
2893 while ($line = db_fetch_assoc($result)) {
2894 if ($line["id"] == $default_id) {
2895 $is_selected = "selected";
2899 printf("<option $is_selected value='%d'>%s</option>",
2900 $line["id"], htmlspecialchars($line["title"]));
2906 function print_feed_cat_select($link, $id, $default_id = "",
2907 $attributes = "", $include_all_cats = true) {
2909 print "<select id=\"$id\" name=\"$id\" $attributes>";
2911 if ($include_all_cats) {
2912 print "<option value=\"0\">".__('Uncategorized')."</option>";
2915 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2916 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2918 if (db_num_rows($result) > 0 && $include_all_cats) {
2919 print "<option disabled>--------</option>";
2922 while ($line = db_fetch_assoc($result)) {
2923 if ($line["id"] == $default_id) {
2924 $is_selected = "selected";
2928 printf("<option $is_selected value='%d'>%s</option>",
2929 $line["id"], htmlspecialchars($line["title"]));
2935 function checkbox_to_sql_bool($val) {
2936 return ($val == "on") ?
"true" : "false";
2939 function getFeedCatTitle($link, $id) {
2941 return __("Special");
2942 } else if ($id < -10) {
2943 return __("Labels");
2944 } else if ($id > 0) {
2945 $result = db_query($link, "SELECT ttrss_feed_categories.title
2946 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2947 cat_id = ttrss_feed_categories.id");
2948 if (db_num_rows($result) == 1) {
2949 return db_fetch_result($result, 0, "title");
2951 return __("Uncategorized");
2954 return "getFeedCatTitle($id) failed";
2959 function getFeedTitle($link, $id) {
2961 return __("Starred articles");
2962 } else if ($id == -2) {
2963 return __("Published articles");
2964 } else if ($id == -3) {
2965 return __("Fresh articles");
2966 } else if ($id < -10) {
2967 $label_id = -$id - 11;
2968 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2969 if (db_num_rows($result) == 1) {
2970 return db_fetch_result($result, 0, "caption");
2972 return "Unknown label ($label_id)";
2975 } else if ($id > 0) {
2976 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2977 if (db_num_rows($result) == 1) {
2978 return db_fetch_result($result, 0, "title");
2980 return "Unknown feed ($id)";
2983 return "getFeedTitle($id) failed";
2988 function get_session_cookie_name() {
2989 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2992 function print_init_params($link) {
2993 print "<init-params>";
2994 if ($_SESSION["stored-params"]) {
2995 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2997 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2998 print "<param key=\"$key\" value=\"$value\"/>";
3003 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
3004 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
3005 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
3006 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3008 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
3009 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
3011 print "<param key=\"hide_read_feeds\" value=\"" .
3012 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
3014 print "<param key=\"feeds_sort_by_unread\" value=\"" .
3015 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
3017 print "<param key=\"confirm_feed_catchup\" value=\"" .
3018 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3020 print "<param key=\"cdm_auto_catchup\" value=\"" .
3021 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3023 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3025 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3027 print "<param key=\"default_view_mode\" value=\"" .
3028 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3030 print "<param key=\"default_view_limit\" value=\"" .
3031 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3033 print "<param key=\"default_view_order_by\" value=\"" .
3034 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3036 print "<param key=\"prefs_active_tab\" value=\"" .
3037 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3039 print "<param key=\"infobox_disable_overlay\" value=\"" .
3040 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3042 print "<param key=\"icons_location\" value=\"" .
3045 print "<param key=\"hide_read_shows_special\" value=\"" .
3046 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3048 print "<param key=\"hide_feedlist\" value=\"" .
3049 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3051 print "<param key=\"bw_limit\" value=\"".
3052 (int) $_SESSION["bw_limit"]."\"/>";
3054 // print "<param key=\"sync_counters\" value=\"" .
3055 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3057 print "<param key=\"sync_counters\" value=\"1\"/>";
3059 print "</init-params>";
3062 function print_runtime_info($link) {
3063 print "<runtime-info>";
3065 if (ENABLE_UPDATE_DAEMON
) {
3066 print "<param key=\"daemon_is_running\" value=\"".
3067 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3069 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3071 $stamp = (int)read_stampfile("update_daemon.stamp");
3073 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3076 $stamp_delta = time() - $stamp;
3078 if ($stamp_delta > 1800) {
3082 $_SESSION["daemon_stamp_check"] = time();
3085 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3087 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3089 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3094 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3096 if ($_SESSION["last_version_check"] +
86400 < time()) {
3097 $new_version_details = check_for_update($link);
3099 print "<param key=\"new_version_available\" value=\"".
3100 sprintf("%d", $new_version_details != ""). "\"/>";
3102 $_SESSION["last_version_check"] = time();
3106 // print "<param key=\"new_version_available\" value=\"1\"/>";
3108 print "</runtime-info>";
3111 function getSearchSql($search, $match_on) {
3113 $search_query_part = "";
3115 $keywords = split(" ", $search);
3116 $query_keywords = array();
3118 if ($match_on == "both") {
3120 foreach ($keywords as $k) {
3121 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3122 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3125 $search_query_part = implode("AND", $query_keywords) . " AND ";
3127 } else if ($match_on == "title") {
3129 foreach ($keywords as $k) {
3130 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3133 $search_query_part = implode("AND", $query_keywords) . " AND ";
3135 } else if ($match_on == "content") {
3137 foreach ($keywords as $k) {
3138 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3142 $search_query_part = implode("AND", $query_keywords);
3144 return $search_query_part;
3147 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3149 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3153 $search_query_part = getSearchSql($search, $match_on);
3154 $search_query_part .= " AND ";
3157 $search_query_part = "";
3160 $view_query_part = "";
3162 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3164 $view_query_part = " ";
3165 } else if ($feed != -1) {
3166 $unread = getFeedUnread($link, $feed, $cat_view);
3168 $view_query_part = " unread = true AND ";
3173 if ($view_mode == "marked") {
3174 $view_query_part = " marked = true AND ";
3177 if ($view_mode == "unread") {
3178 $view_query_part = " unread = true AND ";
3182 $limit_query_part = "LIMIT " . $limit;
3185 $vfeed_query_part = "";
3187 // override query strategy and enable feed display when searching globally
3188 if ($search && $search_mode == "all_feeds") {
3189 $query_strategy_part = "ttrss_entries.id > 0";
3190 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3191 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3192 $query_strategy_part = "ttrss_entries.id > 0";
3193 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3194 id = feed_id) as feed_title,";
3195 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3197 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3199 $tmp_result = false;
3202 $tmp_result = db_query($link, "SELECT id
3203 FROM ttrss_feeds WHERE cat_id = '$feed'");
3205 $tmp_result = db_query($link, "SELECT id
3206 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3207 WHERE id = '$feed') AND id != '$feed'");
3210 $cat_siblings = array();
3212 if (db_num_rows($tmp_result) > 0) {
3213 while ($p = db_fetch_assoc($tmp_result)) {
3214 array_push($cat_siblings, "feed_id = " . $p["id"]);
3217 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3218 $feed, implode(" OR ", $cat_siblings));
3221 $query_strategy_part = "ttrss_entries.id > 0";
3224 } else if ($feed >= 0) {
3229 $query_strategy_part = "cat_id = '$feed'";
3231 $query_strategy_part = "cat_id IS NULL";
3234 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3237 $tmp_result = db_query($link, "SELECT id
3238 FROM ttrss_feeds WHERE parent_feed = '$feed'
3239 ORDER BY cat_id,title");
3241 $parent_ids = array();
3243 if (db_num_rows($tmp_result) > 0) {
3244 while ($p = db_fetch_assoc($tmp_result)) {
3245 array_push($parent_ids, "feed_id = " . $p["id"]);
3248 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3249 $feed, implode(" OR ", $parent_ids));
3251 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3253 $query_strategy_part = "feed_id = '$feed'";
3256 } else if ($feed == -1) { // starred virtual feed
3257 $query_strategy_part = "marked = true";
3258 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3259 } else if ($feed == -2) { // published virtual feed
3260 $query_strategy_part = "published = true";
3261 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3262 } else if ($feed == -3) { // fresh virtual feed
3263 $query_strategy_part = "unread = true";
3265 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3267 if (DB_TYPE
== "pgsql") {
3268 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3270 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3273 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3274 } else if ($feed <= -10) { // labels
3275 $label_id = -$feed - 11;
3277 $query_strategy_part = "label_id = '$label_id' AND
3278 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3279 ttrss_user_labels2.article_id = ref_id";
3281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3282 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3285 $query_strategy_part = "id > 0"; // dumb
3288 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3289 $order_by = "updated";
3291 $order_by = "updated DESC";
3294 if ($view_mode != "noscores") {
3295 $order_by = "score DESC, $order_by";
3298 if ($override_order) {
3299 $order_by = $override_order;
3304 if ($search && $search_mode == "all_feeds") {
3305 $feed_title = __("Search results")." ($search)";
3306 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3307 $feed_title = __("Search results")." ($search, $feed)";
3308 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3309 $feed_title = $feed;
3310 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3315 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3316 WHERE id = '$feed' AND owner_uid = $owner_uid");
3317 $feed_title = db_fetch_result($result, 0, "title");
3319 $feed_title = __("Uncategorized");
3323 $feed_title = __("Searched for")." $search ($feed_title)";
3328 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3329 WHERE id = '$feed' AND owner_uid = $owner_uid");
3331 $feed_title = db_fetch_result($result, 0, "title");
3332 $feed_site_url = db_fetch_result($result, 0, "site_url");
3333 $last_error = db_fetch_result($result, 0, "last_error");
3336 $feed_title = __("Searched for") . " $search ($feed_title)";
3340 } else if ($feed == -1) {
3341 $feed_title = __("Starred articles");
3342 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3343 } else if ($feed == -2) {
3344 $feed_title = __("Published articles");
3345 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3346 } else if ($feed == -3) {
3347 $feed_title = __("Fresh articles");
3348 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3349 } else if ($feed < -10) {
3350 $label_id = -$feed - 11;
3351 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3352 WHERE id = '$label_id'");
3353 $feed_title = db_fetch_result($result, 0, "caption");
3356 $feed_title = __("Searched for") . " $search ($feed_title)";
3362 if ($feed < -10) error_reporting (0);
3364 $content_query_part = "content as content_preview,";
3366 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3369 $feed_kind = "Feeds";
3371 $feed_kind = "Labels";
3374 if ($limit_query_part) {
3375 $offset_query_part = "OFFSET $offset";
3378 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3379 if (!$override_order) {
3380 $order_by = "ttrss_feeds.title, $order_by";
3383 // Special output for Fresh feed
3385 /* if ($feed == -3) {
3386 $group_limit_part = "(select count(*) from
3387 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3388 t1.ref_id = t2.id and t1.owner_uid = 2 and
3389 t1.feed_id = ttrss_user_entries.feed_id and
3390 t2.updated > ttrss_entries.updated) <= 5 AND";
3396 ttrss_entries.id,ttrss_entries.title,
3398 unread,feed_id,marked,published,link,last_read,
3399 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3402 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3405 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3408 ttrss_feeds.hidden = false AND
3409 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3410 ttrss_user_entries.ref_id = ttrss_entries.id AND
3411 ttrss_user_entries.owner_uid = '$owner_uid' AND
3414 $query_strategy_part ORDER BY $order_by
3415 $limit_query_part $offset_query_part";
3417 if ($_GET["debug"]) print $query;
3419 $result = db_query($link, $query);
3424 $feed_kind = "Tags";
3426 $result = db_query($link, "SELECT
3428 ttrss_entries.id as id,title,
3431 marked,link,last_read,
3432 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3435 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3438 ttrss_entries,ttrss_user_entries,ttrss_tags
3440 ref_id = ttrss_entries.id AND
3441 ttrss_user_entries.owner_uid = '$owner_uid' AND
3442 post_int_id = int_id AND tag_name = '$feed' AND
3445 $query_strategy_part ORDER BY $order_by
3446 $limit_query_part");
3449 return array($result, $feed_title, $feed_site_url, $last_error);
3453 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3454 $limit, $search, $search_mode, $match_on) {
3456 if (!$limit) $limit = 30;
3458 $qfh_ret = queryFeedHeadlines($link, $feed,
3459 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3462 $result = $qfh_ret[0];
3463 $feed_title = htmlspecialchars($qfh_ret[1]);
3464 $feed_site_url = $qfh_ret[2];
3465 $last_error = $qfh_ret[3];
3467 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3469 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3470 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3471 <rss version=\"2.0\">
3473 <title>$feed_title</title>
3474 <link>$feed_site_url</link>
3475 <description>Feed generated by Tiny Tiny RSS</description>";
3477 while ($line = db_fetch_assoc($result)) {
3479 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3480 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3482 $tags = get_article_tags($link, $line["id"], $owner_uid);
3484 foreach ($tags as $tag) {
3485 print "<category>" . htmlspecialchars($tag) . "</category>";
3488 $rfc822_date = date('r', strtotime($line["updated"]));
3490 print "<pubDate>$rfc822_date</pubDate>";
3493 htmlspecialchars($line["title"]) . "</title>";
3495 print "<description><![CDATA[" .
3496 $line["content_preview"] . "]]></description>";
3501 print "</channel></rss>";
3505 function getCategoryTitle($link, $cat_id) {
3507 if ($cat_id == -1) {
3508 return __("Special");
3509 } else if ($cat_id == -2) {
3510 return __("Labels");
3513 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3516 if (db_num_rows($result) == 1) {
3517 return db_fetch_result($result, 0, "title");
3519 return "Uncategorized";
3524 // http://ru2.php.net/strip-tags
3526 function strip_tags_long($textstring, $allowed){
3527 while($textstring != strip_tags($textstring, $allowed))
3529 while (strlen($textstring) != 0)
3531 if (strlen($textstring) > 1024) {
3534 $otherlen = strlen($textstring);
3536 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3537 $safetext .= $temptext;
3538 $textstring = substr_replace($textstring,'',0,$otherlen);
3540 $textstring = $safetext;
3546 function sanitize_rss($link, $str, $force_strip_tags = false) {
3549 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3551 $res = strip_tags_long($res,
3552 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3554 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3555 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3558 if (get_pref($link, "STRIP_IMAGES")) {
3560 $res = preg_replace('/<img[^>]+>/is', '', $res);
3568 * Send by mail a digest of last articles.
3570 * @param mixed $link The database connection.
3571 * @param integer $limit The maximum number of articles by digest.
3572 * @return boolean Return false if digests are not enabled.
3574 function send_headlines_digests($link, $limit = 100) {
3576 if (!DIGEST_ENABLE
) return false;
3578 $user_limit = DIGEST_EMAIL_LIMIT
;
3581 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3583 if (DB_TYPE
== "pgsql") {
3584 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3585 } else if (DB_TYPE
== "mysql") {
3586 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3589 $result = db_query($link, "SELECT id,email FROM ttrss_users
3590 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3592 while ($line = db_fetch_assoc($result)) {
3594 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3595 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3597 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3599 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3600 $digest = $tuple[0];
3601 $headlines_count = $tuple[1];
3602 $affected_ids = $tuple[2];
3603 $digest_text = $tuple[3];
3605 if ($headlines_count > 0) {
3607 $mail = new PHPMailer();
3609 $mail->PluginDir
= "phpmailer/";
3610 $mail->SetLanguage("en", "phpmailer/language/");
3612 $mail->CharSet
= "UTF-8";
3614 $mail->From
= DIGEST_FROM_ADDRESS
;
3615 $mail->FromName
= DIGEST_FROM_NAME
;
3616 $mail->AddAddress($line["email"], $line["login"]);
3618 if (DIGEST_SMTP_HOST
) {
3619 $mail->Host
= DIGEST_SMTP_HOST
;
3620 $mail->Mailer
= "smtp";
3621 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3622 $mail->Username
= DIGEST_SMTP_LOGIN
;
3623 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3626 $mail->IsHTML(true);
3627 $mail->Subject
= DIGEST_SUBJECT
;
3628 $mail->Body
= $digest;
3629 $mail->AltBody
= $digest_text;
3631 $rc = $mail->Send();
3633 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3637 if ($rc && $do_catchup) {
3638 print "Marking affected articles as read...\n";
3639 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3642 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3643 WHERE id = " . $line["id"]);
3645 print "No headlines\n";
3650 print "All done.\n";
3654 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3656 require_once "MiniTemplator.class.php";
3658 $tpl = new MiniTemplator
;
3659 $tpl_t = new MiniTemplator
;
3661 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3662 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3664 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3665 $tpl->setVariable('CUR_TIME', date('G:i'));
3667 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3668 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3670 $affected_ids = array();
3672 if (DB_TYPE
== "pgsql") {
3673 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3674 } else if (DB_TYPE
== "mysql") {
3675 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3678 $result = db_query($link, "SELECT ttrss_entries.title,
3679 ttrss_feeds.title AS feed_title,
3681 ttrss_user_entries.ref_id,
3683 SUBSTRING(content, 1, 120) AS excerpt,
3684 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3686 ttrss_user_entries,ttrss_entries,ttrss_feeds
3688 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3689 AND include_in_digest = true
3692 AND ttrss_user_entries.owner_uid = $user_id
3694 ORDER BY ttrss_feeds.title, date_entered DESC
3697 $cur_feed_title = "";
3699 $headlines_count = db_num_rows($result);
3701 $headlines = array();
3703 while ($line = db_fetch_assoc($result)) {
3704 array_push($headlines, $line);
3707 for ($i = 0; $i < sizeof($headlines); $i++
) {
3709 $line = $headlines[$i];
3711 array_push($affected_ids, $line["ref_id"]);
3713 $updated = smart_date_time(strtotime($line["last_updated"]));
3715 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3716 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3717 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3718 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3719 $tpl->setVariable('ARTICLE_EXCERPT',
3720 truncate_string(strip_tags($line["excerpt"]), 100));
3722 $tpl->addBlock('article');
3724 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3725 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3726 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3727 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3728 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3729 // truncate_string(strip_tags($line["excerpt"]), 100));
3731 $tpl_t->addBlock('article');
3733 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3734 $tpl->addBlock('feed');
3735 $tpl_t->addBlock('feed');
3740 $tpl->addBlock('digest');
3741 $tpl->generateOutputToString($tmp);
3743 $tpl_t->addBlock('digest');
3744 $tpl_t->generateOutputToString($tmp_t);
3746 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3749 function check_for_update($link, $brief_fmt = true) {
3750 $releases_feed = "http://tt-rss.org/releases.rss";
3752 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3757 if (ENABLE_SIMPLEPIE
) {
3758 $rss = new SimplePie();
3759 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3760 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3761 $rss->set_feed_url($fetch_url);
3762 $rss->set_output_encoding('UTF-8');
3765 $rss = fetch_rss($releases_feed);
3767 error_reporting (DEFAULT_ERROR_LEVEL
);
3771 if (ENABLE_SIMPLEPIE
) {
3772 $items = $rss->get_items();
3774 $items = $rss->items
;
3776 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3777 if (!$items ||
!is_array($items)) $items = $rss;
3780 if (!is_array($items) ||
count($items) == 0) {
3784 $latest_item = $items[0];
3786 if (ENABLE_SIMPLEPIE
) {
3787 $last_title = $latest_item->get_title();
3789 $last_title = $latest_item["title"];
3792 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3794 if (ENABLE_SIMPLEPIE
) {
3795 $release_url = sanitize_rss($link, $latest_item->get_link());
3796 $content = sanitize_rss($link, $latest_item->get_description());
3798 $release_url = sanitize_rss($link, $latest_item["link"]);
3799 $content = sanitize_rss($link, $latest_item["description"]);
3802 if (version_compare(VERSION
, $latest_version) == -1) {
3804 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3805 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3806 <div id=\"milestoneDetails\">$content</div>");
3808 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3809 <div class='milestoneDetails'>$content</div>
3810 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3811 download and update information.";
3818 function markArticlesById($link, $ids, $cmode) {
3822 foreach ($ids as $id) {
3823 array_push($tmp_ids, "ref_id = '$id'");
3826 $ids_qpart = join(" OR ", $tmp_ids);
3829 db_query($link, "UPDATE ttrss_user_entries SET
3830 marked = false,last_read = NOW()
3831 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3832 } else if ($cmode == 1) {
3833 db_query($link, "UPDATE ttrss_user_entries SET
3835 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3837 db_query($link, "UPDATE ttrss_user_entries SET
3838 marked = NOT marked,last_read = NOW()
3839 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3843 function publishArticlesById($link, $ids, $cmode) {
3847 foreach ($ids as $id) {
3848 array_push($tmp_ids, "ref_id = '$id'");
3851 $ids_qpart = join(" OR ", $tmp_ids);
3854 db_query($link, "UPDATE ttrss_user_entries SET
3855 published = false,last_read = NOW()
3856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3857 } else if ($cmode == 1) {
3858 db_query($link, "UPDATE ttrss_user_entries SET
3860 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3862 db_query($link, "UPDATE ttrss_user_entries SET
3863 published = NOT published,last_read = NOW()
3864 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3868 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3870 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3874 foreach ($ids as $id) {
3875 array_push($tmp_ids, "ref_id = '$id'");
3878 $ids_qpart = join(" OR ", $tmp_ids);
3881 db_query($link, "UPDATE ttrss_user_entries SET
3882 unread = false,last_read = NOW()
3883 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3884 } else if ($cmode == 1) {
3885 db_query($link, "UPDATE ttrss_user_entries SET
3887 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3889 db_query($link, "UPDATE ttrss_user_entries SET
3890 unread = NOT unread,last_read = NOW()
3891 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3896 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3897 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3899 while ($line = db_fetch_assoc($result)) {
3900 ccache_update($link, $line["feed_id"], $owner_uid);
3904 function catchupArticleById($link, $id, $cmode) {
3907 db_query($link, "UPDATE ttrss_user_entries SET
3908 unread = false,last_read = NOW()
3909 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3910 } else if ($cmode == 1) {
3911 db_query($link, "UPDATE ttrss_user_entries SET
3913 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3915 db_query($link, "UPDATE ttrss_user_entries SET
3916 unread = NOT unread,last_read = NOW()
3917 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3921 function make_guid_from_title($title) {
3922 return preg_replace("/[ \"\',.:;]/", "-",
3923 mb_strtolower(strip_tags($title), 'utf-8'));
3926 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3927 $bottom = false, $rtl_content = false, $feed_id = 0,
3928 $is_cat = false, $search = false, $match_on = false,
3929 $search_mode = false, $offset = 0, $limit = 0,
3930 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3932 $user_page_offset = $offset +
1;
3935 $class = "headlinesSubToolbar";
3936 $tid = "headlineActionsTop";
3938 $class = "headlinesSubToolbar";
3939 $tid = "headlineActionsBottom";
3942 print "<nobr><table class=\"$class\" id=\"$tid\"
3943 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3951 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3952 $page_next_link = "javascript:viewFeedGoPage(1)";
3953 $page_first_link = "javascript:viewFeedGoPage(0)";
3955 $catchup_page_link = "javascript:catchupPage()";
3956 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3957 $catchup_sel_link = "javascript:catchupSelection()";
3959 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3961 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3962 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3963 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3964 $sel_inv_link = "javascript:invertHeadlineSelection()";
3966 $tog_unread_link = "javascript:selectionToggleUnread()";
3967 $tog_marked_link = "javascript:selectionToggleMarked()";
3968 $tog_published_link = "javascript:selectionTogglePublished()";
3972 $sel_all_link = "javascript:cdmSelectArticles('all')";
3973 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3974 $sel_none_link = "javascript:cdmSelectArticles('none')";
3976 $sel_inv_link = "javascript:invertHeadlineSelection()";
3978 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3979 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3980 $tog_published_link = "javascript:selectionTogglePublished(true)";
3984 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3986 print "<td class=\"headlineActions$rtl_cpart\">
3987 <ul class=\"headlineDropdownMenu\">
3990 <a href=\"$sel_all_link\">".__('All')."</a>,
3991 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3992 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3993 <a href=\"$sel_none_link\">".__('None')."</a></li>
3994 <li class=\"vsep\"> </li>
3995 <li class=\"top\">".__('Actions...')."<ul>
3996 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
3997 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
3998 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
3999 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4000 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4001 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
4002 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4004 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4007 <li onclick=\"catchupRelativeToArticle(0)\"> ".__("Above active article")."</li>
4008 <li onclick=\"catchupRelativeToArticle(1)\"> ".__("Below active article")."</li>";
4011 <li><span class=\"insensitive\"> ".__("Above active article")."</span></li>
4012 <li><span class=\"insensitive\"> ".__("Below active article")."</span></li>";
4016 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4018 //print "<li><span class=\"insensitive\">--------</span></li>";
4019 print "<li><span class=\"insensitive\">".__('Assign label:')."</span></li>";
4021 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
4022 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4024 while ($line = db_fetch_assoc($result)) {
4026 $label_id = $line["id"];
4027 $label_caption = $line["caption"];
4029 if ($feed_id < -10 && $feed_id == -11-$label_id) {
4030 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
4031 $label_caption ".__('(remove)')."</li>";
4033 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
4034 $label_caption</li>";
4038 print "</ul></li></ul>";
4042 // old style subtoolbar:
4044 print "<td class=\"headlineActions$rtl_cpart\">".
4046 <a href=\"$sel_all_link\">".__('All')."</a>,
4047 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4048 <a href=\"$sel_none_link\">".__('None')."</a>
4050 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4051 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4053 __('Mark as read:')."
4054 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4055 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4061 print "<td class=\"headlineTitle$rtl_cpart\">";
4063 print "<span id=\"subtoolbar_search\"
4064 style=\"display : none\"><input
4065 id=\"subtoolbar_search_box\"
4066 onblur=\"javascript:enableHotkeys();\"
4067 onfocus=\"javascript:disableHotkeys();\"
4068 onchange=\"subtoolbarSearch()\"
4069 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4071 print "<span id=\"subtoolbar_ftitle\">";
4073 if ($feed_site_url) {
4075 $target = "target=\"_blank\"";
4077 print "<a $target href=\"$feed_site_url\">".
4078 truncate_string($feed_title,30)."</a>";
4084 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4087 if ($user_page_offset > 1) {
4088 print " [$user_page_offset] ";
4091 if (!$bottom && !$disable_feed) {
4093 <a target=\"_blank\"
4094 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4095 <img class=\"noborder\"
4096 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4098 } else if ($feed_small_icon) {
4099 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4105 print "</tr></table></nobr>";
4109 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4111 $tmp_category = getCategoryTitle($link, $cat_id);
4114 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4116 $cat_unread = getCategoryUnread($link, $cat_id);
4120 $holder_style = "display:none;";
4127 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4130 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4131 $inner_title_class = "catTitle";
4133 $browse_cat_link = "";
4134 $inner_title_class = "catTitleNL";
4138 $cat_class = "feedCat";
4140 $cat_class = "virtCat";
4143 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4144 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4145 title=\"".__('Click to collapse category')."\"
4146 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4147 id=\"FCATN-$cat_id\" $browse_cat_link
4148 \">$tmp_category</span>";
4150 print "<span id=\"FCAP-$cat_id\">";
4152 print " <span id=\"FCATCTR-$cat_id\"
4153 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4159 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4163 function outputFeedList($link, $tags = false) {
4165 print "<ul class=\"feedList\" id=\"feedList\">";
4167 $owner_uid = $_SESSION["uid"];
4171 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4173 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4176 $cat_hidden = false;
4179 printCategoryHeader($link, -1, $cat_hidden, false);
4182 $num_starred = getFeedUnread($link, -1);
4183 $num_published = getFeedUnread($link, -2);
4184 $num_fresh = getFeedUnread($link, -3);
4188 if ($num_fresh > 0) $class .= "Unread";
4190 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4191 "images/fresh.png", $link);
4195 if ($num_starred > 0) $class .= "Unread";
4197 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4200 $mark_img_ext = "gif";
4202 $mark_img_ext = "png";
4205 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4206 "images/mark_set.$mark_img_ext", $link);
4210 if ($num_published > 0) $class .= "Unread";
4212 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4213 "images/pub_set.gif", $link);
4215 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4222 $result = db_query($link, "SELECT id,caption FROM
4223 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4225 if (db_num_rows($result) > 0) {
4226 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4228 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4231 $cat_hidden = false;
4234 printCategoryHeader($link, -2, $cat_hidden, false);
4237 print "<li><hr></li>";
4241 while ($line = db_fetch_assoc($result)) {
4243 $label_id = -$line['id'] - 11;
4244 $count = getFeedUnread($link, $label_id);
4252 printFeedEntry($label_id,
4253 $class, $line["caption"],
4254 $count, "images/label.png", $link);
4258 if (db_num_rows($result) > 0) {
4259 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4265 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4266 print "<li><hr></li>";
4269 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4270 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4271 $order_by_qpart = "order_id,category,unread DESC,title";
4273 $order_by_qpart = "order_id,category,title";
4276 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4277 $order_by_qpart = "unread DESC,title";
4279 $order_by_qpart = "title";
4283 $age_qpart = getMaxAgeSubquery();
4285 $query = "SELECT ttrss_feeds.*,
4286 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4288 ttrss_feed_categories.title AS category,
4289 ttrss_feed_categories.collapsed
4290 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4291 ON (ttrss_feed_categories.id = cat_id)
4293 ttrss_feeds.hidden = false AND
4294 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4295 ORDER BY $order_by_qpart";
4297 $result = db_query($link, $query);
4299 $actid = $_GET["actid"];
4309 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4311 while ($line = db_fetch_assoc($result)) {
4313 $feed = trim($line["title"]);
4315 if (!$feed) $feed = "[Untitled]";
4317 $feed_id = $line["id"];
4319 $subop = $_GET["subop"];
4321 $unread = ccache_find($link, $feed_id, $_SESSION["uid"]);
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 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4618 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4620 $entry_comments = "";
4623 $num_comments = $line["num_comments"];
4624 $entry_comments = "";
4626 if ($num_comments > 0) {
4627 if ($line["comments"]) {
4628 $comments_url = $line["comments"];
4630 $comments_url = $line["link"];
4632 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4634 if ($line["comments"] && $line["link"] != $line["comments"]) {
4635 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4640 header("Content-Type: text/html");
4642 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4643 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4644 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4649 print "<div class=\"postReply\">";
4651 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4652 onmouseout=\"enable_resize(false)\">";
4654 $entry_author = $line["author"];
4656 if ($entry_author) {
4657 $entry_author = __(" - ") . $entry_author;
4660 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4661 strtotime($line["updated"]));
4663 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4665 if ($line["link"]) {
4666 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4667 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4669 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4672 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4673 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4674 ORDER BY tag_name"); */
4676 $tags = get_article_tags($link, $id);
4679 $tags_nolinks_str = "";
4684 if ($_SESSION["theme"] == "3pane") {
4690 foreach ($tags as $tag) {
4692 $tag_escaped = str_replace("'", "\\'", $tag);
4694 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4696 if ($num_tags == $tag_limit) {
4697 $tags_str .= "…";
4698 $tags_nolinks_str .= "…";
4700 } else if ($num_tags < $tag_limit) {
4701 $tags_str .= $tag_str;
4702 $tags_nolinks_str .= "$tag, ";
4704 $f_tags_str .= $tag_str;
4707 $tags_str = preg_replace("/, $/", "", $tags_str);
4708 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4709 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4711 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4712 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4714 if (!$entry_comments) $entry_comments = " "; # placeholder
4716 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4717 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4719 print "<div style='float : right'>
4720 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4724 <a title=\"".__('Edit tags for this article')."\"
4725 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4727 if (defined('_ENABLE_INLINE_VIEW')) {
4729 print "<img src=\"images/art-inline.png\" class='tagsPic'
4730 style=\"cursor : pointer\" style=\"cursor : pointer\"
4731 onclick=\"showOriginalArticleInline($id)\"
4732 alt='Inline' title='".__('Display original article content')."'>";
4736 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4737 style=\"cursor : pointer\" style=\"cursor : pointer\"
4738 onclick=\"zoomToArticle($id)\"
4739 alt='Zoom' title='".__('Show article summary in new window')."'>";
4741 print "$tags_nolinks_str";
4744 print "<div clear='both'>$entry_comments</div>";
4748 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4749 print "<div class=\"postContent\">";
4751 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4753 $article_content = sanitize_rss($link, $line["content"]);
4755 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4756 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4760 print $article_content;
4762 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4763 post_id = '$id' AND content_url != ''");
4765 if (db_num_rows($result) > 0) {
4767 $entries_html = array();
4770 while ($line = db_fetch_assoc($result)) {
4772 $url = $line["content_url"];
4773 $ctype = $line["content_type"];
4775 if (!$ctype) $ctype = __("unknown type");
4777 $filename = substr($url, strrpos($url, "/")+
1);
4781 if (($ctype == __("audio/mpeg")) &&
4782 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4784 $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> ";
4788 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4789 $filename . " (" . $ctype . ")" . "</a>";
4791 array_push($entries_html, $entry);
4795 $entry["type"] = $ctype;
4796 $entry["filename"] = $filename;
4797 $entry["url"] = $url;
4799 array_push($entries, $entry);
4802 print "<div class=\"postEnclosures\">";
4804 if (!preg_match("/img/i", $article_content)) {
4805 foreach ($entries as $entry) {
4806 if (preg_match("/image/", $entry["type"])) {
4808 alt=\"".htmlspecialchars($entry["filename"])."\"
4809 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4814 print "<div class=\"postEnclosures\">";
4816 if (db_num_rows($result) == 1) {
4817 print __("Attachment:") . " ";
4819 print __("Attachments:") . " ";
4822 print join(", ", $entries_html);
4834 print "]]></article>";
4837 <div style=\"text-align : center\">
4838 <input type=\"submit\" onclick=\"return window.close()\"
4839 value=\"".__("Close this window")."\"></div>";
4840 print "</body></html>";
4846 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4847 $next_unread_feed, $offset, $vgr_last_feed = false,
4848 $override_order = false) {
4850 $disable_cache = false;
4852 $timing_info = getmicrotime();
4854 $topmost_article_ids = array();
4860 if ($subop == "undefined") $subop = "";
4862 $subop_split = split(":", $subop);
4864 if ($subop == "CatchupSelected") {
4865 $ids = split(",", db_escape_string($_GET["ids"]));
4866 $cmode = sprintf("%d", $_GET["cmode"]);
4868 catchupArticlesById($link, $ids, $cmode);
4871 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4872 update_generic_feed($link, $feed, $cat_view, true);
4875 if ($subop == "MarkAllRead") {
4876 catchup_feed($link, $feed, $cat_view);
4878 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4879 if ($next_unread_feed) {
4880 $feed = $next_unread_feed;
4885 if ($subop_split[0] == "MarkAllReadGR") {
4886 catchup_feed($link, $subop_split[1], false);
4891 $result = db_query($link,
4892 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4894 if (db_num_rows($result) == 0) {
4895 print "<div align='center'>".__('Feed not found.')."</div>";
4900 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4902 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4903 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4905 if (db_num_rows($result) == 1) {
4906 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4908 $rtl_content = false;
4912 $rtl_tag = "dir=\"RTL\"";
4918 $rtl_content = false;
4921 $script_dt_add = get_script_dt_add();
4923 /// START /////////////////////////////////////////////////////////////////////////////////
4925 $search = db_escape_string($_GET["query"]);
4928 $disable_cache = true;
4931 $search_mode = db_escape_string($_GET["search_mode"]);
4932 $match_on = db_escape_string($_GET["match_on"]);
4938 $real_offset = $offset * $limit;
4940 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4942 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4943 $search, $search_mode, $match_on, $override_order, $real_offset);
4945 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4947 $result = $qfh_ret[0];
4948 $feed_title = $qfh_ret[1];
4949 $feed_site_url = $qfh_ret[2];
4950 $last_error = $qfh_ret[3];
4952 $vgroup_last_feed = $vgr_last_feed;
4955 $feed_site_url = article_publish_url($link);
4958 /// STOP //////////////////////////////////////////////////////////////////////////////////
4961 print "<div id=\"headlinesContainer\" $rtl_tag>";
4964 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4968 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4969 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4972 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4975 $headlines_count = db_num_rows($result);
4977 if (db_num_rows($result) > 0) {
4979 # print "\{$offset}";
4981 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4982 print "<table class=\"headlinesList\" id=\"headlinesList\"
4983 cellspacing=\"0\">";
4986 $lnum = $limit*$offset;
4988 error_reporting (DEFAULT_ERROR_LEVEL
);
4991 $cur_feed_title = '';
4993 while ($line = db_fetch_assoc($result)) {
4995 $class = ($lnum %
2) ?
"even" : "odd";
4998 $feed_id = $line["feed_id"];
5000 if (count($topmost_article_ids) < 5) {
5001 array_push($topmost_article_ids, $id);
5004 if ($line["last_read"] == "" &&
5005 ($line["unread"] != "t" && $line["unread"] != "1")) {
5007 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5010 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5014 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5022 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5025 $mark_img_ext = "gif";
5027 $mark_img_ext = "png";
5030 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5031 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5033 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5035 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5037 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5040 if ($line["published"] == "t" ||
$line["published"] == "1") {
5041 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5043 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5045 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5047 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5050 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5051 # $line["title"] . "</a>";
5053 # $content_link = "<a
5054 # href=\"" . htmlspecialchars($line["link"]) . "\"
5055 # onclick=\"view($id,$feed_id);\">" .
5056 # $line["title"] . "</a>";
5058 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5059 # $line["title"] . "</a>";
5061 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5062 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5064 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5065 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5068 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5069 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5073 $score = $line["score"];
5075 $score_pic = get_score_pic($score);
5077 $score_title = __("(Click to change)");
5079 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5080 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">";
5084 } else if ($score < -100) {
5090 $entry_author = $line["author"];
5092 if ($entry_author) {
5093 $entry_author = " - $entry_author";
5096 $has_feed_icon = feed_has_icon($feed_id);
5098 if ($has_feed_icon) {
5099 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5101 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5102 $feed_icon_img = "";
5105 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5107 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5108 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5110 $cur_feed_title = $line["feed_title"];
5111 $vgroup_last_feed = $feed_id;
5113 $cur_feed_title = htmlspecialchars($cur_feed_title);
5115 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5117 print "<tr class='feedTitle'><td colspan='7'>".
5118 "<div style=\"float : right\">$feed_icon_img</div>".
5119 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5120 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5124 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5125 onmouseout='postMouseOut($id)'";
5127 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5129 print "<td class='hlUpdPic'>$update_pic</td>";
5131 print "<td class='hlSelectRow'>
5132 <input type=\"checkbox\" onclick=\"tSR(this)\"
5136 print "<td class='hlMarkedPic'>$marked_pic</td>";
5137 print "<td class='hlMarkedPic'>$published_pic</td>";
5139 # if ($line["feed_title"]) {
5140 # print "<td class='hlContent'>$content_link</td>";
5141 # print "<td class='hlFeed'>
5142 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5143 # truncate_string($line["feed_title"],30)."</a> </td>";
5146 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5148 print "<a id=\"RTITLE-$id\"
5149 href=\"" . htmlspecialchars($line["link"]) . "\"
5150 onclick=\"return view($id,$feed_id);\">" .
5153 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5154 if ($content_preview) {
5155 print "<span class=\"contentPreview\"> - $content_preview</span>";
5161 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5162 # $line["feed_title"]."</a>
5164 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5165 if ($line["feed_title"]) {
5166 print "<span class=\"hlFeed\">
5167 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5168 $line["feed_title"]."</a>)
5176 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5178 print "<td class='hlMarkedPic'>$score_pic</td>";
5180 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5181 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5188 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5189 if ($feed_id != $vgroup_last_feed) {
5191 $cur_feed_title = $line["feed_title"];
5192 $vgroup_last_feed = $feed_id;
5194 $cur_feed_title = htmlspecialchars($cur_feed_title);
5196 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5198 $has_feed_icon = feed_has_icon($feed_id);
5200 if ($has_feed_icon) {
5201 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5203 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5206 print "<div class='cdmFeedTitle'>".
5207 "<div style=\"float : right\">$feed_icon_img</div>".
5208 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5209 $line["feed_title"]."</a> $vf_catchup_link</div>";
5214 $add_class = "Unread";
5219 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5220 $show_excerpt = false;
5222 if ($expand_cdm && $score >= -100) {
5224 $show_excerpt = false;
5226 $cdm_cstyle = "style=\"display : none\"";
5227 $show_excerpt = true;
5230 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5231 onmouseout='postMouseOut($id)'";
5233 print "<div class=\"cdmArticle$add_class\"
5235 $mouseover_attrs'>";
5237 print "<div class=\"cdmHeader\">";
5239 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5240 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5243 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5246 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5247 onclick=\"javascript:toggleUnread($id, 0)\"
5248 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5251 print $entry_author;
5253 /* if (!$expand_cdm || $score < -100) {
5254 print " <a id=\"CICH-$id\"
5255 href=\"javascript:cdmExpandArticle($id)\">
5256 (".__('Show article').")</a>";
5260 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5261 if ($line["feed_title"]) {
5262 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5266 print "</span></div>";
5268 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5269 $line["content_preview"] = preg_replace("/href=/i",
5270 "target=\"_blank\" href=", $line["content_preview"]);
5273 if ($show_excerpt) {
5274 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5275 onclick=\"cdmExpandArticle($id)\"
5276 title=\"".__('Click to expand article')."\">";
5277 print truncate_string(strip_tags($line["content_preview"]), 100);
5281 print "<div class=\"cdmContent\"
5282 onclick=\"cdmClicked($id)\"
5283 id=\"CICD-$id\" $cdm_cstyle>";
5285 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5287 print sanitize_rss($link, $line["content_preview"]);
5288 $article_content = $line["content_preview"];
5290 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5291 post_id = '$id' AND content_url != ''");
5293 if (db_num_rows($e_result) > 0) {
5295 $entries_html = array();
5298 while ($e_line = db_fetch_assoc($e_result)) {
5300 $url = $e_line["content_url"];
5301 $ctype = $e_line["content_type"];
5302 if (!$ctype) $ctype = __("unknown type");
5304 $filename = substr($url, strrpos($url, "/")+
1);
5308 if (($ctype == __("audio/mpeg")) &&
5309 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5311 $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> ";
5315 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5316 $filename . " (" . $ctype . ")" . "</a>";
5318 array_push($entries_html, $entry);
5322 $entry["type"] = $ctype;
5323 $entry["filename"] = $filename;
5324 $entry["url"] = $url;
5326 array_push($entries, $entry);
5329 if (!preg_match("/img/i", $article_content)) {
5330 foreach ($entries as $entry) {
5331 if (preg_match("/image/", $entry["type"])) {
5333 alt=\"".htmlspecialchars($entry["filename"])."\"
5334 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5339 print "<div class=\"cdmEnclosures\">";
5341 if (db_num_rows($e_result) == 1) {
5342 print __("Attachment:") . " ";
5344 print __("Attachments:") . " ";
5347 print join(", ", $entries_html);
5353 print "<br clear='both'>";
5356 /* if (!$expand_cdm) {
5357 print "<a id=\"CICH-$id\"
5358 href=\"javascript:cdmExpandArticle($id)\">
5364 print "<div class=\"cdmFooter\"><span class='s0'>";
5366 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5368 print __("Select:").
5369 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5370 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5372 print "</span><span class='s1'>$marked_pic</span> ";
5373 print "<span class='s1'>$published_pic</span> ";
5374 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5375 onclick=\"zoomToArticle($id)\"
5376 style=\"cursor : pointer\"
5378 title='".__('Show article summary in new window')."'></span>";
5380 $tags = get_article_tags($link, $id);
5383 $full_tags_str = "";
5386 foreach ($tags as $tag) {
5388 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5389 if ($num_tags < 5) {
5390 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5391 } else if ($num_tags == 5) {
5392 $tags_str .= "…";
5396 $tags_str = preg_replace("/, $/", "", $tags_str);
5397 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5399 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5401 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5404 if ($tags_str == "") $tags_str = "no tags";
5406 // print "<img src='images/tag.png' class='markedPic'>";
5408 print "<span class='s1'>
5409 <img class='tagsPic' src='images/tag.png' alt='Tags'
5410 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5411 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5415 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5416 href=\"javascript:toggleUnread($id)\">
5427 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5431 // print_headline_subtoolbar($link,
5432 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5438 switch ($view_mode) {
5440 $message = __("No unread articles found to display.");
5443 $message = __("No starred articles found to display.");
5446 $message = __("No articles found to display.");
5449 if (!$offset) print "<div class='whiteBox'>$message</div>";
5457 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5460 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5462 function printTagCloud($link) {
5464 /* get first ref_id to count from */
5470 if (DB_TYPE == "pgsql") {
5471 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5472 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5473 AND date_entered > NOW() - INTERVAL '30 days'";
5475 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5476 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5477 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5480 $result = db_query($link, $query);
5481 $first_id = db_fetch_result($result, 0, "id"); */
5483 //AND post_int_id >= '$first_id'
5484 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5485 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5486 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5488 $result = db_query($link, $query);
5492 while ($line = db_fetch_assoc($result)) {
5493 $tags[$line["tag_name"]] = $line["count"];
5498 $max_size = 32; // max font size in pixels
5499 $min_size = 11; // min font size in pixels
5501 // largest and smallest array values
5502 $max_qty = max(array_values($tags));
5503 $min_qty = min(array_values($tags));
5505 // find the range of values
5506 $spread = $max_qty - $min_qty;
5507 if ($spread == 0) { // we don't want to divide by zero
5511 // set the font-size increment
5512 $step = ($max_size - $min_size) / ($spread);
5514 // loop through the tag array
5515 foreach ($tags as $key => $value) {
5516 // calculate font-size
5517 // find the $value in excess of $min_qty
5518 // multiply by the font-size increment ($size)
5519 // and add the $min_size set above
5520 $size = round($min_size +
(($value - $min_qty) * $step));
5522 $key_escaped = str_replace("'", "\\'", $key);
5524 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5525 $size . "px\" title=\"$value articles tagged with " .
5526 $key . '">' . $key . '</a> ';
5530 function print_checkpoint($n, $s) {
5531 $ts = getmicrotime();
5532 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5536 function sanitize_tag($tag) {
5539 $tag = mb_strtolower($tag, 'utf-8');
5541 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5543 // $tag = str_replace('"', "", $tag);
5544 // $tag = str_replace("+", " ", $tag);
5545 $tag = str_replace("technorati tag: ", "", $tag);
5550 function generate_publish_key() {
5551 return sha1(uniqid(rand(), true));
5554 function article_publish_url($link) {
5559 if ($_SERVER['HTTPS'] != "on") {
5560 $url_path = "http://";
5562 $url_path = "https://";
5565 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5566 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5572 * Purge a feed contents, marked articles excepted.
5574 * @param mixed $link The database connection.
5575 * @param integer $id The id of the feed to purge.
5578 function clear_feed_articles($link, $id) {
5579 $result = db_query($link, "DELETE FROM ttrss_user_entries
5580 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5582 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5583 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5585 ccache_update($link, $id, $_SESSION['uid']);
5586 } // function clear_feed_articles
5589 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5591 * @return string The Mozilla Firefox feed adding URL.
5593 function add_feed_url() {
5594 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5595 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5597 } // function add_feed_url
5600 * Encrypt a password in SHA1.
5602 * @param string $pass The password to encrypt.
5603 * @param string $login A optionnal login.
5604 * @return string The encrypted password.
5606 function encrypt_password($pass, $login = '') {
5608 return "SHA1X:" . sha1("$login:$pass");
5610 return "SHA1:" . sha1($pass);
5612 } // function encrypt_password
5615 * Update a feed batch.
5616 * Used by daemons to update n feeds by run.
5617 * Only update feed needing a update, and not being processed
5618 * by another process.
5620 * @param mixed $link Database link
5621 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5622 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5623 * @param boolean $debug Set to false to disable debug output. Default to true.
5626 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5627 // Process all other feeds using last_updated and interval parameters
5629 // Test if the user has loggued in recently. If not, it does not update its feeds.
5630 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5631 if (DB_TYPE
== "pgsql") {
5632 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5634 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5637 $login_thresh_qpart = "";
5640 // Test if the feed need a update (update interval exceded).
5641 if (DB_TYPE
== "pgsql") {
5642 $update_limit_qpart = "AND ((
5643 ttrss_feeds.update_interval = 0
5644 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5646 ttrss_feeds.update_interval > 0
5647 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5648 ) OR ttrss_feeds.last_updated IS NULL)";
5650 $update_limit_qpart = "AND ((
5651 ttrss_feeds.update_interval = 0
5652 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5654 ttrss_feeds.update_interval > 0
5655 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5656 ) OR ttrss_feeds.last_updated IS NULL)";
5659 // Test if feed is currently being updated by another process.
5660 if (DB_TYPE
== "pgsql") {
5661 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5663 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5666 // Test if there is a limit to number of updated feeds
5668 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5670 $random_qpart = sql_random_function();
5672 // We search for feed needing update.
5673 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5674 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5675 ttrss_feeds.update_interval
5677 ttrss_feeds, ttrss_users, ttrss_user_prefs
5679 ttrss_feeds.owner_uid = ttrss_users.id
5680 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5681 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5682 $login_thresh_qpart $update_limit_qpart
5683 $updstart_thresh_qpart
5684 ORDER BY $random_qpart $query_limit");
5686 $user_prefs_cache = array();
5688 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5690 // Here is a little cache magic in order to minimize risk of double feed updates.
5691 $feeds_to_update = array();
5692 while ($line = db_fetch_assoc($result)) {
5693 $feeds_to_update[$line['id']] = $line;
5696 // We update the feed last update started date before anything else.
5697 // There is no lag due to feed contents downloads
5698 // It prevent an other process to update the same feed.
5699 $feed_ids = array_keys($feeds_to_update);
5701 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5702 WHERE id IN (%s)", implode(',', $feed_ids)));
5705 // For each feed, we call the feed update function.
5706 while ($line = array_pop($feeds_to_update)) {
5708 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5710 // We setup a alarm to alert if the feed take more than 300s to update.
5712 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5713 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5714 // Cancel the alarm (the update went well)
5715 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5717 sleep(1); // prevent flood (FIXME make this an option?)
5720 // Send feed digests by email if needed.
5721 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5723 } // function update_daemon_common
5725 function sanitize_article_content($text) {
5726 # we don't support CDATA sections in articles, they break our own escaping
5727 $text = preg_replace("/\[\[CDATA/", "", $text);
5728 $text = preg_replace("/\]\]\>/", "", $text);
5732 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5735 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5737 $result = db_query($link, "SELECT reg_exp,
5738 ttrss_filter_types.name AS name,
5739 ttrss_filter_actions.name AS action,
5743 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5746 owner_uid = $owner_uid AND
5747 ttrss_filter_types.id = filter_type AND
5748 ttrss_filter_actions.id = action_id AND
5749 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5751 while ($line = db_fetch_assoc($result)) {
5752 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5753 $filter["reg_exp"] = $line["reg_exp"];
5754 $filter["action"] = $line["action"];
5755 $filter["action_param"] = $line["action_param"];
5756 $filter["filter_param"] = $line["filter_param"];
5757 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5759 array_push($filters[$line["name"]], $filter);
5765 function get_score_pic($score) {
5767 return "score_high.png";
5768 } else if ($score > 0) {
5769 return "score_half_high.png";
5770 } else if ($score < -100) {
5771 return "score_low.png";
5772 } else if ($score < 0) {
5773 return "score_half_low.png";
5775 return "score_neutral.png";
5779 function rounded_table_start($classname, $header = " ") {
5780 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5781 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5782 print "<tr><td class='left'> </td><td class='content'>";
5785 function rounded_table_end($footer = " ") {
5786 print "</td><td class='right'> </td></tr>";
5787 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5791 function print_label_dlg_common_examples() {
5793 print __("Match ") . " ";
5795 /* print "<select name=\"label_andor\">";
5796 print "<option value=\"and\">AND</option>";
5797 print "<option value=\"or\">OR</option>";
5798 print "</select>"; */
5800 print "<select name=\"label_fields\" onchange=\"labelFieldsCheck(this)\">";
5801 print "<option value=\"unread\">".__("Unread articles")."</option>";
5802 print "<option value=\"updated\">".__("Updated articles")."</option>";
5803 print "<option value=\"kw_title\">".__("Title contains")."</option>";
5804 print "<option value=\"kw_content\">".__("Content contains")."</option>";
5805 print "<option value=\"scoreE\">".__("Score equals")."</option>";
5806 print "<option value=\"scoreG\">".__("Score is greater than")."</option>";
5807 print "<option value=\"scoreL\">".__("Score is less than")."</option>";
5808 print "<option value=\"newerH\">".__("Articles newer than X hours")."</option>";
5809 print "<option value=\"newerD\">".__("Articles newer than X days")."</option>";
5813 print "<input style=\"display : none\" name=\"label_fields_param\"
5816 print " <input type=\"submit\"
5817 onclick=\"return addLabelExample()\"
5818 value=\"".__("Add")."\">";
5821 function feed_has_icon($id) {
5822 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5825 function init_connection($link) {
5826 if (DB_TYPE
== "pgsql") {
5827 pg_query($link, "set client_encoding = 'UTF-8'");
5828 pg_set_client_encoding("UNICODE");
5829 pg_query($link, "set datestyle = 'ISO, european'");
5831 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5832 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5833 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5838 function update_feedbrowser_cache($link) {
5840 $result = db_query($link, "SELECT feed_url,COUNT(id) AS subscribers
5841 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5842 WHERE tf.feed_url = ttrss_feeds.feed_url
5843 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5844 GROUP BY feed_url ORDER BY subscribers DESC LIMIT 200");
5846 db_query($link, "BEGIN");
5848 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5852 while ($line = db_fetch_assoc($result)) {
5853 $subscribers = db_escape_string($line["subscribers"]);
5854 $feed_url = db_escape_string($line["feed_url"]);
5856 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5857 (feed_url, subscribers) VALUES ('$feed_url', '$subscribers')");
5862 db_query($link, "COMMIT");
5868 function ccache_zero($link, $feed_id, $owner_uid) {
5869 db_query($link, "UPDATE ttrss_counters_cache SET
5870 value = 0, updated = NOW() WHERE
5871 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5874 function ccache_zero_all($link, $owner_uid) {
5875 db_query($link, "UPDATE ttrss_counters_cache SET
5876 value = 0 WHERE owner_uid = '$owner_uid'");
5878 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5879 value = 0 WHERE owner_uid = '$owner_uid'");
5882 function ccache_update_all($link, $owner_uid) {
5884 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5886 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5887 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5889 while ($line = db_fetch_assoc($result)) {
5890 ccache_update($link, $line["feed_id"], $owner_uid, true);
5893 /* We have to manually include category 0 */
5895 ccache_update($link, 0, $owner_uid, true);
5898 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5899 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5901 while ($line = db_fetch_assoc($result)) {
5902 print ccache_update($link, $line["feed_id"], $owner_uid);
5909 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5910 $no_update = false) {
5913 $table = "ttrss_counters_cache";
5915 $table = "ttrss_cat_counters_cache";
5918 if (DB_TYPE
== "pgsql") {
5919 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5920 } else if (DB_TYPE
== "mysql") {
5921 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5924 $result = db_query($link, "SELECT value FROM $table
5925 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5928 if (db_num_rows($result) == 1) {
5929 return db_fetch_result($result, 0, "value");
5934 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5940 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5941 $update_pcat = true) {
5943 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5945 /* When updating a label, all we need to do is recalculate feed counters
5946 * because labels are not cached */
5949 ccache_update_all($link, $owner_uid);
5954 $table = "ttrss_counters_cache";
5956 $table = "ttrss_cat_counters_cache";
5959 if ($is_cat && $feed_id >= 0) {
5960 if ($feed_id != 0) {
5961 $cat_qpart = "cat_id = '$feed_id'";
5963 $cat_qpart = "cat_id IS NULL";
5966 /* Recalculate counters for child feeds */
5968 $result = db_query($link, "SELECT id FROM ttrss_feeds
5969 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5971 while ($line = db_fetch_assoc($result)) {
5972 ccache_update($link, $line["id"], $owner_uid, false, false);
5975 $result = db_query($link, "SELECT SUM(value) AS sv
5976 FROM ttrss_counters_cache, ttrss_feeds
5977 WHERE id = feed_id AND $cat_qpart AND
5978 ttrss_feeds.owner_uid = '$owner_uid'");
5980 $unread = (int) db_fetch_result($result, 0, "sv");
5983 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5986 $result = db_query($link, "SELECT feed_id FROM $table
5987 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5989 if (db_num_rows($result) == 1) {
5990 db_query($link, "UPDATE $table SET
5991 value = '$unread', updated = NOW() WHERE
5992 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5995 db_query($link, "INSERT INTO $table
5996 (feed_id, value, owner_uid, updated)
5998 ($feed_id, $unread, $owner_uid, NOW())");
6001 if ($feed_id > 0 && $prev_unread != $unread) {
6005 /* Update parent category */
6009 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6010 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6012 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6014 ccache_update($link, $cat_id, $owner_uid, true);
6018 } else if ($feed_id < 0) {
6019 ccache_update_all($link, $owner_uid);
6025 function label_find_id($link, $label, $owner_uid) {
6026 $result = db_query($link,
6027 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6028 AND owner_uid = '$owner_uid' LIMIT 1");
6030 if (db_num_rows($result) == 1) {
6031 return db_fetch_result($result, 0, "id");
6037 function label_find_caption($link, $label, $owner_uid) {
6038 $result = db_query($link,
6039 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6040 AND owner_uid = '$owner_uid' LIMIT 1");
6042 if (db_num_rows($result) == 1) {
6043 return db_fetch_result($result, 0, "caption");
6049 function label_remove_article($link, $id, $label, $owner_uid) {
6051 $label_id = label_find_id($link, $label, $owner_uid);
6053 if (!$label_id) return;
6055 $result = db_query($link,
6056 "DELETE FROM ttrss_user_labels2
6058 label_id = '$label_id' AND
6059 article_id = '$id'");
6062 function label_add_article($link, $id, $label, $owner_uid) {
6064 $label_id = label_find_id($link, $label, $owner_uid);
6066 if (!$label_id) return;
6068 $result = db_query($link,
6070 article_id FROM ttrss_labels2, ttrss_user_labels2
6073 label_id = '$label_id' AND
6074 article_id = '$id' AND owner_uid = '$owner_uid'
6077 if (db_num_rows($result) == 0) {
6078 db_query($link, "INSERT INTO ttrss_user_labels2
6079 (label_id, article_id) VALUES ('$label_id', '$id')");