3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if (!$owner_uid) return;
150 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
153 if (!$purge_unread) $query_limit = " unread = false AND ";
155 if (DB_TYPE
== "pgsql") {
156 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
157 marked = false AND feed_id = '$feed_id' AND
158 (SELECT date_entered FROM ttrss_entries WHERE
159 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
161 $pg_version = get_pgsql_version($link);
163 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
165 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
166 ttrss_entries.id = ref_id AND
168 feed_id = '$feed_id' AND
170 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
174 $result = db_query($link, "DELETE FROM ttrss_user_entries
176 WHERE ttrss_entries.id = ref_id AND
178 feed_id = '$feed_id' AND
180 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
183 $rows = pg_affected_rows($result);
187 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
188 marked = false AND feed_id = '$feed_id' AND
189 (SELECT date_entered FROM ttrss_entries WHERE
190 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_user_entries, ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
196 feed_id = '$feed_id' AND
198 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
200 $rows = mysql_affected_rows($link);
205 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
207 } // function purge_feed
210 * Purge old posts from old feeds.
212 * @param mixed $link A database connection
213 * @param boolean $do_output Set to true to enable printed output, false by default.
214 * @param integer $limit The maximal number of removed posts.
218 function global_purge_old_posts($link, $do_output = false, $limit = false) {
220 $random_qpart = sql_random_function();
223 $limit_qpart = "LIMIT $limit";
228 $result = db_query($link,
229 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
230 ORDER BY $random_qpart $limit_qpart");
232 while ($line = db_fetch_assoc($result)) {
234 $feed_id = $line["id"];
235 $purge_interval = $line["purge_interval"];
236 $owner_uid = $line["owner_uid"];
238 if ($purge_interval == 0) {
240 $tmp_result = db_query($link,
241 "SELECT value FROM ttrss_user_prefs WHERE
242 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
244 if (db_num_rows($tmp_result) != 0) {
245 $purge_interval = db_fetch_result($tmp_result, 0, "value");
250 // print "Feed $feed_id: purge interval = $purge_interval\n";
253 if ($purge_interval > 0) {
254 purge_feed($link, $feed_id, $purge_interval, $do_output);
258 // purge orphaned posts in main content table
259 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
260 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
263 $rows = db_affected_rows($link, $result);
264 _debug("Purged $rows orphaned posts.");
267 } // function global_purge_old_posts
269 function feed_purge_interval($link, $feed_id) {
271 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
272 WHERE id = '$feed_id'");
274 if (db_num_rows($result) == 1) {
275 $purge_interval = db_fetch_result($result, 0, "purge_interval");
276 $owner_uid = db_fetch_result($result, 0, "owner_uid");
278 if ($purge_interval == 0) $purge_interval = get_pref($link,
279 'PURGE_OLD_DAYS', $user_id);
281 return $purge_interval;
288 function purge_old_posts($link) {
290 $user_id = $_SESSION["uid"];
292 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
293 WHERE owner_uid = '$user_id'");
295 while ($line = db_fetch_assoc($result)) {
297 $feed_id = $line["id"];
298 $purge_interval = $line["purge_interval"];
300 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
302 if ($purge_interval > 0) {
303 purge_feed($link, $feed_id, $purge_interval);
307 // purge orphaned posts in main content table
308 db_query($link, "DELETE FROM ttrss_entries WHERE
309 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
312 function get_feed_update_interval($link, $feed_id) {
313 $result = db_query($link, "SELECT owner_uid, update_interval FROM
314 ttrss_feeds WHERE id = '$feed_id'");
316 if (db_num_rows($result) == 1) {
317 $update_interval = db_fetch_result($result, 0, "update_interval");
318 $owner_uid = db_fetch_result($result, 0, "owner_uid");
320 if ($update_interval != 0) {
321 return $update_interval;
323 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
331 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
333 if (WEB_DEMO_MODE
) return;
336 $user_id = $_SESSION["uid"];
337 purge_old_posts($link);
340 // db_query($link, "BEGIN");
342 if (MAX_UPDATE_TIME
> 0) {
343 if (DB_TYPE
== "mysql") {
346 $q_order = "RANDOM()";
349 $q_order = "last_updated DESC";
352 $result = db_query($link, "SELECT feed_url,id,
353 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
354 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
359 while ($line = db_fetch_assoc($result)) {
360 $upd_intl = $line["update_interval"];
362 if (!$upd_intl ||
$upd_intl == 0) {
363 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
367 // Updates for this feed are disabled
371 if ($fetch ||
(!$line["last_updated"] ||
372 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
374 // print "<!-- feed: ".$line["feed_url"]." -->";
376 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
378 $upd_elapsed = time() - $upd_start;
380 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
386 // db_query($link, "COMMIT");
390 function fetch_file_contents($url) {
391 if (USE_CURL_FOR_ICONS
) {
392 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
394 $ch = curl_init($url);
395 $fp = fopen($tmpfile, "w");
398 curl_setopt($ch, CURLOPT_FILE
, $fp);
399 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
400 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
406 $contents = file_get_contents($tmpfile);
412 return file_get_contents($url);
418 * Try to determine the favicon URL for a feed.
419 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
420 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
422 * @param string $url A feed or page URL
424 * @return mixed The favicon URL, or false if none was found.
426 function get_favicon_url($url) {
428 if ($html = @fetch_file_contents
($url)) {
430 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
431 // Attempt to grab a favicon link from their webpage url
432 $linkUrl = html_entity_decode($matches[1]);
434 if (substr($linkUrl, 0, 1) == '/') {
435 $urlParts = parse_url($url);
436 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
437 } else if (substr($linkUrl, 0, 7) == 'http://') {
438 $faviconURL = $linkUrl;
439 } else if (substr($url, -1, 1) == '/') {
440 $faviconURL = $url.$linkUrl;
442 $faviconURL = $url.'/'.$linkUrl;
446 // If unsuccessful, attempt to "guess" the favicon location
447 $urlParts = parse_url($url);
448 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
452 // Run a test to see if what we have attempted to get actually exists.
453 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
458 } // function get_favicon_url
461 * Check if a link is a valid and working URL.
463 * @param mixed $link A URL to check
465 * @return boolean True if the URL is valid, false otherwise.
467 function url_validate($link) {
469 $url_parts = @parse_url
($link);
471 if ( empty( $url_parts["host"] ) )
474 if ( !empty( $url_parts["path"] ) ) {
475 $documentpath = $url_parts["path"];
480 if ( !empty( $url_parts["query"] ) )
481 $documentpath .= "?" . $url_parts["query"];
483 $host = $url_parts["host"];
484 $port = $url_parts["port"];
489 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
494 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
496 $http_response = fgets( $socket, 22 );
498 $responses = "/(200 OK)|(30[0-9] Moved)/";
499 if ( preg_match($responses, $http_response) ) {
506 } // function url_validate
508 function check_feed_favicon($site_url, $feed, $link) {
509 $favicon_url = get_favicon_url($site_url);
511 # print "FAVICON [$site_url]: $favicon_url\n";
515 $icon_file = ICONS_DIR
. "/$feed.ico";
517 if ($favicon_url && !file_exists($icon_file)) {
518 $contents = fetch_file_contents($favicon_url);
520 $fp = fopen($icon_file, "w");
523 fwrite($fp, $contents);
525 chmod($icon_file, 0644);
529 error_reporting(DEFAULT_ERROR_LEVEL
);
533 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
535 if (!$_GET["daemon"] && !$ignore_daemon) {
539 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
540 _debug("update_rss_feed: start");
543 if (!$ignore_daemon) {
545 if (DB_TYPE
== "pgsql") {
546 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
548 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
551 $result = db_query($link, "SELECT id,update_interval,auth_login,
552 auth_pass,cache_images,update_method
553 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
557 $result = db_query($link, "SELECT id,update_interval,auth_login,
558 auth_pass,cache_images,update_method
559 FROM ttrss_feeds WHERE id = '$feed'");
563 if (db_num_rows($result) == 0) {
564 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
565 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
570 $update_method = db_fetch_result($result, 0, "update_method");
572 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
573 WHERE id = '$feed'");
575 $auth_login = db_fetch_result($result, 0, "auth_login");
576 $auth_pass = db_fetch_result($result, 0, "auth_pass");
578 if (ALLOW_SELECT_UPDATE_METHOD
) {
579 if (ENABLE_SIMPLEPIE
) {
580 $use_simplepie = $update_method != 1;
582 $use_simplepie = $update_method == 2;
585 $use_simplepie = ENABLE_SIMPLEPIE
;
588 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
589 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
592 if (!$use_simplepie) {
593 $auth_login = urlencode($auth_login);
594 $auth_pass = urlencode($auth_pass);
597 $update_interval = db_fetch_result($result, 0, "update_interval");
598 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
600 if ($update_interval < 0) { return; }
602 $feed = db_escape_string($feed);
604 $fetch_url = $feed_url;
606 if ($auth_login && $auth_pass) {
607 $url_parts = array();
608 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
610 if ($url_parts[1] && $url_parts[2]) {
611 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
616 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
617 _debug("update_rss_feed: fetching [$fetch_url]...");
620 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
624 if (!$use_simplepie) {
625 $rss = fetch_rss($fetch_url);
627 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
628 mkdir(SIMPLEPIE_CACHE_DIR
);
631 $rss = new SimplePie();
632 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
633 # $rss->set_timeout(10);
634 $rss->set_feed_url($fetch_url);
635 $rss->set_output_encoding('UTF-8');
637 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
638 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
639 _debug("enabling image cache");
642 $rss->set_image_handler('./image.php', 'i');
645 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
646 _debug("feed update interval (sec): " .
647 get_feed_update_interval($link, $feed)*60);
650 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
651 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
652 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
660 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
661 _debug("update_rss_feed: fetch done, parsing...");
663 error_reporting (DEFAULT_ERROR_LEVEL
);
666 $feed = db_escape_string($feed);
668 if ($use_simplepie) {
669 $fetch_ok = !$rss->error();
676 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
677 _debug("update_rss_feed: processing feed data...");
680 // db_query($link, "BEGIN");
682 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
683 FROM ttrss_feeds WHERE id = '$feed'");
685 $registered_title = db_fetch_result($result, 0, "title");
686 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
687 $orig_site_url = db_fetch_result($result, 0, "site_url");
689 $owner_uid = db_fetch_result($result, 0, "owner_uid");
691 if ($use_simplepie) {
692 $site_url = $rss->get_link();
694 $site_url = $rss->channel
["link"];
697 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
698 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
699 _debug("update_rss_feed: checking favicon...");
702 check_feed_favicon($site_url, $feed, $link);
705 if (!$registered_title ||
$registered_title == "[Unknown]") {
707 if ($use_simplepie) {
708 $feed_title = db_escape_string($rss->get_title());
710 $feed_title = db_escape_string($rss->channel
["title"]);
713 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
714 _debug("update_rss_feed: registering title: $feed_title");
717 db_query($link, "UPDATE ttrss_feeds SET
718 title = '$feed_title' WHERE id = '$feed'");
721 // weird, weird Magpie
722 if (!$use_simplepie) {
723 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
726 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
727 db_query($link, "UPDATE ttrss_feeds SET
728 site_url = '$site_url' WHERE id = '$feed'");
731 // print "I: " . $rss->channel["image"]["url"];
733 if (!$use_simplepie) {
734 $icon_url = $rss->image
["url"];
736 $icon_url = $rss->get_image_url();
739 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
740 $icon_url = db_escape_string($icon_url);
741 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
744 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
745 _debug("update_rss_feed: loading filters...");
748 $filters = load_filters($link, $feed, $owner_uid);
750 if ($use_simplepie) {
751 $iterator = $rss->get_items();
753 $iterator = $rss->items
;
754 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
755 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
758 if (!is_array($iterator)) {
759 /* db_query($link, "UPDATE ttrss_feeds
760 SET last_error = 'Parse error: can\'t find any articles.'
761 WHERE id = '$feed'"); */
763 // clear any errors and mark feed as updated if fetched okay
764 // even if it's blank
766 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
767 _debug("update_rss_feed: entry iterator is not an array, no articles?");
770 db_query($link, "UPDATE ttrss_feeds
771 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
773 return; // no articles
776 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
777 _debug("update_rss_feed: processing articles...");
780 foreach ($iterator as $item) {
782 if ($_GET['xdebug']) {
787 if ($use_simplepie) {
788 $entry_guid = $item->get_id();
789 if (!$entry_guid) $entry_guid = $item->get_link();
790 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
794 $entry_guid = $item["id"];
796 if (!$entry_guid) $entry_guid = $item["guid"];
797 if (!$entry_guid) $entry_guid = $item["link"];
798 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
801 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
802 _debug("update_rss_feed: guid $entry_guid");
805 if (!$entry_guid) continue;
807 $entry_timestamp = "";
809 if ($use_simplepie) {
810 $entry_timestamp = strtotime($item->get_date());
812 $rss_2_date = $item['pubdate'];
813 $rss_1_date = $item['dc']['date'];
814 $atom_date = $item['issued'];
815 if (!$atom_date) $atom_date = $item['updated'];
817 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
818 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
819 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
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 (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
832 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
835 if ($use_simplepie) {
836 $entry_title = $item->get_title();
838 $entry_title = trim(strip_tags($item["title"]));
841 if ($use_simplepie) {
842 $entry_link = $item->get_link();
844 // strange Magpie workaround
845 $entry_link = $item["link_"];
846 if (!$entry_link) $entry_link = $item["link"];
849 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
850 _debug("update_rss_feed: title $entry_title");
853 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
855 $entry_link = strip_tags($entry_link);
857 if ($use_simplepie) {
858 $entry_content = $item->get_content();
859 if (!$entry_content) $entry_content = $item->get_description();
861 $entry_content = $item["content:escaped"];
863 if (!$entry_content) $entry_content = $item["content:encoded"];
864 if (!$entry_content) $entry_content = $item["content"]["encoded"];
865 if (!$entry_content) $entry_content = $item["content"];
867 // Magpie bugs are getting ridiculous
868 if (trim($entry_content) == "Array") $entry_content = false;
870 if (!$entry_content) $entry_content = $item["atom_content"];
871 if (!$entry_content) $entry_content = $item["summary"];
873 if (!$entry_content ||
874 strlen($entry_content) < strlen($item["description"])) {
875 $entry_content = $item["description"];
879 if (is_array($entry_content)) {
880 $entry_content = $entry_content["encoded"];
881 if (!$entry_content) $entry_content = $entry_content["escaped"];
885 if ($_GET["xdebug"]) {
886 print "update_rss_feed: content: ";
887 print_r(htmlspecialchars($entry_content));
890 $entry_content_unescaped = $entry_content;
892 if ($use_simplepie) {
893 $entry_comments = strip_tags($item->data
["comments"]);
894 if ($item->get_author()) {
895 $entry_author_item = $item->get_author();
896 $entry_author = $entry_author_item->get_name();
897 if (!$entry_author) $entry_author = $entry_author_item->get_email();
899 $entry_author = db_escape_string($entry_author);
902 $entry_comments = strip_tags($item["comments"]);
904 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
906 if ($item['author']) {
908 if (is_array($item['author'])) {
910 if (!$entry_author) {
911 $entry_author = db_escape_string(strip_tags($item['author']['name']));
914 if (!$entry_author) {
915 $entry_author = db_escape_string(strip_tags($item['author']['email']));
919 if (!$entry_author) {
920 $entry_author = db_escape_string(strip_tags($item['author']));
925 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
927 $entry_guid = db_escape_string(strip_tags($entry_guid));
928 $entry_guid = mb_substr($entry_guid, 0, 250);
930 $result = db_query($link, "SELECT id FROM ttrss_entries
931 WHERE guid = '$entry_guid'");
933 $entry_content = db_escape_string($entry_content);
935 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
937 $entry_title = db_escape_string($entry_title);
938 $entry_link = db_escape_string($entry_link);
939 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
940 $entry_author = mb_substr($entry_author, 0, 250);
942 if ($use_simplepie) {
943 $num_comments = 0; #FIXME#
945 $num_comments = db_escape_string($item["slash"]["comments"]);
948 if (!$num_comments) $num_comments = 0;
950 // parse <category> entries into tags
952 if ($use_simplepie) {
954 $additional_tags = array();
955 $additional_tags_src = $item->get_categories();
957 if (is_array($additional_tags_src)) {
958 foreach ($additional_tags_src as $tobj) {
959 array_push($additional_tags, $tobj->get_term());
963 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
964 _debug("update_rss_feed: category tags:");
965 print_r($additional_tags);
970 $t_ctr = $item['category#'];
972 $additional_tags = false;
975 $additional_tags = false;
976 } else if ($t_ctr > 0) {
977 $additional_tags = array($item['category']);
979 if ($item['category@term']) {
980 array_push($additional_tags, $item['category@term']);
983 for ($i = 0; $i <= $t_ctr; $i++
) {
984 if ($item["category#$i"]) {
985 array_push($additional_tags, $item["category#$i"]);
988 if ($item["category#$i@term"]) {
989 array_push($additional_tags, $item["category#$i@term"]);
994 // parse <dc:subject> elements
996 $t_ctr = $item['dc']['subject#'];
999 $additional_tags = array($item['dc']['subject']);
1001 for ($i = 0; $i <= $t_ctr; $i++
) {
1002 if ($item['dc']["subject#$i"]) {
1003 array_push($additional_tags, $item['dc']["subject#$i"]);
1011 $enclosures = array();
1013 if ($use_simplepie) {
1014 $encs = $item->get_enclosures();
1016 if (is_array($encs)) {
1017 foreach ($encs as $e) {
1019 $e->link
, $e->type
, $e->length
);
1021 array_push($enclosures, $e_item);
1028 $e_ctr = $item['enclosure#'];
1031 $e_item = array($item['enclosure@url'],
1032 $item['enclosure@type'],
1033 $item['enclosure@length']);
1035 array_push($enclosures, $e_item);
1037 for ($i = 0; $i <= $e_ctr; $i++
) {
1039 if ($item["enclosure#$i@url"]) {
1040 $e_item = array($item["enclosure#$i@url"],
1041 $item["enclosure#$i@type"],
1042 $item["enclosure#$i@length"]);
1043 array_push($enclosures, $e_item);
1049 // can there be many of those? yes -fox
1051 $m_ctr = $item['media']['content#'];
1054 $e_item = array($item['media']['content@url'],
1055 $item['media']['content@medium'],
1056 $item['media']['content@length']);
1058 array_push($enclosures, $e_item);
1060 for ($i = 0; $i <= $m_ctr; $i++
) {
1062 if ($item["media"]["content#$i@url"]) {
1063 $e_item = array($item["media"]["content#$i@url"],
1064 $item["media"]["content#$i@medium"],
1065 $item["media"]["content#$i@length"]);
1066 array_push($enclosures, $e_item);
1075 $entry_content = sanitize_article_content($entry_content);
1076 $entry_title = sanitize_article_content($entry_title);
1078 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1079 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1082 db_query($link, "BEGIN");
1084 if (db_num_rows($result) == 0) {
1086 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1087 _debug("update_rss_feed: base guid not found");
1090 // base post entry does not exist, create it
1092 $result = db_query($link,
1093 "INSERT INTO ttrss_entries
1109 '$entry_timestamp_fmt',
1118 // we keep encountering the entry in feeds, so we need to
1119 // update date_entered column so that we don't get horrible
1120 // dupes when the entry gets purged and reinserted again e.g.
1121 // in the case of SLOW SLOW OMG SLOW updating feeds
1123 $base_entry_id = db_fetch_result($result, 0, "id");
1125 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1126 WHERE id = '$base_entry_id'");
1129 // now it should exist, if not - bad luck then
1131 $result = db_query($link, "SELECT
1132 id,content_hash,no_orig_date,title,
1133 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1134 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1138 WHERE guid = '$entry_guid'");
1143 if (db_num_rows($result) == 1) {
1145 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1146 _debug("update_rss_feed: base guid found, checking for user record");
1149 // this will be used below in update handler
1150 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1151 $orig_title = db_fetch_result($result, 0, "title");
1152 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1153 $orig_date_entered = strtotime(db_fetch_result($result,
1154 0, "date_entered"));
1156 $ref_id = db_fetch_result($result, 0, "id");
1157 $entry_ref_id = $ref_id;
1159 // check for user post link to main table
1161 // do we allow duplicate posts with same GUID in different feeds?
1162 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1163 $dupcheck_qpart = "AND feed_id = '$feed'";
1165 $dupcheck_qpart = "";
1168 // error_reporting(0);
1170 $article_filters = get_article_filters($filters, $entry_title,
1171 $entry_content, $entry_link, $entry_timestamp);
1173 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1174 _debug("update_rss_feed: article filters: ");
1175 if (count($article_filters) != 0) {
1176 print_r($article_filters);
1180 if (find_article_filter($article_filters, "filter")) {
1181 db_query($link, "COMMIT"); // close transaction in progress
1185 // error_reporting (DEFAULT_ERROR_LEVEL);
1187 $score = calculate_article_score($article_filters);
1189 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1190 _debug("update_rss_feed: initial score: $score");
1193 $result = db_query($link,
1194 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1195 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1198 // okay it doesn't exist - create user entry
1199 if (db_num_rows($result) == 0) {
1201 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1202 _debug("update_rss_feed: user record not found, creating...");
1205 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1207 $last_read_qpart = 'NULL';
1210 $last_read_qpart = 'NOW()';
1213 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1219 if (find_article_filter($article_filters, 'publish')) {
1220 $published = 'true';
1222 $published = 'false';
1225 $result = db_query($link,
1226 "INSERT INTO ttrss_user_entries
1227 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1229 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1230 $last_read_qpart, $marked, $published, '$score')");
1232 $result = db_query($link,
1233 "SELECT int_id FROM ttrss_user_entries WHERE
1234 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1235 feed_id = '$feed' LIMIT 1");
1237 if (db_num_rows($result) == 1) {
1238 $entry_int_id = db_fetch_result($result, 0, "int_id");
1241 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1242 $entry_int_id = db_fetch_result($result, 0, "int_id");
1245 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1246 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1249 $post_needs_update = false;
1251 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1252 ($content_hash != $orig_content_hash)) {
1253 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1254 $post_needs_update = true;
1257 if (db_escape_string($orig_title) != $entry_title) {
1258 $post_needs_update = true;
1261 if ($orig_num_comments != $num_comments) {
1262 $post_needs_update = true;
1265 // this doesn't seem to be very reliable
1267 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1268 // $post_needs_update = true;
1271 // if post needs update, update it and mark all user entries
1272 // linking to this post as updated
1273 if ($post_needs_update) {
1275 if (defined('DAEMON_EXTENDED_DEBUG')) {
1276 _debug("update_rss_feed: post $entry_guid needs update...");
1279 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1281 db_query($link, "UPDATE ttrss_entries
1282 SET title = '$entry_title', content = '$entry_content',
1283 content_hash = '$content_hash',
1284 num_comments = '$num_comments'
1285 WHERE id = '$ref_id'");
1287 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1288 db_query($link, "UPDATE ttrss_user_entries
1289 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1291 db_query($link, "UPDATE ttrss_user_entries
1292 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1298 db_query($link, "COMMIT");
1300 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1301 _debug("update_rss_feed: looking for enclosures...");
1304 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1305 print_r($enclosures);
1308 db_query($link, "BEGIN");
1310 foreach ($enclosures as $enc) {
1311 $enc_url = db_escape_string($enc[0]);
1312 $enc_type = db_escape_string($enc[1]);
1313 $enc_dur = db_escape_string($enc[2]);
1315 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1316 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1318 if (db_num_rows($result) == 0) {
1319 db_query($link, "INSERT INTO ttrss_enclosures
1320 (content_url, content_type, title, duration, post_id) VALUES
1321 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1325 db_query($link, "COMMIT");
1327 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1328 _debug("update_rss_feed: looking for tags...");
1332 // <a href="..." rel="tag">Xorg</a>, //
1336 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1337 $entry_content_unescaped, $entry_tags);
1339 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1340 print_r($entry_tags);
1341 print "<br/></p>"; */
1343 $entry_tags = $entry_tags[1];
1345 # check for manual tags
1347 $tag_filter = find_article_filter($article_filters, "tag");
1351 $manual_tags = trim_array(split(",", $tag_filter[1]));
1353 foreach ($manual_tags as $tag) {
1354 if (tag_is_valid($tag)) {
1355 array_push($entry_tags, $tag);
1360 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1361 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1363 if ($additional_tags && is_array($additional_tags)) {
1364 foreach ($additional_tags as $tag) {
1365 if (tag_is_valid($tag) &&
1366 array_search($tag, $boring_tags) === FALSE) {
1367 array_push($entry_tags, $tag);
1372 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1374 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1375 print_r($entry_tags);
1378 if (count($entry_tags) > 0) {
1380 db_query($link, "BEGIN");
1382 foreach ($entry_tags as $tag) {
1384 $tag = sanitize_tag($tag);
1385 $tag = db_escape_string($tag);
1387 if (!tag_is_valid($tag)) continue;
1389 $result = db_query($link, "SELECT id FROM ttrss_tags
1390 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1391 owner_uid = '$owner_uid' LIMIT 1");
1393 // print db_fetch_result($result, 0, "id");
1395 if ($result && db_num_rows($result) == 0) {
1397 db_query($link, "INSERT INTO ttrss_tags
1398 (owner_uid,tag_name,post_int_id)
1399 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1403 db_query($link, "COMMIT");
1406 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1407 _debug("update_rss_feed: article processed");
1411 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1412 _debug("update_rss_feed: updating counters cache...");
1415 ccache_update($link, $feed, $owner_uid);
1417 db_query($link, "UPDATE ttrss_feeds
1418 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1420 // db_query($link, "COMMIT");
1424 if ($use_simplepie) {
1425 $error_msg = mb_substr($rss->error(), 0, 250);
1427 $error_msg = mb_substr(magpie_error(), 0, 250);
1430 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1431 _debug("update_rss_feed: error fetching feed: $error_msg");
1434 $error_msg = db_escape_string($error_msg);
1437 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1438 last_updated = NOW() WHERE id = '$feed'");
1441 if ($use_simplepie) {
1445 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1446 _debug("update_rss_feed: done");
1451 function print_select($id, $default, $values, $attributes = "") {
1452 print "<select name=\"$id\" id=\"$id\" $attributes>";
1453 foreach ($values as $v) {
1459 print "<option$sel>$v</option>";
1464 function print_select_hash($id, $default, $values, $attributes = "") {
1465 print "<select name=\"$id\" id='$id' $attributes>";
1466 foreach (array_keys($values) as $v) {
1468 $sel = 'selected="selected"';
1472 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1478 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1481 if ($filters["title"]) {
1482 foreach ($filters["title"] as $filter) {
1483 $reg_exp = $filter["reg_exp"];
1484 $inverse = $filter["inverse"];
1485 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1486 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1488 array_push($matches, array($filter["action"], $filter["action_param"]));
1493 if ($filters["content"]) {
1494 foreach ($filters["content"] as $filter) {
1495 $reg_exp = $filter["reg_exp"];
1496 $inverse = $filter["inverse"];
1498 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1499 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1501 array_push($matches, array($filter["action"], $filter["action_param"]));
1506 if ($filters["both"]) {
1507 foreach ($filters["both"] as $filter) {
1508 $reg_exp = $filter["reg_exp"];
1509 $inverse = $filter["inverse"];
1512 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1513 array_push($matches, array($filter["action"], $filter["action_param"]));
1516 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1517 array_push($matches, array($filter["action"], $filter["action_param"]));
1523 if ($filters["link"]) {
1524 $reg_exp = $filter["reg_exp"];
1525 foreach ($filters["link"] as $filter) {
1526 $reg_exp = $filter["reg_exp"];
1527 $inverse = $filter["inverse"];
1529 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1530 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1532 array_push($matches, array($filter["action"], $filter["action_param"]));
1537 if ($filters["date"]) {
1538 $reg_exp = $filter["reg_exp"];
1539 foreach ($filters["date"] as $filter) {
1540 $date_modifier = $filter["filter_param"];
1541 $inverse = $filter["inverse"];
1542 $check_timestamp = strtotime($filter["reg_exp"]);
1544 # no-op when timestamp doesn't parse to prevent misfires
1546 if ($check_timestamp) {
1549 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1550 $date_modifier == "after" && $timestamp > $check_timestamp) {
1554 if ($inverse) $match_ok = !$match_ok;
1557 array_push($matches, array($filter["action"], $filter["action_param"]));
1566 function find_article_filter($filters, $filter_name) {
1567 foreach ($filters as $f) {
1568 if ($f[0] == $filter_name) {
1575 function calculate_article_score($filters) {
1578 foreach ($filters as $f) {
1579 if ($f[0] == "score") {
1587 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1588 $rtl_content = false, $last_updated = false, $last_error = false) {
1590 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1591 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1593 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1597 $rtl_tag = "dir=\"rtl\"";
1599 $rtl_tag = "dir=\"ltr\"";
1602 $error_notify_msg = "";
1605 $link_title = "Error: $last_error ($last_updated)";
1606 $error_notify_msg = "(Error)";
1607 } else if ($last_updated) {
1608 $link_title = "Updated: $last_updated";
1611 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1612 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1614 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1615 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1619 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1622 $fctr_class = "class=\"feedCtrHasUnread\"";
1624 $fctr_class = "class=\"feedCtrNoUnread\"";
1627 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1628 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1630 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1631 $total = getFeedArticles($link, $feed_id);
1632 print "<div class=\"feedExtInfo\">
1633 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1640 function getmicrotime() {
1641 list($usec, $sec) = explode(" ",microtime());
1642 return ((float)$usec +
(float)$sec);
1645 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1646 foreach ($values as $v) {
1653 if ($v == $true_is) {
1654 $sel .= " value=\"1\"";
1656 $sel .= " value=\"0\"";
1659 print "<input class=\"noborder\"
1660 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1665 function initialize_user_prefs($link, $uid) {
1667 $uid = db_escape_string($uid);
1669 db_query($link, "BEGIN");
1671 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1673 $u_result = db_query($link, "SELECT pref_name
1674 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1676 $active_prefs = array();
1678 while ($line = db_fetch_assoc($u_result)) {
1679 array_push($active_prefs, $line["pref_name"]);
1682 while ($line = db_fetch_assoc($result)) {
1683 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1684 // print "adding " . $line["pref_name"] . "<br>";
1686 db_query($link, "INSERT INTO ttrss_user_prefs
1687 (owner_uid,pref_name,value) VALUES
1688 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1693 db_query($link, "COMMIT");
1697 function lookup_user_id($link, $user) {
1699 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1702 if (db_num_rows($result) == 1) {
1703 return db_fetch_result($result, 0, "id");
1709 function http_authenticate_user($link) {
1711 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1713 if (!$_SERVER["PHP_AUTH_USER"]) {
1715 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1716 header('HTTP/1.0 401 Unauthorized');
1720 $auth_result = authenticate_user($link,
1721 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1723 if (!$auth_result) {
1724 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1725 header('HTTP/1.0 401 Unauthorized');
1733 function authenticate_user($link, $login, $password, $force_auth = false) {
1735 if (!SINGLE_USER_MODE
) {
1737 $pwd_hash1 = encrypt_password($password);
1738 $pwd_hash2 = encrypt_password($password, $login);
1740 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1741 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1743 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1745 $query = "SELECT id,login,access_level,pwd_hash
1746 FROM ttrss_users WHERE
1750 $query = "SELECT id,login,access_level,pwd_hash
1751 FROM ttrss_users WHERE
1752 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1753 pwd_hash = '$pwd_hash2')";
1756 $result = db_query($link, $query);
1758 if (db_num_rows($result) == 1) {
1759 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1760 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1761 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1763 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1766 $user_theme = get_user_theme_path($link);
1768 $_SESSION["theme"] = $user_theme;
1769 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1770 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1772 initialize_user_prefs($link, $_SESSION["uid"]);
1781 $_SESSION["uid"] = 1;
1782 $_SESSION["name"] = "admin";
1784 $user_theme = get_user_theme_path($link);
1786 $_SESSION["theme"] = $user_theme;
1787 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1789 initialize_user_prefs($link, $_SESSION["uid"]);
1795 function make_password($length = 8) {
1798 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1802 while ($i < $length) {
1803 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1805 if (!strstr($password, $char)) {
1813 // this is called after user is created to initialize default feeds, labels
1816 // user preferences are checked on every login, not here
1818 function initialize_user($link, $uid) {
1820 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1821 values ('$uid','unread = true', 'Unread articles')");
1823 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1824 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1826 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1827 values ('$uid', 'Tiny Tiny RSS: New Releases',
1828 'http://tt-rss.spb.ru/releases.rss')");
1830 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1831 values ('$uid', 'Tiny Tiny RSS: Forum',
1832 'http://tt-rss.spb.ru/forum/rss.php')");
1835 function logout_user() {
1837 if (isset($_COOKIE[session_name()])) {
1838 setcookie(session_name(), '', time()-42000, '/');
1842 function get_script_urlpath() {
1843 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1846 function validate_session($link) {
1847 if (SINGLE_USER_MODE
) {
1851 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1852 if ($_SESSION["ip_address"]) {
1853 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1854 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1860 if ($_SESSION["uid"]) {
1862 $result = db_query($link,
1863 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1865 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1867 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1872 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1874 //print_r($_SESSION);
1876 if (time() > $_SESSION["cookie_lifetime"]) {
1884 function login_sequence($link, $mobile = false) {
1885 if (!SINGLE_USER_MODE
) {
1887 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1888 $swu = db_escape_string($_REQUEST["swu"]);
1890 $_SESSION["prefs_cache"] = false;
1891 return authenticate_user($link, $swu, null, true);
1895 $login_action = $_POST["login_action"];
1897 # try to authenticate user if called from login form
1898 if ($login_action == "do_login") {
1899 $login = $_POST["login"];
1900 $password = $_POST["password"];
1901 $remember_me = $_POST["remember_me"];
1903 if (authenticate_user($link, $login, $password)) {
1904 $_POST["password"] = "";
1906 $_SESSION["language"] = $_POST["language"];
1907 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1909 header("Location: " . $_SERVER["REQUEST_URI"]);
1914 $_SESSION["login_error_msg"] = "Incorrect username or password";
1918 // print session_id();
1919 // print_r($_SESSION);
1921 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1922 render_login_form($link, $mobile);
1925 /* bump login timestamp */
1926 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1929 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1930 setcookie("ttrss_lang", $_SESSION["language"],
1931 time() + SESSION_COOKIE_LIFETIME
);
1934 /* bump counters stamp since we're getting reloaded anyway */
1936 $_SESSION["get_all_counters_stamp"] = time();
1940 return authenticate_user($link, "admin", null);
1944 function truncate_string($str, $max_len) {
1945 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1946 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1952 function get_user_theme_path($link) {
1953 $result = db_query($link, "SELECT theme_path
1955 ttrss_themes,ttrss_users
1956 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1957 if (db_num_rows($result) != 0) {
1958 return db_fetch_result($result, 0, "theme_path");
1964 function smart_date_time($timestamp) {
1965 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1966 return date("G:i", $timestamp);
1967 } else if (date("Y", $timestamp) == date("Y")) {
1968 return date("M d, G:i", $timestamp);
1970 return date("Y/m/d, G:i", $timestamp);
1974 function smart_date($timestamp) {
1975 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1977 } else if (date("Y", $timestamp) == date("Y")) {
1978 return date("D m", $timestamp);
1980 return date("Y/m/d", $timestamp);
1984 function sql_bool_to_string($s) {
1985 if ($s == "t" ||
$s == "1") {
1992 function sql_bool_to_bool($s) {
1993 if ($s == "t" ||
$s == "1") {
2001 function toggleEvenOdd($a) {
2008 function sanity_check($link) {
2013 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2014 $schema_version = db_fetch_result($result, 0, "schema_version");
2016 if ($schema_version != SCHEMA_VERSION
) {
2020 if (DB_TYPE
== "mysql") {
2021 $result = db_query($link, "SELECT true", false);
2022 if (db_num_rows($result) != 1) {
2027 if (db_escape_string("testTEST") != "testTEST") {
2031 error_reporting (DEFAULT_ERROR_LEVEL
);
2033 if ($error_code != 0) {
2034 print_error_xml($error_code);
2041 function file_is_locked($filename) {
2042 if (function_exists('flock')) {
2044 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2045 error_reporting(DEFAULT_ERROR_LEVEL
);
2047 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2048 flock($fp, LOCK_UN
);
2058 return true; // consider the file always locked and skip the test
2061 function make_lockfile($filename) {
2062 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2064 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2071 function make_stampfile($filename) {
2072 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2074 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2075 fwrite($fp, time() . "\n");
2076 flock($fp, LOCK_UN
);
2084 function read_stampfile($filename) {
2087 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2088 error_reporting (DEFAULT_ERROR_LEVEL
);
2091 if (flock($fp, LOCK_EX
)) {
2092 $stamp = fgets($fp);
2093 flock($fp, LOCK_UN
);
2104 function sql_random_function() {
2105 if (DB_TYPE
== "mysql") {
2112 function catchup_feed($link, $feed, $cat_view) {
2114 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2119 $cat_qpart = "cat_id = '$feed'";
2121 $cat_qpart = "cat_id IS NULL";
2124 $tmp_result = db_query($link, "SELECT id
2125 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2128 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2130 $tmp_feed = $tmp_line["id"];
2132 db_query($link, "UPDATE ttrss_user_entries
2133 SET unread = false,last_read = NOW()
2134 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2137 } else if ($feed > 0) {
2139 $tmp_result = db_query($link, "SELECT id
2140 FROM ttrss_feeds WHERE parent_feed = '$feed'
2141 ORDER BY cat_id,title");
2143 $parent_ids = array();
2145 if (db_num_rows($tmp_result) > 0) {
2146 while ($p = db_fetch_assoc($tmp_result)) {
2147 array_push($parent_ids, "feed_id = " . $p["id"]);
2150 $children_qpart = implode(" OR ", $parent_ids);
2152 db_query($link, "UPDATE ttrss_user_entries
2153 SET unread = false,last_read = NOW()
2154 WHERE (feed_id = '$feed' OR $children_qpart)
2155 AND owner_uid = " . $_SESSION["uid"]);
2158 db_query($link, "UPDATE ttrss_user_entries
2159 SET unread = false,last_read = NOW()
2160 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2163 } else if ($feed < 0 && $feed > -10) { // special, like starred
2166 db_query($link, "UPDATE ttrss_user_entries
2167 SET unread = false,last_read = NOW()
2168 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2172 db_query($link, "UPDATE ttrss_user_entries
2173 SET unread = false,last_read = NOW()
2174 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2179 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2181 if (DB_TYPE
== "pgsql") {
2182 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2184 $match_part = "updated > DATE_SUB(NOW(),
2185 INTERVAL $intl HOUR) ";
2188 $result = db_query($link, "SELECT id FROM ttrss_entries,
2189 ttrss_user_entries WHERE $match_part AND
2191 ttrss_user_entries.ref_id = ttrss_entries.id AND
2192 owner_uid = ".$_SESSION["uid"]);
2194 $affected_ids = array();
2196 while ($line = db_fetch_assoc($result)) {
2197 array_push($affected_ids, $line["id"]);
2200 catchupArticlesById($link, $affected_ids, 0);
2203 } else if ($feed < -10) { // label
2205 // TODO make this more efficient
2207 $label_id = -$feed - 11;
2209 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2210 WHERE id = '$label_id'");
2213 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2215 db_query($link, "BEGIN");
2217 $tmp2_result = db_query($link,
2221 ttrss_user_entries,ttrss_entries,ttrss_feeds
2223 ref_id = ttrss_entries.id AND
2224 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2226 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2228 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2229 db_query($link, "UPDATE
2232 unread = false, last_read = NOW()
2234 int_id = " . $tmp_line["int_id"]);
2237 db_query($link, "COMMIT");
2239 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2240 SET unread = false,last_read = NOW()
2243 AND owner_uid = ".$_SESSION["uid"]); */
2247 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2250 db_query($link, "BEGIN");
2252 $tag_name = db_escape_string($feed);
2254 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2255 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2257 while ($line = db_fetch_assoc($result)) {
2258 db_query($link, "UPDATE ttrss_user_entries SET
2259 unread = false, last_read = NOW()
2260 WHERE int_id = " . $line["post_int_id"]);
2262 db_query($link, "COMMIT");
2266 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2270 $cat_qpart = "cat_id = '$feed'";
2272 $cat_qpart = "cat_id IS NULL";
2275 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2276 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2278 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2279 $feed_url = $tmp_line["feed_url"];
2280 $feed_id = $tmp_line["id"];
2281 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2285 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2286 WHERE id = '$feed'");
2287 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2288 update_rss_feed($link, $feed_url, $feed, $force_update);
2292 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2294 /* getting all counters is a resource intensive operation, so we
2295 * rate limit it a little bit */
2299 // if (get_pref($link, "SYNC_COUNTERS") ||
2300 // time() - $_SESSION["get_all_counters_stamp"] > 5) {
2302 if (!$omode) $omode = "flc";
2304 getGlobalCounters($link);
2306 if (strchr($omode, "l")) getLabelCounters($link);
2307 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2308 if (strchr($omode, "t")) getTagCounters($link);
2309 if (strchr($omode, "c")) {
2310 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2311 getCategoryCounters($link);
2315 $_SESSION["get_all_counters_stamp"] = time();
2320 function getCategoryCounters($link) {
2321 # two special categories are -1 and -2 (all virtuals; all labels)
2323 $ctr = getCategoryUnread($link, -1);
2325 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2327 $ctr = getCategoryUnread($link, -2);
2329 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2331 $age_qpart = getMaxAgeSubquery();
2333 $result = db_query($link, "SELECT cat_id, value AS unread
2334 FROM ttrss_feeds, ttrss_cat_counters_cache
2336 ttrss_cat_counters_cache.feed_id = cat_id AND
2338 ttrss_feeds.owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2340 while ($line = db_fetch_assoc($result)) {
2341 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2343 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2344 $line["unread"]."\"/>";
2347 /* Special case: NULL category doesn't actually exist in the DB */
2349 print "<counter type=\"category\" id=\"0\" counter=\"".
2350 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2354 function getCategoryUnread($link, $cat) {
2359 $cat_query = "cat_id = '$cat'";
2361 $cat_query = "cat_id IS NULL";
2364 $age_qpart = getMaxAgeSubquery();
2366 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2368 AND owner_uid = " . $_SESSION["uid"]);
2370 $cat_feeds = array();
2371 while ($line = db_fetch_assoc($result)) {
2372 array_push($cat_feeds, "feed_id = " . $line["id"]);
2375 if (count($cat_feeds) == 0) return 0;
2377 $match_part = implode(" OR ", $cat_feeds);
2379 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2380 FROM ttrss_user_entries,ttrss_entries
2381 WHERE unread = true AND ($match_part) AND id = ref_id
2382 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2386 # this needs to be rewritten
2387 while ($line = db_fetch_assoc($result)) {
2388 $unread +
= $line["unread"];
2392 } else if ($cat == -1) {
2393 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2394 } else if ($cat == -2) {
2396 $rv = getLabelCounters($link, false, true);
2399 foreach (array_keys($rv) as $k) {
2401 $ctr +
= $rv[$k]["counter"];
2409 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2410 if (DB_TYPE
== "pgsql") {
2411 return "ttrss_entries.date_entered >
2412 NOW() - INTERVAL '$days days'";
2414 return "ttrss_entries.date_entered >
2415 DATE_SUB(NOW(), INTERVAL $days DAY)";
2419 function getFeedUnread($link, $feed, $is_cat = false) {
2420 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2423 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2424 $owner_uid = false) {
2426 $n_feed = sprintf("%d", $feed);
2428 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2431 $unread_qpart = "unread = true";
2433 $unread_qpart = "true";
2436 $age_qpart = getMaxAgeSubquery();
2439 return getCategoryUnread($link, $n_feed);
2440 } else if ($n_feed == -1) {
2441 $match_part = "marked = true";
2442 } else if ($n_feed == -2) {
2443 $match_part = "published = true";
2444 } else if ($n_feed == -3) {
2445 $match_part = "unread = true";
2447 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2449 if (DB_TYPE
== "pgsql") {
2450 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2452 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2455 } else if ($n_feed > 0) {
2457 $result = db_query($link, "SELECT id FROM ttrss_feeds
2458 WHERE parent_feed = '$n_feed'
2460 AND owner_uid = " . $owner_uid);
2462 if (db_num_rows($result) > 0) {
2464 $linked_feeds = array();
2465 while ($line = db_fetch_assoc($result)) {
2466 array_push($linked_feeds, "feed_id = " . $line["id"]);
2469 array_push($linked_feeds, "feed_id = $n_feed");
2471 $match_part = implode(" OR ", $linked_feeds);
2473 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2474 FROM ttrss_user_entries,ttrss_entries
2475 WHERE $unread_qpart AND
2476 ttrss_user_entries.ref_id = ttrss_entries.id AND
2479 owner_uid = " . $owner_uid);
2483 # this needs to be rewritten
2484 while ($line = db_fetch_assoc($result)) {
2485 $unread +
= $line["unread"];
2491 $match_part = "feed_id = '$n_feed'";
2493 } else if ($feed < -10) {
2495 $label_id = -$feed - 11;
2497 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2498 id = '$label_id' AND owner_uid = " . $owner_uid);
2500 $match_part = db_fetch_result($result, 0, "sql_exp");
2505 $result = db_query($link, "SELECT count(int_id) AS unread
2506 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2507 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2508 ttrss_user_entries.ref_id = ttrss_entries.id AND
2509 ttrss_feeds.hidden = false AND
2511 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2515 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2516 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2517 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2518 AND $unread_qpart AND $age_qpart AND
2519 ttrss_tags.owner_uid = " . $owner_uid);
2522 $unread = db_fetch_result($result, 0, "unread");
2527 /* FIXME this needs reworking */
2529 function getGlobalUnread($link, $user_id = false) {
2532 $user_id = $_SESSION["uid"];
2535 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2536 WHERE owner_uid = '$user_id' AND feed_id > 0");
2538 $c_id = db_fetch_result($result, 0, "c_id");
2543 function getGlobalCounters($link, $global_unread = -1) {
2544 if ($global_unread == -1) {
2545 $global_unread = getGlobalUnread($link);
2547 print "<counter type=\"global\" id='global-unread'
2548 counter='$global_unread'/>";
2550 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2551 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2553 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2555 print "<counter type=\"global\" id='subscribed-feeds'
2556 counter='$subscribed_feeds'/>";
2560 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2563 if (!$_SESSION["tctr_last_value"]) {
2564 $_SESSION["tctr_last_value"] = array();
2568 $old_counters = $_SESSION["tctr_last_value"];
2570 $tctrs_modified = false;
2572 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2573 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2574 ttrss_user_entries.ref_id = ttrss_entries.id AND
2575 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2576 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2578 select tag_name,0 as count FROM ttrss_tags
2579 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2581 $age_qpart = getMaxAgeSubquery();
2583 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2584 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2585 AND ref_id = id AND $age_qpart
2586 AND unread = true)) AS count FROM ttrss_tags
2587 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2588 ORDER BY count DESC LIMIT 55");
2592 while ($line = db_fetch_assoc($result)) {
2593 $tags[$line["tag_name"]] +
= $line["count"];
2596 foreach (array_keys($tags) as $tag) {
2597 $unread = $tags[$tag];
2599 $tag = htmlspecialchars($tag);
2601 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2602 $old_counters[$tag] = $unread;
2603 $tctrs_modified = true;
2604 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2609 if ($smart_mode && $tctrs_modified) {
2610 $_SESSION["tctr_last_value"] = $old_counters;
2615 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2617 $age_qpart = getMaxAgeSubquery();
2620 if (!$_SESSION["lctr_last_value"]) {
2621 $_SESSION["lctr_last_value"] = array();
2627 $old_counters = $_SESSION["lctr_last_value"];
2628 $lctrs_modified = false;
2630 $count = getFeedUnread($link, -1);
2634 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2635 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2640 print "<counter type=\"label\" id=\"-1\" counter=\"$count\" $xmsg_part/>";
2642 $ret_arr["-1"]["counter"] = $count;
2643 $ret_arr["-1"]["description"] = __("Starred articles");
2646 $count = getFeedUnread($link, -2);
2650 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2651 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2656 print "<counter type=\"label\" id=\"-2\" counter=\"$count\" $xmsg_part/>";
2658 $ret_arr["-2"]["counter"] = $count;
2659 $ret_arr["-2"]["description"] = __("Published articles");
2662 $count = getFeedUnread($link, -3);
2666 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2667 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2672 print "<counter type=\"label\" id=\"-3\" counter=\"$count\" $xmsg_part/>";
2674 $ret_arr["-3"]["counter"] = $count;
2675 $ret_arr["-3"]["description"] = __("Fresh articles");
2679 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2680 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2682 while ($line = db_fetch_assoc($result)) {
2684 $id = -$line["id"] - 11;
2686 $label_name = $line["description"];
2688 $count = ccache_find($link, $id, $_SESSION["uid"]);
2690 error_reporting (0);
2692 /* $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2693 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2694 ttrss_feeds.hidden = false AND
2696 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2697 ttrss_user_entries.ref_id = ttrss_entries.id AND
2698 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2700 $count = db_fetch_result($tmp_result, 0, "count");
2702 if (!$smart_mode || $old_counters[$id] != $count) {
2703 $old_counters[$id] = $count;
2704 $lctrs_modified = true;
2707 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2708 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2713 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2715 $ret_arr[$id]["counter"] = $count;
2716 $ret_arr[$id]["description"] = $label_name;
2720 if (!$smart_mode ||
$old_counters[$id] != $count) {
2721 $old_counters[$id] = $count;
2722 $lctrs_modified = true;
2725 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2726 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2731 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2733 $ret_arr[$id]["counter"] = $count;
2734 $ret_arr[$id]["description"] = $label_name;
2739 error_reporting (DEFAULT_ERROR_LEVEL
);
2742 if ($smart_mode && $lctrs_modified) {
2743 $_SESSION["lctr_last_value"] = $old_counters;
2749 /* function getFeedCounter($link, $id) {
2751 $result = db_query($link, "SELECT
2752 count(id) as count,last_error
2753 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2754 WHERE feed_id = '$id' AND unread = true
2755 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2756 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2758 $count = db_fetch_result($result, 0, "count");
2759 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2761 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2764 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2766 $age_qpart = getMaxAgeSubquery();
2769 if (!$_SESSION["fctr_last_value"]) {
2770 $_SESSION["fctr_last_value"] = array();
2774 $old_counters = $_SESSION["fctr_last_value"];
2776 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2777 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated,
2779 FROM ttrss_entries,ttrss_user_entries
2780 WHERE feed_id = ttrss_feeds.id AND
2781 ttrss_user_entries.ref_id = ttrss_entries.id
2782 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2783 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2784 AND parent_feed IS NULL"); */
2786 /* $query = "SELECT ttrss_feeds.id,
2788 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2790 COUNT(ttrss_entries.id) AS count
2792 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2793 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2794 AND ttrss_user_entries.unread = true)
2795 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2797 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2798 AND parent_feed IS NULL
2799 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error"; */
2801 $query = "SELECT ttrss_feeds.id,
2803 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2804 last_error, value AS count
2805 FROM ttrss_feeds, ttrss_counters_cache
2806 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2807 AND parent_feed IS NULL
2808 AND ttrss_counters_cache.feed_id = id";
2810 $result = db_query($link, $query);
2811 $fctrs_modified = false;
2813 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2815 while ($line = db_fetch_assoc($result)) {
2818 $count = $line["count"];
2819 $last_error = htmlspecialchars($line["last_error"]);
2821 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2822 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2824 $last_updated = date($short_date, strtotime($line["last_updated"]));
2827 $last_updated = htmlspecialchars($last_updated);
2829 $has_img = feed_has_icon($id);
2831 /* $tmp_result = db_query($link,
2832 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2833 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2834 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2835 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2836 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id"); */
2838 $tmp_result = db_query($link,
2839 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2840 WHERE parent_feed = '$id' AND feed_id = id");
2842 $count +
= db_fetch_result($tmp_result, 0, "unread");
2844 if (!$smart_mode ||
$old_counters[$id] != $count) {
2845 $old_counters[$id] = $count;
2846 $fctrs_modified = true;
2849 $error_part = "error=\"$last_error\"";
2855 $has_img_part = "hi=\"$has_img\"";
2860 if ($active_feed && $id == $active_feed) {
2861 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2863 $has_title_part = "";
2866 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2867 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2870 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2874 if ($smart_mode && $fctrs_modified) {
2875 $_SESSION["fctr_last_value"] = $old_counters;
2879 function get_script_dt_add() {
2880 if (strpos(VERSION
, ".99") === false) {
2887 function get_pgsql_version($link) {
2888 $result = db_query($link, "SELECT version() AS version");
2889 $version = split(" ", db_fetch_result($result, 0, "version"));
2893 function print_error_xml($code, $add_msg = "") {
2896 $error_msg = $ERRORS[$code];
2899 $error_msg = "$error_msg; $add_msg";
2902 print "<rpc-reply>";
2903 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2904 print "</rpc-reply>";
2907 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2908 $auth_login = '', $auth_pass = '') {
2910 # check for feed:http://url
2911 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2913 # check for feed://URL
2914 if (strpos($feed_link, "//") === 0) {
2915 $feed_link = "http:$feed_link";
2918 if ($feed_link == "") return;
2920 if ($cat_id == "0" ||
!$cat_id) {
2921 $cat_qpart = "NULL";
2923 $cat_qpart = "'$cat_id'";
2926 $result = db_query($link,
2927 "SELECT id FROM ttrss_feeds
2928 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2930 if (db_num_rows($result) == 0) {
2932 $result = db_query($link,
2933 "INSERT INTO ttrss_feeds
2934 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2935 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2936 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2938 $result = db_query($link,
2939 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2940 AND owner_uid = " . $_SESSION["uid"]);
2942 $feed_id = db_fetch_result($result, 0, "id");
2945 update_rss_feed($link, $feed_link, $feed_id, true);
2954 function print_feed_select($link, $id, $default_id = "",
2955 $attributes = "", $include_all_feeds = true) {
2957 print "<select id=\"$id\" name=\"$id\" $attributes>";
2958 if ($include_all_feeds) {
2959 print "<option value=\"0\">".__('All feeds')."</option>";
2962 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2963 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2965 if (db_num_rows($result) > 0 && $include_all_feeds) {
2966 print "<option disabled>--------</option>";
2969 while ($line = db_fetch_assoc($result)) {
2970 if ($line["id"] == $default_id) {
2971 $is_selected = "selected";
2975 printf("<option $is_selected value='%d'>%s</option>",
2976 $line["id"], htmlspecialchars($line["title"]));
2982 function print_feed_cat_select($link, $id, $default_id = "",
2983 $attributes = "", $include_all_cats = true) {
2985 print "<select id=\"$id\" name=\"$id\" $attributes>";
2987 if ($include_all_cats) {
2988 print "<option value=\"0\">".__('Uncategorized')."</option>";
2991 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2992 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2994 if (db_num_rows($result) > 0 && $include_all_cats) {
2995 print "<option disabled>--------</option>";
2998 while ($line = db_fetch_assoc($result)) {
2999 if ($line["id"] == $default_id) {
3000 $is_selected = "selected";
3004 printf("<option $is_selected value='%d'>%s</option>",
3005 $line["id"], htmlspecialchars($line["title"]));
3011 function checkbox_to_sql_bool($val) {
3012 return ($val == "on") ?
"true" : "false";
3015 function getFeedCatTitle($link, $id) {
3017 return __("Special");
3018 } else if ($id < -10) {
3019 return __("Labels");
3020 } else if ($id > 0) {
3021 $result = db_query($link, "SELECT ttrss_feed_categories.title
3022 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3023 cat_id = ttrss_feed_categories.id");
3024 if (db_num_rows($result) == 1) {
3025 return db_fetch_result($result, 0, "title");
3027 return __("Uncategorized");
3030 return "getFeedCatTitle($id) failed";
3035 function getFeedTitle($link, $id) {
3037 return __("Starred articles");
3038 } else if ($id == -2) {
3039 return __("Published articles");
3040 } else if ($id == -3) {
3041 return __("Fresh articles");
3042 } else if ($id < -10) {
3043 $label_id = -$id - 11;
3044 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
3045 if (db_num_rows($result) == 1) {
3046 return db_fetch_result($result, 0, "description");
3048 return "Unknown label ($label_id)";
3051 } else if ($id > 0) {
3052 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3053 if (db_num_rows($result) == 1) {
3054 return db_fetch_result($result, 0, "title");
3056 return "Unknown feed ($id)";
3059 return "getFeedTitle($id) failed";
3064 function get_session_cookie_name() {
3065 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3068 function print_init_params($link) {
3069 print "<init-params>";
3070 if ($_SESSION["stored-params"]) {
3071 foreach (array_keys($_SESSION["stored-params"]) as $key) {
3073 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
3074 print "<param key=\"$key\" value=\"$value\"/>";
3079 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
3080 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
3081 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
3082 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3084 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
3085 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
3087 print "<param key=\"hide_read_feeds\" value=\"" .
3088 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
3090 print "<param key=\"feeds_sort_by_unread\" value=\"" .
3091 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
3093 print "<param key=\"confirm_feed_catchup\" value=\"" .
3094 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3096 print "<param key=\"cdm_auto_catchup\" value=\"" .
3097 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3099 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3101 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3103 print "<param key=\"default_view_mode\" value=\"" .
3104 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3106 print "<param key=\"default_view_limit\" value=\"" .
3107 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3109 print "<param key=\"default_view_order_by\" value=\"" .
3110 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3112 print "<param key=\"prefs_active_tab\" value=\"" .
3113 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3115 print "<param key=\"infobox_disable_overlay\" value=\"" .
3116 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3118 print "<param key=\"icons_location\" value=\"" .
3121 print "<param key=\"hide_read_shows_special\" value=\"" .
3122 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3124 print "<param key=\"hide_feedlist\" value=\"" .
3125 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3127 print "<param key=\"bw_limit\" value=\"".
3128 (int) $_SESSION["bw_limit"]."\"/>";
3130 // print "<param key=\"sync_counters\" value=\"" .
3131 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3133 print "<param key=\"sync_counters\" value=\"1\"/>";
3135 print "</init-params>";
3138 function print_runtime_info($link) {
3139 print "<runtime-info>";
3141 if (ENABLE_UPDATE_DAEMON
) {
3142 print "<param key=\"daemon_is_running\" value=\"".
3143 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3145 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3147 $stamp = (int)read_stampfile("update_daemon.stamp");
3149 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3152 $stamp_delta = time() - $stamp;
3154 if ($stamp_delta > 1800) {
3158 $_SESSION["daemon_stamp_check"] = time();
3161 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3163 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3165 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3170 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3172 if ($_SESSION["last_version_check"] +
86400 < time()) {
3173 $new_version_details = check_for_update($link);
3175 print "<param key=\"new_version_available\" value=\"".
3176 sprintf("%d", $new_version_details != ""). "\"/>";
3178 $_SESSION["last_version_check"] = time();
3182 // print "<param key=\"new_version_available\" value=\"1\"/>";
3184 print "</runtime-info>";
3187 function getSearchSql($search, $match_on) {
3189 $search_query_part = "";
3191 $keywords = split(" ", $search);
3192 $query_keywords = array();
3194 if ($match_on == "both") {
3196 foreach ($keywords as $k) {
3197 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3198 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3201 $search_query_part = implode("AND", $query_keywords) . " AND ";
3203 } else if ($match_on == "title") {
3205 foreach ($keywords as $k) {
3206 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3209 $search_query_part = implode("AND", $query_keywords) . " AND ";
3211 } else if ($match_on == "content") {
3213 foreach ($keywords as $k) {
3214 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3218 $search_query_part = implode("AND", $query_keywords);
3220 return $search_query_part;
3223 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3225 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3229 $search_query_part = getSearchSql($search, $match_on);
3230 $search_query_part .= " AND ";
3233 $search_query_part = "";
3236 $view_query_part = "";
3238 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3240 $view_query_part = " ";
3241 } else if ($feed != -1) {
3242 $unread = getFeedUnread($link, $feed, $cat_view);
3244 $view_query_part = " unread = true AND ";
3249 if ($view_mode == "marked") {
3250 $view_query_part = " marked = true AND ";
3253 if ($view_mode == "unread") {
3254 $view_query_part = " unread = true AND ";
3258 $limit_query_part = "LIMIT " . $limit;
3261 $vfeed_query_part = "";
3263 // override query strategy and enable feed display when searching globally
3264 if ($search && $search_mode == "all_feeds") {
3265 $query_strategy_part = "ttrss_entries.id > 0";
3266 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3267 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3268 $query_strategy_part = "ttrss_entries.id > 0";
3269 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3270 id = feed_id) as feed_title,";
3271 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3273 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3275 $tmp_result = false;
3278 $tmp_result = db_query($link, "SELECT id
3279 FROM ttrss_feeds WHERE cat_id = '$feed'");
3281 $tmp_result = db_query($link, "SELECT id
3282 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3283 WHERE id = '$feed') AND id != '$feed'");
3286 $cat_siblings = array();
3288 if (db_num_rows($tmp_result) > 0) {
3289 while ($p = db_fetch_assoc($tmp_result)) {
3290 array_push($cat_siblings, "feed_id = " . $p["id"]);
3293 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3294 $feed, implode(" OR ", $cat_siblings));
3297 $query_strategy_part = "ttrss_entries.id > 0";
3300 } else if ($feed >= 0) {
3305 $query_strategy_part = "cat_id = '$feed'";
3307 $query_strategy_part = "cat_id IS NULL";
3310 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3313 $tmp_result = db_query($link, "SELECT id
3314 FROM ttrss_feeds WHERE parent_feed = '$feed'
3315 ORDER BY cat_id,title");
3317 $parent_ids = array();
3319 if (db_num_rows($tmp_result) > 0) {
3320 while ($p = db_fetch_assoc($tmp_result)) {
3321 array_push($parent_ids, "feed_id = " . $p["id"]);
3324 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3325 $feed, implode(" OR ", $parent_ids));
3327 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3329 $query_strategy_part = "feed_id = '$feed'";
3332 } else if ($feed == -1) { // starred virtual feed
3333 $query_strategy_part = "marked = true";
3334 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3335 } else if ($feed == -2) { // published virtual feed
3336 $query_strategy_part = "published = true";
3337 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3338 } else if ($feed == -3) { // fresh virtual feed
3339 $query_strategy_part = "unread = true";
3341 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3343 if (DB_TYPE
== "pgsql") {
3344 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3346 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3349 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3350 } else if ($feed <= -10) { // labels
3351 $label_id = -$feed - 11;
3353 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3354 WHERE id = '$label_id'");
3356 $query_strategy_part = "(" . db_fetch_result($tmp_result, 0, "sql_exp") . ")";
3358 if (!$query_strategy_part) {
3362 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3364 $query_strategy_part = "id > 0"; // dumb
3367 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3368 $order_by = "updated";
3370 $order_by = "updated DESC";
3373 if ($view_mode != "noscores") {
3374 $order_by = "score DESC, $order_by";
3377 if ($override_order) {
3378 $order_by = $override_order;
3383 if ($search && $search_mode == "all_feeds") {
3384 $feed_title = __("Search results")." ($search)";
3385 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3386 $feed_title = __("Search results")." ($search, $feed)";
3387 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3388 $feed_title = $feed;
3389 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3394 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3395 WHERE id = '$feed' AND owner_uid = $owner_uid");
3396 $feed_title = db_fetch_result($result, 0, "title");
3398 $feed_title = __("Uncategorized");
3402 $feed_title = __("Searched for")." $search ($feed_title)";
3407 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3408 WHERE id = '$feed' AND owner_uid = $owner_uid");
3410 $feed_title = db_fetch_result($result, 0, "title");
3411 $feed_site_url = db_fetch_result($result, 0, "site_url");
3412 $last_error = db_fetch_result($result, 0, "last_error");
3415 $feed_title = __("Searched for") . " $search ($feed_title)";
3419 } else if ($feed == -1) {
3420 $feed_title = __("Starred articles");
3421 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3422 } else if ($feed == -2) {
3423 $feed_title = __("Published articles");
3424 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3425 } else if ($feed == -3) {
3426 $feed_title = __("Fresh articles");
3427 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3428 } else if ($feed < -10) {
3429 $label_id = -$feed - 11;
3430 $result = db_query($link, "SELECT description FROM ttrss_labels
3431 WHERE id = '$label_id'");
3432 $feed_title = db_fetch_result($result, 0, "description");
3435 $feed_title = __("Searched for") . " $search ($feed_title)";
3441 if ($feed < -10) error_reporting (0);
3443 $content_query_part = "content as content_preview,";
3445 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3448 $feed_kind = "Feeds";
3450 $feed_kind = "Labels";
3453 if ($limit_query_part) {
3454 $offset_query_part = "OFFSET $offset";
3457 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3458 if (!$override_order) {
3459 $order_by = "ttrss_feeds.title, $order_by";
3462 // Special output for Fresh feed
3464 /* if ($feed == -3) {
3465 $group_limit_part = "(select count(*) from
3466 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3467 t1.ref_id = t2.id and t1.owner_uid = 2 and
3468 t1.feed_id = ttrss_user_entries.feed_id and
3469 t2.updated > ttrss_entries.updated) <= 5 AND";
3475 ttrss_entries.id,ttrss_entries.title,
3477 unread,feed_id,marked,published,link,last_read,
3478 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3481 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3484 ttrss_entries,ttrss_user_entries,ttrss_feeds
3487 ttrss_feeds.hidden = false AND
3488 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3489 ttrss_user_entries.ref_id = ttrss_entries.id AND
3490 ttrss_user_entries.owner_uid = '$owner_uid' AND
3493 $query_strategy_part ORDER BY $order_by
3494 $limit_query_part $offset_query_part";
3496 if ($_GET["debug"]) print $query;
3498 $result = db_query($link, $query);
3503 $feed_kind = "Tags";
3505 $result = db_query($link, "SELECT
3507 ttrss_entries.id as id,title,
3510 marked,link,last_read,
3511 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3514 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3517 ttrss_entries,ttrss_user_entries,ttrss_tags
3519 ref_id = ttrss_entries.id AND
3520 ttrss_user_entries.owner_uid = '$owner_uid' AND
3521 post_int_id = int_id AND tag_name = '$feed' AND
3524 $query_strategy_part ORDER BY $order_by
3525 $limit_query_part");
3528 return array($result, $feed_title, $feed_site_url, $last_error);
3532 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3533 $limit, $search, $search_mode, $match_on) {
3535 if (!$limit) $limit = 30;
3537 $qfh_ret = queryFeedHeadlines($link, $feed,
3538 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3541 $result = $qfh_ret[0];
3542 $feed_title = htmlspecialchars($qfh_ret[1]);
3543 $feed_site_url = $qfh_ret[2];
3544 $last_error = $qfh_ret[3];
3546 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3548 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3549 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3550 <rss version=\"2.0\">
3552 <title>$feed_title</title>
3553 <link>$feed_site_url</link>
3554 <description>Feed generated by Tiny Tiny RSS</description>";
3556 while ($line = db_fetch_assoc($result)) {
3558 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3559 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3561 $tags = get_article_tags($link, $line["id"], $owner_uid);
3563 foreach ($tags as $tag) {
3564 print "<category>" . htmlspecialchars($tag) . "</category>";
3567 $rfc822_date = date('r', strtotime($line["updated"]));
3569 print "<pubDate>$rfc822_date</pubDate>";
3572 htmlspecialchars($line["title"]) . "</title>";
3574 print "<description><![CDATA[" .
3575 $line["content_preview"] . "]]></description>";
3580 print "</channel></rss>";
3584 function getCategoryTitle($link, $cat_id) {
3586 if ($cat_id == -1) {
3587 return __("Special");
3588 } else if ($cat_id == -2) {
3589 return __("Labels");
3592 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3595 if (db_num_rows($result) == 1) {
3596 return db_fetch_result($result, 0, "title");
3598 return "Uncategorized";
3603 // http://ru2.php.net/strip-tags
3605 function strip_tags_long($textstring, $allowed){
3606 while($textstring != strip_tags($textstring, $allowed))
3608 while (strlen($textstring) != 0)
3610 if (strlen($textstring) > 1024) {
3613 $otherlen = strlen($textstring);
3615 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3616 $safetext .= $temptext;
3617 $textstring = substr_replace($textstring,'',0,$otherlen);
3619 $textstring = $safetext;
3625 function sanitize_rss($link, $str, $force_strip_tags = false) {
3628 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3630 $res = strip_tags_long($res,
3631 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3633 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3634 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3637 if (get_pref($link, "STRIP_IMAGES")) {
3639 $res = preg_replace('/<img[^>]+>/is', '', $res);
3647 * Send by mail a digest of last articles.
3649 * @param mixed $link The database connection.
3650 * @param integer $limit The maximum number of articles by digest.
3651 * @return boolean Return false if digests are not enabled.
3653 function send_headlines_digests($link, $limit = 100) {
3655 if (!DIGEST_ENABLE
) return false;
3657 $user_limit = DIGEST_EMAIL_LIMIT
;
3660 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3662 if (DB_TYPE
== "pgsql") {
3663 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3664 } else if (DB_TYPE
== "mysql") {
3665 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3668 $result = db_query($link, "SELECT id,email FROM ttrss_users
3669 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3671 while ($line = db_fetch_assoc($result)) {
3673 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3674 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3676 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3678 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3679 $digest = $tuple[0];
3680 $headlines_count = $tuple[1];
3681 $affected_ids = $tuple[2];
3682 $digest_text = $tuple[3];
3684 if ($headlines_count > 0) {
3686 $mail = new PHPMailer();
3688 $mail->PluginDir
= "phpmailer/";
3689 $mail->SetLanguage("en", "phpmailer/language/");
3691 $mail->CharSet
= "UTF-8";
3693 $mail->From
= DIGEST_FROM_ADDRESS
;
3694 $mail->FromName
= DIGEST_FROM_NAME
;
3695 $mail->AddAddress($line["email"], $line["login"]);
3697 if (DIGEST_SMTP_HOST
) {
3698 $mail->Host
= DIGEST_SMTP_HOST
;
3699 $mail->Mailer
= "smtp";
3700 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3701 $mail->Username
= DIGEST_SMTP_LOGIN
;
3702 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3705 $mail->IsHTML(true);
3706 $mail->Subject
= DIGEST_SUBJECT
;
3707 $mail->Body
= $digest;
3708 $mail->AltBody
= $digest_text;
3710 $rc = $mail->Send();
3712 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3716 if ($rc && $do_catchup) {
3717 print "Marking affected articles as read...\n";
3718 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3721 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3722 WHERE id = " . $line["id"]);
3724 print "No headlines\n";
3729 print "All done.\n";
3733 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3735 require_once "MiniTemplator.class.php";
3737 $tpl = new MiniTemplator
;
3738 $tpl_t = new MiniTemplator
;
3740 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3741 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3743 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3744 $tpl->setVariable('CUR_TIME', date('G:i'));
3746 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3747 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3749 $affected_ids = array();
3751 if (DB_TYPE
== "pgsql") {
3752 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3753 } else if (DB_TYPE
== "mysql") {
3754 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3757 $result = db_query($link, "SELECT ttrss_entries.title,
3758 ttrss_feeds.title AS feed_title,
3760 ttrss_user_entries.ref_id,
3762 SUBSTRING(content, 1, 120) AS excerpt,
3763 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3765 ttrss_user_entries,ttrss_entries,ttrss_feeds
3767 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3768 AND include_in_digest = true
3771 AND ttrss_user_entries.owner_uid = $user_id
3773 ORDER BY ttrss_feeds.title, date_entered DESC
3776 $cur_feed_title = "";
3778 $headlines_count = db_num_rows($result);
3780 $headlines = array();
3782 while ($line = db_fetch_assoc($result)) {
3783 array_push($headlines, $line);
3786 for ($i = 0; $i < sizeof($headlines); $i++
) {
3788 $line = $headlines[$i];
3790 array_push($affected_ids, $line["ref_id"]);
3792 $updated = smart_date_time(strtotime($line["last_updated"]));
3794 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3795 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3796 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3797 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3798 $tpl->setVariable('ARTICLE_EXCERPT',
3799 truncate_string(strip_tags($line["excerpt"]), 100));
3801 $tpl->addBlock('article');
3803 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3804 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3805 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3806 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3807 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3808 // truncate_string(strip_tags($line["excerpt"]), 100));
3810 $tpl_t->addBlock('article');
3812 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3813 $tpl->addBlock('feed');
3814 $tpl_t->addBlock('feed');
3819 $tpl->addBlock('digest');
3820 $tpl->generateOutputToString($tmp);
3822 $tpl_t->addBlock('digest');
3823 $tpl_t->generateOutputToString($tmp_t);
3825 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3828 function check_for_update($link, $brief_fmt = true) {
3829 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3831 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3836 if (ENABLE_SIMPLEPIE
) {
3837 $rss = new SimplePie();
3838 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3839 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3840 $rss->set_feed_url($fetch_url);
3841 $rss->set_output_encoding('UTF-8');
3844 $rss = fetch_rss($releases_feed);
3846 error_reporting (DEFAULT_ERROR_LEVEL
);
3850 if (ENABLE_SIMPLEPIE
) {
3851 $items = $rss->get_items();
3853 $items = $rss->items
;
3855 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3856 if (!$items ||
!is_array($items)) $items = $rss;
3859 if (!is_array($items) ||
count($items) == 0) {
3863 $latest_item = $items[0];
3865 if (ENABLE_SIMPLEPIE
) {
3866 $last_title = $latest_item->get_title();
3868 $last_title = $latest_item["title"];
3871 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3873 if (ENABLE_SIMPLEPIE
) {
3874 $release_url = sanitize_rss($link, $latest_item->get_link());
3875 $content = sanitize_rss($link, $latest_item->get_description());
3877 $release_url = sanitize_rss($link, $latest_item["link"]);
3878 $content = sanitize_rss($link, $latest_item["description"]);
3881 if (version_compare(VERSION
, $latest_version) == -1) {
3883 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3884 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3885 <div id=\"milestoneDetails\">$content</div>");
3887 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3888 <div class='milestoneDetails'>$content</div>
3889 Visit <a target=\"_blank\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3890 download and update information.";
3897 function markArticlesById($link, $ids, $cmode) {
3901 foreach ($ids as $id) {
3902 array_push($tmp_ids, "ref_id = '$id'");
3905 $ids_qpart = join(" OR ", $tmp_ids);
3908 db_query($link, "UPDATE ttrss_user_entries SET
3909 marked = false,last_read = NOW()
3910 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3911 } else if ($cmode == 1) {
3912 db_query($link, "UPDATE ttrss_user_entries SET
3914 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3916 db_query($link, "UPDATE ttrss_user_entries SET
3917 marked = NOT marked,last_read = NOW()
3918 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3922 function publishArticlesById($link, $ids, $cmode) {
3926 foreach ($ids as $id) {
3927 array_push($tmp_ids, "ref_id = '$id'");
3930 $ids_qpart = join(" OR ", $tmp_ids);
3933 db_query($link, "UPDATE ttrss_user_entries SET
3934 published = false,last_read = NOW()
3935 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3936 } else if ($cmode == 1) {
3937 db_query($link, "UPDATE ttrss_user_entries SET
3939 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3941 db_query($link, "UPDATE ttrss_user_entries SET
3942 published = NOT published,last_read = NOW()
3943 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3947 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3949 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3953 foreach ($ids as $id) {
3954 array_push($tmp_ids, "ref_id = '$id'");
3957 $ids_qpart = join(" OR ", $tmp_ids);
3960 db_query($link, "UPDATE ttrss_user_entries SET
3961 unread = false,last_read = NOW()
3962 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3963 } else if ($cmode == 1) {
3964 db_query($link, "UPDATE ttrss_user_entries SET
3966 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3968 db_query($link, "UPDATE ttrss_user_entries SET
3969 unread = NOT unread,last_read = NOW()
3970 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3975 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3976 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3978 while ($line = db_fetch_assoc($result)) {
3979 ccache_update($link, $line["feed_id"], $owner_uid);
3983 function catchupArticleById($link, $id, $cmode) {
3986 db_query($link, "UPDATE ttrss_user_entries SET
3987 unread = false,last_read = NOW()
3988 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3989 } else if ($cmode == 1) {
3990 db_query($link, "UPDATE ttrss_user_entries SET
3992 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3994 db_query($link, "UPDATE ttrss_user_entries SET
3995 unread = NOT unread,last_read = NOW()
3996 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4000 function make_guid_from_title($title) {
4001 return preg_replace("/[ \"\',.:;]/", "-",
4002 mb_strtolower(strip_tags($title), 'utf-8'));
4005 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4006 $bottom = false, $rtl_content = false, $feed_id = 0,
4007 $is_cat = false, $search = false, $match_on = false,
4008 $search_mode = false, $offset = 0, $limit = 0,
4009 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
4011 $user_page_offset = $offset +
1;
4014 $class = "headlinesSubToolbar";
4015 $tid = "headlineActionsTop";
4017 $class = "headlinesSubToolbar";
4018 $tid = "headlineActionsBottom";
4021 print "<nobr><table class=\"$class\" id=\"$tid\"
4022 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
4030 $page_prev_link = "javascript:viewFeedGoPage(-1)";
4031 $page_next_link = "javascript:viewFeedGoPage(1)";
4032 $page_first_link = "javascript:viewFeedGoPage(0)";
4034 $catchup_page_link = "javascript:catchupPage()";
4035 $catchup_feed_link = "javascript:catchupCurrentFeed()";
4036 $catchup_sel_link = "javascript:catchupSelection()";
4038 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4040 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
4041 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
4042 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
4043 $sel_inv_link = "javascript:invertHeadlineSelection()";
4045 $tog_unread_link = "javascript:selectionToggleUnread()";
4046 $tog_marked_link = "javascript:selectionToggleMarked()";
4047 $tog_published_link = "javascript:selectionTogglePublished()";
4051 $sel_all_link = "javascript:cdmSelectArticles('all')";
4052 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
4053 $sel_none_link = "javascript:cdmSelectArticles('none')";
4055 $sel_inv_link = "javascript:invertHeadlineSelection()";
4057 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4058 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4059 $tog_published_link = "javascript:selectionTogglePublished(true)";
4063 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
4065 print "<td class=\"headlineActions$rtl_cpart\">
4066 <ul class=\"headlineDropdownMenu\">
4069 <a href=\"$sel_all_link\">".__('All')."</a>,
4070 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4071 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4072 <a href=\"$sel_none_link\">".__('None')."</a></li>
4073 <li class=\"vsep\"> </li>
4074 <li class=\"top\">".__('Actions...')."<ul>
4075 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
4076 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4077 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4078 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4079 <li><span class=\"insensitive\">--------</span></li>
4080 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
4081 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4083 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4086 <li onclick=\"catchupRelativeToArticle(0)\"> ".__("Above active article")."</li>
4087 <li onclick=\"catchupRelativeToArticle(1)\"> ".__("Below active article")."</li>";
4090 <li><span class=\"insensitive\"> ".__("Above active article")."</span></li>
4091 <li><span class=\"insensitive\"> ".__("Below active article")."</span></li>";
4095 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4097 print "<li><span class=\"insensitive\">--------</span></li>";
4098 print "<li><span class=\"insensitive\">".__('Other actions:')."</span></li>";
4101 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4103 <li onclick=\"javascript:labelFromSearch('$search', '$search_mode',
4104 '$match_on', '$feed_id', '$is_cat');\">
4105 ".__('Search to label')."</li>";
4107 print "<li><span class=\"insensitive\"> ".__('Search to label')."</li>";
4111 print "</ul></li></ul>";
4115 // old style subtoolbar:
4117 print "<td class=\"headlineActions$rtl_cpart\">".
4119 <a href=\"$sel_all_link\">".__('All')."</a>,
4120 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4121 <a href=\"$sel_none_link\">".__('None')."</a>
4123 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4124 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4126 __('Mark as read:')."
4127 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4128 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4130 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
4133 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
4134 '$match_on', '$feed_id', '$is_cat');\">
4135 ".__('Convert to label')."</a>";
4142 print "<td class=\"headlineTitle$rtl_cpart\">";
4144 print "<span id=\"subtoolbar_search\"
4145 style=\"display : none\"><input
4146 id=\"subtoolbar_search_box\"
4147 onblur=\"javascript:enableHotkeys();\"
4148 onfocus=\"javascript:disableHotkeys();\"
4149 onchange=\"subtoolbarSearch()\"
4150 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4152 print "<span id=\"subtoolbar_ftitle\">";
4154 if ($feed_site_url) {
4156 $target = "target=\"_blank\"";
4158 print "<a $target href=\"$feed_site_url\">".
4159 truncate_string($feed_title,30)."</a>";
4165 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4168 if ($user_page_offset > 1) {
4169 print " [$user_page_offset] ";
4172 if (!$bottom && !$disable_feed) {
4174 <a target=\"_blank\"
4175 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4176 <img class=\"noborder\"
4177 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4179 } else if ($feed_small_icon) {
4180 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4186 print "</tr></table></nobr>";
4190 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4192 $tmp_category = getCategoryTitle($link, $cat_id);
4195 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4197 $cat_unread = getCategoryUnread($link, $cat_id);
4201 $holder_style = "display:none;";
4208 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4211 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4212 $inner_title_class = "catTitle";
4214 $browse_cat_link = "";
4215 $inner_title_class = "catTitleNL";
4219 $cat_class = "feedCat";
4221 $cat_class = "virtCat";
4224 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4225 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4226 title=\"".__('Click to collapse category')."\"
4227 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4228 id=\"FCATN-$cat_id\" $browse_cat_link
4229 \">$tmp_category</span>";
4231 print "<span id=\"FCAP-$cat_id\">";
4233 print " <span id=\"FCATCTR-$cat_id\"
4234 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4240 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4244 function outputFeedList($link, $tags = false) {
4246 print "<ul class=\"feedList\" id=\"feedList\">";
4248 $owner_uid = $_SESSION["uid"];
4252 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4254 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4257 $cat_hidden = false;
4260 printCategoryHeader($link, -1, $cat_hidden, false);
4263 $num_starred = getFeedUnread($link, -1);
4264 $num_published = getFeedUnread($link, -2);
4265 $num_fresh = getFeedUnread($link, -3);
4269 if ($num_fresh > 0) $class .= "Unread";
4271 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4272 "images/fresh.png", $link);
4276 if ($num_starred > 0) $class .= "Unread";
4278 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4281 $mark_img_ext = "gif";
4283 $mark_img_ext = "png";
4286 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4287 "images/mark_set.$mark_img_ext", $link);
4291 if ($num_published > 0) $class .= "Unread";
4293 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4294 "images/pub_set.gif", $link);
4296 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4302 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4304 $result = db_query($link, "SELECT id,sql_exp,description FROM
4305 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4307 if (db_num_rows($result) > 0) {
4308 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4310 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4313 $cat_hidden = false;
4316 printCategoryHeader($link, -2, $cat_hidden, false);
4319 print "<li><hr></li>";
4323 while ($line = db_fetch_assoc($result)) {
4325 error_reporting (0);
4327 $label_id = -$line['id'] - 11;
4328 $count = getFeedUnread($link, $label_id);
4336 error_reporting (DEFAULT_ERROR_LEVEL
);
4338 printFeedEntry($label_id,
4339 $class, $line["description"],
4340 $count, "images/label.png", $link);
4344 if (db_num_rows($result) > 0) {
4345 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4352 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4353 print "<li><hr></li>";
4356 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4357 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4358 $order_by_qpart = "order_id,category,unread DESC,title";
4360 $order_by_qpart = "order_id,category,title";
4363 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4364 $order_by_qpart = "unread DESC,title";
4366 $order_by_qpart = "title";
4370 $age_qpart = getMaxAgeSubquery();
4372 $query = "SELECT ttrss_feeds.*,
4373 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4375 ttrss_feed_categories.title AS category,
4376 ttrss_feed_categories.collapsed
4377 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4378 ON (ttrss_feed_categories.id = cat_id)
4380 ttrss_feeds.hidden = false AND
4381 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4382 ORDER BY $order_by_qpart";
4384 $result = db_query($link, $query);
4386 $actid = $_GET["actid"];
4396 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4398 while ($line = db_fetch_assoc($result)) {
4400 $feed = trim($line["title"]);
4402 if (!$feed) $feed = "[Untitled]";
4404 $feed_id = $line["id"];
4406 $subop = $_GET["subop"];
4408 $unread = ccache_find($link, $feed_id, $_SESSION["uid"]);
4410 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4411 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4413 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4416 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4419 $rtl_tag = "dir=\"RTL\"";
4424 $tmp_result = db_query($link,
4425 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4426 WHERE parent_feed = '$feed_id' AND feed_id = id");
4428 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4430 $cat_id = $line["cat_id"];
4432 $tmp_category = $line["category"];
4434 if (!$tmp_category) {
4435 $tmp_category = __("Uncategorized");
4438 // $class = ($lnum % 2) ? "even" : "odd";
4440 if ($line["last_error"]) {
4446 if ($unread > 0) $class .= "Unread";
4448 if ($actid == $feed_id) {
4449 $class .= "Selected";
4452 $total_unread +
= $unread;
4454 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4460 $category = $tmp_category;
4462 $collapsed = sql_bool_to_bool($line["collapsed"]);
4464 // workaround for NULL category
4465 if ($category == __("Uncategorized")) {
4466 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4471 $cat_id = sprintf("%d", $cat_id);
4473 printCategoryHeader($link, $cat_id, $collapsed, true);
4477 printFeedEntry($feed_id, $class, $feed, $unread,
4478 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4479 $last_updated, $line["last_error"]);
4484 if (db_num_rows($result) == 0) {
4485 print "<li>".__('No feeds to display.')."</li>";
4492 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4493 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4494 post_int_id = ttrss_user_entries.int_id AND
4495 unread = true AND ref_id = ttrss_entries.id
4496 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4498 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4499 ORDER BY tag_name"); */
4501 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4502 print "<li class=\"feedCat\">".__('Tags')."</li>";
4503 print "<ul class=\"feedCatList\">";
4506 $age_qpart = getMaxAgeSubquery();
4508 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4509 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4510 AND ref_id = id AND $age_qpart
4511 AND unread = true)) AS count FROM ttrss_tags
4512 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4513 ORDER BY count DESC LIMIT 50");
4517 while ($line = db_fetch_assoc($result)) {
4518 $tags[$line["tag_name"]] +
= $line["count"];
4521 foreach (array_keys($tags) as $tag) {
4523 $unread = $tags[$tag];
4531 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4535 if (db_num_rows($result) == 0) {
4536 print "<li>No tags to display.</li>";
4539 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4549 function get_article_tags($link, $id, $owner_uid = 0) {
4551 $a_id = db_escape_string($id);
4553 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4555 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4556 owner_uid as owner FROM
4557 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4558 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4562 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4563 array_push($tags, $tmp_line["tag_name"]);
4569 function trim_value(&$value) {
4570 $value = trim($value);
4573 function trim_array($array) {
4575 array_walk($tmp, 'trim_value');
4579 function tag_is_valid($tag) {
4580 if ($tag == '') return false;
4581 if (preg_match("/^[0-9]*$/", $tag)) return false;
4583 if (function_exists('iconv')) {
4584 $tag = iconv("utf-8", "utf-8", $tag);
4587 if (!$tag) return false;
4592 function render_login_form($link, $mobile = false) {
4594 require_once "login_form.php";
4596 require_once "mobile/login_form.php";
4600 // from http://developer.apple.com/internet/safari/faq.html
4601 function no_cache_incantation() {
4602 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4603 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4604 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4605 header("Cache-Control: post-check=0, pre-check=0", false);
4606 header("Pragma: no-cache"); // HTTP/1.0
4609 function format_warning($msg, $id = "") {
4610 return "<div class=\"warning\" id=\"$id\">
4611 <img src=\"images/sign_excl.gif\">$msg</div>";
4614 function format_notice($msg) {
4615 return "<div class=\"notice\">
4616 <img src=\"images/sign_info.gif\">$msg</div>";
4619 function format_error($msg) {
4620 return "<div class=\"error\">
4621 <img src=\"images/sign_excl.gif\">$msg</div>";
4624 function print_notice($msg) {
4625 return print format_notice($msg);
4628 function print_warning($msg) {
4629 return print format_warning($msg);
4632 function print_error($msg) {
4633 return print format_error($msg);
4637 function T_sprintf() {
4638 $args = func_get_args();
4639 return vsprintf(__(array_shift($args)), $args);
4642 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4643 $zoom_mode = false) {
4645 /* we can figure out feed_id from article id anyway, why do we
4646 * pass feed_id here? */
4648 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4649 WHERE ref_id = '$id'");
4651 $feed_id = db_fetch_result($result, 0, "feed_id");
4653 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4655 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4656 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4658 if (db_num_rows($result) == 1) {
4659 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4661 $rtl_content = false;
4665 $rtl_tag = "dir=\"RTL\"";
4672 if ($mark_as_read) {
4673 $result = db_query($link, "UPDATE ttrss_user_entries
4674 SET unread = false,last_read = NOW()
4675 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4677 ccache_update($link, $feed_id, $_SESSION["uid"]);
4680 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4681 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4682 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4685 FROM ttrss_entries,ttrss_user_entries
4686 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4692 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4693 $link_target = "target=\"_blank\"";
4696 $line = db_fetch_assoc($result);
4698 if ($line["icon_url"]) {
4699 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4701 $feed_icon = " ";
4704 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4705 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4707 $entry_comments = "";
4710 $num_comments = $line["num_comments"];
4711 $entry_comments = "";
4713 if ($num_comments > 0) {
4714 if ($line["comments"]) {
4715 $comments_url = $line["comments"];
4717 $comments_url = $line["link"];
4719 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4721 if ($line["comments"] && $line["link"] != $line["comments"]) {
4722 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4727 header("Content-Type: text/html");
4729 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4730 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4731 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4736 print "<div class=\"postReply\">";
4738 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4739 onmouseout=\"enable_resize(false)\">";
4741 $entry_author = $line["author"];
4743 if ($entry_author) {
4744 $entry_author = __(" - ") . $entry_author;
4747 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4748 strtotime($line["updated"]));
4750 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4752 if ($line["link"]) {
4753 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4754 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4756 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4759 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4760 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4761 ORDER BY tag_name"); */
4763 $tags = get_article_tags($link, $id);
4766 $tags_nolinks_str = "";
4771 if ($_SESSION["theme"] == "3pane") {
4777 foreach ($tags as $tag) {
4779 $tag_escaped = str_replace("'", "\\'", $tag);
4781 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4783 if ($num_tags == $tag_limit) {
4784 $tags_str .= "…";
4785 $tags_nolinks_str .= "…";
4787 } else if ($num_tags < $tag_limit) {
4788 $tags_str .= $tag_str;
4789 $tags_nolinks_str .= "$tag, ";
4791 $f_tags_str .= $tag_str;
4794 $tags_str = preg_replace("/, $/", "", $tags_str);
4795 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4796 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4798 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4799 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4801 if (!$entry_comments) $entry_comments = " "; # placeholder
4803 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4804 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4806 print "<div style='float : right'>
4807 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4811 <a title=\"".__('Edit tags for this article')."\"
4812 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4814 if (defined('_ENABLE_INLINE_VIEW')) {
4816 print "<img src=\"images/art-inline.png\" class='tagsPic'
4817 style=\"cursor : pointer\" style=\"cursor : pointer\"
4818 onclick=\"showOriginalArticleInline($id)\"
4819 alt='Inline' title='".__('Display original article content')."'>";
4823 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4824 style=\"cursor : pointer\" style=\"cursor : pointer\"
4825 onclick=\"zoomToArticle($id)\"
4826 alt='Zoom' title='".__('Show article summary in new window')."'>";
4828 print "$tags_nolinks_str";
4831 print "<div clear='both'>$entry_comments</div>";
4835 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4836 print "<div class=\"postContent\">";
4838 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4840 $article_content = sanitize_rss($link, $line["content"]);
4842 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4843 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4847 print $article_content;
4849 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4850 post_id = '$id' AND content_url != ''");
4852 if (db_num_rows($result) > 0) {
4854 $entries_html = array();
4857 while ($line = db_fetch_assoc($result)) {
4859 $url = $line["content_url"];
4860 $ctype = $line["content_type"];
4862 if (!$ctype) $ctype = __("unknown type");
4864 $filename = substr($url, strrpos($url, "/")+
1);
4868 if (($ctype == __("audio/mpeg")) &&
4869 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4871 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
4875 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4876 $filename . " (" . $ctype . ")" . "</a>";
4878 array_push($entries_html, $entry);
4882 $entry["type"] = $ctype;
4883 $entry["filename"] = $filename;
4884 $entry["url"] = $url;
4886 array_push($entries, $entry);
4889 print "<div class=\"postEnclosures\">";
4891 if (!preg_match("/img/i", $article_content)) {
4892 foreach ($entries as $entry) {
4893 if (preg_match("/image/", $entry["type"])) {
4895 alt=\"".htmlspecialchars($entry["filename"])."\"
4896 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4901 print "<div class=\"postEnclosures\">";
4903 if (db_num_rows($result) == 1) {
4904 print __("Attachment:") . " ";
4906 print __("Attachments:") . " ";
4909 print join(", ", $entries_html);
4921 print "]]></article>";
4924 <div style=\"text-align : center\">
4925 <input type=\"submit\" onclick=\"return window.close()\"
4926 value=\"".__("Close this window")."\"></div>";
4927 print "</body></html>";
4933 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4934 $next_unread_feed, $offset, $vgr_last_feed = false,
4935 $override_order = false) {
4937 $disable_cache = false;
4939 $timing_info = getmicrotime();
4941 $topmost_article_ids = array();
4947 if ($subop == "undefined") $subop = "";
4949 $subop_split = split(":", $subop);
4951 if ($subop == "CatchupSelected") {
4952 $ids = split(",", db_escape_string($_GET["ids"]));
4953 $cmode = sprintf("%d", $_GET["cmode"]);
4955 catchupArticlesById($link, $ids, $cmode);
4958 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4959 update_generic_feed($link, $feed, $cat_view, true);
4962 if ($subop == "MarkAllRead") {
4963 catchup_feed($link, $feed, $cat_view);
4965 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4966 if ($next_unread_feed) {
4967 $feed = $next_unread_feed;
4972 if ($subop_split[0] == "MarkAllReadGR") {
4973 catchup_feed($link, $subop_split[1], false);
4978 $result = db_query($link,
4979 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4981 if (db_num_rows($result) == 0) {
4982 print "<div align='center'>".__('Feed not found.')."</div>";
4987 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4989 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4990 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4992 if (db_num_rows($result) == 1) {
4993 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4995 $rtl_content = false;
4999 $rtl_tag = "dir=\"RTL\"";
5005 $rtl_content = false;
5008 $script_dt_add = get_script_dt_add();
5010 /// START /////////////////////////////////////////////////////////////////////////////////
5012 $search = db_escape_string($_GET["query"]);
5015 $disable_cache = true;
5018 $search_mode = db_escape_string($_GET["search_mode"]);
5019 $match_on = db_escape_string($_GET["match_on"]);
5025 $real_offset = $offset * $limit;
5027 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5029 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
5030 $search, $search_mode, $match_on, $override_order, $real_offset);
5032 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5034 $result = $qfh_ret[0];
5035 $feed_title = $qfh_ret[1];
5036 $feed_site_url = $qfh_ret[2];
5037 $last_error = $qfh_ret[3];
5039 $vgroup_last_feed = $vgr_last_feed;
5042 $feed_site_url = article_publish_url($link);
5045 /// STOP //////////////////////////////////////////////////////////////////////////////////
5048 print "<div id=\"headlinesContainer\" $rtl_tag>";
5051 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
5055 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
5056 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
5059 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
5062 $headlines_count = db_num_rows($result);
5064 if (db_num_rows($result) > 0) {
5066 # print "\{$offset}";
5068 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5069 print "<table class=\"headlinesList\" id=\"headlinesList\"
5070 cellspacing=\"0\">";
5073 $lnum = $limit*$offset;
5075 error_reporting (DEFAULT_ERROR_LEVEL
);
5078 $cur_feed_title = '';
5080 while ($line = db_fetch_assoc($result)) {
5082 $class = ($lnum %
2) ?
"even" : "odd";
5085 $feed_id = $line["feed_id"];
5087 if (count($topmost_article_ids) < 5) {
5088 array_push($topmost_article_ids, $id);
5091 if ($line["last_read"] == "" &&
5092 ($line["unread"] != "t" && $line["unread"] != "1")) {
5094 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5097 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5101 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5109 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5112 $mark_img_ext = "gif";
5114 $mark_img_ext = "png";
5117 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5118 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5120 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5122 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5124 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5127 if ($line["published"] == "t" ||
$line["published"] == "1") {
5128 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5130 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5132 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5134 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5137 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5138 # $line["title"] . "</a>";
5140 # $content_link = "<a
5141 # href=\"" . htmlspecialchars($line["link"]) . "\"
5142 # onclick=\"view($id,$feed_id);\">" .
5143 # $line["title"] . "</a>";
5145 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5146 # $line["title"] . "</a>";
5148 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5149 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5151 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5152 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5155 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5156 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5160 $score = $line["score"];
5162 $score_pic = get_score_pic($score);
5164 $score_title = __("(Click to change)");
5166 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5167 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">";
5171 } else if ($score < -100) {
5177 $entry_author = $line["author"];
5179 if ($entry_author) {
5180 $entry_author = " - $entry_author";
5183 $has_feed_icon = feed_has_icon($feed_id);
5185 if ($has_feed_icon) {
5186 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5188 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5189 $feed_icon_img = "";
5192 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5194 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5195 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5197 $cur_feed_title = $line["feed_title"];
5198 $vgroup_last_feed = $feed_id;
5200 $cur_feed_title = htmlspecialchars($cur_feed_title);
5202 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5204 print "<tr class='feedTitle'><td colspan='7'>".
5205 "<div style=\"float : right\">$feed_icon_img</div>".
5206 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5207 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5211 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5212 onmouseout='postMouseOut($id)'";
5214 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5216 print "<td class='hlUpdPic'>$update_pic</td>";
5218 print "<td class='hlSelectRow'>
5219 <input type=\"checkbox\" onclick=\"tSR(this)\"
5223 print "<td class='hlMarkedPic'>$marked_pic</td>";
5224 print "<td class='hlMarkedPic'>$published_pic</td>";
5226 # if ($line["feed_title"]) {
5227 # print "<td class='hlContent'>$content_link</td>";
5228 # print "<td class='hlFeed'>
5229 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5230 # truncate_string($line["feed_title"],30)."</a> </td>";
5233 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5235 print "<a id=\"RTITLE-$id\"
5236 href=\"" . htmlspecialchars($line["link"]) . "\"
5237 onclick=\"return view($id,$feed_id);\">" .
5240 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5241 if ($content_preview) {
5242 print "<span class=\"contentPreview\"> - $content_preview</span>";
5248 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5249 # $line["feed_title"]."</a>
5251 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5252 if ($line["feed_title"]) {
5253 print "<span class=\"hlFeed\">
5254 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5255 $line["feed_title"]."</a>)
5263 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5265 print "<td class='hlMarkedPic'>$score_pic</td>";
5267 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5268 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5275 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5276 if ($feed_id != $vgroup_last_feed) {
5278 $cur_feed_title = $line["feed_title"];
5279 $vgroup_last_feed = $feed_id;
5281 $cur_feed_title = htmlspecialchars($cur_feed_title);
5283 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5285 $has_feed_icon = feed_has_icon($feed_id);
5287 if ($has_feed_icon) {
5288 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5290 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5293 print "<div class='cdmFeedTitle'>".
5294 "<div style=\"float : right\">$feed_icon_img</div>".
5295 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5296 $line["feed_title"]."</a> $vf_catchup_link</div>";
5301 $add_class = "Unread";
5306 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5307 $show_excerpt = false;
5309 if ($expand_cdm && $score >= -100) {
5311 $show_excerpt = false;
5313 $cdm_cstyle = "style=\"display : none\"";
5314 $show_excerpt = true;
5317 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5318 onmouseout='postMouseOut($id)'";
5320 print "<div class=\"cdmArticle$add_class\"
5322 $mouseover_attrs'>";
5324 print "<div class=\"cdmHeader\">";
5326 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5327 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5330 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5333 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5334 onclick=\"javascript:toggleUnread($id, 0)\"
5335 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5338 print $entry_author;
5340 /* if (!$expand_cdm || $score < -100) {
5341 print " <a id=\"CICH-$id\"
5342 href=\"javascript:cdmExpandArticle($id)\">
5343 (".__('Show article').")</a>";
5347 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5348 if ($line["feed_title"]) {
5349 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5353 print "</span></div>";
5355 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5356 $line["content_preview"] = preg_replace("/href=/i",
5357 "target=\"_blank\" href=", $line["content_preview"]);
5360 if ($show_excerpt) {
5361 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5362 onclick=\"cdmExpandArticle($id)\"
5363 title=\"".__('Click to expand article')."\">";
5364 print truncate_string(strip_tags($line["content_preview"]), 100);
5368 print "<div class=\"cdmContent\"
5369 onclick=\"cdmClicked($id)\"
5370 id=\"CICD-$id\" $cdm_cstyle>";
5372 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5374 print sanitize_rss($link, $line["content_preview"]);
5375 $article_content = $line["content_preview"];
5377 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5378 post_id = '$id' AND content_url != ''");
5380 if (db_num_rows($e_result) > 0) {
5382 $entries_html = array();
5385 while ($e_line = db_fetch_assoc($e_result)) {
5387 $url = $e_line["content_url"];
5388 $ctype = $e_line["content_type"];
5389 if (!$ctype) $ctype = __("unknown type");
5391 $filename = substr($url, strrpos($url, "/")+
1);
5395 if (($ctype == __("audio/mpeg")) &&
5396 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5398 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
5402 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5403 $filename . " (" . $ctype . ")" . "</a>";
5405 array_push($entries_html, $entry);
5409 $entry["type"] = $ctype;
5410 $entry["filename"] = $filename;
5411 $entry["url"] = $url;
5413 array_push($entries, $entry);
5416 if (!preg_match("/img/i", $article_content)) {
5417 foreach ($entries as $entry) {
5418 if (preg_match("/image/", $entry["type"])) {
5420 alt=\"".htmlspecialchars($entry["filename"])."\"
5421 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5426 print "<div class=\"cdmEnclosures\">";
5428 if (db_num_rows($e_result) == 1) {
5429 print __("Attachment:") . " ";
5431 print __("Attachments:") . " ";
5434 print join(", ", $entries_html);
5440 print "<br clear='both'>";
5443 /* if (!$expand_cdm) {
5444 print "<a id=\"CICH-$id\"
5445 href=\"javascript:cdmExpandArticle($id)\">
5451 print "<div class=\"cdmFooter\"><span class='s0'>";
5453 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5455 print __("Select:").
5456 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5457 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5459 print "</span><span class='s1'>$marked_pic</span> ";
5460 print "<span class='s1'>$published_pic</span> ";
5461 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5462 onclick=\"zoomToArticle($id)\"
5463 style=\"cursor : pointer\"
5465 title='".__('Show article summary in new window')."'></span>";
5467 $tags = get_article_tags($link, $id);
5470 $full_tags_str = "";
5473 foreach ($tags as $tag) {
5475 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5476 if ($num_tags < 5) {
5477 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5478 } else if ($num_tags == 5) {
5479 $tags_str .= "…";
5483 $tags_str = preg_replace("/, $/", "", $tags_str);
5484 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5486 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5488 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5491 if ($tags_str == "") $tags_str = "no tags";
5493 // print "<img src='images/tag.png' class='markedPic'>";
5495 print "<span class='s1'>
5496 <img class='tagsPic' src='images/tag.png' alt='Tags'
5497 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5498 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5502 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5503 href=\"javascript:toggleUnread($id)\">
5514 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5518 // print_headline_subtoolbar($link,
5519 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5525 switch ($view_mode) {
5527 $message = __("No unread articles found to display.");
5530 $message = __("No starred articles found to display.");
5533 $message = __("No articles found to display.");
5536 if (!$offset) print "<div class='whiteBox'>$message</div>";
5544 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5547 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5549 function printTagCloud($link) {
5551 /* get first ref_id to count from */
5557 if (DB_TYPE == "pgsql") {
5558 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5559 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5560 AND date_entered > NOW() - INTERVAL '30 days'";
5562 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5563 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5564 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5567 $result = db_query($link, $query);
5568 $first_id = db_fetch_result($result, 0, "id"); */
5570 //AND post_int_id >= '$first_id'
5571 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5572 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5573 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5575 $result = db_query($link, $query);
5579 while ($line = db_fetch_assoc($result)) {
5580 $tags[$line["tag_name"]] = $line["count"];
5585 $max_size = 32; // max font size in pixels
5586 $min_size = 11; // min font size in pixels
5588 // largest and smallest array values
5589 $max_qty = max(array_values($tags));
5590 $min_qty = min(array_values($tags));
5592 // find the range of values
5593 $spread = $max_qty - $min_qty;
5594 if ($spread == 0) { // we don't want to divide by zero
5598 // set the font-size increment
5599 $step = ($max_size - $min_size) / ($spread);
5601 // loop through the tag array
5602 foreach ($tags as $key => $value) {
5603 // calculate font-size
5604 // find the $value in excess of $min_qty
5605 // multiply by the font-size increment ($size)
5606 // and add the $min_size set above
5607 $size = round($min_size +
(($value - $min_qty) * $step));
5609 $key_escaped = str_replace("'", "\\'", $key);
5611 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5612 $size . "px\" title=\"$value articles tagged with " .
5613 $key . '">' . $key . '</a> ';
5617 function print_checkpoint($n, $s) {
5618 $ts = getmicrotime();
5619 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5623 function sanitize_tag($tag) {
5626 $tag = mb_strtolower($tag, 'utf-8');
5628 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5630 // $tag = str_replace('"', "", $tag);
5631 // $tag = str_replace("+", " ", $tag);
5632 $tag = str_replace("technorati tag: ", "", $tag);
5637 function generate_publish_key() {
5638 return sha1(uniqid(rand(), true));
5641 function article_publish_url($link) {
5646 if ($_SERVER['HTTPS'] != "on") {
5647 $url_path = "http://";
5649 $url_path = "https://";
5652 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5653 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5659 * Purge a feed contents, marked articles excepted.
5661 * @param mixed $link The database connection.
5662 * @param integer $id The id of the feed to purge.
5665 function clear_feed_articles($link, $id) {
5666 $result = db_query($link, "DELETE FROM ttrss_user_entries
5667 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5669 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5670 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5671 } // function clear_feed_articles
5674 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5676 * @return string The Mozilla Firefox feed adding URL.
5678 function add_feed_url() {
5679 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5680 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5682 } // function add_feed_url
5685 * Encrypt a password in SHA1.
5687 * @param string $pass The password to encrypt.
5688 * @param string $login A optionnal login.
5689 * @return string The encrypted password.
5691 function encrypt_password($pass, $login = '') {
5693 return "SHA1X:" . sha1("$login:$pass");
5695 return "SHA1:" . sha1($pass);
5697 } // function encrypt_password
5700 * Update a feed batch.
5701 * Used by daemons to update n feeds by run.
5702 * Only update feed needing a update, and not being processed
5703 * by another process.
5705 * @param mixed $link Database link
5706 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5707 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5708 * @param boolean $debug Set to false to disable debug output. Default to true.
5711 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5712 // Process all other feeds using last_updated and interval parameters
5714 // Test if the user has loggued in recently. If not, it does not update its feeds.
5715 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5716 if (DB_TYPE
== "pgsql") {
5717 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5719 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5722 $login_thresh_qpart = "";
5725 // Test if the feed need a update (update interval exceded).
5726 if (DB_TYPE
== "pgsql") {
5727 $update_limit_qpart = "AND ((
5728 ttrss_feeds.update_interval = 0
5729 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5731 ttrss_feeds.update_interval > 0
5732 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5733 ) OR ttrss_feeds.last_updated IS NULL)";
5735 $update_limit_qpart = "AND ((
5736 ttrss_feeds.update_interval = 0
5737 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5739 ttrss_feeds.update_interval > 0
5740 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5741 ) OR ttrss_feeds.last_updated IS NULL)";
5744 // Test if feed is currently being updated by another process.
5745 if (DB_TYPE
== "pgsql") {
5746 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5748 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5751 // Test if there is a limit to number of updated feeds
5753 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5755 $random_qpart = sql_random_function();
5757 // We search for feed needing update.
5758 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5759 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5760 ttrss_feeds.update_interval
5762 ttrss_feeds, ttrss_users, ttrss_user_prefs
5764 ttrss_feeds.owner_uid = ttrss_users.id
5765 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5766 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5767 $login_thresh_qpart $update_limit_qpart
5768 $updstart_thresh_qpart
5769 ORDER BY $random_qpart $query_limit");
5771 $user_prefs_cache = array();
5773 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5775 // Here is a little cache magic in order to minimize risk of double feed updates.
5776 $feeds_to_update = array();
5777 while ($line = db_fetch_assoc($result)) {
5778 $feeds_to_update[$line['id']] = $line;
5781 // We update the feed last update started date before anything else.
5782 // There is no lag due to feed contents downloads
5783 // It prevent an other process to update the same feed.
5784 $feed_ids = array_keys($feeds_to_update);
5786 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5787 WHERE id IN (%s)", implode(',', $feed_ids)));
5790 // For each feed, we call the feed update function.
5791 while ($line = array_pop($feeds_to_update)) {
5793 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5795 // We setup a alarm to alert if the feed take more than 300s to update.
5797 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5798 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5799 // Cancel the alarm (the update went well)
5800 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5802 sleep(1); // prevent flood (FIXME make this an option?)
5805 // Send feed digests by email if needed.
5806 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5808 } // function update_daemon_common
5810 function sanitize_article_content($text) {
5811 # we don't support CDATA sections in articles, they break our own escaping
5812 $text = preg_replace("/\[\[CDATA/", "", $text);
5813 $text = preg_replace("/\]\]\>/", "", $text);
5817 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5820 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5822 $result = db_query($link, "SELECT reg_exp,
5823 ttrss_filter_types.name AS name,
5824 ttrss_filter_actions.name AS action,
5828 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5831 owner_uid = $owner_uid AND
5832 ttrss_filter_types.id = filter_type AND
5833 ttrss_filter_actions.id = action_id AND
5834 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5836 while ($line = db_fetch_assoc($result)) {
5837 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5838 $filter["reg_exp"] = $line["reg_exp"];
5839 $filter["action"] = $line["action"];
5840 $filter["action_param"] = $line["action_param"];
5841 $filter["filter_param"] = $line["filter_param"];
5842 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5844 array_push($filters[$line["name"]], $filter);
5850 function get_score_pic($score) {
5852 return "score_high.png";
5853 } else if ($score > 0) {
5854 return "score_half_high.png";
5855 } else if ($score < -100) {
5856 return "score_low.png";
5857 } else if ($score < 0) {
5858 return "score_half_low.png";
5860 return "score_neutral.png";
5864 function rounded_table_start($classname, $header = " ") {
5865 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5866 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5867 print "<tr><td class='left'> </td><td class='content'>";
5870 function rounded_table_end($footer = " ") {
5871 print "</td><td class='right'> </td></tr>";
5872 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5876 function print_label_dlg_common_examples() {
5878 print __("Match ") . " ";
5880 /* print "<select name=\"label_andor\">";
5881 print "<option value=\"and\">AND</option>";
5882 print "<option value=\"or\">OR</option>";
5883 print "</select>"; */
5885 print "<select name=\"label_fields\" onchange=\"labelFieldsCheck(this)\">";
5886 print "<option value=\"unread\">".__("Unread articles")."</option>";
5887 print "<option value=\"updated\">".__("Updated articles")."</option>";
5888 print "<option value=\"kw_title\">".__("Title contains")."</option>";
5889 print "<option value=\"kw_content\">".__("Content contains")."</option>";
5890 print "<option value=\"scoreE\">".__("Score equals")."</option>";
5891 print "<option value=\"scoreG\">".__("Score is greater than")."</option>";
5892 print "<option value=\"scoreL\">".__("Score is less than")."</option>";
5893 print "<option value=\"newerH\">".__("Articles newer than X hours")."</option>";
5894 print "<option value=\"newerD\">".__("Articles newer than X days")."</option>";
5898 print "<input style=\"display : none\" name=\"label_fields_param\"
5901 print " <input type=\"submit\"
5902 onclick=\"return addLabelExample()\"
5903 value=\"".__("Add")."\">";
5906 function feed_has_icon($id) {
5907 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5910 function init_connection($link) {
5911 if (DB_TYPE
== "pgsql") {
5912 pg_query($link, "set client_encoding = 'UTF-8'");
5913 pg_set_client_encoding("UNICODE");
5914 pg_query($link, "set datestyle = 'ISO, european'");
5916 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5917 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5918 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5923 function update_feedbrowser_cache($link) {
5925 $result = db_query($link, "SELECT feed_url,COUNT(id) AS subscribers
5926 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5927 WHERE tf.feed_url = ttrss_feeds.feed_url
5928 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5929 GROUP BY feed_url ORDER BY subscribers DESC LIMIT 200");
5931 db_query($link, "BEGIN");
5933 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5937 while ($line = db_fetch_assoc($result)) {
5938 $subscribers = db_escape_string($line["subscribers"]);
5939 $feed_url = db_escape_string($line["feed_url"]);
5941 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5942 (feed_url, subscribers) VALUES ('$feed_url', '$subscribers')");
5947 db_query($link, "COMMIT");
5953 function ccache_zero($link, $feed_id, $owner_uid) {
5954 db_query($link, "UPDATE ttrss_counters_cache SET
5955 value = 0, updated = NOW() WHERE
5956 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5959 function ccache_zero_all($link, $owner_uid) {
5960 db_query($link, "UPDATE ttrss_counters_cache SET
5961 value = 0 WHERE owner_uid = '$owner_uid'");
5963 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5964 value = 0 WHERE owner_uid = '$owner_uid'");
5967 /* function ccache_invalidate($link, $feed_id, $owner_uid, $is_cat = false) {
5970 $table = "ttrss_counters_cache";
5972 $table = "ttrss_cat_counters_cache";
5975 db_query($link, "DELETE FROM $table
5976 WHERE feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5979 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false) {
5982 $table = "ttrss_counters_cache";
5984 $table = "ttrss_cat_counters_cache";
5987 if (DB_TYPE
== "pgsql") {
5988 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5989 } else if (DB_TYPE
== "mysql") {
5990 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5993 $result = db_query($link, "SELECT value FROM $table
5994 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5997 if (db_num_rows($result) == 1) {
5998 return db_fetch_result($result, 0, "value");
6000 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
6005 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false) {
6008 $table = "ttrss_counters_cache";
6010 $table = "ttrss_cat_counters_cache";
6013 if ($is_cat && $feed_id > 0) {
6014 if ($feed_id != 0) {
6015 $cat_qpart = "cat_id = '$feed_id'";
6017 $cat_qpart = "cat_id IS NULL";
6020 $result = db_query($link, "SELECT SUM(value) AS sv
6021 FROM ttrss_counters_cache, ttrss_feeds
6022 WHERE id = feed_id AND $cat_qpart AND
6023 ttrss_feeds.owner_uid = '$owner_uid'");
6025 $unread = db_fetch_result($result, 0, "sv");
6028 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6031 $result = db_query($link, "SELECT feed_id FROM $table
6032 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6034 if (db_num_rows($result) == 1) {
6035 db_query($link, "UPDATE $table SET
6036 value = '$unread', updated = NOW() WHERE
6037 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6040 db_query($link, "INSERT INTO $table
6041 (feed_id, value, owner_uid, updated)
6043 ($feed_id, $unread, $owner_uid, NOW())");
6051 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6052 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6054 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6056 ccache_update($link, $cat_id, $owner_uid, true);
6058 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
6059 WHERE owner_uid = '$owner_uid' AND feed_id < 0");
6061 while ($line = db_fetch_assoc($result)) {
6062 ccache_update($link, $line["feed_id"], $owner_uid);