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_article_content($entry_content);
1042 $entry_title = sanitize_article_content($entry_title);
1044 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1045 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1048 db_query($link, "BEGIN");
1050 if (db_num_rows($result) == 0) {
1052 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1053 _debug("update_rss_feed: base guid not found");
1056 // base post entry does not exist, create it
1058 $result = db_query($link,
1059 "INSERT INTO ttrss_entries
1075 '$entry_timestamp_fmt',
1084 // we keep encountering the entry in feeds, so we need to
1085 // update date_entered column so that we don't get horrible
1086 // dupes when the entry gets purged and reinserted again e.g.
1087 // in the case of SLOW SLOW OMG SLOW updating feeds
1089 $base_entry_id = db_fetch_result($result, 0, "id");
1091 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1092 WHERE id = '$base_entry_id'");
1095 // now it should exist, if not - bad luck then
1097 $result = db_query($link, "SELECT
1098 id,content_hash,no_orig_date,title,
1099 substring(date_entered,1,19) as date_entered,
1100 substring(updated,1,19) as updated,
1104 WHERE guid = '$entry_guid'");
1109 if (db_num_rows($result) == 1) {
1111 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1112 _debug("update_rss_feed: base guid found, checking for user record");
1115 // this will be used below in update handler
1116 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1117 $orig_title = db_fetch_result($result, 0, "title");
1118 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1119 $orig_date_entered = strtotime(db_fetch_result($result,
1120 0, "date_entered"));
1122 $ref_id = db_fetch_result($result, 0, "id");
1123 $entry_ref_id = $ref_id;
1125 // check for user post link to main table
1127 // do we allow duplicate posts with same GUID in different feeds?
1128 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1129 $dupcheck_qpart = "AND feed_id = '$feed'";
1131 $dupcheck_qpart = "";
1134 // error_reporting(0);
1136 $article_filters = get_article_filters($filters, $entry_title,
1137 $entry_content, $entry_link);
1139 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1140 _debug("update_rss_feed: article filters: ");
1141 if (count($article_filters) != 0) {
1142 print_r($article_filters);
1146 if (find_article_filter($article_filters, "filter")) {
1150 // error_reporting (DEFAULT_ERROR_LEVEL);
1152 $result = db_query($link,
1153 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1154 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1157 // okay it doesn't exist - create user entry
1158 if (db_num_rows($result) == 0) {
1160 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1161 _debug("update_rss_feed: user record not found, creating...");
1164 if (!find_article_filter($article_filters, 'catchup')) {
1166 $last_read_qpart = 'NULL';
1169 $last_read_qpart = 'NOW()';
1172 if (find_article_filter($article_filters, 'mark')) {
1178 if (find_article_filter($article_filters, 'publish')) {
1179 $published = 'true';
1181 $published = 'false';
1184 $result = db_query($link,
1185 "INSERT INTO ttrss_user_entries
1186 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
1187 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1188 $last_read_qpart, $marked, $published)");
1190 $result = db_query($link,
1191 "SELECT int_id FROM ttrss_user_entries WHERE
1192 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1193 feed_id = '$feed' LIMIT 1");
1195 if (db_num_rows($result) == 1) {
1196 $entry_int_id = db_fetch_result($result, 0, "int_id");
1199 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1200 $entry_int_id = db_fetch_result($result, 0, "int_id");
1203 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1204 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1207 $post_needs_update = false;
1209 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1210 ($content_hash != $orig_content_hash)) {
1211 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1212 $post_needs_update = true;
1215 if (db_escape_string($orig_title) != $entry_title) {
1216 $post_needs_update = true;
1219 if ($orig_num_comments != $num_comments) {
1220 $post_needs_update = true;
1223 // this doesn't seem to be very reliable
1225 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1226 // $post_needs_update = true;
1229 // if post needs update, update it and mark all user entries
1230 // linking to this post as updated
1231 if ($post_needs_update) {
1233 if (defined('DAEMON_EXTENDED_DEBUG')) {
1234 _debug("update_rss_feed: post $entry_guid needs update...");
1237 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1239 db_query($link, "UPDATE ttrss_entries
1240 SET title = '$entry_title', content = '$entry_content',
1241 content_hash = '$content_hash',
1242 num_comments = '$num_comments'
1243 WHERE id = '$ref_id'");
1245 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1246 db_query($link, "UPDATE ttrss_user_entries
1247 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1249 db_query($link, "UPDATE ttrss_user_entries
1250 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1256 db_query($link, "COMMIT");
1258 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1259 _debug("update_rss_feed: looking for enclosures...");
1262 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1263 print_r($enclosures);
1266 db_query($link, "BEGIN");
1268 foreach ($enclosures as $enc) {
1269 $enc_url = db_escape_string($enc[0]);
1270 $enc_type = db_escape_string($enc[1]);
1271 $enc_dur = db_escape_string($enc[2]);
1273 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1274 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1276 if (db_num_rows($result) == 0) {
1277 db_query($link, "INSERT INTO ttrss_enclosures
1278 (content_url, content_type, title, duration, post_id) VALUES
1279 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1283 db_query($link, "COMMIT");
1285 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1286 _debug("update_rss_feed: looking for tags...");
1290 // <a href="..." rel="tag">Xorg</a>, //
1294 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1295 $entry_content_unescaped, $entry_tags);
1297 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1298 print_r($entry_tags);
1299 print "<br/></p>"; */
1301 $entry_tags = $entry_tags[1];
1303 # check for manual tags
1305 $tag_filter = find_article_filter($article_filters, "tag");
1309 $manual_tags = trim_array(split(",", $tag_filter[1]));
1311 foreach ($manual_tags as $tag) {
1312 if (tag_is_valid($tag)) {
1313 array_push($entry_tags, $tag);
1318 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1319 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1321 if ($additional_tags && is_array($additional_tags)) {
1322 foreach ($additional_tags as $tag) {
1323 if (tag_is_valid($tag) &&
1324 array_search($tag, $boring_tags) === FALSE) {
1325 array_push($entry_tags, $tag);
1330 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1332 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1333 print_r($entry_tags);
1336 if (count($entry_tags) > 0) {
1338 db_query($link, "BEGIN");
1340 foreach ($entry_tags as $tag) {
1342 $tag = sanitize_tag($tag);
1343 $tag = db_escape_string($tag);
1345 if (!tag_is_valid($tag)) continue;
1347 $result = db_query($link, "SELECT id FROM ttrss_tags
1348 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1349 owner_uid = '$owner_uid' LIMIT 1");
1351 // print db_fetch_result($result, 0, "id");
1353 if ($result && db_num_rows($result) == 0) {
1355 db_query($link, "INSERT INTO ttrss_tags
1356 (owner_uid,tag_name,post_int_id)
1357 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1361 db_query($link, "COMMIT");
1364 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1365 _debug("update_rss_feed: article processed");
1369 db_query($link, "UPDATE ttrss_feeds
1370 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1372 // db_query($link, "COMMIT");
1376 if ($use_simplepie) {
1377 $error_msg = mb_substr($rss->error(), 0, 250);
1379 $error_msg = mb_substr(magpie_error(), 0, 250);
1382 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1383 _debug("update_rss_feed: error fetching feed: $error_msg");
1386 $error_msg = db_escape_string($error_msg);
1389 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1390 last_updated = NOW() WHERE id = '$feed'");
1393 if ($use_simplepie) {
1397 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1398 _debug("update_rss_feed: done");
1403 function print_select($id, $default, $values, $attributes = "") {
1404 print "<select name=\"$id\" id=\"$id\" $attributes>";
1405 foreach ($values as $v) {
1411 print "<option$sel>$v</option>";
1416 function print_select_hash($id, $default, $values, $attributes = "") {
1417 print "<select name=\"$id\" id='$id' $attributes>";
1418 foreach (array_keys($values) as $v) {
1424 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1430 function get_article_filters($filters, $title, $content, $link) {
1433 if ($filters["title"]) {
1434 foreach ($filters["title"] as $filter) {
1435 $reg_exp = $filter["reg_exp"];
1436 $inverse = $filter["inverse"];
1437 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1438 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1440 array_push($matches, array($filter["action"], $filter["action_param"]));
1445 if ($filters["content"]) {
1446 foreach ($filters["content"] as $filter) {
1447 $reg_exp = $filter["reg_exp"];
1448 $inverse = $filter["inverse"];
1450 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1451 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1453 array_push($matches, array($filter["action"], $filter["action_param"]));
1458 if ($filters["both"]) {
1459 foreach ($filters["both"] as $filter) {
1460 $reg_exp = $filter["reg_exp"];
1461 $inverse = $filter["inverse"];
1464 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1465 array_push($matches, array($filter["action"], $filter["action_param"]));
1468 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1469 array_push($matches, array($filter["action"], $filter["action_param"]));
1475 if ($filters["link"]) {
1476 $reg_exp = $filter["reg_exp"];
1477 foreach ($filters["link"] as $filter) {
1478 $reg_exp = $filter["reg_exp"];
1479 $inverse = $filter["inverse"];
1481 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1482 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1484 array_push($matches, array($filter["action"], $filter["action_param"]));
1492 function find_article_filter($filters, $filter_name) {
1493 foreach ($filters as $f) {
1494 if ($f[0] == $filter_name) {
1501 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1502 $rtl_content = false, $last_updated = false, $last_error = false) {
1504 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1505 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1507 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1511 $rtl_tag = "dir=\"rtl\"";
1513 $rtl_tag = "dir=\"ltr\"";
1516 $error_notify_msg = "";
1519 $link_title = "Error: $last_error ($last_updated)";
1520 $error_notify_msg = "(Error)";
1521 } else if ($last_updated) {
1522 $link_title = "Updated: $last_updated";
1525 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1526 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1528 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1529 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1533 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1538 $fctr_class = "class=\"invisible\"";
1541 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1542 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1544 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1545 print "<div class=\"feedExtInfo\">
1546 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1553 function getmicrotime() {
1554 list($usec, $sec) = explode(" ",microtime());
1555 return ((float)$usec +
(float)$sec);
1558 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1559 foreach ($values as $v) {
1566 if ($v == $true_is) {
1567 $sel .= " value=\"1\"";
1569 $sel .= " value=\"0\"";
1572 print "<input class=\"noborder\"
1573 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1578 function initialize_user_prefs($link, $uid) {
1580 $uid = db_escape_string($uid);
1582 db_query($link, "BEGIN");
1584 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1586 $u_result = db_query($link, "SELECT pref_name
1587 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1589 $active_prefs = array();
1591 while ($line = db_fetch_assoc($u_result)) {
1592 array_push($active_prefs, $line["pref_name"]);
1595 while ($line = db_fetch_assoc($result)) {
1596 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1597 // print "adding " . $line["pref_name"] . "<br>";
1599 db_query($link, "INSERT INTO ttrss_user_prefs
1600 (owner_uid,pref_name,value) VALUES
1601 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1606 db_query($link, "COMMIT");
1610 function lookup_user_id($link, $user) {
1612 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1615 if (db_num_rows($result) == 1) {
1616 return db_fetch_result($result, 0, "id");
1622 function http_authenticate_user($link) {
1624 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1626 if (!$_SERVER["PHP_AUTH_USER"]) {
1628 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1629 header('HTTP/1.0 401 Unauthorized');
1633 $auth_result = authenticate_user($link,
1634 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1636 if (!$auth_result) {
1637 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1638 header('HTTP/1.0 401 Unauthorized');
1646 function authenticate_user($link, $login, $password, $force_auth = false) {
1648 if (!SINGLE_USER_MODE
) {
1650 $pwd_hash1 = encrypt_password($password);
1651 $pwd_hash2 = encrypt_password($password, $login);
1653 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1654 && $_SERVER["REMOTE_USER"]) {
1656 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1658 $query = "SELECT id,login,access_level
1659 FROM ttrss_users WHERE
1663 $query = "SELECT id,login,access_level,pwd_hash
1664 FROM ttrss_users WHERE
1665 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1666 pwd_hash = '$pwd_hash2')";
1669 $result = db_query($link, $query);
1671 if (db_num_rows($result) == 1) {
1672 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1673 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1674 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1676 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1679 $user_theme = get_user_theme_path($link);
1681 $_SESSION["theme"] = $user_theme;
1682 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1683 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1685 initialize_user_prefs($link, $_SESSION["uid"]);
1694 $_SESSION["uid"] = 1;
1695 $_SESSION["name"] = "admin";
1697 $user_theme = get_user_theme_path($link);
1699 $_SESSION["theme"] = $user_theme;
1700 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1702 initialize_user_prefs($link, $_SESSION["uid"]);
1708 function make_password($length = 8) {
1711 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1715 while ($i < $length) {
1716 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1718 if (!strstr($password, $char)) {
1726 // this is called after user is created to initialize default feeds, labels
1729 // user preferences are checked on every login, not here
1731 function initialize_user($link, $uid) {
1733 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1734 values ('$uid','unread = true', 'Unread articles')");
1736 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1737 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1739 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1740 values ('$uid', 'Tiny Tiny RSS: New Releases',
1741 'http://tt-rss.spb.ru/releases.rss')");
1743 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1744 values ('$uid', 'Tiny Tiny RSS: Forum',
1745 'http://tt-rss.spb.ru/forum/rss.php')");
1748 function logout_user() {
1750 if (isset($_COOKIE[session_name()])) {
1751 setcookie(session_name(), '', time()-42000, '/');
1755 function get_script_urlpath() {
1756 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1759 function validate_session($link) {
1760 if (SINGLE_USER_MODE
) {
1764 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1765 if ($_SESSION["ip_address"]) {
1766 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1767 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1773 if ($_SESSION["uid"]) {
1775 $result = db_query($link,
1776 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1778 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1780 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1785 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1787 //print_r($_SESSION);
1789 if (time() > $_SESSION["cookie_lifetime"]) {
1797 function login_sequence($link, $mobile = false) {
1798 if (!SINGLE_USER_MODE
) {
1800 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1801 $swu = db_escape_string($_REQUEST["swu"]);
1803 $_SESSION["prefs_cache"] = false;
1804 return authenticate_user($link, $swu, null, true);
1808 $login_action = $_POST["login_action"];
1810 # try to authenticate user if called from login form
1811 if ($login_action == "do_login") {
1812 $login = $_POST["login"];
1813 $password = $_POST["password"];
1814 $remember_me = $_POST["remember_me"];
1816 if (authenticate_user($link, $login, $password)) {
1817 $_POST["password"] = "";
1819 $_SESSION["language"] = $_POST["language"];
1821 header("Location: " . $_SERVER["REQUEST_URI"]);
1826 $_SESSION["login_error_msg"] = "Incorrect username or password";
1830 // print session_id();
1831 // print_r($_SESSION);
1833 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1834 render_login_form($link, $mobile);
1837 /* bump login timestamp */
1838 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1841 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1842 setcookie("ttrss_lang", $_SESSION["language"],
1843 time() + SESSION_COOKIE_LIFETIME
);
1848 return authenticate_user($link, "admin", null);
1852 function truncate_string($str, $max_len) {
1853 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1854 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1860 function get_user_theme_path($link) {
1861 $result = db_query($link, "SELECT theme_path
1863 ttrss_themes,ttrss_users
1864 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1865 if (db_num_rows($result) != 0) {
1866 return db_fetch_result($result, 0, "theme_path");
1872 function smart_date_time($timestamp) {
1873 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1874 return date("G:i", $timestamp);
1875 } else if (date("Y", $timestamp) == date("Y")) {
1876 return date("M d, G:i", $timestamp);
1878 return date("Y/m/d, G:i", $timestamp);
1882 function smart_date($timestamp) {
1883 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1885 } else if (date("Y", $timestamp) == date("Y")) {
1886 return date("D m", $timestamp);
1888 return date("Y/m/d", $timestamp);
1892 function sql_bool_to_string($s) {
1893 if ($s == "t" ||
$s == "1") {
1900 function sql_bool_to_bool($s) {
1901 if ($s == "t" ||
$s == "1") {
1909 function toggleEvenOdd($a) {
1916 function sanity_check($link) {
1921 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1922 $schema_version = db_fetch_result($result, 0, "schema_version");
1924 if ($schema_version != SCHEMA_VERSION
) {
1928 if (DB_TYPE
== "mysql") {
1929 $result = db_query($link, "SELECT true", false);
1930 if (db_num_rows($result) != 1) {
1935 error_reporting (DEFAULT_ERROR_LEVEL
);
1937 if ($error_code != 0) {
1938 print_error_xml($error_code);
1945 function file_is_locked($filename) {
1946 if (function_exists('flock')) {
1948 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1949 error_reporting(DEFAULT_ERROR_LEVEL
);
1951 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1952 flock($fp, LOCK_UN
);
1963 function make_lockfile($filename) {
1964 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1966 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1973 function make_stampfile($filename) {
1974 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1976 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1977 fwrite($fp, time() . "\n");
1978 flock($fp, LOCK_UN
);
1986 function read_stampfile($filename) {
1989 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1990 error_reporting (DEFAULT_ERROR_LEVEL
);
1992 if (flock($fp, LOCK_EX
)) {
1993 $stamp = fgets($fp);
1994 flock($fp, LOCK_UN
);
2002 function sql_random_function() {
2003 if (DB_TYPE
== "mysql") {
2010 function catchup_feed($link, $feed, $cat_view) {
2012 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2017 $cat_qpart = "cat_id = '$feed'";
2019 $cat_qpart = "cat_id IS NULL";
2022 $tmp_result = db_query($link, "SELECT id
2023 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2026 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2028 $tmp_feed = $tmp_line["id"];
2030 db_query($link, "UPDATE ttrss_user_entries
2031 SET unread = false,last_read = NOW()
2032 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2035 } else if ($feed > 0) {
2037 $tmp_result = db_query($link, "SELECT id
2038 FROM ttrss_feeds WHERE parent_feed = '$feed'
2039 ORDER BY cat_id,title");
2041 $parent_ids = array();
2043 if (db_num_rows($tmp_result) > 0) {
2044 while ($p = db_fetch_assoc($tmp_result)) {
2045 array_push($parent_ids, "feed_id = " . $p["id"]);
2048 $children_qpart = implode(" OR ", $parent_ids);
2050 db_query($link, "UPDATE ttrss_user_entries
2051 SET unread = false,last_read = NOW()
2052 WHERE (feed_id = '$feed' OR $children_qpart)
2053 AND owner_uid = " . $_SESSION["uid"]);
2056 db_query($link, "UPDATE ttrss_user_entries
2057 SET unread = false,last_read = NOW()
2058 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2061 } else if ($feed < 0 && $feed > -10) { // special, like starred
2064 db_query($link, "UPDATE ttrss_user_entries
2065 SET unread = false,last_read = NOW()
2066 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2070 db_query($link, "UPDATE ttrss_user_entries
2071 SET unread = false,last_read = NOW()
2072 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2077 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2079 if (DB_TYPE
== "pgsql") {
2080 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
2082 $match_part = "date_entered > DATE_SUB(NOW(),
2083 INTERVAL $intl HOUR) ";
2086 $result = db_query($link, "SELECT id FROM ttrss_entries,
2087 ttrss_user_entries WHERE $match_part AND
2089 ttrss_user_entries.ref_id = ttrss_entries.id AND
2090 owner_uid = ".$_SESSION["uid"]);
2092 $affected_ids = array();
2094 while ($line = db_fetch_assoc($result)) {
2095 array_push($affected_ids, $line["id"]);
2098 catchupArticlesById($link, $affected_ids, 0);
2101 } else if ($feed < -10) { // label
2103 // TODO make this more efficient
2105 $label_id = -$feed - 11;
2107 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2108 WHERE id = '$label_id'");
2111 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2113 db_query($link, "BEGIN");
2115 $tmp2_result = db_query($link,
2119 ttrss_user_entries,ttrss_entries,ttrss_feeds
2121 ref_id = ttrss_entries.id AND
2122 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2124 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2126 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2127 db_query($link, "UPDATE
2130 unread = false, last_read = NOW()
2132 int_id = " . $tmp_line["int_id"]);
2135 db_query($link, "COMMIT");
2137 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2138 SET unread = false,last_read = NOW()
2141 AND owner_uid = ".$_SESSION["uid"]); */
2145 db_query($link, "BEGIN");
2147 $tag_name = db_escape_string($feed);
2149 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2150 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2152 while ($line = db_fetch_assoc($result)) {
2153 db_query($link, "UPDATE ttrss_user_entries SET
2154 unread = false, last_read = NOW()
2155 WHERE int_id = " . $line["post_int_id"]);
2157 db_query($link, "COMMIT");
2161 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2165 $cat_qpart = "cat_id = '$feed'";
2167 $cat_qpart = "cat_id IS NULL";
2170 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2171 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2173 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2174 $feed_url = $tmp_line["feed_url"];
2175 $feed_id = $tmp_line["id"];
2176 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2180 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2181 WHERE id = '$feed'");
2182 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2183 update_rss_feed($link, $feed_url, $feed, $force_update);
2187 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2188 /* getLabelCounters($link);
2189 getFeedCounters($link);
2190 getTagCounters($link);
2191 getGlobalCounters($link);
2192 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2193 getCategoryCounters($link);
2196 if (!$omode) $omode = "flc";
2198 getGlobalCounters($link);
2200 if (strchr($omode, "l")) getLabelCounters($link);
2201 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2202 if (strchr($omode, "t")) getTagCounters($link);
2203 if (strchr($omode, "c")) {
2204 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2205 getCategoryCounters($link);
2210 function getCategoryCounters($link) {
2211 # two special categories are -1 and -2 (all virtuals; all labels)
2213 $ctr = getCategoryUnread($link, -1);
2215 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2217 $ctr = getCategoryUnread($link, -2);
2219 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2221 $age_qpart = getMaxAgeSubquery();
2223 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
2224 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2225 AND id = ref_id AND $age_qpart
2226 AND unread = true)) AS unread FROM ttrss_feeds
2228 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2230 while ($line = db_fetch_assoc($result)) {
2231 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2232 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2233 $line["unread"]."\"/>";
2237 function getCategoryUnread($link, $cat) {
2242 $cat_query = "cat_id = '$cat'";
2244 $cat_query = "cat_id IS NULL";
2247 $age_qpart = getMaxAgeSubquery();
2249 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2251 AND owner_uid = " . $_SESSION["uid"]);
2253 $cat_feeds = array();
2254 while ($line = db_fetch_assoc($result)) {
2255 array_push($cat_feeds, "feed_id = " . $line["id"]);
2258 if (count($cat_feeds) == 0) return 0;
2260 $match_part = implode(" OR ", $cat_feeds);
2262 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2263 FROM ttrss_user_entries,ttrss_entries
2264 WHERE unread = true AND ($match_part) AND id = ref_id
2265 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2269 # this needs to be rewritten
2270 while ($line = db_fetch_assoc($result)) {
2271 $unread +
= $line["unread"];
2275 } else if ($cat == -1) {
2276 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2277 } else if ($cat == -2) {
2279 $rv = getLabelCounters($link, false, true);
2282 foreach (array_keys($rv) as $k) {
2284 $ctr +
= $rv[$k]["counter"];
2292 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2293 if (DB_TYPE
== "pgsql") {
2294 return "ttrss_entries.date_entered >
2295 NOW() - INTERVAL '$days days'";
2297 return "ttrss_entries.date_entered >
2298 DATE_SUB(NOW(), INTERVAL $days DAY)";
2302 function getFeedUnread($link, $feed, $is_cat = false) {
2303 $n_feed = sprintf("%d", $feed);
2305 $age_qpart = getMaxAgeSubquery();
2308 return getCategoryUnread($link, $n_feed);
2309 } else if ($n_feed == -1) {
2310 $match_part = "marked = true";
2311 } else if ($n_feed == -2) {
2312 $match_part = "published = true";
2313 } else if ($n_feed == -3) {
2314 $match_part = "unread = true";
2316 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2318 if (DB_TYPE
== "pgsql") {
2319 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2321 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2324 } else if ($n_feed > 0) {
2326 $result = db_query($link, "SELECT id FROM ttrss_feeds
2327 WHERE parent_feed = '$n_feed'
2329 AND owner_uid = " . $_SESSION["uid"]);
2331 if (db_num_rows($result) > 0) {
2333 $linked_feeds = array();
2334 while ($line = db_fetch_assoc($result)) {
2335 array_push($linked_feeds, "feed_id = " . $line["id"]);
2338 array_push($linked_feeds, "feed_id = $n_feed");
2340 $match_part = implode(" OR ", $linked_feeds);
2342 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2343 FROM ttrss_user_entries,ttrss_entries
2344 WHERE unread = true AND
2345 ttrss_user_entries.ref_id = ttrss_entries.id AND
2348 owner_uid = " . $_SESSION["uid"]);
2352 # this needs to be rewritten
2353 while ($line = db_fetch_assoc($result)) {
2354 $unread +
= $line["unread"];
2360 $match_part = "feed_id = '$n_feed'";
2362 } else if ($feed < -10) {
2364 $label_id = -$feed - 11;
2366 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2367 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2369 $match_part = db_fetch_result($result, 0, "sql_exp");
2374 $result = db_query($link, "SELECT count(int_id) AS unread
2375 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2376 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2377 ttrss_user_entries.ref_id = ttrss_entries.id AND
2378 ttrss_feeds.hidden = false AND
2380 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2384 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2385 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2386 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2387 AND unread = true AND $age_qpart AND
2388 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2391 $unread = db_fetch_result($result, 0, "unread");
2396 /* FIXME this needs reworking */
2398 function getGlobalUnread($link, $user_id = false) {
2401 $user_id = $_SESSION["uid"];
2404 $age_qpart = getMaxAgeSubquery();
2406 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2407 WHERE unread = true AND
2408 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2409 ttrss_user_entries.ref_id = ttrss_entries.id AND
2412 ttrss_user_entries.owner_uid = '$user_id'");
2413 $c_id = db_fetch_result($result, 0, "c_id");
2417 function getGlobalCounters($link, $global_unread = -1) {
2418 if ($global_unread == -1) {
2419 $global_unread = getGlobalUnread($link);
2421 print "<counter type=\"global\" id='global-unread'
2422 counter='$global_unread'/>";
2424 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2425 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2427 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2429 print "<counter type=\"global\" id='subscribed-feeds'
2430 counter='$subscribed_feeds'/>";
2434 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2437 if (!$_SESSION["tctr_last_value"]) {
2438 $_SESSION["tctr_last_value"] = array();
2442 $old_counters = $_SESSION["tctr_last_value"];
2444 $tctrs_modified = false;
2446 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2447 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2448 ttrss_user_entries.ref_id = ttrss_entries.id AND
2449 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2450 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2452 select tag_name,0 as count FROM ttrss_tags
2453 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2455 $age_qpart = getMaxAgeSubquery();
2457 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2458 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2459 AND ref_id = id AND $age_qpart
2460 AND unread = true)) AS count FROM ttrss_tags
2461 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2462 ORDER BY count DESC LIMIT 55");
2466 while ($line = db_fetch_assoc($result)) {
2467 $tags[$line["tag_name"]] +
= $line["count"];
2470 foreach (array_keys($tags) as $tag) {
2471 $unread = $tags[$tag];
2473 $tag = htmlspecialchars($tag);
2475 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2476 $old_counters[$tag] = $unread;
2477 $tctrs_modified = true;
2478 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2483 if ($smart_mode && $tctrs_modified) {
2484 $_SESSION["tctr_last_value"] = $old_counters;
2489 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2491 $age_qpart = getMaxAgeSubquery();
2494 if (!$_SESSION["lctr_last_value"]) {
2495 $_SESSION["lctr_last_value"] = array();
2501 $old_counters = $_SESSION["lctr_last_value"];
2502 $lctrs_modified = false;
2504 $count = getFeedUnread($link, -1);
2507 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2509 $ret_arr["-1"]["counter"] = $count;
2510 $ret_arr["-1"]["description"] = __("Starred articles");
2513 $count = getFeedUnread($link, -2);
2516 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2518 $ret_arr["-2"]["counter"] = $count;
2519 $ret_arr["-2"]["description"] = __("Published articles");
2522 $count = getFeedUnread($link, -3);
2525 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2527 $ret_arr["-3"]["counter"] = $count;
2528 $ret_arr["-3"]["description"] = __("Fresh articles");
2532 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2533 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2535 while ($line = db_fetch_assoc($result)) {
2537 $id = -$line["id"] - 11;
2539 $label_name = $line["description"];
2541 error_reporting (0);
2543 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2544 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2545 ttrss_feeds.hidden = false AND
2547 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2548 ttrss_user_entries.ref_id = ttrss_entries.id AND
2549 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2551 $count = db_fetch_result($tmp_result, 0, "count");
2553 if (!$smart_mode ||
$old_counters[$id] != $count) {
2554 $old_counters[$id] = $count;
2555 $lctrs_modified = true;
2557 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2559 $ret_arr[$id]["counter"] = $count;
2560 $ret_arr[$id]["description"] = $label_name;
2564 error_reporting (DEFAULT_ERROR_LEVEL
);
2567 if ($smart_mode && $lctrs_modified) {
2568 $_SESSION["lctr_last_value"] = $old_counters;
2574 /* function getFeedCounter($link, $id) {
2576 $result = db_query($link, "SELECT
2577 count(id) as count,last_error
2578 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2579 WHERE feed_id = '$id' AND unread = true
2580 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2581 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2583 $count = db_fetch_result($result, 0, "count");
2584 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2586 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2589 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2591 $age_qpart = getMaxAgeSubquery();
2594 if (!$_SESSION["fctr_last_value"]) {
2595 $_SESSION["fctr_last_value"] = array();
2599 $old_counters = $_SESSION["fctr_last_value"];
2601 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2602 SUBSTRING(last_updated,1,19) AS last_updated,
2604 FROM ttrss_entries,ttrss_user_entries
2605 WHERE feed_id = ttrss_feeds.id AND
2606 ttrss_user_entries.ref_id = ttrss_entries.id
2607 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2608 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2609 AND parent_feed IS NULL"); */
2611 $query = "SELECT ttrss_feeds.id,
2613 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2615 COUNT(ttrss_entries.id) AS count
2617 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2618 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2619 AND ttrss_user_entries.unread = true)
2620 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2622 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2623 AND parent_feed IS NULL
2624 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2626 $result = db_query($link, $query);
2627 $fctrs_modified = false;
2629 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2631 while ($line = db_fetch_assoc($result)) {
2634 $count = $line["count"];
2635 $last_error = htmlspecialchars($line["last_error"]);
2637 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2638 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2640 $last_updated = date($short_date, strtotime($line["last_updated"]));
2643 $last_updated = htmlspecialchars($last_updated);
2645 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2647 $tmp_result = db_query($link,
2648 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2649 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2650 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2651 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2652 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2654 if (db_num_rows($tmp_result) > 0) {
2655 while ($l = db_fetch_assoc($tmp_result)) {
2656 $count +
= $l["unread"];
2660 if (!$smart_mode ||
$old_counters[$id] != $count) {
2661 $old_counters[$id] = $count;
2662 $fctrs_modified = true;
2665 $error_part = "error=\"$last_error\"";
2671 $has_img_part = "hi=\"$has_img\"";
2676 if ($active_feed && $id == $active_feed) {
2677 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2679 $has_title_part = "";
2682 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2686 if ($smart_mode && $fctrs_modified) {
2687 $_SESSION["fctr_last_value"] = $old_counters;
2691 function get_script_dt_add() {
2692 if (strpos(VERSION
, ".99") === false) {
2699 function get_pgsql_version($link) {
2700 $result = db_query($link, "SELECT version() AS version");
2701 $version = split(" ", db_fetch_result($result, 0, "version"));
2705 function print_error_xml($code, $add_msg = "") {
2708 $error_msg = $ERRORS[$code];
2711 $error_msg = "$error_msg; $add_msg";
2714 print "<rpc-reply>";
2715 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2716 print "</rpc-reply>";
2719 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2720 $auth_login = '', $auth_pass = '') {
2722 # check for feed:http://url
2723 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2725 # check for feed://URL
2726 if (strpos($feed_link, "//") === 0) {
2727 $feed_link = "http:$feed_link";
2730 if ($feed_link == "") return;
2732 if ($cat_id == "0" ||
!$cat_id) {
2733 $cat_qpart = "NULL";
2735 $cat_qpart = "'$cat_id'";
2738 $result = db_query($link,
2739 "SELECT id FROM ttrss_feeds
2740 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2742 if (db_num_rows($result) == 0) {
2744 $result = db_query($link,
2745 "INSERT INTO ttrss_feeds
2746 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2747 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2748 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2750 $result = db_query($link,
2751 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2752 AND owner_uid = " . $_SESSION["uid"]);
2754 $feed_id = db_fetch_result($result, 0, "id");
2757 update_rss_feed($link, $feed_link, $feed_id, true);
2766 function print_feed_select($link, $id, $default_id = "",
2767 $attributes = "", $include_all_feeds = true) {
2769 print "<select id=\"$id\" name=\"$id\" $attributes>";
2770 if ($include_all_feeds) {
2771 print "<option value=\"0\">".__('All feeds')."</option>";
2774 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2775 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2777 if (db_num_rows($result) > 0 && $include_all_feeds) {
2778 print "<option disabled>--------</option>";
2781 while ($line = db_fetch_assoc($result)) {
2782 if ($line["id"] == $default_id) {
2783 $is_selected = "selected";
2787 printf("<option $is_selected value='%d'>%s</option>",
2788 $line["id"], htmlspecialchars($line["title"]));
2794 function print_feed_cat_select($link, $id, $default_id = "",
2795 $attributes = "", $include_all_cats = true) {
2797 print "<select id=\"$id\" name=\"$id\" $attributes>";
2799 if ($include_all_cats) {
2800 print "<option value=\"0\">".__('Uncategorized')."</option>";
2803 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2804 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2806 if (db_num_rows($result) > 0 && $include_all_cats) {
2807 print "<option disabled>--------</option>";
2810 while ($line = db_fetch_assoc($result)) {
2811 if ($line["id"] == $default_id) {
2812 $is_selected = "selected";
2816 printf("<option $is_selected value='%d'>%s</option>",
2817 $line["id"], htmlspecialchars($line["title"]));
2823 function checkbox_to_sql_bool($val) {
2824 return ($val == "on") ?
"true" : "false";
2827 function getFeedCatTitle($link, $id) {
2829 return __("Special");
2830 } else if ($id < -10) {
2831 return __("Labels");
2832 } else if ($id > 0) {
2833 $result = db_query($link, "SELECT ttrss_feed_categories.title
2834 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2835 cat_id = ttrss_feed_categories.id");
2836 if (db_num_rows($result) == 1) {
2837 return db_fetch_result($result, 0, "title");
2839 return __("Uncategorized");
2842 return "getFeedCatTitle($id) failed";
2847 function getFeedTitle($link, $id) {
2849 return __("Starred articles");
2850 } else if ($id == -2) {
2851 return __("Published articles");
2852 } else if ($id == -3) {
2853 return __("Fresh articles");
2854 } else if ($id < -10) {
2855 $label_id = -10 - $id;
2856 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2857 if (db_num_rows($result) == 1) {
2858 return db_fetch_result($result, 0, "description");
2860 return "Unknown label ($label_id)";
2863 } else if ($id > 0) {
2864 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2865 if (db_num_rows($result) == 1) {
2866 return db_fetch_result($result, 0, "title");
2868 return "Unknown feed ($id)";
2871 return "getFeedTitle($id) failed";
2876 function get_session_cookie_name() {
2877 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2880 function print_init_params($link) {
2881 print "<init-params>";
2882 if ($_SESSION["stored-params"]) {
2883 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2885 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2886 print "<param key=\"$key\" value=\"$value\"/>";
2891 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2892 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2893 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2894 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2896 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2897 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2899 print "<param key=\"hide_read_feeds\" value=\"" .
2900 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2902 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2903 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2905 print "<param key=\"confirm_feed_catchup\" value=\"" .
2906 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2908 print "<param key=\"cdm_auto_catchup\" value=\"" .
2909 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2911 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2913 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2915 print "<param key=\"default_view_mode\" value=\"" .
2916 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2918 print "<param key=\"default_view_limit\" value=\"" .
2919 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2921 print "<param key=\"prefs_active_tab\" value=\"" .
2922 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2924 print "<param key=\"infobox_disable_overlay\" value=\"" .
2925 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2927 print "<param key=\"icons_location\" value=\"" .
2930 print "<param key=\"hide_read_shows_special\" value=\"" .
2931 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2933 print "<param key=\"hide_feedlist\" value=\"" .
2934 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
2936 print "</init-params>";
2939 function print_runtime_info($link) {
2940 print "<runtime-info>";
2942 if (ENABLE_UPDATE_DAEMON
) {
2943 print "<param key=\"daemon_is_running\" value=\"".
2944 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2946 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2948 $stamp = (int)read_stampfile("update_daemon.stamp");
2950 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2953 $stamp_delta = time() - $stamp;
2955 if ($stamp_delta > 1800) {
2959 $_SESSION["daemon_stamp_check"] = time();
2962 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2964 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2966 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2971 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2973 if ($_SESSION["last_version_check"] +
7200 < time()) {
2974 $new_version_details = check_for_update($link);
2976 print "<param key=\"new_version_available\" value=\"".
2977 sprintf("%d", $new_version_details != ""). "\"/>";
2979 $_SESSION["last_version_check"] = time();
2983 // print "<param key=\"new_version_available\" value=\"1\"/>";
2985 print "</runtime-info>";
2988 function getSearchSql($search, $match_on) {
2990 $search_query_part = "";
2992 $keywords = split(" ", $search);
2993 $query_keywords = array();
2995 if ($match_on == "both") {
2997 foreach ($keywords as $k) {
2998 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2999 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3002 $search_query_part = implode("AND", $query_keywords) . " AND ";
3004 } else if ($match_on == "title") {
3006 foreach ($keywords as $k) {
3007 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3010 $search_query_part = implode("AND", $query_keywords) . " AND ";
3012 } else if ($match_on == "content") {
3014 foreach ($keywords as $k) {
3015 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3019 $search_query_part = implode("AND", $query_keywords);
3021 return $search_query_part;
3024 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3026 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3030 $search_query_part = getSearchSql($search, $match_on);
3031 $search_query_part .= " AND ";
3034 $search_query_part = "";
3037 $view_query_part = "";
3039 if ($view_mode == "adaptive") {
3041 $view_query_part = " ";
3042 } else if ($feed != -1) {
3043 $unread = getFeedUnread($link, $feed, $cat_view);
3045 $view_query_part = " unread = true AND ";
3050 if ($view_mode == "marked") {
3051 $view_query_part = " marked = true AND ";
3054 if ($view_mode == "unread") {
3055 $view_query_part = " unread = true AND ";
3059 $limit_query_part = "LIMIT " . $limit;
3062 $vfeed_query_part = "";
3064 // override query strategy and enable feed display when searching globally
3065 if ($search && $search_mode == "all_feeds") {
3066 $query_strategy_part = "ttrss_entries.id > 0";
3067 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3068 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3069 $query_strategy_part = "ttrss_entries.id > 0";
3070 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3071 id = feed_id) as feed_title,";
3072 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3074 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3076 $tmp_result = false;
3079 $tmp_result = db_query($link, "SELECT id
3080 FROM ttrss_feeds WHERE cat_id = '$feed'");
3082 $tmp_result = db_query($link, "SELECT id
3083 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3084 WHERE id = '$feed') AND id != '$feed'");
3087 $cat_siblings = array();
3089 if (db_num_rows($tmp_result) > 0) {
3090 while ($p = db_fetch_assoc($tmp_result)) {
3091 array_push($cat_siblings, "feed_id = " . $p["id"]);
3094 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3095 $feed, implode(" OR ", $cat_siblings));
3098 $query_strategy_part = "ttrss_entries.id > 0";
3101 } else if ($feed >= 0) {
3106 $query_strategy_part = "cat_id = '$feed'";
3108 $query_strategy_part = "cat_id IS NULL";
3111 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3114 $tmp_result = db_query($link, "SELECT id
3115 FROM ttrss_feeds WHERE parent_feed = '$feed'
3116 ORDER BY cat_id,title");
3118 $parent_ids = array();
3120 if (db_num_rows($tmp_result) > 0) {
3121 while ($p = db_fetch_assoc($tmp_result)) {
3122 array_push($parent_ids, "feed_id = " . $p["id"]);
3125 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3126 $feed, implode(" OR ", $parent_ids));
3128 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3130 $query_strategy_part = "feed_id = '$feed'";
3133 } else if ($feed == -1) { // starred virtual feed
3134 $query_strategy_part = "marked = true";
3135 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3136 } else if ($feed == -2) { // published virtual feed
3137 $query_strategy_part = "published = true";
3138 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3139 } else if ($feed == -3) { // fresh virtual feed
3140 $query_strategy_part = "unread = true";
3142 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3144 if (DB_TYPE
== "pgsql") {
3145 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
3147 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3150 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3151 } else if ($feed <= -10) { // labels
3152 $label_id = -$feed - 11;
3154 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3155 WHERE id = '$label_id'");
3157 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
3159 if (!$query_strategy_part) {
3163 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3165 $query_strategy_part = "id > 0"; // dumb
3168 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3169 $order_by = "updated";
3171 $order_by = "updated DESC";
3174 if ($override_order) {
3175 $order_by = $override_order;
3180 if ($search && $search_mode == "all_feeds") {
3181 $feed_title = __("Search results")." ($search)";
3182 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3183 $feed_title = __("Search results")." ($search, $feed)";
3184 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3185 $feed_title = $feed;
3186 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3191 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3192 WHERE id = '$feed' AND owner_uid = $owner_uid");
3193 $feed_title = db_fetch_result($result, 0, "title");
3195 $feed_title = __("Uncategorized");
3199 $feed_title = __("Searched for")." $search ($feed_title)";
3204 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3205 WHERE id = '$feed' AND owner_uid = $owner_uid");
3207 $feed_title = db_fetch_result($result, 0, "title");
3208 $feed_site_url = db_fetch_result($result, 0, "site_url");
3209 $last_error = db_fetch_result($result, 0, "last_error");
3212 $feed_title = __("Searched for") . " $search ($feed_title)";
3216 } else if ($feed == -1) {
3217 $feed_title = __("Starred articles");
3218 } else if ($feed == -2) {
3219 $feed_title = __("Published articles");
3220 } else if ($feed == -3) {
3221 $feed_title = __("Fresh articles");
3222 } else if ($feed < -10) {
3223 $label_id = -$feed - 11;
3224 $result = db_query($link, "SELECT description FROM ttrss_labels
3225 WHERE id = '$label_id'");
3226 $feed_title = db_fetch_result($result, 0, "description");
3229 $feed_title = __("Searched for") . " $search ($feed_title)";
3235 if ($feed < -10) error_reporting (0);
3237 $content_query_part = "content as content_preview,";
3239 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3242 $feed_kind = "Feeds";
3244 $feed_kind = "Labels";
3247 if ($limit_query_part) {
3248 $offset_query_part = "OFFSET $offset";
3253 ttrss_entries.id,ttrss_entries.title,
3255 unread,feed_id,marked,published,link,last_read,
3256 SUBSTRING(last_read,1,19) as last_read_noms,
3259 SUBSTRING(updated,1,19) as updated_noms,
3262 ttrss_entries,ttrss_user_entries,ttrss_feeds
3264 ttrss_feeds.hidden = false AND
3265 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3266 ttrss_user_entries.ref_id = ttrss_entries.id AND
3267 ttrss_user_entries.owner_uid = '$owner_uid' AND
3270 $query_strategy_part ORDER BY $order_by
3271 $limit_query_part $offset_query_part";
3273 $result = db_query($link, $query);
3275 if ($_GET["debug"]) print $query;
3280 $feed_kind = "Tags";
3282 $result = db_query($link, "SELECT
3284 ttrss_entries.id as id,title,
3287 marked,link,last_read,
3288 SUBSTRING(last_read,1,19) as last_read_noms,
3291 SUBSTRING(updated,1,19) as updated_noms
3293 ttrss_entries,ttrss_user_entries,ttrss_tags
3295 ref_id = ttrss_entries.id AND
3296 ttrss_user_entries.owner_uid = '$owner_uid' AND
3297 post_int_id = int_id AND tag_name = '$feed' AND
3300 $query_strategy_part ORDER BY $order_by
3301 $limit_query_part");
3304 return array($result, $feed_title, $feed_site_url, $last_error);
3308 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3309 $search, $search_mode, $match_on) {
3311 $qfh_ret = queryFeedHeadlines($link, $feed,
3312 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3315 $result = $qfh_ret[0];
3316 $feed_title = htmlspecialchars($qfh_ret[1]);
3317 $feed_site_url = $qfh_ret[2];
3318 $last_error = $qfh_ret[3];
3320 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3322 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3323 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3324 <rss version=\"2.0\">
3326 <title>$feed_title</title>
3327 <link>$feed_site_url</link>
3328 <description>Feed generated by Tiny Tiny RSS</description>";
3330 while ($line = db_fetch_assoc($result)) {
3332 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3333 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3335 $tags = get_article_tags($link, $line["id"], $owner_uid);
3337 foreach ($tags as $tag) {
3338 print "<category>" . htmlspecialchars($tag) . "</category>";
3341 $rfc822_date = date('r', strtotime($line["updated"]));
3343 print "<pubDate>$rfc822_date</pubDate>";
3346 htmlspecialchars($line["title"]) . "</title>";
3348 print "<description><![CDATA[" .
3349 $line["content_preview"] . "]]></description>";
3354 print "</channel></rss>";
3358 function getCategoryTitle($link, $cat_id) {
3360 if ($cat_id == -1) {
3361 return __("Special");
3362 } else if ($cat_id == -2) {
3363 return __("Labels");
3366 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3369 if (db_num_rows($result) == 1) {
3370 return db_fetch_result($result, 0, "title");
3372 return "Uncategorized";
3377 // http://ru2.php.net/strip-tags
3379 function strip_tags_long($textstring, $allowed){
3380 while($textstring != strip_tags($textstring, $allowed))
3382 while (strlen($textstring) != 0)
3384 if (strlen($textstring) > 1024) {
3387 $otherlen = strlen($textstring);
3389 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3390 $safetext .= $temptext;
3391 $textstring = substr_replace($textstring,'',0,$otherlen);
3393 $textstring = $safetext;
3399 function sanitize_rss($link, $str, $force_strip_tags = false) {
3402 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3404 $res = strip_tags_long($res,
3405 "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
3407 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3408 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3415 * Send by mail a digest of last articles.
3417 * @param mixed $link The database connection.
3418 * @param integer $limit The maximum number of articles by digest.
3419 * @return boolean Return false if digests are not enabled.
3421 function send_headlines_digests($link, $limit = 100) {
3423 if (!DIGEST_ENABLE
) return false;
3425 $user_limit = DIGEST_EMAIL_LIMIT
;
3428 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3430 if (DB_TYPE
== "pgsql") {
3431 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3432 } else if (DB_TYPE
== "mysql") {
3433 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3436 $result = db_query($link, "SELECT id,email FROM ttrss_users
3437 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3439 while ($line = db_fetch_assoc($result)) {
3441 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3442 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3444 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3446 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3447 $digest = $tuple[0];
3448 $headlines_count = $tuple[1];
3449 $affected_ids = $tuple[2];
3450 $digest_text = $tuple[3];
3452 if ($headlines_count > 0) {
3454 $mail = new PHPMailer();
3456 $mail->PluginDir
= "phpmailer/";
3457 $mail->SetLanguage("en", "phpmailer/language/");
3459 $mail->CharSet
= "UTF-8";
3461 $mail->From
= DIGEST_FROM_ADDRESS
;
3462 $mail->FromName
= DIGEST_FROM_NAME
;
3463 $mail->AddAddress($line["email"], $line["login"]);
3465 if (DIGEST_SMTP_HOST
) {
3466 $mail->Host
= DIGEST_SMTP_HOST
;
3467 $mail->Mailer
= "smtp";
3468 $mail->Username
= DIGEST_SMTP_LOGIN
;
3469 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3472 $mail->IsHTML(true);
3473 $mail->Subject
= DIGEST_SUBJECT
;
3474 $mail->Body
= $digest;
3475 $mail->AltBody
= $digest_text;
3477 $rc = $mail->Send();
3479 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3483 if ($rc && $do_catchup) {
3484 print "Marking affected articles as read...\n";
3485 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3488 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3489 WHERE id = " . $line["id"]);
3491 print "No headlines\n";
3496 print "All done.\n";
3500 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3502 require_once "MiniTemplator.class.php";
3504 $tpl = new MiniTemplator
;
3505 $tpl_t = new MiniTemplator
;
3507 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3508 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3510 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3511 $tpl->setVariable('CUR_TIME', date('G:i'));
3513 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3514 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3516 $affected_ids = array();
3518 if (DB_TYPE
== "pgsql") {
3519 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3520 } else if (DB_TYPE
== "mysql") {
3521 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3524 $result = db_query($link, "SELECT ttrss_entries.title,
3525 ttrss_feeds.title AS feed_title,
3527 ttrss_user_entries.ref_id,
3529 SUBSTRING(content, 1, 120) AS excerpt,
3530 SUBSTRING(last_updated,1,19) AS last_updated
3532 ttrss_user_entries,ttrss_entries,ttrss_feeds
3534 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3535 AND include_in_digest = true
3538 AND ttrss_user_entries.owner_uid = $user_id
3540 ORDER BY ttrss_feeds.title, date_entered DESC
3543 $cur_feed_title = "";
3545 $headlines_count = db_num_rows($result);
3547 $headlines = array();
3549 while ($line = db_fetch_assoc($result)) {
3550 array_push($headlines, $line);
3553 for ($i = 0; $i < sizeof($headlines); $i++
) {
3555 $line = $headlines[$i];
3557 array_push($affected_ids, $line["ref_id"]);
3559 $updated = smart_date_time(strtotime($line["last_updated"]));
3561 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3562 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3563 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3564 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3565 $tpl->setVariable('ARTICLE_EXCERPT',
3566 truncate_string(strip_tags($line["excerpt"]), 100));
3568 $tpl->addBlock('article');
3570 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3571 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3572 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3573 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3574 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3575 // truncate_string(strip_tags($line["excerpt"]), 100));
3577 $tpl_t->addBlock('article');
3579 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3580 $tpl->addBlock('feed');
3581 $tpl_t->addBlock('feed');
3586 $tpl->addBlock('digest');
3587 $tpl->generateOutputToString($tmp);
3589 $tpl_t->addBlock('digest');
3590 $tpl_t->generateOutputToString($tmp_t);
3592 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3595 function check_for_update($link, $brief_fmt = true) {
3596 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3598 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3603 if (ENABLE_SIMPLEPIE
) {
3604 $rss = new SimplePie();
3605 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3606 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3607 $rss->set_feed_url($fetch_url);
3608 $rss->set_output_encoding('UTF-8');
3611 $rss = fetch_rss($releases_feed);
3613 error_reporting (DEFAULT_ERROR_LEVEL
);
3617 if (ENABLE_SIMPLEPIE
) {
3618 $items = $rss->get_items();
3620 $items = $rss->items
;
3622 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3623 if (!$items ||
!is_array($items)) $items = $rss;
3626 if (!is_array($items) ||
count($items) == 0) {
3630 $latest_item = $items[0];
3632 if (ENABLE_SIMPLEPIE
) {
3633 $last_title = $latest_item->get_title();
3635 $last_title = $latest_item["title"];
3638 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3640 if (ENABLE_SIMPLEPIE
) {
3641 $release_url = sanitize_rss($link, $latest_item->get_link());
3642 $content = sanitize_rss($link, $latest_item->get_description());
3644 $release_url = sanitize_rss($link, $latest_item["link"]);
3645 $content = sanitize_rss($link, $latest_item["description"]);
3648 if (version_compare(VERSION
, $latest_version) == -1) {
3650 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3651 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3652 <div id=\"milestoneDetails\">$content</div>");
3654 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3655 <div class='milestoneDetails'>$content</div>
3656 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3657 download and update information.";
3664 function markArticlesById($link, $ids, $cmode) {
3668 foreach ($ids as $id) {
3669 array_push($tmp_ids, "ref_id = '$id'");
3672 $ids_qpart = join(" OR ", $tmp_ids);
3675 db_query($link, "UPDATE ttrss_user_entries SET
3676 marked = false,last_read = NOW()
3677 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3678 } else if ($cmode == 1) {
3679 db_query($link, "UPDATE ttrss_user_entries SET
3681 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3683 db_query($link, "UPDATE ttrss_user_entries SET
3684 marked = NOT marked,last_read = NOW()
3685 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3689 function publishArticlesById($link, $ids, $cmode) {
3693 foreach ($ids as $id) {
3694 array_push($tmp_ids, "ref_id = '$id'");
3697 $ids_qpart = join(" OR ", $tmp_ids);
3700 db_query($link, "UPDATE ttrss_user_entries SET
3701 published = false,last_read = NOW()
3702 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3703 } else if ($cmode == 1) {
3704 db_query($link, "UPDATE ttrss_user_entries SET
3706 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3708 db_query($link, "UPDATE ttrss_user_entries SET
3709 published = NOT published,last_read = NOW()
3710 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3714 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3716 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3720 foreach ($ids as $id) {
3721 array_push($tmp_ids, "ref_id = '$id'");
3724 $ids_qpart = join(" OR ", $tmp_ids);
3727 db_query($link, "UPDATE ttrss_user_entries SET
3728 unread = false,last_read = NOW()
3729 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3730 } else if ($cmode == 1) {
3731 db_query($link, "UPDATE ttrss_user_entries SET
3733 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3735 db_query($link, "UPDATE ttrss_user_entries SET
3736 unread = NOT unread,last_read = NOW()
3737 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3741 function catchupArticleById($link, $id, $cmode) {
3744 db_query($link, "UPDATE ttrss_user_entries SET
3745 unread = false,last_read = NOW()
3746 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3747 } else if ($cmode == 1) {
3748 db_query($link, "UPDATE ttrss_user_entries SET
3750 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3752 db_query($link, "UPDATE ttrss_user_entries SET
3753 unread = NOT unread,last_read = NOW()
3754 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3758 function make_guid_from_title($title) {
3759 return preg_replace("/[ \"\',.:;]/", "-",
3760 mb_strtolower(strip_tags($title), 'utf-8'));
3763 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3764 $bottom = false, $rtl_content = false, $feed_id = 0,
3765 $is_cat = false, $search = false, $match_on = false,
3766 $search_mode = false, $offset = 0, $limit = 0,
3767 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3769 $user_page_offset = $offset +
1;
3772 $class = "headlinesSubToolbar";
3773 $tid = "headlineActionsTop";
3775 $class = "headlinesSubToolbar";
3776 $tid = "headlineActionsBottom";
3779 print "<table class=\"$class\" id=\"$tid\"
3780 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3788 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3789 $page_next_link = "javascript:viewFeedGoPage(1)";
3790 $page_first_link = "javascript:viewFeedGoPage(0)";
3792 $catchup_page_link = "javascript:catchupPage()";
3793 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3794 $catchup_sel_link = "javascript:catchupSelection()";
3796 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3798 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3799 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3800 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3802 $tog_unread_link = "javascript:selectionToggleUnread()";
3803 $tog_marked_link = "javascript:selectionToggleMarked()";
3804 $tog_published_link = "javascript:selectionTogglePublished()";
3808 $sel_all_link = "javascript:cdmSelectArticles('all')";
3809 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3810 $sel_none_link = "javascript:cdmSelectArticles('none')";
3812 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3813 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3814 $tog_published_link = "javascript:selectionTogglePublished(true)";
3818 if (!$dashboard_menu) {
3820 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3822 print "<td class=\"headlineActions$rtl_cpart\">
3823 <ul class=\"headlineDropdownMenu\">
3826 <a href=\"$sel_all_link\">".__('All')."</a>,
3827 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3828 <a href=\"$sel_none_link\">".__('None')."</a></li>
3829 <li class=\"vsep\"> </li>
3830 <li class=\"top\">".__('Toggle')."<ul>
3831 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3832 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3833 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3835 <li class=\"vsep\"> </li>
3836 <li class=\"top\">".__('Mark as read')."<ul>
3837 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3838 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->";
3840 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3843 <li><span class=\"insensitive\">--------</span></li>
3844 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3845 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3846 <li><span class=\"insensitive\">--------</span></li>";
3850 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3853 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3855 if ($limit != 0 && !$search && $enable_pagination) {
3857 <li class=\"vsep\"> </li>
3858 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3859 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3860 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3864 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3866 <li class=\"vsep\"> </li>
3868 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3869 '$match_on', '$feed_id', '$is_cat');\">
3870 ".__('Convert to label')."</a></td>";
3876 // old style subtoolbar:
3878 print "<td class=\"headlineActions$rtl_cpart\">".
3880 <a href=\"$sel_all_link\">".__('All')."</a>,
3881 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3882 <a href=\"$sel_none_link\">".__('None')."</a>
3884 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3885 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3887 __('Mark as read:')."
3888 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3889 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3891 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3894 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3895 '$match_on', '$feed_id', '$is_cat');\">
3896 ".__('Convert to label')."</a>";
3902 } else { // dashboard menu actions
3904 print "<td class=\"headlineActions$rtl_cpart\">
3905 <ul class=\"headlineDropdownMenu\">
3907 <a href=\"#\" onclick=\"return displayDlg('quickAddFeed');\">".
3908 __('Subscribe to feed')."</a>
3910 <li class=\"vsep\"> </li>
3911 <li class=\"top\">".__('Placeholder')."<ul>
3912 <li onclick=\"\">".__('Placeholder')."</li>
3913 <li onclick=\"\">".__('Placeholder')."</li>
3914 <li onclick=\"\">".__('Placeholder')."</li>
3916 <li class=\"vsep\"> </li>
3917 <li class=\"top\">".__('Show')."<ul>
3918 <li onclick=\"\">".__('Update errors')."</li>
3925 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3926 print "<td class=\"headlineActions$rtl_cpart\">
3927 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3928 '$match_on', '$feed_id', '$is_cat');\">
3929 ".__('Convert to Label')."</a></td>";
3932 print "<td class=\"headlineTitle$rtl_cpart\">";
3934 print "<span class=\"headlineInnerTitle\">";
3936 if ($feed_site_url) {
3938 $target = "target=\"_new\"";
3940 print "<a $target href=\"$feed_site_url\">".
3941 truncate_string($feed_title,30)."</a>";
3947 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3950 if ($user_page_offset > 1) {
3951 print " [$user_page_offset] ";
3956 if (!$bottom && !$disable_feed) {
3959 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3960 <img class=\"noborder\"
3961 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3963 } else if ($feed_small_icon) {
3964 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
3968 print "</tr></table>";
3972 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3974 $tmp_category = getCategoryTitle($link, $cat_id);
3975 $cat_unread = getCategoryUnread($link, $cat_id);
3978 $holder_style = "display:none;";
3985 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3987 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3988 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3991 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3993 print "<span id=\"FCAP-$cat_id\">";
3996 print " <span id=\"FCATCTR-$cat_id\"
3997 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4007 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4010 function outputFeedList($link, $tags = false) {
4012 print "<ul class=\"feedList\" id=\"feedList\">";
4014 $owner_uid = $_SESSION["uid"];
4018 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4020 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4023 $cat_hidden = false;
4026 # print "<li class=\"feedCat\">".__('Special')."</li>";
4027 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
4028 # print "<li class=\"feedCat\">".
4029 # "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
4030 # __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
4032 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
4033 # <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
4035 # $cat_unread = getCategoryUnread($link, -1);
4036 # $tmp_category = __("Special");
4037 # $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4039 printCategoryHeader($link, -1, $cat_hidden, false);
4042 if (defined('_ENABLE_DASHBOARD')) {
4043 printFeedEntry(-4, "virt", __("Dashboard"), 0,
4044 "images/tag.png", $link);
4047 $num_starred = getFeedUnread($link, -1);
4048 $num_published = getFeedUnread($link, -2);
4049 $num_fresh = getFeedUnread($link, -3);
4053 if ($num_fresh > 0) $class .= "Unread";
4055 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4056 "images/fresh.png", $link);
4060 if ($num_starred > 0) $class .= "Unread";
4062 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4065 $mark_img_ext = "gif";
4067 $mark_img_ext = "png";
4070 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4071 "images/mark_set.$mark_img_ext", $link);
4075 if ($num_published > 0) $class .= "Unread";
4077 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4078 "images/pub_set.gif", $link);
4080 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4086 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4088 $result = db_query($link, "SELECT id,sql_exp,description FROM
4089 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4091 if (db_num_rows($result) > 0) {
4092 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4094 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4097 $cat_hidden = false;
4100 printCategoryHeader($link, -2, $cat_hidden, false);
4102 # print "<li class=\"feedCat\">".
4103 # "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
4104 # __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
4106 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
4108 print "<li><hr></li>";
4112 while ($line = db_fetch_assoc($result)) {
4114 error_reporting (0);
4116 $label_id = -$line['id'] - 11;
4117 $count = getFeedUnread($link, $label_id);
4125 error_reporting (DEFAULT_ERROR_LEVEL
);
4127 printFeedEntry($label_id,
4128 $class, $line["description"],
4129 $count, "images/label.png", $link);
4133 if (db_num_rows($result) > 0) {
4134 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4141 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4142 print "<li><hr></li>";
4145 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4146 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4147 $order_by_qpart = "category,unread DESC,title";
4149 $order_by_qpart = "category,title";
4152 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4153 $order_by_qpart = "unread DESC,title";
4155 $order_by_qpart = "title";
4159 $age_qpart = getMaxAgeSubquery();
4161 $result = db_query($link, "SELECT ttrss_feeds.*,
4162 SUBSTRING(last_updated,1,19) AS last_updated_noms,
4163 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4164 WHERE feed_id = ttrss_feeds.id AND unread = true
4166 AND ttrss_user_entries.ref_id = ttrss_entries.id
4167 AND owner_uid = '$owner_uid') as unread,
4169 ttrss_feed_categories.title AS category,
4170 ttrss_feed_categories.collapsed
4171 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4172 ON (ttrss_feed_categories.id = cat_id)
4174 ttrss_feeds.hidden = false AND
4175 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4176 ORDER BY $order_by_qpart");
4178 $actid = $_GET["actid"];
4188 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4190 while ($line = db_fetch_assoc($result)) {
4192 $feed = trim($line["title"]);
4194 if (!$feed) $feed = "[Untitled]";
4196 $feed_id = $line["id"];
4198 $subop = $_GET["subop"];
4200 $unread = $line["unread"];
4202 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4203 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4205 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4208 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4211 $rtl_tag = "dir=\"RTL\"";
4216 $tmp_result = db_query($link,
4217 "SELECT id,COUNT(unread) AS unread
4218 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
4219 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
4220 WHERE parent_feed = '$feed_id' AND unread = true
4221 GROUP BY ttrss_feeds.id");
4223 if (db_num_rows($tmp_result) > 0) {
4224 while ($l = db_fetch_assoc($tmp_result)) {
4225 $unread +
= $l["unread"];
4229 $cat_id = $line["cat_id"];
4231 $tmp_category = $line["category"];
4233 if (!$tmp_category) {
4234 $tmp_category = __("Uncategorized");
4237 // $class = ($lnum % 2) ? "even" : "odd";
4239 if ($line["last_error"]) {
4245 if ($unread > 0) $class .= "Unread";
4247 if ($actid == $feed_id) {
4248 $class .= "Selected";
4251 $total_unread +
= $unread;
4253 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4259 $category = $tmp_category;
4261 $collapsed = $line["collapsed"];
4263 // workaround for NULL category
4264 if ($category == __("Uncategorized")) {
4265 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4270 if ($collapsed == "t" ||
$collapsed == "1") {
4271 $holder_class = "feedCatHolder";
4272 $holder_style = "display:none;";
4275 $holder_class = "feedCatHolder";
4280 $cat_id = sprintf("%d", $cat_id);
4282 $cat_unread = getCategoryUnread($link, $cat_id);
4284 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4286 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
4287 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
4288 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
4289 <span id=\"FCATCTR-$cat_id\"
4290 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
4293 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4296 printFeedEntry($feed_id, $class, $feed, $unread,
4297 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4298 $last_updated, $line["last_error"]);
4303 if (db_num_rows($result) == 0) {
4304 print "<li>".__('No feeds to display.')."</li>";
4311 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4312 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4313 post_int_id = ttrss_user_entries.int_id AND
4314 unread = true AND ref_id = ttrss_entries.id
4315 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4317 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4318 ORDER BY tag_name"); */
4320 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4321 print "<li class=\"feedCat\">".__('Tags')."</li>";
4322 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4325 $age_qpart = getMaxAgeSubquery();
4327 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4328 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4329 AND ref_id = id AND $age_qpart
4330 AND unread = true)) AS count FROM ttrss_tags
4331 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4332 ORDER BY count DESC LIMIT 50");
4336 while ($line = db_fetch_assoc($result)) {
4337 $tags[$line["tag_name"]] +
= $line["count"];
4340 foreach (array_keys($tags) as $tag) {
4342 $unread = $tags[$tag];
4350 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4354 if (db_num_rows($result) == 0) {
4355 print "<li>No tags to display.</li>";
4358 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4368 function get_article_tags($link, $id, $owner_uid = 0) {
4370 $a_id = db_escape_string($id);
4372 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4374 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4375 owner_uid as owner FROM
4376 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4377 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4381 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4382 array_push($tags, $tmp_line["tag_name"]);
4388 function trim_value(&$value) {
4389 $value = trim($value);
4392 function trim_array($array) {
4394 array_walk($tmp, 'trim_value');
4398 function tag_is_valid($tag) {
4399 if ($tag == '') return false;
4400 if (preg_match("/^[0-9]*$/", $tag)) return false;
4402 $tag = iconv("utf-8", "utf-8", $tag);
4403 if (!$tag) return false;
4408 function render_login_form($link, $mobile = false) {
4410 require_once "login_form.php";
4412 require_once "mobile/login_form.php";
4416 // from http://developer.apple.com/internet/safari/faq.html
4417 function no_cache_incantation() {
4418 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4419 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4420 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4421 header("Cache-Control: post-check=0, pre-check=0", false);
4422 header("Pragma: no-cache"); // HTTP/1.0
4425 function format_warning($msg, $id = "") {
4426 return "<div class=\"warning\" id=\"$id\">
4427 <img src=\"images/sign_excl.gif\">$msg</div>";
4430 function format_notice($msg) {
4431 return "<div class=\"notice\">
4432 <img src=\"images/sign_info.gif\">$msg</div>";
4435 function format_error($msg) {
4436 return "<div class=\"error\">
4437 <img src=\"images/sign_excl.gif\">$msg</div>";
4440 function print_notice($msg) {
4441 return print format_notice($msg);
4444 function print_warning($msg) {
4445 return print format_warning($msg);
4448 function print_error($msg) {
4449 return print format_error($msg);
4453 function T_sprintf() {
4454 $args = func_get_args();
4455 return vsprintf(__(array_shift($args)), $args);
4458 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4460 /* we can figure out feed_id from article id anyway, why do we
4461 * pass feed_id here? */
4463 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4464 WHERE ref_id = '$id'");
4466 $feed_id = db_fetch_result($result, 0, "feed_id");
4468 print "<article id='$id'><![CDATA[";
4470 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4471 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4473 if (db_num_rows($result) == 1) {
4474 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4476 $rtl_content = false;
4480 $rtl_tag = "dir=\"RTL\"";
4487 if ($mark_as_read) {
4488 $result = db_query($link, "UPDATE ttrss_user_entries
4489 SET unread = false,last_read = NOW()
4490 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4493 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4494 SUBSTRING(updated,1,16) as updated,
4495 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4498 FROM ttrss_entries,ttrss_user_entries
4499 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4505 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4506 $link_target = "target=\"_new\"";
4509 $line = db_fetch_assoc($result);
4511 if ($line["icon_url"]) {
4512 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4514 $feed_icon = " ";
4517 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4518 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4520 $entry_comments = "";
4523 $num_comments = $line["num_comments"];
4524 $entry_comments = "";
4526 if ($num_comments > 0) {
4527 if ($line["comments"]) {
4528 $comments_url = $line["comments"];
4530 $comments_url = $line["link"];
4532 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4534 if ($line["comments"] && $line["link"] != $line["comments"]) {
4535 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4539 print "<div class=\"postReply\">";
4541 print "<div class=\"postHeader\">";
4543 $entry_author = $line["author"];
4545 if ($entry_author) {
4546 $entry_author = __(" - ") . $entry_author;
4549 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4550 strtotime($line["updated"]));
4552 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4554 if ($line["link"]) {
4555 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4556 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4558 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4561 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4562 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4563 ORDER BY tag_name"); */
4565 $tags = get_article_tags($link, $id);
4572 if ($_SESSION["theme"] == "3pane") {
4578 foreach ($tags as $tag) {
4580 $tag_escaped = str_replace("'", "\\'", $tag);
4582 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4584 if ($num_tags == $tag_limit) {
4585 $tags_str .= "…";
4587 } else if ($num_tags < $tag_limit) {
4588 $tags_str .= $tag_str;
4590 $f_tags_str .= $tag_str;
4593 $tags_str = preg_replace("/, $/", "", $tags_str);
4594 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4596 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4597 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4599 if (!$entry_comments) $entry_comments = " "; # placeholder
4601 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4603 print "<div style='float : right'>
4604 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4606 <a title=\"Edit tags for this article\"
4607 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4608 <div clear='both'>$entry_comments</div>";
4612 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4613 print "<div class=\"postContent\">";
4615 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4617 $line["content"] = sanitize_rss($link, $line["content"]);
4619 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4620 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4623 print $line["content"];
4625 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4626 post_id = '$id' AND content_url != ''");
4628 if (db_num_rows($result) > 0) {
4629 print "<div class=\"postEnclosures\">";
4631 if (db_num_rows($result) == 1) {
4632 print __("Attachment:") . " ";
4634 print __("Attachments:") . " ";
4639 while ($line = db_fetch_assoc($result)) {
4641 $url = $line["content_url"];
4642 $ctype = $line["content_type"];
4644 if (!$ctype) $ctype = __("unknown type");
4646 $filename = substr($url, strrpos($url, "/")+
1);
4648 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4649 $filename . " (" . $ctype . ")" . "</a>";
4651 array_push($entries, $entry);
4654 print join(", ", $entries);
4665 print "]]></article>";
4669 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4670 $next_unread_feed, $offset) {
4672 $disable_cache = false;
4674 $timing_info = getmicrotime();
4676 $topmost_article_ids = array();
4682 if ($subop == "undefined") $subop = "";
4684 if ($subop == "CatchupSelected") {
4685 $ids = split(",", db_escape_string($_GET["ids"]));
4686 $cmode = sprintf("%d", $_GET["cmode"]);
4688 catchupArticlesById($link, $ids, $cmode);
4691 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4692 update_generic_feed($link, $feed, $cat_view, true);
4695 if ($subop == "MarkAllRead") {
4696 catchup_feed($link, $feed, $cat_view);
4698 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4699 if ($next_unread_feed) {
4700 $feed = $next_unread_feed;
4706 $result = db_query($link,
4707 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4709 if (db_num_rows($result) == 0) {
4710 print "<div align='center'>".__('Feed not found.')."</div>";
4715 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4717 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4718 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4720 if (db_num_rows($result) == 1) {
4721 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4723 $rtl_content = false;
4727 $rtl_tag = "dir=\"RTL\"";
4733 $rtl_content = false;
4736 $script_dt_add = get_script_dt_add();
4738 /// START /////////////////////////////////////////////////////////////////////////////////
4740 $search = db_escape_string($_GET["query"]);
4743 $disable_cache = true;
4746 $search_mode = db_escape_string($_GET["search_mode"]);
4747 $match_on = db_escape_string($_GET["match_on"]);
4753 $real_offset = $offset * $limit;
4755 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4757 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4758 $search, $search_mode, $match_on, false, $real_offset);
4760 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4762 $result = $qfh_ret[0];
4763 $feed_title = $qfh_ret[1];
4764 $feed_site_url = $qfh_ret[2];
4765 $last_error = $qfh_ret[3];
4768 $feed_site_url = article_publish_url($link);
4771 /// STOP //////////////////////////////////////////////////////////////////////////////////
4774 print "<div id=\"headlinesContainer\" $rtl_tag>";
4777 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4781 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4782 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4785 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4788 $headlines_count = db_num_rows($result);
4790 if (db_num_rows($result) > 0) {
4792 # print "\{$offset}";
4794 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4795 print "<table class=\"headlinesList\" id=\"headlinesList\"
4796 cellspacing=\"0\">";
4799 $lnum = $limit*$offset;
4801 error_reporting (DEFAULT_ERROR_LEVEL
);
4805 while ($line = db_fetch_assoc($result)) {
4807 $class = ($lnum %
2) ?
"even" : "odd";
4810 $feed_id = $line["feed_id"];
4812 if (count($topmost_article_ids) < 5) {
4813 array_push($topmost_article_ids, $id);
4816 if ($line["last_read"] == "" &&
4817 ($line["unread"] != "t" && $line["unread"] != "1")) {
4819 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4822 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4826 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4834 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4837 $mark_img_ext = "gif";
4839 $mark_img_ext = "png";
4842 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4843 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4845 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4847 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4849 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4852 if ($line["published"] == "t" ||
$line["published"] == "1") {
4853 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4855 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4857 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4859 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4862 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4863 # $line["title"] . "</a>";
4865 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4866 $line["title"] . "</a>";
4868 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4869 # $line["title"] . "</a>";
4871 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4872 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4874 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4875 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4878 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4879 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4883 $entry_author = $line["author"];
4885 if ($entry_author) {
4886 $entry_author = " - $entry_author";
4889 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4891 print "<tr class='$class' id='RROW-$id'>";
4893 print "<td class='hlUpdPic'>$update_pic</td>";
4895 print "<td class='hlSelectRow'>
4896 <input type=\"checkbox\" onclick=\"tSR(this)\"
4900 print "<td class='hlMarkedPic'>$marked_pic</td>";
4901 print "<td class='hlMarkedPic'>$published_pic</td>";
4903 # if ($line["feed_title"]) {
4904 # print "<td class='hlContent'>$content_link</td>";
4905 # print "<td class='hlFeed'>
4906 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4907 # truncate_string($line["feed_title"],30)."</a> </td>";
4910 print "<td class='hlContent' valign='middle'>";
4912 print "<a href=\"javascript:view($id,$feed_id);\">" .
4915 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4916 if ($content_preview) {
4917 print "<span class=\"contentPreview\"> - $content_preview</span>";
4923 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4924 # $line["feed_title"]."</a>
4926 if ($line["feed_title"]) {
4927 print "<span class=\"hlFeed\">
4928 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4929 $line["feed_title"]."</a>)
4938 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
4945 $add_class = "Unread";
4950 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
4955 $cdm_cstyle = "style=\"display : none\"";
4958 print "<div class=\"cdmArticle$add_class\"
4959 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4960 onmouseout='cdmMouseOut(this)'>";
4962 print "<div class=\"cdmHeader\">";
4964 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4966 print "<a class=\"title\"
4967 onclick=\"javascript:toggleUnread($id, 0)\"
4968 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4970 print $entry_author;
4973 print " <a id=\"CICH-$id\"
4974 href=\"javascript:cdmExpandArticle($id)\">
4975 (".__('Show article').")</a>";
4979 if ($line["feed_title"]) {
4980 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4985 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4986 $line["content_preview"] = preg_replace("/href=/i",
4987 "target=\"_new\" href=", $line["content_preview"]);
4990 print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
4992 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
4994 print $line["content_preview"];
4996 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4997 post_id = '$id' AND content_url != ''");
4999 if (db_num_rows($e_result) > 0) {
5000 print "<div class=\"cdmEnclosures\">";
5002 if (db_num_rows($e_result) == 1) {
5003 print __("Attachment:") . " ";
5005 print __("Attachments:") . " ";
5010 while ($e_line = db_fetch_assoc($e_result)) {
5012 $url = $e_line["content_url"];
5013 $ctype = $e_line["content_type"];
5014 if (!$ctype) $ctype = __("unknown type");
5016 $filename = substr($url, strrpos($url, "/")+
1);
5018 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5019 $filename . " (" . $ctype . ")" . "</a>";
5021 array_push($entries, $entry);
5024 print join(", ", $entries);
5029 print "<br clear='both'>";
5032 /* if (!$expand_cdm) {
5033 print "<a id=\"CICH-$id\"
5034 href=\"javascript:cdmExpandArticle($id)\">
5040 print "<div class=\"cdmFooter\"><span class='s0'>";
5042 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5044 print __("Select:").
5045 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5046 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5048 print "</span><span class='s1'>$marked_pic</span> ";
5049 print "<span class='s1'>$published_pic</span> ";
5051 $tags = get_article_tags($link, $id);
5054 $full_tags_str = "";
5057 foreach ($tags as $tag) {
5059 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5060 if ($num_tags < 5) {
5061 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5062 } else if ($num_tags == 5) {
5063 $tags_str .= "…";
5067 $tags_str = preg_replace("/, $/", "", $tags_str);
5068 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5070 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5072 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5075 if ($tags_str == "") $tags_str = "no tags";
5077 // print "<img src='images/tag.png' class='markedPic'>";
5079 print "<span class='s1'>
5080 <img class='tagsPic' src='images/tag.png' alt='Tags'
5081 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5082 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5086 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5087 href=\"javascript:toggleUnread($id)\">
5098 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5102 // print_headline_subtoolbar($link,
5103 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5109 switch ($view_mode) {
5111 $message = __("No unread articles found to display.");
5114 $message = __("No starred articles found to display.");
5117 $message = __("No articles found to display.");
5120 if (!$offset) print "<div class='whiteBox'>$message</div>";
5128 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
5131 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5133 function printTagCloud($link) {
5135 /* get first ref_id to count from */
5141 if (DB_TYPE == "pgsql") {
5142 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5143 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5144 AND date_entered > NOW() - INTERVAL '30 days'";
5146 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5147 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5148 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5151 $result = db_query($link, $query);
5152 $first_id = db_fetch_result($result, 0, "id"); */
5154 //AND post_int_id >= '$first_id'
5155 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5156 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5157 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5159 $result = db_query($link, $query);
5163 while ($line = db_fetch_assoc($result)) {
5164 $tags[$line["tag_name"]] = $line["count"];
5169 $max_size = 32; // max font size in pixels
5170 $min_size = 11; // min font size in pixels
5172 // largest and smallest array values
5173 $max_qty = max(array_values($tags));
5174 $min_qty = min(array_values($tags));
5176 // find the range of values
5177 $spread = $max_qty - $min_qty;
5178 if ($spread == 0) { // we don't want to divide by zero
5182 // set the font-size increment
5183 $step = ($max_size - $min_size) / ($spread);
5185 // loop through the tag array
5186 foreach ($tags as $key => $value) {
5187 // calculate font-size
5188 // find the $value in excess of $min_qty
5189 // multiply by the font-size increment ($size)
5190 // and add the $min_size set above
5191 $size = round($min_size +
(($value - $min_qty) * $step));
5193 $key_escaped = str_replace("'", "\\'", $key);
5195 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5196 $size . "px\" title=\"$value articles tagged with " .
5197 $key . '">' . $key . '</a> ';
5201 function print_checkpoint($n, $s) {
5202 $ts = getmicrotime();
5203 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5207 function sanitize_tag($tag) {
5210 $tag = mb_strtolower($tag, 'utf-8');
5212 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5214 // $tag = str_replace('"', "", $tag);
5215 // $tag = str_replace("+", " ", $tag);
5216 $tag = str_replace("technorati tag: ", "", $tag);
5221 function generate_publish_key() {
5222 return sha1(uniqid(rand(), true));
5225 function article_publish_url($link) {
5227 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5229 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5235 * Purge a feed contents, marked articles excepted.
5237 * @param mixed $link The database connection.
5238 * @param integer $id The id of the feed to purge.
5241 function clear_feed_articles($link, $id) {
5242 $result = db_query($link, "DELETE FROM ttrss_user_entries
5243 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5245 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5246 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5247 } // function clear_feed_articles
5250 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5252 * @return string The Mozilla Firefox feed adding URL.
5254 function add_feed_url() {
5255 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5256 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5258 } // function add_feed_url
5261 * Encrypt a password in SHA1.
5263 * @param string $pass The password to encrypt.
5264 * @param string $login A optionnal login.
5265 * @return string The encrypted password.
5267 function encrypt_password($pass, $login = '') {
5269 return "SHA1X:" . sha1("$login:$pass");
5271 return "SHA1:" . sha1($pass);
5273 } // function encrypt_password
5276 * Update a feed batch.
5277 * Used by daemons to update n feeds by run.
5278 * Only update feed needing a update, and not being processed
5279 * by another process.
5281 * @param mixed $link Database link
5282 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5283 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5284 * @param boolean $debug Set to false to disable debug output. Default to true.
5287 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5288 // Process all other feeds using last_updated and interval parameters
5290 // Test if the user has loggued in recently. If not, it does not update its feeds.
5291 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5292 if (DB_TYPE
== "pgsql") {
5293 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5295 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5298 $login_thresh_qpart = "";
5301 // Test if the feed need a update (update interval exceded).
5302 if (DB_TYPE
== "pgsql") {
5303 $update_limit_qpart = "AND ((
5304 ttrss_feeds.update_interval = 0
5305 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5307 ttrss_feeds.update_interval > 0
5308 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5309 ) OR ttrss_feeds.last_updated IS NULL)";
5311 $update_limit_qpart = "AND ((
5312 ttrss_feeds.update_interval = 0
5313 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5315 ttrss_feeds.update_interval > 0
5316 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5317 ) OR ttrss_feeds.last_updated IS NULL)";
5320 // Test if feed is currently being updated by another process.
5321 if (DB_TYPE
== "pgsql") {
5322 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5324 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5327 // Test if there is a limit to number of updated feeds
5329 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5331 $random_qpart = sql_random_function();
5333 // We search for feed needing update.
5334 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5335 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
5336 ttrss_feeds.update_interval
5338 ttrss_feeds, ttrss_users, ttrss_user_prefs
5340 ttrss_feeds.owner_uid = ttrss_users.id
5341 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5342 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5343 $login_thresh_qpart $update_limit_qpart
5344 $updstart_thresh_qpart
5345 ORDER BY $random_qpart $query_limit");
5347 $user_prefs_cache = array();
5349 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5351 // Here is a little cache magic in order to minimize risk of double feed updates.
5352 $feeds_to_update = array();
5353 while ($line = db_fetch_assoc($result)) {
5354 $feeds_to_update[$line['id']] = $line;
5357 // We update the feed last update started date before anything else.
5358 // There is no lag due to feed contents downloads
5359 // It prevent an other process to update the same feed.
5360 $feed_ids = array_keys($feeds_to_update);
5362 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5363 WHERE id IN (%s)", implode(',', $feed_ids)));
5366 // For each feed, we call the feed update function.
5367 while ($line = array_pop($feeds_to_update)) {
5369 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5371 // We setup a alarm to alert if the feed take more than 300s to update.
5373 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5374 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5375 // Cancel the alarm (the update went well)
5376 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5378 sleep(1); // prevent flood (FIXME make this an option?)
5381 // Send feed digests by email if needed.
5382 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5384 } // function update_daemon_common
5386 function generate_dashboard_feed($link) {
5388 print "<div id=\"headlinesContainer\">";
5390 print_headline_subtoolbar($link, "", "Dashboard",
5391 false, false, -4, false, false, false,
5392 false, 0, 0, true, true, "tag.png");
5394 print "<div id=\"headlinesInnerContainer\" class=\"dashboard\">";
5395 print "<div>There is <b>666</b> unread articles in <b>666</b> feeds.</div>";
5400 print "]]></headlines>";
5401 print "<headlines-count value=\"0\"/>";
5402 print "<headlines-unread value=\"0\"/>";
5403 print "<disable-cache value=\"1\"/>";
5406 print "</articles>";
5409 function sanitize_article_content($text) {
5410 # we don't support CDATA sections in articles, they break our own escaping
5411 $text = preg_replace("/\[\[CDATA/", "", $text);
5412 $text = preg_replace("/\]\]\>/", "", $text);