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';
12 * Return available translations names.
15 * @return array A array of available translations.
17 function get_translations() {
19 "auto" => "Detect automatically",
21 "fr_FR" => "Français",
22 "hu_HU" => "Magyar (Hungarian)",
23 "nb_NO" => "Norsk Bokmål",
25 "pt_BR" => "Portuguese/Brazil",
26 "zh_CN" => "Simplified Chinese");
31 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
32 require_once "accept-to-gettext.php";
33 require_once "gettext/gettext.inc";
35 function startup_gettext() {
37 # Get locale from Accept-Language header
38 $lang = al2gt(array_keys(get_translations()), "text/html");
40 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
41 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
44 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
45 $lang = $_COOKIE["ttrss_lang"];
49 _setlocale(LC_MESSAGES
, $lang);
50 _bindtextdomain("messages", "locale");
51 _textdomain("messages");
52 _bind_textdomain_codeset("messages", "UTF-8");
58 } else { // If translations are enabled.
62 function startup_gettext() {
66 } // If translations are enabled.
68 require_once 'db-prefs.php';
69 require_once 'compat.php';
70 require_once 'errors.php';
71 require_once 'version.php';
73 require_once 'phpmailer/class.phpmailer.php';
75 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
76 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
78 require_once "simplepie/simplepie.inc";
79 require_once "magpierss/rss_fetch.inc";
80 require_once 'magpierss/rss_utils.inc';
83 * Print a timestamped debug message.
85 * @param string $msg The debug message.
88 function _debug($msg) {
89 $ts = strftime("%H:%M:%S", time());
90 if (function_exists('posix_getpid')) {
91 $ts = "$ts/" . posix_getpid();
97 * Purge a feed old posts.
99 * @param mixed $link A database connection.
100 * @param mixed $feed_id The id of the purged feed.
101 * @param mixed $purge_interval Olderness of purged posts.
102 * @param boolean $debug Set to True to enable the debug. False by default.
106 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
108 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
112 $result = db_query($link,
113 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
117 if (db_num_rows($result) == 1) {
118 $owner_uid = db_fetch_result($result, 0, "owner_uid");
121 if (!$owner_uid) return;
123 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
126 if (!$purge_unread) $query_limit = " unread = false AND ";
128 if (DB_TYPE
== "pgsql") {
129 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
130 marked = false AND feed_id = '$feed_id' AND
131 (SELECT date_entered FROM ttrss_entries WHERE
132 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
134 $pg_version = get_pgsql_version($link);
136 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
138 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
139 ttrss_entries.id = ref_id AND
141 feed_id = '$feed_id' AND
143 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
147 $result = db_query($link, "DELETE FROM ttrss_user_entries
149 WHERE ttrss_entries.id = ref_id AND
151 feed_id = '$feed_id' AND
153 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
156 $rows = pg_affected_rows($result);
160 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
161 marked = false AND feed_id = '$feed_id' AND
162 (SELECT date_entered FROM ttrss_entries WHERE
163 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
165 $result = db_query($link, "DELETE FROM ttrss_user_entries
166 USING ttrss_user_entries, ttrss_entries
167 WHERE ttrss_entries.id = ref_id AND
169 feed_id = '$feed_id' AND
171 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
173 $rows = mysql_affected_rows($link);
178 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
180 } // function purge_feed
183 * Purge old posts from old feeds.
185 * @param mixed $link A database connection
186 * @param boolean $do_output Set to true to enable printed output, false by default.
187 * @param integer $limit The maximal number of removed posts.
191 function global_purge_old_posts($link, $do_output = false, $limit = false) {
193 $random_qpart = sql_random_function();
196 $limit_qpart = "LIMIT $limit";
201 $result = db_query($link,
202 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
203 ORDER BY $random_qpart $limit_qpart");
205 while ($line = db_fetch_assoc($result)) {
207 $feed_id = $line["id"];
208 $purge_interval = $line["purge_interval"];
209 $owner_uid = $line["owner_uid"];
211 if ($purge_interval == 0) {
213 $tmp_result = db_query($link,
214 "SELECT value FROM ttrss_user_prefs WHERE
215 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
217 if (db_num_rows($tmp_result) != 0) {
218 $purge_interval = db_fetch_result($tmp_result, 0, "value");
223 // print "Feed $feed_id: purge interval = $purge_interval\n";
226 if ($purge_interval > 0) {
227 purge_feed($link, $feed_id, $purge_interval, $do_output);
231 // purge orphaned posts in main content table
232 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
233 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
236 $rows = db_affected_rows($link, $result);
237 _debug("Purged $rows orphaned posts.");
240 } // function global_purge_old_posts
242 function feed_purge_interval($link, $feed_id) {
244 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
245 WHERE id = '$feed_id'");
247 if (db_num_rows($result) == 1) {
248 $purge_interval = db_fetch_result($result, 0, "purge_interval");
249 $owner_uid = db_fetch_result($result, 0, "owner_uid");
251 if ($purge_interval == 0) $purge_interval = get_pref($link,
252 'PURGE_OLD_DAYS', $user_id);
254 return $purge_interval;
261 function purge_old_posts($link) {
263 $user_id = $_SESSION["uid"];
265 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
266 WHERE owner_uid = '$user_id'");
268 while ($line = db_fetch_assoc($result)) {
270 $feed_id = $line["id"];
271 $purge_interval = $line["purge_interval"];
273 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
275 if ($purge_interval > 0) {
276 purge_feed($link, $feed_id, $purge_interval);
280 // purge orphaned posts in main content table
281 db_query($link, "DELETE FROM ttrss_entries WHERE
282 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
285 function get_feed_update_interval($link, $feed_id) {
286 $result = db_query($link, "SELECT owner_uid, update_interval FROM
287 ttrss_feeds WHERE id = '$feed_id'");
289 if (db_num_rows($result) == 1) {
290 $update_interval = db_fetch_result($result, 0, "update_interval");
291 $owner_uid = db_fetch_result($result, 0, "owner_uid");
293 if ($update_interval != 0) {
294 return $update_interval;
296 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
304 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
306 if (WEB_DEMO_MODE
) return;
309 $user_id = $_SESSION["uid"];
310 purge_old_posts($link);
313 // db_query($link, "BEGIN");
315 if (MAX_UPDATE_TIME
> 0) {
316 if (DB_TYPE
== "mysql") {
319 $q_order = "RANDOM()";
322 $q_order = "last_updated DESC";
325 $result = db_query($link, "SELECT feed_url,id,
326 SUBSTRING(last_updated,1,19) AS last_updated,
327 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
332 while ($line = db_fetch_assoc($result)) {
333 $upd_intl = $line["update_interval"];
335 if (!$upd_intl ||
$upd_intl == 0) {
336 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
340 // Updates for this feed are disabled
344 if ($fetch ||
(!$line["last_updated"] ||
345 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
347 // print "<!-- feed: ".$line["feed_url"]." -->";
349 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
351 $upd_elapsed = time() - $upd_start;
353 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
359 // db_query($link, "COMMIT");
363 function fetch_file_contents($url) {
364 if (USE_CURL_FOR_ICONS
) {
365 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
367 $ch = curl_init($url);
368 $fp = fopen($tmpfile, "w");
371 curl_setopt($ch, CURLOPT_FILE
, $fp);
372 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
373 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
379 $contents = file_get_contents($tmpfile);
385 return file_get_contents($url);
391 * Try to determine the favicon URL for a feed.
392 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
393 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
395 * @param string $url A feed or page URL
397 * @return mixed The favicon URL, or false if none was found.
399 function get_favicon_url($url) {
401 if ($html = @fetch_file_contents
($url)) {
403 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
404 // Attempt to grab a favicon link from their webpage url
405 $linkUrl = html_entity_decode($matches[1]);
407 if (substr($linkUrl, 0, 1) == '/') {
408 $urlParts = parse_url($url);
409 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
410 } else if (substr($linkUrl, 0, 7) == 'http://') {
411 $faviconURL = $linkUrl;
412 } else if (substr($url, -1, 1) == '/') {
413 $faviconURL = $url.$linkUrl;
415 $faviconURL = $url.'/'.$linkUrl;
419 // If unsuccessful, attempt to "guess" the favicon location
420 $urlParts = parse_url($url);
421 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
425 // Run a test to see if what we have attempted to get actually exists.
426 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
431 } // function get_favicon_url
434 * Check if a link is a valid and working URL.
436 * @param mixed $link A URL to check
438 * @return boolean True if the URL is valid, false otherwise.
440 function url_validate($link) {
442 $url_parts = @parse_url
($link);
444 if ( empty( $url_parts["host"] ) )
447 if ( !empty( $url_parts["path"] ) ) {
448 $documentpath = $url_parts["path"];
453 if ( !empty( $url_parts["query"] ) )
454 $documentpath .= "?" . $url_parts["query"];
456 $host = $url_parts["host"];
457 $port = $url_parts["port"];
462 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
467 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
469 $http_response = fgets( $socket, 22 );
471 $responses = "/(200 OK)|(30[0-9] Moved)/";
472 if ( preg_match($responses, $http_response) ) {
479 } // function url_validate
481 function check_feed_favicon($site_url, $feed, $link) {
482 $favicon_url = get_favicon_url($site_url);
484 # print "FAVICON [$site_url]: $favicon_url\n";
488 $icon_file = ICONS_DIR
. "/$feed.ico";
490 if ($favicon_url && !file_exists($icon_file)) {
491 $contents = fetch_file_contents($favicon_url);
493 $fp = fopen($icon_file, "w");
496 fwrite($fp, $contents);
498 chmod($icon_file, 0644);
502 error_reporting(DEFAULT_ERROR_LEVEL
);
506 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
508 if (!$_GET["daemon"] && !$ignore_daemon) {
512 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
513 _debug("update_rss_feed: start");
516 if (!$ignore_daemon) {
518 if (DB_TYPE
== "pgsql") {
519 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
521 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
524 $result = db_query($link, "SELECT id,update_interval,auth_login,
525 auth_pass,cache_images,update_method
526 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
530 $result = db_query($link, "SELECT id,update_interval,auth_login,
531 auth_pass,cache_images,update_method
532 FROM ttrss_feeds WHERE id = '$feed'");
536 if (db_num_rows($result) == 0) {
537 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
538 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
543 $update_method = db_fetch_result($result, 0, "update_method");
545 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
546 WHERE id = '$feed'");
548 $auth_login = db_fetch_result($result, 0, "auth_login");
549 $auth_pass = db_fetch_result($result, 0, "auth_pass");
551 if (ALLOW_SELECT_UPDATE_METHOD
) {
552 if (ENABLE_SIMPLEPIE
) {
553 $use_simplepie = $update_method != 1;
555 $use_simplepie = $update_method == 2;
558 $use_simplepie = ENABLE_SIMPLEPIE
;
561 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
562 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
565 if (!$use_simplepie) {
566 $auth_login = urlencode($auth_login);
567 $auth_pass = urlencode($auth_pass);
570 $update_interval = db_fetch_result($result, 0, "update_interval");
571 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
573 if ($update_interval < 0) { return; }
575 $feed = db_escape_string($feed);
577 $fetch_url = $feed_url;
579 if ($auth_login && $auth_pass) {
580 $url_parts = array();
581 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
583 if ($url_parts[1] && $url_parts[2]) {
584 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
589 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
590 _debug("update_rss_feed: fetching [$fetch_url]...");
593 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
597 if (!$use_simplepie) {
598 $rss = fetch_rss($fetch_url);
600 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
601 mkdir(SIMPLEPIE_CACHE_DIR
);
604 $rss = new SimplePie();
605 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
606 # $rss->set_timeout(10);
607 $rss->set_feed_url($fetch_url);
608 $rss->set_output_encoding('UTF-8');
610 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
611 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
612 _debug("enabling image cache");
615 $rss->set_image_handler('./image.php', 'i');
618 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
619 _debug("feed update interval (sec): " .
620 get_feed_update_interval($link, $feed)*60);
623 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
624 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
625 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
633 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
634 _debug("update_rss_feed: fetch done, parsing...");
636 error_reporting (DEFAULT_ERROR_LEVEL
);
639 $feed = db_escape_string($feed);
641 if ($use_simplepie) {
642 $fetch_ok = !$rss->error();
649 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
650 _debug("update_rss_feed: processing feed data...");
653 // db_query($link, "BEGIN");
655 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
656 FROM ttrss_feeds WHERE id = '$feed'");
658 $registered_title = db_fetch_result($result, 0, "title");
659 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
660 $orig_site_url = db_fetch_result($result, 0, "site_url");
662 $owner_uid = db_fetch_result($result, 0, "owner_uid");
664 if ($use_simplepie) {
665 $site_url = $rss->get_link();
667 $site_url = $rss->channel
["link"];
670 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
671 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
672 _debug("update_rss_feed: checking favicon...");
675 check_feed_favicon($site_url, $feed, $link);
678 if (!$registered_title ||
$registered_title == "[Unknown]") {
680 if ($use_simplepie) {
681 $feed_title = db_escape_string($rss->get_title());
683 $feed_title = db_escape_string($rss->channel
["title"]);
686 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
687 _debug("update_rss_feed: registering title: $feed_title");
690 db_query($link, "UPDATE ttrss_feeds SET
691 title = '$feed_title' WHERE id = '$feed'");
694 // weird, weird Magpie
695 if (!$use_simplepie) {
696 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
699 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
700 db_query($link, "UPDATE ttrss_feeds SET
701 site_url = '$site_url' WHERE id = '$feed'");
704 // print "I: " . $rss->channel["image"]["url"];
706 if (!$use_simplepie) {
707 $icon_url = $rss->image
["url"];
709 $icon_url = $rss->get_image_url();
712 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
713 $icon_url = db_escape_string($icon_url);
714 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
717 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
718 _debug("update_rss_feed: loading filters...");
723 $result = db_query($link, "SELECT reg_exp,
724 ttrss_filter_types.name AS name,
725 ttrss_filter_actions.name AS action,
728 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
730 owner_uid = $owner_uid AND
731 ttrss_filter_types.id = filter_type AND
732 ttrss_filter_actions.id = action_id AND
733 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
735 while ($line = db_fetch_assoc($result)) {
736 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
738 $filter["reg_exp"] = $line["reg_exp"];
739 $filter["action"] = $line["action"];
740 $filter["action_param"] = $line["action_param"];
741 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
743 array_push($filters[$line["name"]], $filter);
746 if ($use_simplepie) {
747 $iterator = $rss->get_items();
749 $iterator = $rss->items
;
750 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
751 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
754 if (!is_array($iterator)) {
755 /* db_query($link, "UPDATE ttrss_feeds
756 SET last_error = 'Parse error: can\'t find any articles.'
757 WHERE id = '$feed'"); */
759 // clear any errors and mark feed as updated if fetched okay
760 // even if it's blank
762 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
763 _debug("update_rss_feed: entry iterator is not an array, no articles?");
766 db_query($link, "UPDATE ttrss_feeds
767 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
769 return; // no articles
772 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
773 _debug("update_rss_feed: processing articles...");
776 foreach ($iterator as $item) {
778 if ($_GET['xdebug']) {
783 if ($use_simplepie) {
784 $entry_guid = $item->get_id();
785 if (!$entry_guid) $entry_guid = $item->get_link();
786 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
790 $entry_guid = $item["id"];
792 if (!$entry_guid) $entry_guid = $item["guid"];
793 if (!$entry_guid) $entry_guid = $item["link"];
794 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
797 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
798 _debug("update_rss_feed: guid $entry_guid");
801 if (!$entry_guid) continue;
803 $entry_timestamp = "";
805 if ($use_simplepie) {
806 $entry_timestamp = strtotime($item->get_date());
808 $rss_2_date = $item['pubdate'];
809 $rss_1_date = $item['dc']['date'];
810 $atom_date = $item['issued'];
811 if (!$atom_date) $atom_date = $item['updated'];
813 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
814 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
815 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
818 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
819 _debug("update_rss_feed: date $entry_timestamp");
822 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
823 $entry_timestamp = time();
824 $no_orig_date = 'true';
826 $no_orig_date = 'false';
829 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
831 if ($use_simplepie) {
832 $entry_title = $item->get_title();
834 $entry_title = trim(strip_tags($item["title"]));
837 if ($use_simplepie) {
838 $entry_link = $item->get_link();
840 // strange Magpie workaround
841 $entry_link = $item["link_"];
842 if (!$entry_link) $entry_link = $item["link"];
845 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
846 _debug("update_rss_feed: title $entry_title");
849 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
851 $entry_link = strip_tags($entry_link);
853 if ($use_simplepie) {
854 $entry_content = $item->get_content();
855 if (!$entry_content) $entry_content = $item->get_description();
857 $entry_content = $item["content:escaped"];
859 if (!$entry_content) $entry_content = $item["content:encoded"];
860 if (!$entry_content) $entry_content = $item["content"];
862 // Magpie bugs are getting ridiculous
863 if (trim($entry_content) == "Array") $entry_content = false;
865 if (!$entry_content) $entry_content = $item["atom_content"];
866 if (!$entry_content) $entry_content = $item["summary"];
867 if (!$entry_content) $entry_content = $item["description"];
870 if (is_array($entry_content)) {
871 $entry_content = $entry_content["encoded"];
872 if (!$entry_content) $entry_content = $entry_content["escaped"];
876 if ($_GET["xdebug"]) {
877 print "update_rss_feed: content: ";
878 print_r(htmlspecialchars($entry_content));
881 $entry_content_unescaped = $entry_content;
883 if ($use_simplepie) {
884 $entry_comments = strip_tags($item->data
["comments"]);
885 if ($item->get_author()) {
886 $entry_author_item = $item->get_author();
887 $entry_author = $entry_author_item->get_name();
888 if (!$entry_author) $entry_author = $entry_author_item->get_email();
890 $entry_author = db_escape_string($entry_author);
893 $entry_comments = strip_tags($item["comments"]);
895 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
897 if ($item['author']) {
899 if (is_array($item['author'])) {
901 if (!$entry_author) {
902 $entry_author = db_escape_string(strip_tags($item['author']['name']));
905 if (!$entry_author) {
906 $entry_author = db_escape_string(strip_tags($item['author']['email']));
910 if (!$entry_author) {
911 $entry_author = db_escape_string(strip_tags($item['author']));
916 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
918 $entry_guid = db_escape_string(strip_tags($entry_guid));
919 $entry_guid = mb_substr($entry_guid, 0, 250);
921 $result = db_query($link, "SELECT id FROM ttrss_entries
922 WHERE guid = '$entry_guid'");
924 $entry_content = db_escape_string($entry_content);
926 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
928 $entry_title = db_escape_string($entry_title);
929 $entry_link = db_escape_string($entry_link);
930 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
931 $entry_author = mb_substr($entry_author, 0, 250);
933 if ($use_simplepie) {
934 $num_comments = 0; #FIXME#
936 $num_comments = db_escape_string($item["slash"]["comments"]);
939 if (!$num_comments) $num_comments = 0;
941 // parse <category> entries into tags
943 if ($use_simplepie) {
945 $additional_tags = array();
946 $additional_tags_src = $item->get_categories();
948 if (is_array($additional_tags_src)) {
949 foreach ($additional_tags_src as $tobj) {
950 array_push($additional_tags, $tobj->get_term());
954 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
955 _debug("update_rss_feed: category tags:");
956 print_r($additional_tags);
961 $t_ctr = $item['category#'];
963 $additional_tags = false;
966 $additional_tags = false;
967 } else if ($t_ctr > 0) {
968 $additional_tags = array($item['category']);
970 if ($item['category@term']) {
971 array_push($additional_tags, $item['category@term']);
974 for ($i = 0; $i <= $t_ctr; $i++
) {
975 if ($item["category#$i"]) {
976 array_push($additional_tags, $item["category#$i"]);
979 if ($item["category#$i@term"]) {
980 array_push($additional_tags, $item["category#$i@term"]);
985 // parse <dc:subject> elements
987 $t_ctr = $item['dc']['subject#'];
990 $additional_tags = array($item['dc']['subject']);
992 for ($i = 0; $i <= $t_ctr; $i++
) {
993 if ($item['dc']["subject#$i"]) {
994 array_push($additional_tags, $item['dc']["subject#$i"]);
1002 $enclosures = array();
1004 if ($use_simplepie) {
1005 $encs = $item->get_enclosures();
1007 if (is_array($encs)) {
1008 foreach ($encs as $e) {
1010 $e->link
, $e->type
, $e->length
);
1012 array_push($enclosures, $e_item);
1017 $e_ctr = $item['enclosure#'];
1020 $e_item = array($item['enclosure@url'],
1021 $item['enclosure@type'],
1022 $item['enclosure@length']);
1024 array_push($enclosures, $e_item);
1026 for ($i = 0; $i <= $e_ctr; $i++
) {
1028 if ($item["enclosure#$i@url"]) {
1029 $e_item = array($item["enclosure#$i@url"],
1030 $item["enclosure#$i@type"],
1031 $item["enclosure#$i@length"]);
1032 array_push($enclosures, $e_item);
1041 // $entry_content = sanitize_rss($entry_content);
1043 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1044 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1047 db_query($link, "BEGIN");
1049 if (db_num_rows($result) == 0) {
1051 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1052 _debug("update_rss_feed: base guid not found");
1055 // base post entry does not exist, create it
1057 $result = db_query($link,
1058 "INSERT INTO ttrss_entries
1074 '$entry_timestamp_fmt',
1083 // we keep encountering the entry in feeds, so we need to
1084 // update date_entered column so that we don't get horrible
1085 // dupes when the entry gets purged and reinserted again e.g.
1086 // in the case of SLOW SLOW OMG SLOW updating feeds
1088 $base_entry_id = db_fetch_result($result, 0, "id");
1090 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1091 WHERE id = '$base_entry_id'");
1094 // now it should exist, if not - bad luck then
1096 $result = db_query($link, "SELECT
1097 id,content_hash,no_orig_date,title,
1098 substring(date_entered,1,19) as date_entered,
1099 substring(updated,1,19) as updated,
1103 WHERE guid = '$entry_guid'");
1108 if (db_num_rows($result) == 1) {
1110 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1111 _debug("update_rss_feed: base guid found, checking for user record");
1114 // this will be used below in update handler
1115 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1116 $orig_title = db_fetch_result($result, 0, "title");
1117 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1118 $orig_date_entered = strtotime(db_fetch_result($result,
1119 0, "date_entered"));
1121 $ref_id = db_fetch_result($result, 0, "id");
1122 $entry_ref_id = $ref_id;
1124 // check for user post link to main table
1126 // do we allow duplicate posts with same GUID in different feeds?
1127 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1128 $dupcheck_qpart = "AND feed_id = '$feed'";
1130 $dupcheck_qpart = "";
1133 // error_reporting(0);
1135 $article_filters = get_article_filters($filters, $entry_title,
1136 $entry_content, $entry_link);
1138 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1139 _debug("update_rss_feed: article filters: ");
1140 if (count($article_filters) != 0) {
1141 print_r($article_filters);
1145 if (find_article_filter($article_filters, "filter")) {
1149 // error_reporting (DEFAULT_ERROR_LEVEL);
1151 $result = db_query($link,
1152 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1153 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1156 // okay it doesn't exist - create user entry
1157 if (db_num_rows($result) == 0) {
1159 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1160 _debug("update_rss_feed: user record not found, creating...");
1163 if (!find_article_filter($article_filters, 'catchup')) {
1165 $last_read_qpart = 'NULL';
1168 $last_read_qpart = 'NOW()';
1171 if (find_article_filter($article_filters, 'mark')) {
1177 if (find_article_filter($article_filters, 'publish')) {
1178 $published = 'true';
1180 $published = 'false';
1183 $result = db_query($link,
1184 "INSERT INTO ttrss_user_entries
1185 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
1186 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1187 $last_read_qpart, $marked, $published)");
1189 $result = db_query($link,
1190 "SELECT int_id FROM ttrss_user_entries WHERE
1191 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1192 feed_id = '$feed' LIMIT 1");
1194 if (db_num_rows($result) == 1) {
1195 $entry_int_id = db_fetch_result($result, 0, "int_id");
1198 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1199 $entry_int_id = db_fetch_result($result, 0, "int_id");
1202 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1203 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1206 $post_needs_update = false;
1208 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1209 ($content_hash != $orig_content_hash)) {
1210 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1211 $post_needs_update = true;
1214 if (db_escape_string($orig_title) != $entry_title) {
1215 $post_needs_update = true;
1218 if ($orig_num_comments != $num_comments) {
1219 $post_needs_update = true;
1222 // this doesn't seem to be very reliable
1224 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1225 // $post_needs_update = true;
1228 // if post needs update, update it and mark all user entries
1229 // linking to this post as updated
1230 if ($post_needs_update) {
1232 if (defined('DAEMON_EXTENDED_DEBUG')) {
1233 _debug("update_rss_feed: post $entry_guid needs update...");
1236 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1238 db_query($link, "UPDATE ttrss_entries
1239 SET title = '$entry_title', content = '$entry_content',
1240 content_hash = '$content_hash',
1241 num_comments = '$num_comments'
1242 WHERE id = '$ref_id'");
1244 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1245 db_query($link, "UPDATE ttrss_user_entries
1246 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1248 db_query($link, "UPDATE ttrss_user_entries
1249 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1255 db_query($link, "COMMIT");
1257 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1258 _debug("update_rss_feed: looking for enclosures...");
1261 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1262 print_r($enclosures);
1265 db_query($link, "BEGIN");
1267 foreach ($enclosures as $enc) {
1268 $enc_url = db_escape_string($enc[0]);
1269 $enc_type = db_escape_string($enc[1]);
1270 $enc_dur = db_escape_string($enc[2]);
1272 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1273 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1275 if (db_num_rows($result) == 0) {
1276 db_query($link, "INSERT INTO ttrss_enclosures
1277 (content_url, content_type, title, duration, post_id) VALUES
1278 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1282 db_query($link, "COMMIT");
1284 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1285 _debug("update_rss_feed: looking for tags...");
1289 // <a href="..." rel="tag">Xorg</a>, //
1293 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1294 $entry_content_unescaped, $entry_tags);
1296 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1297 print_r($entry_tags);
1298 print "<br/></p>"; */
1300 $entry_tags = $entry_tags[1];
1302 # check for manual tags
1304 $tag_filter = find_article_filter($article_filters, "tag");
1308 $manual_tags = trim_array(split(",", $tag_filter[1]));
1310 foreach ($manual_tags as $tag) {
1311 if (tag_is_valid($tag)) {
1312 array_push($entry_tags, $tag);
1317 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1318 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1320 if ($additional_tags && is_array($additional_tags)) {
1321 foreach ($additional_tags as $tag) {
1322 if (tag_is_valid($tag) &&
1323 array_search($tag, $boring_tags) === FALSE) {
1324 array_push($entry_tags, $tag);
1329 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1331 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1332 print_r($entry_tags);
1335 if (count($entry_tags) > 0) {
1337 db_query($link, "BEGIN");
1339 foreach ($entry_tags as $tag) {
1341 $tag = sanitize_tag($tag);
1342 $tag = db_escape_string($tag);
1344 if (!tag_is_valid($tag)) continue;
1346 $result = db_query($link, "SELECT id FROM ttrss_tags
1347 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1348 owner_uid = '$owner_uid' LIMIT 1");
1350 // print db_fetch_result($result, 0, "id");
1352 if ($result && db_num_rows($result) == 0) {
1354 db_query($link, "INSERT INTO ttrss_tags
1355 (owner_uid,tag_name,post_int_id)
1356 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1360 db_query($link, "COMMIT");
1363 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1364 _debug("update_rss_feed: article processed");
1368 db_query($link, "UPDATE ttrss_feeds
1369 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1371 // db_query($link, "COMMIT");
1375 if ($use_simplepie) {
1376 $error_msg = mb_substr($rss->error(), 0, 250);
1378 $error_msg = mb_substr(magpie_error(), 0, 250);
1381 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1382 _debug("update_rss_feed: error fetching feed: $error_msg");
1385 $error_msg = db_escape_string($error_msg);
1388 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1389 last_updated = NOW() WHERE id = '$feed'");
1392 if ($use_simplepie) {
1396 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1397 _debug("update_rss_feed: done");
1402 function print_select($id, $default, $values, $attributes = "") {
1403 print "<select name=\"$id\" id=\"$id\" $attributes>";
1404 foreach ($values as $v) {
1410 print "<option$sel>$v</option>";
1415 function print_select_hash($id, $default, $values, $attributes = "") {
1416 print "<select name=\"$id\" id='$id' $attributes>";
1417 foreach (array_keys($values) as $v) {
1423 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1429 function get_article_filters($filters, $title, $content, $link) {
1432 if ($filters["title"]) {
1433 foreach ($filters["title"] as $filter) {
1434 $reg_exp = $filter["reg_exp"];
1435 $inverse = $filter["inverse"];
1436 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1437 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1439 array_push($matches, array($filter["action"], $filter["action_param"]));
1444 if ($filters["content"]) {
1445 foreach ($filters["content"] as $filter) {
1446 $reg_exp = $filter["reg_exp"];
1447 $inverse = $filter["inverse"];
1449 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1450 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1452 array_push($matches, array($filter["action"], $filter["action_param"]));
1457 if ($filters["both"]) {
1458 foreach ($filters["both"] as $filter) {
1459 $reg_exp = $filter["reg_exp"];
1460 $inverse = $filter["inverse"];
1463 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1464 array_push($matches, array($filter["action"], $filter["action_param"]));
1467 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1468 array_push($matches, array($filter["action"], $filter["action_param"]));
1474 if ($filters["link"]) {
1475 $reg_exp = $filter["reg_exp"];
1476 foreach ($filters["link"] as $filter) {
1477 $reg_exp = $filter["reg_exp"];
1478 $inverse = $filter["inverse"];
1480 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1481 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1483 array_push($matches, array($filter["action"], $filter["action_param"]));
1491 function find_article_filter($filters, $filter_name) {
1492 foreach ($filters as $f) {
1493 if ($f[0] == $filter_name) {
1500 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1501 $rtl_content = false, $last_updated = false, $last_error = false) {
1503 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1504 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1506 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1510 $rtl_tag = "dir=\"rtl\"";
1512 $rtl_tag = "dir=\"ltr\"";
1515 $error_notify_msg = "";
1518 $link_title = "Error: $last_error ($last_updated)";
1519 $error_notify_msg = "(Error)";
1520 } else if ($last_updated) {
1521 $link_title = "Updated: $last_updated";
1524 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1525 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1527 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1528 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1532 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1537 $fctr_class = "class=\"invisible\"";
1540 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1541 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1543 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1544 print "<div class=\"feedExtInfo\">
1545 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1552 function getmicrotime() {
1553 list($usec, $sec) = explode(" ",microtime());
1554 return ((float)$usec +
(float)$sec);
1557 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1558 foreach ($values as $v) {
1565 if ($v == $true_is) {
1566 $sel .= " value=\"1\"";
1568 $sel .= " value=\"0\"";
1571 print "<input class=\"noborder\"
1572 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1577 function initialize_user_prefs($link, $uid) {
1579 $uid = db_escape_string($uid);
1581 db_query($link, "BEGIN");
1583 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1585 $u_result = db_query($link, "SELECT pref_name
1586 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1588 $active_prefs = array();
1590 while ($line = db_fetch_assoc($u_result)) {
1591 array_push($active_prefs, $line["pref_name"]);
1594 while ($line = db_fetch_assoc($result)) {
1595 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1596 // print "adding " . $line["pref_name"] . "<br>";
1598 db_query($link, "INSERT INTO ttrss_user_prefs
1599 (owner_uid,pref_name,value) VALUES
1600 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1605 db_query($link, "COMMIT");
1609 function lookup_user_id($link, $user) {
1611 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1614 if (db_num_rows($result) == 1) {
1615 return db_fetch_result($result, 0, "id");
1621 function http_authenticate_user($link) {
1623 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1625 if (!$_SERVER["PHP_AUTH_USER"]) {
1627 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1628 header('HTTP/1.0 401 Unauthorized');
1632 $auth_result = authenticate_user($link,
1633 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1635 if (!$auth_result) {
1636 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1637 header('HTTP/1.0 401 Unauthorized');
1645 function authenticate_user($link, $login, $password, $force_auth = false) {
1647 if (!SINGLE_USER_MODE
) {
1649 $pwd_hash1 = encrypt_password($password);
1650 $pwd_hash2 = encrypt_password($password, $login);
1652 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1653 && $_SERVER["REMOTE_USER"]) {
1655 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1657 $query = "SELECT id,login,access_level
1658 FROM ttrss_users WHERE
1662 $query = "SELECT id,login,access_level,pwd_hash
1663 FROM ttrss_users WHERE
1664 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1665 pwd_hash = '$pwd_hash2')";
1668 $result = db_query($link, $query);
1670 if (db_num_rows($result) == 1) {
1671 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1672 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1673 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1675 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1678 $user_theme = get_user_theme_path($link);
1680 $_SESSION["theme"] = $user_theme;
1681 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1682 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1684 initialize_user_prefs($link, $_SESSION["uid"]);
1693 $_SESSION["uid"] = 1;
1694 $_SESSION["name"] = "admin";
1696 $user_theme = get_user_theme_path($link);
1698 $_SESSION["theme"] = $user_theme;
1699 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1701 initialize_user_prefs($link, $_SESSION["uid"]);
1707 function make_password($length = 8) {
1710 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1714 while ($i < $length) {
1715 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1717 if (!strstr($password, $char)) {
1725 // this is called after user is created to initialize default feeds, labels
1728 // user preferences are checked on every login, not here
1730 function initialize_user($link, $uid) {
1732 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1733 values ('$uid','unread = true', 'Unread articles')");
1735 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1736 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1738 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1739 values ('$uid', 'Tiny Tiny RSS: New Releases',
1740 'http://tt-rss.spb.ru/releases.rss')");
1742 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1743 values ('$uid', 'Tiny Tiny RSS: Forum',
1744 'http://tt-rss.spb.ru/forum/rss.php')");
1747 function logout_user() {
1749 if (isset($_COOKIE[session_name()])) {
1750 setcookie(session_name(), '', time()-42000, '/');
1754 function get_script_urlpath() {
1755 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1758 function validate_session($link) {
1759 if (SINGLE_USER_MODE
) {
1763 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1764 if ($_SESSION["ip_address"]) {
1765 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1766 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1772 if ($_SESSION["uid"]) {
1774 $result = db_query($link,
1775 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1777 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1779 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1784 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1786 //print_r($_SESSION);
1788 if (time() > $_SESSION["cookie_lifetime"]) {
1796 function login_sequence($link, $mobile = false) {
1797 if (!SINGLE_USER_MODE
) {
1799 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1800 $swu = db_escape_string($_REQUEST["swu"]);
1802 $_SESSION["prefs_cache"] = false;
1803 return authenticate_user($link, $swu, null, true);
1807 $login_action = $_POST["login_action"];
1809 # try to authenticate user if called from login form
1810 if ($login_action == "do_login") {
1811 $login = $_POST["login"];
1812 $password = $_POST["password"];
1813 $remember_me = $_POST["remember_me"];
1815 if (authenticate_user($link, $login, $password)) {
1816 $_POST["password"] = "";
1818 $_SESSION["language"] = $_POST["language"];
1820 header("Location: " . $_SERVER["REQUEST_URI"]);
1825 $_SESSION["login_error_msg"] = "Incorrect username or password";
1829 // print session_id();
1830 // print_r($_SESSION);
1832 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1833 render_login_form($link, $mobile);
1836 /* bump login timestamp */
1837 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1840 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1841 setcookie("ttrss_lang", $_SESSION["language"],
1842 time() + SESSION_COOKIE_LIFETIME
);
1847 return authenticate_user($link, "admin", null);
1851 function truncate_string($str, $max_len) {
1852 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1853 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1859 function get_user_theme_path($link) {
1860 $result = db_query($link, "SELECT theme_path
1862 ttrss_themes,ttrss_users
1863 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1864 if (db_num_rows($result) != 0) {
1865 return db_fetch_result($result, 0, "theme_path");
1871 function smart_date_time($timestamp) {
1872 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1873 return date("G:i", $timestamp);
1874 } else if (date("Y", $timestamp) == date("Y")) {
1875 return date("M d, G:i", $timestamp);
1877 return date("Y/m/d, G:i", $timestamp);
1881 function smart_date($timestamp) {
1882 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1884 } else if (date("Y", $timestamp) == date("Y")) {
1885 return date("D m", $timestamp);
1887 return date("Y/m/d", $timestamp);
1891 function sql_bool_to_string($s) {
1892 if ($s == "t" ||
$s == "1") {
1899 function sql_bool_to_bool($s) {
1900 if ($s == "t" ||
$s == "1") {
1908 function toggleEvenOdd($a) {
1915 function sanity_check($link) {
1920 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1921 $schema_version = db_fetch_result($result, 0, "schema_version");
1923 if ($schema_version != SCHEMA_VERSION
) {
1927 if (DB_TYPE
== "mysql") {
1928 $result = db_query($link, "SELECT true", false);
1929 if (db_num_rows($result) != 1) {
1934 error_reporting (DEFAULT_ERROR_LEVEL
);
1936 if ($error_code != 0) {
1937 print_error_xml($error_code);
1944 function file_is_locked($filename) {
1945 if (function_exists('flock')) {
1947 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1948 error_reporting(DEFAULT_ERROR_LEVEL
);
1950 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1951 flock($fp, LOCK_UN
);
1962 function make_lockfile($filename) {
1963 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1965 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1972 function make_stampfile($filename) {
1973 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1975 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1976 fwrite($fp, time() . "\n");
1977 flock($fp, LOCK_UN
);
1985 function read_stampfile($filename) {
1988 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1989 error_reporting (DEFAULT_ERROR_LEVEL
);
1991 if (flock($fp, LOCK_EX
)) {
1992 $stamp = fgets($fp);
1993 flock($fp, LOCK_UN
);
2001 function sql_random_function() {
2002 if (DB_TYPE
== "mysql") {
2009 function catchup_feed($link, $feed, $cat_view) {
2011 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2016 $cat_qpart = "cat_id = '$feed'";
2018 $cat_qpart = "cat_id IS NULL";
2021 $tmp_result = db_query($link, "SELECT id
2022 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2025 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2027 $tmp_feed = $tmp_line["id"];
2029 db_query($link, "UPDATE ttrss_user_entries
2030 SET unread = false,last_read = NOW()
2031 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2034 } else if ($feed > 0) {
2036 $tmp_result = db_query($link, "SELECT id
2037 FROM ttrss_feeds WHERE parent_feed = '$feed'
2038 ORDER BY cat_id,title");
2040 $parent_ids = array();
2042 if (db_num_rows($tmp_result) > 0) {
2043 while ($p = db_fetch_assoc($tmp_result)) {
2044 array_push($parent_ids, "feed_id = " . $p["id"]);
2047 $children_qpart = implode(" OR ", $parent_ids);
2049 db_query($link, "UPDATE ttrss_user_entries
2050 SET unread = false,last_read = NOW()
2051 WHERE (feed_id = '$feed' OR $children_qpart)
2052 AND owner_uid = " . $_SESSION["uid"]);
2055 db_query($link, "UPDATE ttrss_user_entries
2056 SET unread = false,last_read = NOW()
2057 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2060 } else if ($feed < 0 && $feed > -10) { // special, like starred
2063 db_query($link, "UPDATE ttrss_user_entries
2064 SET unread = false,last_read = NOW()
2065 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2069 db_query($link, "UPDATE ttrss_user_entries
2070 SET unread = false,last_read = NOW()
2071 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2076 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2078 if (DB_TYPE
== "pgsql") {
2079 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
2081 $match_part = "date_entered > DATE_SUB(NOW(),
2082 INTERVAL $intl HOUR) ";
2085 $result = db_query($link, "SELECT id FROM ttrss_entries,
2086 ttrss_user_entries WHERE $match_part AND
2088 ttrss_user_entries.ref_id = ttrss_entries.id AND
2089 owner_uid = ".$_SESSION["uid"]);
2091 $affected_ids = array();
2093 while ($line = db_fetch_assoc($result)) {
2094 array_push($affected_ids, $line["id"]);
2097 catchupArticlesById($link, $affected_ids, 0);
2100 } else if ($feed < -10) { // label
2102 // TODO make this more efficient
2104 $label_id = -$feed - 11;
2106 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2107 WHERE id = '$label_id'");
2110 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2112 db_query($link, "BEGIN");
2114 $tmp2_result = db_query($link,
2118 ttrss_user_entries,ttrss_entries,ttrss_feeds
2120 ref_id = ttrss_entries.id AND
2121 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2123 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2125 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2126 db_query($link, "UPDATE
2129 unread = false, last_read = NOW()
2131 int_id = " . $tmp_line["int_id"]);
2134 db_query($link, "COMMIT");
2136 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2137 SET unread = false,last_read = NOW()
2140 AND owner_uid = ".$_SESSION["uid"]); */
2144 db_query($link, "BEGIN");
2146 $tag_name = db_escape_string($feed);
2148 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2149 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2151 while ($line = db_fetch_assoc($result)) {
2152 db_query($link, "UPDATE ttrss_user_entries SET
2153 unread = false, last_read = NOW()
2154 WHERE int_id = " . $line["post_int_id"]);
2156 db_query($link, "COMMIT");
2160 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2164 $cat_qpart = "cat_id = '$feed'";
2166 $cat_qpart = "cat_id IS NULL";
2169 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2170 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2172 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2173 $feed_url = $tmp_line["feed_url"];
2174 $feed_id = $tmp_line["id"];
2175 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2179 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2180 WHERE id = '$feed'");
2181 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2182 update_rss_feed($link, $feed_url, $feed, $force_update);
2186 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2187 /* getLabelCounters($link);
2188 getFeedCounters($link);
2189 getTagCounters($link);
2190 getGlobalCounters($link);
2191 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2192 getCategoryCounters($link);
2195 if (!$omode) $omode = "flc";
2197 getGlobalCounters($link);
2199 if (strchr($omode, "l")) getLabelCounters($link);
2200 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2201 if (strchr($omode, "t")) getTagCounters($link);
2202 if (strchr($omode, "c")) {
2203 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2204 getCategoryCounters($link);
2209 function getCategoryCounters($link) {
2210 # two special categories are -1 and -2 (all virtuals; all labels)
2212 $ctr = getCategoryUnread($link, -1);
2214 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2216 $ctr = getCategoryUnread($link, -2);
2218 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2220 $age_qpart = getMaxAgeSubquery();
2222 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
2223 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2224 AND id = ref_id AND $age_qpart
2225 AND unread = true)) AS unread FROM ttrss_feeds
2227 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2229 while ($line = db_fetch_assoc($result)) {
2230 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2231 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2232 $line["unread"]."\"/>";
2236 function getCategoryUnread($link, $cat) {
2241 $cat_query = "cat_id = '$cat'";
2243 $cat_query = "cat_id IS NULL";
2246 $age_qpart = getMaxAgeSubquery();
2248 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2250 AND owner_uid = " . $_SESSION["uid"]);
2252 $cat_feeds = array();
2253 while ($line = db_fetch_assoc($result)) {
2254 array_push($cat_feeds, "feed_id = " . $line["id"]);
2257 if (count($cat_feeds) == 0) return 0;
2259 $match_part = implode(" OR ", $cat_feeds);
2261 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2262 FROM ttrss_user_entries,ttrss_entries
2263 WHERE unread = true AND ($match_part) AND id = ref_id
2264 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2268 # this needs to be rewritten
2269 while ($line = db_fetch_assoc($result)) {
2270 $unread +
= $line["unread"];
2274 } else if ($cat == -1) {
2275 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2276 } else if ($cat == -2) {
2278 $rv = getLabelCounters($link, false, true);
2281 foreach (array_keys($rv) as $k) {
2283 $ctr +
= $rv[$k]["counter"];
2291 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2292 if (DB_TYPE
== "pgsql") {
2293 return "ttrss_entries.date_entered >
2294 NOW() - INTERVAL '$days days'";
2296 return "ttrss_entries.date_entered >
2297 DATE_SUB(NOW(), INTERVAL $days DAY)";
2301 function getFeedUnread($link, $feed, $is_cat = false) {
2302 $n_feed = sprintf("%d", $feed);
2304 $age_qpart = getMaxAgeSubquery();
2307 return getCategoryUnread($link, $n_feed);
2308 } else if ($n_feed == -1) {
2309 $match_part = "marked = true";
2310 } else if ($n_feed == -2) {
2311 $match_part = "published = true";
2312 } else if ($n_feed == -3) {
2313 $match_part = "unread = true";
2315 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2317 if (DB_TYPE
== "pgsql") {
2318 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2320 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2323 } else if ($n_feed > 0) {
2325 $result = db_query($link, "SELECT id FROM ttrss_feeds
2326 WHERE parent_feed = '$n_feed'
2328 AND owner_uid = " . $_SESSION["uid"]);
2330 if (db_num_rows($result) > 0) {
2332 $linked_feeds = array();
2333 while ($line = db_fetch_assoc($result)) {
2334 array_push($linked_feeds, "feed_id = " . $line["id"]);
2337 array_push($linked_feeds, "feed_id = $n_feed");
2339 $match_part = implode(" OR ", $linked_feeds);
2341 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2342 FROM ttrss_user_entries,ttrss_entries
2343 WHERE unread = true AND
2344 ttrss_user_entries.ref_id = ttrss_entries.id AND
2347 owner_uid = " . $_SESSION["uid"]);
2351 # this needs to be rewritten
2352 while ($line = db_fetch_assoc($result)) {
2353 $unread +
= $line["unread"];
2359 $match_part = "feed_id = '$n_feed'";
2361 } else if ($feed < -10) {
2363 $label_id = -$feed - 11;
2365 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2366 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2368 $match_part = db_fetch_result($result, 0, "sql_exp");
2373 $result = db_query($link, "SELECT count(int_id) AS unread
2374 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2375 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2376 ttrss_user_entries.ref_id = ttrss_entries.id AND
2377 ttrss_feeds.hidden = false AND
2379 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2383 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2384 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2385 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2386 AND unread = true AND $age_qpart AND
2387 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2390 $unread = db_fetch_result($result, 0, "unread");
2395 /* FIXME this needs reworking */
2397 function getGlobalUnread($link, $user_id = false) {
2400 $user_id = $_SESSION["uid"];
2403 $age_qpart = getMaxAgeSubquery();
2405 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2406 WHERE unread = true AND
2407 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2408 ttrss_user_entries.ref_id = ttrss_entries.id AND
2411 ttrss_user_entries.owner_uid = '$user_id'");
2412 $c_id = db_fetch_result($result, 0, "c_id");
2416 function getGlobalCounters($link, $global_unread = -1) {
2417 if ($global_unread == -1) {
2418 $global_unread = getGlobalUnread($link);
2420 print "<counter type=\"global\" id='global-unread'
2421 counter='$global_unread'/>";
2423 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2424 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2426 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2428 print "<counter type=\"global\" id='subscribed-feeds'
2429 counter='$subscribed_feeds'/>";
2433 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2436 if (!$_SESSION["tctr_last_value"]) {
2437 $_SESSION["tctr_last_value"] = array();
2441 $old_counters = $_SESSION["tctr_last_value"];
2443 $tctrs_modified = false;
2445 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2446 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2447 ttrss_user_entries.ref_id = ttrss_entries.id AND
2448 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2449 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2451 select tag_name,0 as count FROM ttrss_tags
2452 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2454 $age_qpart = getMaxAgeSubquery();
2456 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2457 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2458 AND ref_id = id AND $age_qpart
2459 AND unread = true)) AS count FROM ttrss_tags
2460 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2461 ORDER BY count DESC LIMIT 55");
2465 while ($line = db_fetch_assoc($result)) {
2466 $tags[$line["tag_name"]] +
= $line["count"];
2469 foreach (array_keys($tags) as $tag) {
2470 $unread = $tags[$tag];
2472 $tag = htmlspecialchars($tag);
2474 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2475 $old_counters[$tag] = $unread;
2476 $tctrs_modified = true;
2477 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2482 if ($smart_mode && $tctrs_modified) {
2483 $_SESSION["tctr_last_value"] = $old_counters;
2488 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2490 $age_qpart = getMaxAgeSubquery();
2493 if (!$_SESSION["lctr_last_value"]) {
2494 $_SESSION["lctr_last_value"] = array();
2500 $old_counters = $_SESSION["lctr_last_value"];
2501 $lctrs_modified = false;
2503 $count = getFeedUnread($link, -1);
2506 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2508 $ret_arr["-1"]["counter"] = $count;
2509 $ret_arr["-1"]["description"] = __("Starred articles");
2512 $count = getFeedUnread($link, -2);
2515 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2517 $ret_arr["-2"]["counter"] = $count;
2518 $ret_arr["-2"]["description"] = __("Published articles");
2521 $count = getFeedUnread($link, -3);
2524 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2526 $ret_arr["-3"]["counter"] = $count;
2527 $ret_arr["-3"]["description"] = __("Fresh articles");
2531 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2532 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2534 while ($line = db_fetch_assoc($result)) {
2536 $id = -$line["id"] - 11;
2538 $label_name = $line["description"];
2540 error_reporting (0);
2542 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2543 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2544 ttrss_feeds.hidden = false AND
2546 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2547 ttrss_user_entries.ref_id = ttrss_entries.id AND
2548 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2550 $count = db_fetch_result($tmp_result, 0, "count");
2552 if (!$smart_mode ||
$old_counters[$id] != $count) {
2553 $old_counters[$id] = $count;
2554 $lctrs_modified = true;
2556 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2558 $ret_arr[$id]["counter"] = $count;
2559 $ret_arr[$id]["description"] = $label_name;
2563 error_reporting (DEFAULT_ERROR_LEVEL
);
2566 if ($smart_mode && $lctrs_modified) {
2567 $_SESSION["lctr_last_value"] = $old_counters;
2573 /* function getFeedCounter($link, $id) {
2575 $result = db_query($link, "SELECT
2576 count(id) as count,last_error
2577 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2578 WHERE feed_id = '$id' AND unread = true
2579 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2580 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2582 $count = db_fetch_result($result, 0, "count");
2583 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2585 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2588 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2590 $age_qpart = getMaxAgeSubquery();
2593 if (!$_SESSION["fctr_last_value"]) {
2594 $_SESSION["fctr_last_value"] = array();
2598 $old_counters = $_SESSION["fctr_last_value"];
2600 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2601 SUBSTRING(last_updated,1,19) AS last_updated,
2603 FROM ttrss_entries,ttrss_user_entries
2604 WHERE feed_id = ttrss_feeds.id AND
2605 ttrss_user_entries.ref_id = ttrss_entries.id
2606 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2607 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2608 AND parent_feed IS NULL"); */
2610 $query = "SELECT ttrss_feeds.id,
2612 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2614 COUNT(ttrss_entries.id) AS count
2616 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2617 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2618 AND ttrss_user_entries.unread = true)
2619 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2621 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2622 AND parent_feed IS NULL
2623 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2625 $result = db_query($link, $query);
2626 $fctrs_modified = false;
2628 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2630 while ($line = db_fetch_assoc($result)) {
2633 $count = $line["count"];
2634 $last_error = htmlspecialchars($line["last_error"]);
2636 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2637 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2639 $last_updated = date($short_date, strtotime($line["last_updated"]));
2642 $last_updated = htmlspecialchars($last_updated);
2644 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2646 $tmp_result = db_query($link,
2647 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2648 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2649 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2650 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2651 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2653 if (db_num_rows($tmp_result) > 0) {
2654 while ($l = db_fetch_assoc($tmp_result)) {
2655 $count +
= $l["unread"];
2659 if (!$smart_mode ||
$old_counters[$id] != $count) {
2660 $old_counters[$id] = $count;
2661 $fctrs_modified = true;
2664 $error_part = "error=\"$last_error\"";
2670 $has_img_part = "hi=\"$has_img\"";
2675 if ($active_feed && $id == $active_feed) {
2676 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2678 $has_title_part = "";
2681 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2685 if ($smart_mode && $fctrs_modified) {
2686 $_SESSION["fctr_last_value"] = $old_counters;
2690 function get_script_dt_add() {
2691 if (strpos(VERSION
, ".99") === false) {
2698 function get_pgsql_version($link) {
2699 $result = db_query($link, "SELECT version() AS version");
2700 $version = split(" ", db_fetch_result($result, 0, "version"));
2704 function print_error_xml($code, $add_msg = "") {
2707 $error_msg = $ERRORS[$code];
2710 $error_msg = "$error_msg; $add_msg";
2713 print "<rpc-reply>";
2714 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2715 print "</rpc-reply>";
2718 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2719 $auth_login = '', $auth_pass = '') {
2721 # check for feed:http://url
2722 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2724 # check for feed://URL
2725 if (strpos($feed_link, "//") === 0) {
2726 $feed_link = "http:$feed_link";
2729 if ($feed_link == "") return;
2731 if ($cat_id == "0" ||
!$cat_id) {
2732 $cat_qpart = "NULL";
2734 $cat_qpart = "'$cat_id'";
2737 $result = db_query($link,
2738 "SELECT id FROM ttrss_feeds
2739 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2741 if (db_num_rows($result) == 0) {
2743 $result = db_query($link,
2744 "INSERT INTO ttrss_feeds
2745 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2746 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2747 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2749 $result = db_query($link,
2750 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2751 AND owner_uid = " . $_SESSION["uid"]);
2753 $feed_id = db_fetch_result($result, 0, "id");
2756 update_rss_feed($link, $feed_link, $feed_id, true);
2765 function print_feed_select($link, $id, $default_id = "",
2766 $attributes = "", $include_all_feeds = true) {
2768 print "<select id=\"$id\" name=\"$id\" $attributes>";
2769 if ($include_all_feeds) {
2770 print "<option value=\"0\">".__('All feeds')."</option>";
2773 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2774 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2776 if (db_num_rows($result) > 0 && $include_all_feeds) {
2777 print "<option disabled>--------</option>";
2780 while ($line = db_fetch_assoc($result)) {
2781 if ($line["id"] == $default_id) {
2782 $is_selected = "selected";
2786 printf("<option $is_selected value='%d'>%s</option>",
2787 $line["id"], htmlspecialchars($line["title"]));
2793 function print_feed_cat_select($link, $id, $default_id = "",
2794 $attributes = "", $include_all_cats = true) {
2796 print "<select id=\"$id\" name=\"$id\" $attributes>";
2798 if ($include_all_cats) {
2799 print "<option value=\"0\">".__('Uncategorized')."</option>";
2802 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2803 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2805 if (db_num_rows($result) > 0 && $include_all_cats) {
2806 print "<option disabled>--------</option>";
2809 while ($line = db_fetch_assoc($result)) {
2810 if ($line["id"] == $default_id) {
2811 $is_selected = "selected";
2815 printf("<option $is_selected value='%d'>%s</option>",
2816 $line["id"], htmlspecialchars($line["title"]));
2822 function checkbox_to_sql_bool($val) {
2823 return ($val == "on") ?
"true" : "false";
2826 function getFeedCatTitle($link, $id) {
2828 return __("Special");
2829 } else if ($id < -10) {
2830 return __("Labels");
2831 } else if ($id > 0) {
2832 $result = db_query($link, "SELECT ttrss_feed_categories.title
2833 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2834 cat_id = ttrss_feed_categories.id");
2835 if (db_num_rows($result) == 1) {
2836 return db_fetch_result($result, 0, "title");
2838 return __("Uncategorized");
2841 return "getFeedCatTitle($id) failed";
2846 function getFeedTitle($link, $id) {
2848 return __("Starred articles");
2849 } else if ($id == -2) {
2850 return __("Published articles");
2851 } else if ($id == -3) {
2852 return __("Fresh articles");
2853 } else if ($id < -10) {
2854 $label_id = -10 - $id;
2855 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2856 if (db_num_rows($result) == 1) {
2857 return db_fetch_result($result, 0, "description");
2859 return "Unknown label ($label_id)";
2862 } else if ($id > 0) {
2863 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2864 if (db_num_rows($result) == 1) {
2865 return db_fetch_result($result, 0, "title");
2867 return "Unknown feed ($id)";
2870 return "getFeedTitle($id) failed";
2875 function get_session_cookie_name() {
2876 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2879 function print_init_params($link) {
2880 print "<init-params>";
2881 if ($_SESSION["stored-params"]) {
2882 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2884 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2885 print "<param key=\"$key\" value=\"$value\"/>";
2890 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2891 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2892 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2893 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2895 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2896 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2898 print "<param key=\"hide_read_feeds\" value=\"" .
2899 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2901 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2902 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2904 print "<param key=\"confirm_feed_catchup\" value=\"" .
2905 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2907 print "<param key=\"cdm_auto_catchup\" value=\"" .
2908 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2910 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2912 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2914 print "<param key=\"default_view_mode\" value=\"" .
2915 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2917 print "<param key=\"default_view_limit\" value=\"" .
2918 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2920 print "<param key=\"prefs_active_tab\" value=\"" .
2921 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2923 print "<param key=\"infobox_disable_overlay\" value=\"" .
2924 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2926 print "<param key=\"icons_location\" value=\"" .
2929 print "<param key=\"hide_read_shows_special\" value=\"" .
2930 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2932 print "<param key=\"hide_feedlist\" value=\"" .
2933 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
2935 print "</init-params>";
2938 function print_runtime_info($link) {
2939 print "<runtime-info>";
2941 if (ENABLE_UPDATE_DAEMON
) {
2942 print "<param key=\"daemon_is_running\" value=\"".
2943 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2945 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2947 $stamp = (int)read_stampfile("update_daemon.stamp");
2949 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2952 $stamp_delta = time() - $stamp;
2954 if ($stamp_delta > 1800) {
2958 $_SESSION["daemon_stamp_check"] = time();
2961 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2963 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2965 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2970 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2972 if ($_SESSION["last_version_check"] +
7200 < time()) {
2973 $new_version_details = check_for_update($link);
2975 print "<param key=\"new_version_available\" value=\"".
2976 sprintf("%d", $new_version_details != ""). "\"/>";
2978 $_SESSION["last_version_check"] = time();
2982 // print "<param key=\"new_version_available\" value=\"1\"/>";
2984 print "</runtime-info>";
2987 function getSearchSql($search, $match_on) {
2989 $search_query_part = "";
2991 $keywords = split(" ", $search);
2992 $query_keywords = array();
2994 if ($match_on == "both") {
2996 foreach ($keywords as $k) {
2997 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2998 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3001 $search_query_part = implode("AND", $query_keywords) . " AND ";
3003 } else if ($match_on == "title") {
3005 foreach ($keywords as $k) {
3006 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3009 $search_query_part = implode("AND", $query_keywords) . " AND ";
3011 } else if ($match_on == "content") {
3013 foreach ($keywords as $k) {
3014 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3018 $search_query_part = implode("AND", $query_keywords);
3020 return $search_query_part;
3023 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3025 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3029 $search_query_part = getSearchSql($search, $match_on);
3030 $search_query_part .= " AND ";
3033 $search_query_part = "";
3036 $view_query_part = "";
3038 if ($view_mode == "adaptive") {
3040 $view_query_part = " ";
3041 } else if ($feed != -1) {
3042 $unread = getFeedUnread($link, $feed, $cat_view);
3044 $view_query_part = " unread = true AND ";
3049 if ($view_mode == "marked") {
3050 $view_query_part = " marked = true AND ";
3053 if ($view_mode == "unread") {
3054 $view_query_part = " unread = true AND ";
3058 $limit_query_part = "LIMIT " . $limit;
3061 $vfeed_query_part = "";
3063 // override query strategy and enable feed display when searching globally
3064 if ($search && $search_mode == "all_feeds") {
3065 $query_strategy_part = "ttrss_entries.id > 0";
3066 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3067 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3068 $query_strategy_part = "ttrss_entries.id > 0";
3069 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3070 id = feed_id) as feed_title,";
3071 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3073 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3075 $tmp_result = false;
3078 $tmp_result = db_query($link, "SELECT id
3079 FROM ttrss_feeds WHERE cat_id = '$feed'");
3081 $tmp_result = db_query($link, "SELECT id
3082 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3083 WHERE id = '$feed') AND id != '$feed'");
3086 $cat_siblings = array();
3088 if (db_num_rows($tmp_result) > 0) {
3089 while ($p = db_fetch_assoc($tmp_result)) {
3090 array_push($cat_siblings, "feed_id = " . $p["id"]);
3093 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3094 $feed, implode(" OR ", $cat_siblings));
3097 $query_strategy_part = "ttrss_entries.id > 0";
3100 } else if ($feed >= 0) {
3105 $query_strategy_part = "cat_id = '$feed'";
3107 $query_strategy_part = "cat_id IS NULL";
3110 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3113 $tmp_result = db_query($link, "SELECT id
3114 FROM ttrss_feeds WHERE parent_feed = '$feed'
3115 ORDER BY cat_id,title");
3117 $parent_ids = array();
3119 if (db_num_rows($tmp_result) > 0) {
3120 while ($p = db_fetch_assoc($tmp_result)) {
3121 array_push($parent_ids, "feed_id = " . $p["id"]);
3124 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3125 $feed, implode(" OR ", $parent_ids));
3127 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3129 $query_strategy_part = "feed_id = '$feed'";
3132 } else if ($feed == -1) { // starred virtual feed
3133 $query_strategy_part = "marked = true";
3134 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3135 } else if ($feed == -2) { // published virtual feed
3136 $query_strategy_part = "published = true";
3137 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3138 } else if ($feed == -3) { // fresh virtual feed
3139 $query_strategy_part = "unread = true";
3141 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3143 if (DB_TYPE
== "pgsql") {
3144 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
3146 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3149 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3150 } else if ($feed <= -10) { // labels
3151 $label_id = -$feed - 11;
3153 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3154 WHERE id = '$label_id'");
3156 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
3158 if (!$query_strategy_part) {
3162 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3164 $query_strategy_part = "id > 0"; // dumb
3167 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3168 $order_by = "updated";
3170 $order_by = "updated DESC";
3173 if ($override_order) {
3174 $order_by = $override_order;
3179 if ($search && $search_mode == "all_feeds") {
3180 $feed_title = __("Search results")." ($search)";
3181 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3182 $feed_title = __("Search results")." ($search, $feed)";
3183 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3184 $feed_title = $feed;
3185 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3190 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3191 WHERE id = '$feed' AND owner_uid = $owner_uid");
3192 $feed_title = db_fetch_result($result, 0, "title");
3194 $feed_title = __("Uncategorized");
3198 $feed_title = __("Searched for")." $search ($feed_title)";
3203 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3204 WHERE id = '$feed' AND owner_uid = $owner_uid");
3206 $feed_title = db_fetch_result($result, 0, "title");
3207 $feed_site_url = db_fetch_result($result, 0, "site_url");
3208 $last_error = db_fetch_result($result, 0, "last_error");
3211 $feed_title = __("Searched for") . " $search ($feed_title)";
3215 } else if ($feed == -1) {
3216 $feed_title = __("Starred articles");
3217 } else if ($feed == -2) {
3218 $feed_title = __("Published articles");
3219 } else if ($feed == -3) {
3220 $feed_title = __("Fresh articles");
3221 } else if ($feed < -10) {
3222 $label_id = -$feed - 11;
3223 $result = db_query($link, "SELECT description FROM ttrss_labels
3224 WHERE id = '$label_id'");
3225 $feed_title = db_fetch_result($result, 0, "description");
3228 $feed_title = __("Searched for") . " $search ($feed_title)";
3234 if ($feed < -10) error_reporting (0);
3236 $content_query_part = "content as content_preview,";
3238 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3241 $feed_kind = "Feeds";
3243 $feed_kind = "Labels";
3246 if ($limit_query_part) {
3247 $offset_query_part = "OFFSET $offset";
3252 ttrss_entries.id,ttrss_entries.title,
3254 unread,feed_id,marked,published,link,last_read,
3255 SUBSTRING(last_read,1,19) as last_read_noms,
3258 SUBSTRING(updated,1,19) as updated_noms,
3261 ttrss_entries,ttrss_user_entries,ttrss_feeds
3263 ttrss_feeds.hidden = false AND
3264 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3265 ttrss_user_entries.ref_id = ttrss_entries.id AND
3266 ttrss_user_entries.owner_uid = '$owner_uid' AND
3269 $query_strategy_part ORDER BY $order_by
3270 $limit_query_part $offset_query_part";
3272 $result = db_query($link, $query);
3274 if ($_GET["debug"]) print $query;
3279 $feed_kind = "Tags";
3281 $result = db_query($link, "SELECT
3283 ttrss_entries.id as id,title,
3286 marked,link,last_read,
3287 SUBSTRING(last_read,1,19) as last_read_noms,
3290 SUBSTRING(updated,1,19) as updated_noms
3292 ttrss_entries,ttrss_user_entries,ttrss_tags
3294 ref_id = ttrss_entries.id AND
3295 ttrss_user_entries.owner_uid = '$owner_uid' AND
3296 post_int_id = int_id AND tag_name = '$feed' AND
3299 $query_strategy_part ORDER BY $order_by
3300 $limit_query_part");
3303 return array($result, $feed_title, $feed_site_url, $last_error);
3307 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3308 $search, $search_mode, $match_on) {
3310 $qfh_ret = queryFeedHeadlines($link, $feed,
3311 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3314 $result = $qfh_ret[0];
3315 $feed_title = htmlspecialchars($qfh_ret[1]);
3316 $feed_site_url = $qfh_ret[2];
3317 $last_error = $qfh_ret[3];
3319 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3321 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3322 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3323 <rss version=\"2.0\">
3325 <title>$feed_title</title>
3326 <link>$feed_site_url</link>
3327 <description>Feed generated by Tiny Tiny RSS</description>";
3329 while ($line = db_fetch_assoc($result)) {
3331 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3332 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3334 $tags = get_article_tags($link, $line["id"], $owner_uid);
3336 foreach ($tags as $tag) {
3337 print "<category>" . htmlspecialchars($tag) . "</category>";
3340 $rfc822_date = date('r', strtotime($line["updated"]));
3342 print "<pubDate>$rfc822_date</pubDate>";
3345 htmlspecialchars($line["title"]) . "</title>";
3347 print "<description><![CDATA[" .
3348 $line["content_preview"] . "]]></description>";
3353 print "</channel></rss>";
3357 function getCategoryTitle($link, $cat_id) {
3359 if ($cat_id == -1) {
3360 return __("Special");
3361 } else if ($cat_id == -2) {
3362 return __("Labels");
3365 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3368 if (db_num_rows($result) == 1) {
3369 return db_fetch_result($result, 0, "title");
3371 return "Uncategorized";
3376 // http://ru2.php.net/strip-tags
3378 function strip_tags_long($textstring, $allowed){
3379 while($textstring != strip_tags($textstring, $allowed))
3381 while (strlen($textstring) != 0)
3383 if (strlen($textstring) > 1024) {
3386 $otherlen = strlen($textstring);
3388 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3389 $safetext .= $temptext;
3390 $textstring = substr_replace($textstring,'',0,$otherlen);
3392 $textstring = $safetext;
3398 function sanitize_rss($link, $str, $force_strip_tags = false) {
3401 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3403 $res = strip_tags_long($res,
3404 "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
3406 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3407 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3414 * Send by mail a digest of last articles.
3416 * @param mixed $link The database connection.
3417 * @param integer $limit The maximum number of articles by digest.
3418 * @return boolean Return false if digests are not enabled.
3420 function send_headlines_digests($link, $limit = 100) {
3422 if (!DIGEST_ENABLE
) return false;
3424 $user_limit = DIGEST_EMAIL_LIMIT
;
3427 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3429 if (DB_TYPE
== "pgsql") {
3430 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3431 } else if (DB_TYPE
== "mysql") {
3432 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3435 $result = db_query($link, "SELECT id,email FROM ttrss_users
3436 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3438 while ($line = db_fetch_assoc($result)) {
3440 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3441 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3443 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3445 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3446 $digest = $tuple[0];
3447 $headlines_count = $tuple[1];
3448 $affected_ids = $tuple[2];
3449 $digest_text = $tuple[3];
3451 if ($headlines_count > 0) {
3453 $mail = new PHPMailer();
3455 $mail->PluginDir
= "phpmailer/";
3456 $mail->SetLanguage("en", "phpmailer/language/");
3458 $mail->CharSet
= "UTF-8";
3460 $mail->From
= DIGEST_FROM_ADDRESS
;
3461 $mail->FromName
= DIGEST_FROM_NAME
;
3462 $mail->AddAddress($line["email"], $line["login"]);
3464 if (DIGEST_SMTP_HOST
) {
3465 $mail->Host
= DIGEST_SMTP_HOST
;
3466 $mail->Mailer
= "smtp";
3467 $mail->Username
= DIGEST_SMTP_LOGIN
;
3468 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3471 $mail->IsHTML(true);
3472 $mail->Subject
= DIGEST_SUBJECT
;
3473 $mail->Body
= $digest;
3474 $mail->AltBody
= $digest_text;
3476 $rc = $mail->Send();
3478 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3482 if ($rc && $do_catchup) {
3483 print "Marking affected articles as read...\n";
3484 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3487 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3488 WHERE id = " . $line["id"]);
3490 print "No headlines\n";
3495 print "All done.\n";
3499 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3501 require_once "MiniTemplator.class.php";
3503 $tpl = new MiniTemplator
;
3504 $tpl_t = new MiniTemplator
;
3506 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3507 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3509 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3510 $tpl->setVariable('CUR_TIME', date('G:i'));
3512 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3513 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3515 $affected_ids = array();
3517 if (DB_TYPE
== "pgsql") {
3518 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3519 } else if (DB_TYPE
== "mysql") {
3520 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3523 $result = db_query($link, "SELECT ttrss_entries.title,
3524 ttrss_feeds.title AS feed_title,
3526 ttrss_user_entries.ref_id,
3528 SUBSTRING(content, 1, 120) AS excerpt,
3529 SUBSTRING(last_updated,1,19) AS last_updated
3531 ttrss_user_entries,ttrss_entries,ttrss_feeds
3533 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3534 AND include_in_digest = true
3537 AND ttrss_user_entries.owner_uid = $user_id
3539 ORDER BY ttrss_feeds.title, date_entered DESC
3542 $cur_feed_title = "";
3544 $headlines_count = db_num_rows($result);
3546 $headlines = array();
3548 while ($line = db_fetch_assoc($result)) {
3549 array_push($headlines, $line);
3552 for ($i = 0; $i < sizeof($headlines); $i++
) {
3554 $line = $headlines[$i];
3556 array_push($affected_ids, $line["ref_id"]);
3558 $updated = smart_date_time(strtotime($line["last_updated"]));
3560 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3561 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3562 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3563 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3564 $tpl->setVariable('ARTICLE_EXCERPT',
3565 truncate_string(strip_tags($line["excerpt"]), 100));
3567 $tpl->addBlock('article');
3569 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3570 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3571 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3572 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3573 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3574 // truncate_string(strip_tags($line["excerpt"]), 100));
3576 $tpl_t->addBlock('article');
3578 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3579 $tpl->addBlock('feed');
3580 $tpl_t->addBlock('feed');
3585 $tpl->addBlock('digest');
3586 $tpl->generateOutputToString($tmp);
3588 $tpl_t->addBlock('digest');
3589 $tpl_t->generateOutputToString($tmp_t);
3591 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3594 function check_for_update($link, $brief_fmt = true) {
3595 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3597 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3602 if (ENABLE_SIMPLEPIE
) {
3603 $rss = new SimplePie();
3604 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3605 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3606 $rss->set_feed_url($fetch_url);
3607 $rss->set_output_encoding('UTF-8');
3610 $rss = fetch_rss($releases_feed);
3612 error_reporting (DEFAULT_ERROR_LEVEL
);
3616 if (ENABLE_SIMPLEPIE
) {
3617 $items = $rss->get_items();
3619 $items = $rss->items
;
3621 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3622 if (!$items ||
!is_array($items)) $items = $rss;
3625 if (!is_array($items) ||
count($items) == 0) {
3629 $latest_item = $items[0];
3631 if (ENABLE_SIMPLEPIE
) {
3632 $last_title = $latest_item->get_title();
3634 $last_title = $latest_item["title"];
3637 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3639 if (ENABLE_SIMPLEPIE
) {
3640 $release_url = sanitize_rss($link, $latest_item->get_link());
3641 $content = sanitize_rss($link, $latest_item->get_description());
3643 $release_url = sanitize_rss($link, $latest_item["link"]);
3644 $content = sanitize_rss($link, $latest_item["description"]);
3647 if (version_compare(VERSION
, $latest_version) == -1) {
3649 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3650 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3651 <div id=\"milestoneDetails\">$content</div>");
3653 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3654 <div class='milestoneDetails'>$content</div>
3655 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3656 download and update information.";
3663 function markArticlesById($link, $ids, $cmode) {
3667 foreach ($ids as $id) {
3668 array_push($tmp_ids, "ref_id = '$id'");
3671 $ids_qpart = join(" OR ", $tmp_ids);
3674 db_query($link, "UPDATE ttrss_user_entries SET
3675 marked = false,last_read = NOW()
3676 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3677 } else if ($cmode == 1) {
3678 db_query($link, "UPDATE ttrss_user_entries SET
3680 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3682 db_query($link, "UPDATE ttrss_user_entries SET
3683 marked = NOT marked,last_read = NOW()
3684 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3688 function publishArticlesById($link, $ids, $cmode) {
3692 foreach ($ids as $id) {
3693 array_push($tmp_ids, "ref_id = '$id'");
3696 $ids_qpart = join(" OR ", $tmp_ids);
3699 db_query($link, "UPDATE ttrss_user_entries SET
3700 published = false,last_read = NOW()
3701 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3702 } else if ($cmode == 1) {
3703 db_query($link, "UPDATE ttrss_user_entries SET
3705 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3707 db_query($link, "UPDATE ttrss_user_entries SET
3708 published = NOT published,last_read = NOW()
3709 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3713 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3715 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3719 foreach ($ids as $id) {
3720 array_push($tmp_ids, "ref_id = '$id'");
3723 $ids_qpart = join(" OR ", $tmp_ids);
3726 db_query($link, "UPDATE ttrss_user_entries SET
3727 unread = false,last_read = NOW()
3728 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3729 } else if ($cmode == 1) {
3730 db_query($link, "UPDATE ttrss_user_entries SET
3732 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3734 db_query($link, "UPDATE ttrss_user_entries SET
3735 unread = NOT unread,last_read = NOW()
3736 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3740 function catchupArticleById($link, $id, $cmode) {
3743 db_query($link, "UPDATE ttrss_user_entries SET
3744 unread = false,last_read = NOW()
3745 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3746 } else if ($cmode == 1) {
3747 db_query($link, "UPDATE ttrss_user_entries SET
3749 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3751 db_query($link, "UPDATE ttrss_user_entries SET
3752 unread = NOT unread,last_read = NOW()
3753 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3757 function make_guid_from_title($title) {
3758 return preg_replace("/[ \"\',.:;]/", "-",
3759 mb_strtolower(strip_tags($title), 'utf-8'));
3762 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3763 $bottom = false, $rtl_content = false, $feed_id = 0,
3764 $is_cat = false, $search = false, $match_on = false,
3765 $search_mode = false, $offset = 0, $limit = 0,
3766 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3768 $user_page_offset = $offset +
1;
3771 $class = "headlinesSubToolbar";
3772 $tid = "headlineActionsTop";
3774 $class = "headlinesSubToolbar";
3775 $tid = "headlineActionsBottom";
3778 print "<table class=\"$class\" id=\"$tid\"
3779 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3787 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3788 $page_next_link = "javascript:viewFeedGoPage(1)";
3789 $page_first_link = "javascript:viewFeedGoPage(0)";
3791 $catchup_page_link = "javascript:catchupPage()";
3792 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3793 $catchup_sel_link = "javascript:catchupSelection()";
3795 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3797 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3798 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3799 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3801 $tog_unread_link = "javascript:selectionToggleUnread()";
3802 $tog_marked_link = "javascript:selectionToggleMarked()";
3803 $tog_published_link = "javascript:selectionTogglePublished()";
3807 $sel_all_link = "javascript:cdmSelectArticles('all')";
3808 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3809 $sel_none_link = "javascript:cdmSelectArticles('none')";
3811 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3812 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3813 $tog_published_link = "javascript:selectionTogglePublished(true)";
3817 if (!$dashboard_menu) {
3819 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3821 print "<td class=\"headlineActions$rtl_cpart\">
3822 <ul class=\"headlineDropdownMenu\">
3825 <a href=\"$sel_all_link\">".__('All')."</a>,
3826 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3827 <a href=\"$sel_none_link\">".__('None')."</a></li>
3828 <li class=\"vsep\"> </li>
3829 <li class=\"top\">".__('Toggle')."<ul>
3830 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3831 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3832 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3834 <li class=\"vsep\"> </li>
3835 <li class=\"top\">".__('Mark as read')."<ul>
3836 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3837 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->";
3839 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3842 <li><span class=\"insensitive\">--------</span></li>
3843 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3844 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3845 <li><span class=\"insensitive\">--------</span></li>";
3849 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3852 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3854 if ($limit != 0 && !$search && $enable_pagination) {
3856 <li class=\"vsep\"> </li>
3857 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3858 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3859 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3863 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3865 <li class=\"vsep\"> </li>
3867 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3868 '$match_on', '$feed_id', '$is_cat');\">
3869 ".__('Convert to label')."</a></td>";
3875 // old style subtoolbar:
3877 print "<td class=\"headlineActions$rtl_cpart\">".
3879 <a href=\"$sel_all_link\">".__('All')."</a>,
3880 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3881 <a href=\"$sel_none_link\">".__('None')."</a>
3883 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3884 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3886 __('Mark as read:')."
3887 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3888 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3890 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3893 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3894 '$match_on', '$feed_id', '$is_cat');\">
3895 ".__('Convert to label')."</a>";
3901 } else { // dashboard menu actions
3903 print "<td class=\"headlineActions$rtl_cpart\">
3904 <ul class=\"headlineDropdownMenu\">
3906 <a href=\"#\" onclick=\"return displayDlg('quickAddFeed');\">".
3907 __('Subscribe to feed')."</a>
3909 <li class=\"vsep\"> </li>
3910 <li class=\"top\">".__('Placeholder')."<ul>
3911 <li onclick=\"\">".__('Placeholder')."</li>
3912 <li onclick=\"\">".__('Placeholder')."</li>
3913 <li onclick=\"\">".__('Placeholder')."</li>
3915 <li class=\"vsep\"> </li>
3916 <li class=\"top\">".__('Show')."<ul>
3917 <li onclick=\"\">".__('Update errors')."</li>
3924 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3925 print "<td class=\"headlineActions$rtl_cpart\">
3926 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3927 '$match_on', '$feed_id', '$is_cat');\">
3928 ".__('Convert to Label')."</a></td>";
3931 print "<td class=\"headlineTitle$rtl_cpart\">";
3933 print "<span class=\"headlineInnerTitle\">";
3935 if ($feed_site_url) {
3937 $target = "target=\"_new\"";
3939 print "<a $target href=\"$feed_site_url\">".
3940 truncate_string($feed_title,30)."</a>";
3946 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3949 if ($user_page_offset > 1) {
3950 print " [$user_page_offset] ";
3955 if (!$bottom && !$disable_feed) {
3958 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3959 <img class=\"noborder\"
3960 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3962 } else if ($feed_small_icon) {
3963 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
3967 print "</tr></table>";
3971 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3973 $tmp_category = getCategoryTitle($link, $cat_id);
3974 $cat_unread = getCategoryUnread($link, $cat_id);
3977 $holder_style = "display:none;";
3984 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3986 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3987 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3990 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3992 print "<span id=\"FCAP-$cat_id\">";
3995 print " <span id=\"FCATCTR-$cat_id\"
3996 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4006 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4009 function outputFeedList($link, $tags = false) {
4011 print "<ul class=\"feedList\" id=\"feedList\">";
4013 $owner_uid = $_SESSION["uid"];
4017 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4019 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4022 $cat_hidden = false;
4025 # print "<li class=\"feedCat\">".__('Special')."</li>";
4026 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
4027 # print "<li class=\"feedCat\">".
4028 # "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
4029 # __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
4031 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
4032 # <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
4034 # $cat_unread = getCategoryUnread($link, -1);
4035 # $tmp_category = __("Special");
4036 # $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4038 printCategoryHeader($link, -1, $cat_hidden, false);
4041 if (defined('_ENABLE_DASHBOARD')) {
4042 printFeedEntry(-4, "virt", __("Dashboard"), 0,
4043 "images/tag.png", $link);
4046 $num_starred = getFeedUnread($link, -1);
4047 $num_published = getFeedUnread($link, -2);
4048 $num_fresh = getFeedUnread($link, -3);
4052 if ($num_fresh > 0) $class .= "Unread";
4054 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4055 "images/fresh.png", $link);
4059 if ($num_starred > 0) $class .= "Unread";
4061 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4064 $mark_img_ext = "gif";
4066 $mark_img_ext = "png";
4069 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4070 "images/mark_set.$mark_img_ext", $link);
4074 if ($num_published > 0) $class .= "Unread";
4076 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4077 "images/pub_set.gif", $link);
4079 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4085 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4087 $result = db_query($link, "SELECT id,sql_exp,description FROM
4088 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4090 if (db_num_rows($result) > 0) {
4091 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4093 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4096 $cat_hidden = false;
4099 printCategoryHeader($link, -2, $cat_hidden, false);
4101 # print "<li class=\"feedCat\">".
4102 # "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
4103 # __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
4105 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
4107 print "<li><hr></li>";
4111 while ($line = db_fetch_assoc($result)) {
4113 error_reporting (0);
4115 $label_id = -$line['id'] - 11;
4116 $count = getFeedUnread($link, $label_id);
4124 error_reporting (DEFAULT_ERROR_LEVEL
);
4126 printFeedEntry($label_id,
4127 $class, $line["description"],
4128 $count, "images/label.png", $link);
4132 if (db_num_rows($result) > 0) {
4133 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4140 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4141 print "<li><hr></li>";
4144 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4145 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4146 $order_by_qpart = "category,unread DESC,title";
4148 $order_by_qpart = "category,title";
4151 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4152 $order_by_qpart = "unread DESC,title";
4154 $order_by_qpart = "title";
4158 $age_qpart = getMaxAgeSubquery();
4160 $result = db_query($link, "SELECT ttrss_feeds.*,
4161 SUBSTRING(last_updated,1,19) AS last_updated_noms,
4162 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4163 WHERE feed_id = ttrss_feeds.id AND unread = true
4165 AND ttrss_user_entries.ref_id = ttrss_entries.id
4166 AND owner_uid = '$owner_uid') as unread,
4168 ttrss_feed_categories.title AS category,
4169 ttrss_feed_categories.collapsed
4170 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4171 ON (ttrss_feed_categories.id = cat_id)
4173 ttrss_feeds.hidden = false AND
4174 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4175 ORDER BY $order_by_qpart");
4177 $actid = $_GET["actid"];
4187 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4189 while ($line = db_fetch_assoc($result)) {
4191 $feed = trim($line["title"]);
4193 if (!$feed) $feed = "[Untitled]";
4195 $feed_id = $line["id"];
4197 $subop = $_GET["subop"];
4199 $unread = $line["unread"];
4201 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4202 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4204 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4207 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4210 $rtl_tag = "dir=\"RTL\"";
4215 $tmp_result = db_query($link,
4216 "SELECT id,COUNT(unread) AS unread
4217 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
4218 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
4219 WHERE parent_feed = '$feed_id' AND unread = true
4220 GROUP BY ttrss_feeds.id");
4222 if (db_num_rows($tmp_result) > 0) {
4223 while ($l = db_fetch_assoc($tmp_result)) {
4224 $unread +
= $l["unread"];
4228 $cat_id = $line["cat_id"];
4230 $tmp_category = $line["category"];
4232 if (!$tmp_category) {
4233 $tmp_category = __("Uncategorized");
4236 // $class = ($lnum % 2) ? "even" : "odd";
4238 if ($line["last_error"]) {
4244 if ($unread > 0) $class .= "Unread";
4246 if ($actid == $feed_id) {
4247 $class .= "Selected";
4250 $total_unread +
= $unread;
4252 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4258 $category = $tmp_category;
4260 $collapsed = $line["collapsed"];
4262 // workaround for NULL category
4263 if ($category == __("Uncategorized")) {
4264 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4269 if ($collapsed == "t" ||
$collapsed == "1") {
4270 $holder_class = "feedCatHolder";
4271 $holder_style = "display:none;";
4274 $holder_class = "feedCatHolder";
4279 $cat_id = sprintf("%d", $cat_id);
4281 $cat_unread = getCategoryUnread($link, $cat_id);
4283 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4285 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
4286 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
4287 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
4288 <span id=\"FCATCTR-$cat_id\"
4289 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
4292 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4295 printFeedEntry($feed_id, $class, $feed, $unread,
4296 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4297 $last_updated, $line["last_error"]);
4302 if (db_num_rows($result) == 0) {
4303 print "<li>".__('No feeds to display.')."</li>";
4310 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4311 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4312 post_int_id = ttrss_user_entries.int_id AND
4313 unread = true AND ref_id = ttrss_entries.id
4314 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4316 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4317 ORDER BY tag_name"); */
4319 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4320 print "<li class=\"feedCat\">".__('Tags')."</li>";
4321 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4324 $age_qpart = getMaxAgeSubquery();
4326 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4327 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4328 AND ref_id = id AND $age_qpart
4329 AND unread = true)) AS count FROM ttrss_tags
4330 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4331 ORDER BY count DESC LIMIT 50");
4335 while ($line = db_fetch_assoc($result)) {
4336 $tags[$line["tag_name"]] +
= $line["count"];
4339 foreach (array_keys($tags) as $tag) {
4341 $unread = $tags[$tag];
4349 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4353 if (db_num_rows($result) == 0) {
4354 print "<li>No tags to display.</li>";
4357 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4367 function get_article_tags($link, $id, $owner_uid = 0) {
4369 $a_id = db_escape_string($id);
4371 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4373 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4374 owner_uid as owner FROM
4375 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4376 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4380 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4381 array_push($tags, $tmp_line["tag_name"]);
4387 function trim_value(&$value) {
4388 $value = trim($value);
4391 function trim_array($array) {
4393 array_walk($tmp, 'trim_value');
4397 function tag_is_valid($tag) {
4398 if ($tag == '') return false;
4399 if (preg_match("/^[0-9]*$/", $tag)) return false;
4401 $tag = iconv("utf-8", "utf-8", $tag);
4402 if (!$tag) return false;
4407 function render_login_form($link, $mobile = false) {
4409 require_once "login_form.php";
4411 require_once "mobile/login_form.php";
4415 // from http://developer.apple.com/internet/safari/faq.html
4416 function no_cache_incantation() {
4417 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4418 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4419 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4420 header("Cache-Control: post-check=0, pre-check=0", false);
4421 header("Pragma: no-cache"); // HTTP/1.0
4424 function format_warning($msg, $id = "") {
4425 return "<div class=\"warning\" id=\"$id\">
4426 <img src=\"images/sign_excl.gif\">$msg</div>";
4429 function format_notice($msg) {
4430 return "<div class=\"notice\">
4431 <img src=\"images/sign_info.gif\">$msg</div>";
4434 function format_error($msg) {
4435 return "<div class=\"error\">
4436 <img src=\"images/sign_excl.gif\">$msg</div>";
4439 function print_notice($msg) {
4440 return print format_notice($msg);
4443 function print_warning($msg) {
4444 return print format_warning($msg);
4447 function print_error($msg) {
4448 return print format_error($msg);
4452 function T_sprintf() {
4453 $args = func_get_args();
4454 return vsprintf(__(array_shift($args)), $args);
4457 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4459 /* we can figure out feed_id from article id anyway, why do we
4460 * pass feed_id here? */
4462 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4463 WHERE ref_id = '$id'");
4465 $feed_id = db_fetch_result($result, 0, "feed_id");
4467 print "<article id='$id'><![CDATA[";
4469 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4470 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4472 if (db_num_rows($result) == 1) {
4473 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4475 $rtl_content = false;
4479 $rtl_tag = "dir=\"RTL\"";
4486 if ($mark_as_read) {
4487 $result = db_query($link, "UPDATE ttrss_user_entries
4488 SET unread = false,last_read = NOW()
4489 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4492 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4493 SUBSTRING(updated,1,16) as updated,
4494 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4497 FROM ttrss_entries,ttrss_user_entries
4498 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4504 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4505 $link_target = "target=\"_new\"";
4508 $line = db_fetch_assoc($result);
4510 if ($line["icon_url"]) {
4511 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4513 $feed_icon = " ";
4516 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4517 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4519 $entry_comments = "";
4522 $num_comments = $line["num_comments"];
4523 $entry_comments = "";
4525 if ($num_comments > 0) {
4526 if ($line["comments"]) {
4527 $comments_url = $line["comments"];
4529 $comments_url = $line["link"];
4531 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4533 if ($line["comments"] && $line["link"] != $line["comments"]) {
4534 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4538 print "<div class=\"postReply\">";
4540 print "<div class=\"postHeader\">";
4542 $entry_author = $line["author"];
4544 if ($entry_author) {
4545 $entry_author = __(" - ") . $entry_author;
4548 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4549 strtotime($line["updated"]));
4551 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4553 if ($line["link"]) {
4554 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4555 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4557 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4560 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4561 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4562 ORDER BY tag_name"); */
4564 $tags = get_article_tags($link, $id);
4571 if ($_SESSION["theme"] == "3pane") {
4577 foreach ($tags as $tag) {
4579 $tag_escaped = str_replace("'", "\\'", $tag);
4581 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4583 if ($num_tags == $tag_limit) {
4584 $tags_str .= "…";
4586 } else if ($num_tags < $tag_limit) {
4587 $tags_str .= $tag_str;
4589 $f_tags_str .= $tag_str;
4592 $tags_str = preg_replace("/, $/", "", $tags_str);
4593 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4595 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4596 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4598 if (!$entry_comments) $entry_comments = " "; # placeholder
4600 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4602 print "<div style='float : right'>
4603 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4605 <a title=\"Edit tags for this article\"
4606 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4607 <div clear='both'>$entry_comments</div>";
4611 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4612 print "<div class=\"postContent\">";
4614 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4616 $line["content"] = sanitize_rss($link, $line["content"]);
4618 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4619 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4622 print $line["content"];
4624 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4625 post_id = '$id' AND content_url != ''");
4627 if (db_num_rows($result) > 0) {
4628 print "<div class=\"postEnclosures\">";
4630 if (db_num_rows($result) == 1) {
4631 print __("Attachment:") . " ";
4633 print __("Attachments:") . " ";
4638 while ($line = db_fetch_assoc($result)) {
4640 $url = $line["content_url"];
4641 $ctype = $line["content_type"];
4643 if (!$ctype) $ctype = __("unknown type");
4645 $filename = substr($url, strrpos($url, "/")+
1);
4647 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4648 $filename . " (" . $ctype . ")" . "</a>";
4650 array_push($entries, $entry);
4653 print join(", ", $entries);
4664 print "]]></article>";
4668 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4669 $next_unread_feed, $offset) {
4671 $disable_cache = false;
4673 $timing_info = getmicrotime();
4675 $topmost_article_ids = array();
4681 if ($subop == "undefined") $subop = "";
4683 if ($subop == "CatchupSelected") {
4684 $ids = split(",", db_escape_string($_GET["ids"]));
4685 $cmode = sprintf("%d", $_GET["cmode"]);
4687 catchupArticlesById($link, $ids, $cmode);
4690 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4691 update_generic_feed($link, $feed, $cat_view, true);
4694 if ($subop == "MarkAllRead") {
4695 catchup_feed($link, $feed, $cat_view);
4697 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4698 if ($next_unread_feed) {
4699 $feed = $next_unread_feed;
4705 $result = db_query($link,
4706 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4708 if (db_num_rows($result) == 0) {
4709 print "<div align='center'>".__('Feed not found.')."</div>";
4714 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4716 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4717 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4719 if (db_num_rows($result) == 1) {
4720 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4722 $rtl_content = false;
4726 $rtl_tag = "dir=\"RTL\"";
4732 $rtl_content = false;
4735 $script_dt_add = get_script_dt_add();
4737 /// START /////////////////////////////////////////////////////////////////////////////////
4739 $search = db_escape_string($_GET["query"]);
4742 $disable_cache = true;
4745 $search_mode = db_escape_string($_GET["search_mode"]);
4746 $match_on = db_escape_string($_GET["match_on"]);
4752 $real_offset = $offset * $limit;
4754 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4756 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4757 $search, $search_mode, $match_on, false, $real_offset);
4759 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4761 $result = $qfh_ret[0];
4762 $feed_title = $qfh_ret[1];
4763 $feed_site_url = $qfh_ret[2];
4764 $last_error = $qfh_ret[3];
4767 $feed_site_url = article_publish_url($link);
4770 /// STOP //////////////////////////////////////////////////////////////////////////////////
4773 print "<div id=\"headlinesContainer\" $rtl_tag>";
4776 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4780 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4781 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4784 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4787 $headlines_count = db_num_rows($result);
4789 if (db_num_rows($result) > 0) {
4791 # print "\{$offset}";
4793 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4794 print "<table class=\"headlinesList\" id=\"headlinesList\"
4795 cellspacing=\"0\">";
4798 $lnum = $limit*$offset;
4800 error_reporting (DEFAULT_ERROR_LEVEL
);
4804 while ($line = db_fetch_assoc($result)) {
4806 $class = ($lnum %
2) ?
"even" : "odd";
4809 $feed_id = $line["feed_id"];
4811 if (count($topmost_article_ids) < 5) {
4812 array_push($topmost_article_ids, $id);
4815 if ($line["last_read"] == "" &&
4816 ($line["unread"] != "t" && $line["unread"] != "1")) {
4818 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4821 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4825 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4833 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4836 $mark_img_ext = "gif";
4838 $mark_img_ext = "png";
4841 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4842 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4844 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4846 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4848 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4851 if ($line["published"] == "t" ||
$line["published"] == "1") {
4852 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4854 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4856 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4858 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4861 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4862 # $line["title"] . "</a>";
4864 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4865 $line["title"] . "</a>";
4867 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4868 # $line["title"] . "</a>";
4870 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4871 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4873 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4874 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4877 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4878 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4882 $entry_author = $line["author"];
4884 if ($entry_author) {
4885 $entry_author = " - $entry_author";
4888 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4890 print "<tr class='$class' id='RROW-$id'>";
4892 print "<td class='hlUpdPic'>$update_pic</td>";
4894 print "<td class='hlSelectRow'>
4895 <input type=\"checkbox\" onclick=\"tSR(this)\"
4899 print "<td class='hlMarkedPic'>$marked_pic</td>";
4900 print "<td class='hlMarkedPic'>$published_pic</td>";
4902 # if ($line["feed_title"]) {
4903 # print "<td class='hlContent'>$content_link</td>";
4904 # print "<td class='hlFeed'>
4905 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4906 # truncate_string($line["feed_title"],30)."</a> </td>";
4909 print "<td class='hlContent' valign='middle'>";
4911 print "<a href=\"javascript:view($id,$feed_id);\">" .
4914 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4915 if ($content_preview) {
4916 print "<span class=\"contentPreview\"> - $content_preview</span>";
4922 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4923 # $line["feed_title"]."</a>
4925 if ($line["feed_title"]) {
4926 print "<span class=\"hlFeed\">
4927 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4928 $line["feed_title"]."</a>)
4937 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
4944 $add_class = "Unread";
4949 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
4954 $cdm_cstyle = "style=\"display : none\"";
4957 print "<div class=\"cdmArticle$add_class\"
4958 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4959 onmouseout='cdmMouseOut(this)'>";
4961 print "<div class=\"cdmHeader\">";
4963 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4965 print "<a class=\"title\"
4966 onclick=\"javascript:toggleUnread($id, 0)\"
4967 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4969 print $entry_author;
4972 print " <a id=\"CICH-$id\"
4973 href=\"javascript:cdmExpandArticle($id)\">
4974 (".__('Show article').")</a>";
4978 if ($line["feed_title"]) {
4979 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4984 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4985 $line["content_preview"] = preg_replace("/href=/i",
4986 "target=\"_new\" href=", $line["content_preview"]);
4989 print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
4991 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
4992 print $line["content_preview"];
4994 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4995 post_id = '$id' AND content_url != ''");
4997 if (db_num_rows($e_result) > 0) {
4998 print "<div class=\"cdmEnclosures\">";
5000 if (db_num_rows($e_result) == 1) {
5001 print __("Attachment:") . " ";
5003 print __("Attachments:") . " ";
5008 while ($e_line = db_fetch_assoc($e_result)) {
5010 $url = $e_line["content_url"];
5011 $ctype = $e_line["content_type"];
5012 if (!$ctype) $ctype = __("unknown type");
5014 $filename = substr($url, strrpos($url, "/")+
1);
5016 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5017 $filename . " (" . $ctype . ")" . "</a>";
5019 array_push($entries, $entry);
5022 print join(", ", $entries);
5027 print "<br clear='both'>";
5030 /* if (!$expand_cdm) {
5031 print "<a id=\"CICH-$id\"
5032 href=\"javascript:cdmExpandArticle($id)\">
5038 print "<div class=\"cdmFooter\"><span class='s0'>";
5040 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5042 print __("Select:").
5043 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5044 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5046 print "</span><span class='s1'>$marked_pic</span> ";
5047 print "<span class='s1'>$published_pic</span> ";
5049 $tags = get_article_tags($link, $id);
5052 $full_tags_str = "";
5055 foreach ($tags as $tag) {
5057 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5058 if ($num_tags < 5) {
5059 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5060 } else if ($num_tags == 5) {
5061 $tags_str .= "…";
5065 $tags_str = preg_replace("/, $/", "", $tags_str);
5066 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5068 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5070 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5073 if ($tags_str == "") $tags_str = "no tags";
5075 // print "<img src='images/tag.png' class='markedPic'>";
5077 print "<span class='s1'>
5078 <img class='tagsPic' src='images/tag.png' alt='Tags'
5079 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5080 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5084 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5085 href=\"javascript:toggleUnread($id)\">
5096 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5100 // print_headline_subtoolbar($link,
5101 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5107 switch ($view_mode) {
5109 $message = __("No unread articles found to display.");
5112 $message = __("No starred articles found to display.");
5115 $message = __("No articles found to display.");
5118 if (!$offset) print "<div class='whiteBox'>$message</div>";
5126 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
5129 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5131 function printTagCloud($link) {
5133 /* get first ref_id to count from */
5139 if (DB_TYPE == "pgsql") {
5140 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5141 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5142 AND date_entered > NOW() - INTERVAL '30 days'";
5144 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5145 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5146 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5149 $result = db_query($link, $query);
5150 $first_id = db_fetch_result($result, 0, "id"); */
5152 //AND post_int_id >= '$first_id'
5153 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5154 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5155 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5157 $result = db_query($link, $query);
5161 while ($line = db_fetch_assoc($result)) {
5162 $tags[$line["tag_name"]] = $line["count"];
5167 $max_size = 32; // max font size in pixels
5168 $min_size = 11; // min font size in pixels
5170 // largest and smallest array values
5171 $max_qty = max(array_values($tags));
5172 $min_qty = min(array_values($tags));
5174 // find the range of values
5175 $spread = $max_qty - $min_qty;
5176 if ($spread == 0) { // we don't want to divide by zero
5180 // set the font-size increment
5181 $step = ($max_size - $min_size) / ($spread);
5183 // loop through the tag array
5184 foreach ($tags as $key => $value) {
5185 // calculate font-size
5186 // find the $value in excess of $min_qty
5187 // multiply by the font-size increment ($size)
5188 // and add the $min_size set above
5189 $size = round($min_size +
(($value - $min_qty) * $step));
5191 $key_escaped = str_replace("'", "\\'", $key);
5193 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5194 $size . "px\" title=\"$value articles tagged with " .
5195 $key . '">' . $key . '</a> ';
5199 function print_checkpoint($n, $s) {
5200 $ts = getmicrotime();
5201 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5205 function sanitize_tag($tag) {
5208 $tag = mb_strtolower($tag, 'utf-8');
5210 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5212 // $tag = str_replace('"', "", $tag);
5213 // $tag = str_replace("+", " ", $tag);
5214 $tag = str_replace("technorati tag: ", "", $tag);
5219 function generate_publish_key() {
5220 return sha1(uniqid(rand(), true));
5223 function article_publish_url($link) {
5225 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5227 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5233 * Purge a feed contents, marked articles excepted.
5235 * @param mixed $link The database connection.
5236 * @param integer $id The id of the feed to purge.
5239 function clear_feed_articles($link, $id) {
5240 $result = db_query($link, "DELETE FROM ttrss_user_entries
5241 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5243 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5244 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5245 } // function clear_feed_articles
5248 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5250 * @return string The Mozilla Firefox feed adding URL.
5252 function add_feed_url() {
5253 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5254 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5256 } // function add_feed_url
5259 * Encrypt a password in SHA1.
5261 * @param string $pass The password to encrypt.
5262 * @param string $login A optionnal login.
5263 * @return string The encrypted password.
5265 function encrypt_password($pass, $login = '') {
5267 return "SHA1X:" . sha1("$login:$pass");
5269 return "SHA1:" . sha1($pass);
5271 } // function encrypt_password
5274 * Update a feed batch.
5275 * Used by daemons to update n feeds by run.
5276 * Only update feed needing a update, and not being processed
5277 * by another process.
5279 * @param mixed $link Database link
5280 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5281 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5282 * @param boolean $debug Set to false to disable debug output. Default to true.
5285 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5286 // Process all other feeds using last_updated and interval parameters
5288 // Test if the user has loggued in recently. If not, it does not update its feeds.
5289 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5290 if (DB_TYPE
== "pgsql") {
5291 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5293 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5296 $login_thresh_qpart = "";
5299 // Test if the feed need a update (update interval exceded).
5300 if (DB_TYPE
== "pgsql") {
5301 $update_limit_qpart = "AND ((
5302 ttrss_feeds.update_interval = 0
5303 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5305 ttrss_feeds.update_interval > 0
5306 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5307 ) OR ttrss_feeds.last_updated IS NULL)";
5309 $update_limit_qpart = "AND ((
5310 ttrss_feeds.update_interval = 0
5311 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5313 ttrss_feeds.update_interval > 0
5314 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5315 ) OR ttrss_feeds.last_updated IS NULL)";
5318 // Test if feed is currently being updated by another process.
5319 if (DB_TYPE
== "pgsql") {
5320 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5322 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5325 // Test if there is a limit to number of updated feeds
5327 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5329 $random_qpart = sql_random_function();
5331 // We search for feed needing update.
5332 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5333 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
5334 ttrss_feeds.update_interval
5336 ttrss_feeds, ttrss_users, ttrss_user_prefs
5338 ttrss_feeds.owner_uid = ttrss_users.id
5339 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5340 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5341 $login_thresh_qpart $update_limit_qpart
5342 $updstart_thresh_qpart
5343 ORDER BY $random_qpart $query_limit");
5345 $user_prefs_cache = array();
5347 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5349 // Here is a little cache magic in order to minimize risk of double feed updates.
5350 $feeds_to_update = array();
5351 while ($line = db_fetch_assoc($result)) {
5352 $feeds_to_update[$line['id']] = $line;
5355 // We update the feed last update started date before anything else.
5356 // There is no lag due to feed contents downloads
5357 // It prevent an other process to update the same feed.
5358 $feed_ids = array_keys($feeds_to_update);
5360 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5361 WHERE id IN (%s)", implode(',', $feed_ids)));
5364 // For each feed, we call the feed update function.
5365 while ($line = array_pop($feeds_to_update)) {
5367 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5369 // We setup a alarm to alert if the feed take more than 300s to update.
5371 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5372 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5373 // Cancel the alarm (the update went well)
5374 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5376 sleep(1); // prevent flood (FIXME make this an option?)
5379 // Send feed digests by email if needed.
5380 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5382 } // function update_daemon_common
5384 function generate_dashboard_feed($link) {
5386 print "<div id=\"headlinesContainer\">";
5388 print_headline_subtoolbar($link, "", "Dashboard",
5389 false, false, -4, false, false, false,
5390 false, 0, 0, true, true, "tag.png");
5392 print "<div id=\"headlinesInnerContainer\" class=\"dashboard\">";
5393 print "<div>There is <b>666</b> unread articles in <b>666</b> feeds.</div>";
5398 print "]]></headlines>";
5399 print "<headlines-count value=\"0\"/>";
5400 print "<headlines-unread value=\"0\"/>";
5401 print "<disable-cache value=\"1\"/>";
5404 print "</articles>";