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",
28 "fr_FR" => "Français",
29 "hu_HU" => "Magyar (Hungarian)",
30 "it_IT" => "Italiano",
31 "ja_JP" => "日本語 (Japanese)",
32 "nb_NO" => "Norwegian bokmål",
34 "pt_BR" => "Portuguese/Brazil",
35 "zh_CN" => "Simplified Chinese");
40 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
41 require_once "accept-to-gettext.php";
42 require_once "lib/gettext/gettext.inc";
44 function startup_gettext() {
46 # Get locale from Accept-Language header
47 $lang = al2gt(array_keys(get_translations()), "text/html");
49 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
50 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
53 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
54 $lang = $_COOKIE["ttrss_lang"];
57 /* In login action of mobile version */
58 if ($_POST["language"] && defined('MOBILE_VERSION')) {
59 $lang = $_POST["language"];
60 $_COOKIE["ttrss_lang"] = $lang;
64 if (defined('LC_MESSAGES')) {
65 _setlocale(LC_MESSAGES
, $lang);
66 } else if (defined('LC_ALL')) {
67 _setlocale(LC_ALL
, $lang);
69 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
72 if (defined('MOBILE_VERSION')) {
73 _bindtextdomain("messages", "../locale");
75 _bindtextdomain("messages", "locale");
78 _textdomain("messages");
79 _bind_textdomain_codeset("messages", "UTF-8");
85 } else { // If translations are enabled.
89 function startup_gettext() {
93 } // If translations are enabled.
95 require_once 'db-prefs.php';
96 require_once 'compat.php';
97 require_once 'errors.php';
98 require_once 'version.php';
100 require_once 'lib/phpmailer/class.phpmailer.php';
102 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
103 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
104 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
106 require_once "lib/simplepie/simplepie.inc";
107 require_once "lib/magpierss/rss_fetch.inc";
108 require_once 'lib/magpierss/rss_utils.inc';
109 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
112 * Print a timestamped debug message.
114 * @param string $msg The debug message.
117 function _debug($msg) {
118 $ts = strftime("%H:%M:%S", time());
119 if (function_exists('posix_getpid')) {
120 $ts = "$ts/" . posix_getpid();
122 print "[$ts] $msg\n";
126 * Purge a feed old posts.
128 * @param mixed $link A database connection.
129 * @param mixed $feed_id The id of the purged feed.
130 * @param mixed $purge_interval Olderness of purged posts.
131 * @param boolean $debug Set to True to enable the debug. False by default.
135 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
137 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
141 $result = db_query($link,
142 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
146 if (db_num_rows($result) == 1) {
147 $owner_uid = db_fetch_result($result, 0, "owner_uid");
150 if ($purge_interval == -1 ||
!$purge_interval) {
152 ccache_update($link, $feed_id, $owner_uid);
157 if (!$owner_uid) return;
159 if (FORCE_ARTICLE_PURGE
== 0) {
160 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
163 $purge_unread = true;
164 $purge_interval = FORCE_ARTICLE_PURGE
;
167 if (!$purge_unread) $query_limit = " unread = false AND ";
169 if (DB_TYPE
== "pgsql") {
170 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
171 marked = false AND feed_id = '$feed_id' AND
172 (SELECT date_entered FROM ttrss_entries WHERE
173 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
175 $pg_version = get_pgsql_version($link);
177 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
179 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
180 ttrss_entries.id = ref_id AND
182 feed_id = '$feed_id' AND
184 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
188 $result = db_query($link, "DELETE FROM ttrss_user_entries
190 WHERE ttrss_entries.id = ref_id AND
192 feed_id = '$feed_id' AND
194 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
197 $rows = pg_affected_rows($result);
201 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
202 marked = false AND feed_id = '$feed_id' AND
203 (SELECT date_entered FROM ttrss_entries WHERE
204 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
206 $result = db_query($link, "DELETE FROM ttrss_user_entries
207 USING ttrss_user_entries, ttrss_entries
208 WHERE ttrss_entries.id = ref_id AND
210 feed_id = '$feed_id' AND
212 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
214 $rows = mysql_affected_rows($link);
218 ccache_update($link, $feed_id, $owner_uid);
221 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
223 } // function purge_feed
226 * Purge old posts from old feeds.
228 * @param mixed $link A database connection
229 * @param boolean $do_output Set to true to enable printed output, false by default.
230 * @param integer $limit The maximal number of removed posts.
234 function global_purge_old_posts($link, $do_output = false, $limit = false) {
236 $random_qpart = sql_random_function();
239 $limit_qpart = "LIMIT $limit";
244 $result = db_query($link,
245 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
246 ORDER BY $random_qpart $limit_qpart");
248 while ($line = db_fetch_assoc($result)) {
250 $feed_id = $line["id"];
251 $purge_interval = $line["purge_interval"];
252 $owner_uid = $line["owner_uid"];
254 if ($purge_interval == 0) {
256 $tmp_result = db_query($link,
257 "SELECT value FROM ttrss_user_prefs WHERE
258 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
260 if (db_num_rows($tmp_result) != 0) {
261 $purge_interval = db_fetch_result($tmp_result, 0, "value");
266 // print "Feed $feed_id: purge interval = $purge_interval\n";
269 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
270 purge_feed($link, $feed_id, $purge_interval, $do_output);
274 // purge orphaned posts in main content table
275 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
276 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
279 $rows = db_affected_rows($link, $result);
280 _debug("Purged $rows orphaned posts.");
283 } // function global_purge_old_posts
285 function feed_purge_interval($link, $feed_id) {
287 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
288 WHERE id = '$feed_id'");
290 if (db_num_rows($result) == 1) {
291 $purge_interval = db_fetch_result($result, 0, "purge_interval");
292 $owner_uid = db_fetch_result($result, 0, "owner_uid");
294 if ($purge_interval == 0) $purge_interval = get_pref($link,
295 'PURGE_OLD_DAYS', $owner_uid);
297 return $purge_interval;
304 function purge_old_posts($link) {
306 $user_id = $_SESSION["uid"];
308 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
309 WHERE owner_uid = '$user_id'");
311 while ($line = db_fetch_assoc($result)) {
313 $feed_id = $line["id"];
314 $purge_interval = $line["purge_interval"];
316 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
318 if ($purge_interval > 0) {
319 purge_feed($link, $feed_id, $purge_interval);
323 purge_orphans($link);
326 function purge_orphans($link) {
327 // purge orphaned posts in main content table
328 db_query($link, "DELETE FROM ttrss_entries WHERE
329 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
332 function get_feed_update_interval($link, $feed_id) {
333 $result = db_query($link, "SELECT owner_uid, update_interval FROM
334 ttrss_feeds WHERE id = '$feed_id'");
336 if (db_num_rows($result) == 1) {
337 $update_interval = db_fetch_result($result, 0, "update_interval");
338 $owner_uid = db_fetch_result($result, 0, "owner_uid");
340 if ($update_interval != 0) {
341 return $update_interval;
343 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
351 function fetch_file_contents($url) {
352 if (USE_CURL_FOR_ICONS
) {
353 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
355 $ch = curl_init($url);
356 $fp = fopen($tmpfile, "w");
359 curl_setopt($ch, CURLOPT_FILE
, $fp);
360 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
361 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
367 $contents = file_get_contents($tmpfile);
373 return file_get_contents($url);
379 * Try to determine the favicon URL for a feed.
380 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
381 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
383 * @param string $url A feed or page URL
385 * @return mixed The favicon URL, or false if none was found.
387 function get_favicon_url($url) {
389 if ($html = @fetch_file_contents
($url)) {
391 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
392 // Attempt to grab a favicon link from their webpage url
393 $linkUrl = html_entity_decode($matches[1]);
395 if (substr($linkUrl, 0, 1) == '/') {
396 $urlParts = parse_url($url);
397 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
398 } else if (substr($linkUrl, 0, 7) == 'http://') {
399 $faviconURL = $linkUrl;
401 $pos = strrpos($url, "/");
402 // no "/" in url or "/" is part of "://"
403 if ($pos === false ||
$pos == (strpos($url, "://")+
2)) {
404 $faviconURL = $url.'/'.$linkUrl;
406 $faviconURL = substr($url, 0, $pos+
1).$linkUrl;
411 // If unsuccessful, attempt to "guess" the favicon location
412 $urlParts = parse_url($url);
413 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
417 // Run a test to see if what we have attempted to get actually exists.
418 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
423 } // function get_favicon_url
426 * Check if a link is a valid and working URL.
428 * @param mixed $link A URL to check
430 * @return boolean True if the URL is valid, false otherwise.
432 function url_validate($link) {
434 $url_parts = @parse_url
($link);
436 if ( empty( $url_parts["host"] ) )
439 if ( !empty( $url_parts["path"] ) ) {
440 $documentpath = $url_parts["path"];
445 if ( !empty( $url_parts["query"] ) )
446 $documentpath .= "?" . $url_parts["query"];
448 $host = $url_parts["host"];
449 $port = $url_parts["port"];
454 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
459 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
461 $http_response = fgets( $socket, 22 );
463 $responses = "/(200 OK)|(30[123])/";
464 if ( preg_match($responses, $http_response) ) {
471 } // function url_validate
473 function check_feed_favicon($site_url, $feed, $link) {
474 $favicon_url = get_favicon_url($site_url);
476 # print "FAVICON [$site_url]: $favicon_url\n";
480 $icon_file = ICONS_DIR
. "/$feed.ico";
482 if ($favicon_url && !file_exists($icon_file)) {
483 $contents = fetch_file_contents($favicon_url);
485 $fp = fopen($icon_file, "w");
488 fwrite($fp, $contents);
490 chmod($icon_file, 0644);
494 error_reporting(DEFAULT_ERROR_LEVEL
);
498 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
500 if (!$_GET["daemon"] && !$ignore_daemon) {
504 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
505 _debug("update_rss_feed: start");
508 if (!$ignore_daemon) {
510 if (DB_TYPE
== "pgsql") {
511 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
513 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
516 $result = db_query($link, "SELECT id,update_interval,auth_login,
517 auth_pass,cache_images,update_method
518 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
522 $result = db_query($link, "SELECT id,update_interval,auth_login,
523 auth_pass,cache_images,update_method,hidden,last_updated
524 FROM ttrss_feeds WHERE id = '$feed'");
528 if (db_num_rows($result) == 0) {
529 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
530 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
535 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
536 $update_method = db_fetch_result($result, 0, "update_method");
537 $last_updated = db_fetch_result($result, 0, "last_updated");
539 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
540 WHERE id = '$feed'");
542 $auth_login = db_fetch_result($result, 0, "auth_login");
543 $auth_pass = db_fetch_result($result, 0, "auth_pass");
545 if (ALLOW_SELECT_UPDATE_METHOD
) {
546 if (ENABLE_SIMPLEPIE
) {
547 $use_simplepie = $update_method != 1;
549 $use_simplepie = $update_method == 2;
552 $use_simplepie = ENABLE_SIMPLEPIE
;
555 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
556 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
559 if (!$use_simplepie) {
560 $auth_login = urlencode($auth_login);
561 $auth_pass = urlencode($auth_pass);
564 $update_interval = db_fetch_result($result, 0, "update_interval");
565 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
567 if ($update_interval < 0) { return; }
569 $feed = db_escape_string($feed);
571 $fetch_url = $feed_url;
573 if ($auth_login && $auth_pass) {
574 $url_parts = array();
575 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
577 if ($url_parts[1] && $url_parts[2]) {
578 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
583 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
584 _debug("update_rss_feed: fetching [$fetch_url]...");
587 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
591 if (!$use_simplepie) {
592 $rss = fetch_rss($fetch_url);
594 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
595 mkdir(SIMPLEPIE_CACHE_DIR
);
598 $rss = new SimplePie();
599 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
600 # $rss->set_timeout(10);
601 $rss->set_feed_url($fetch_url);
602 $rss->set_output_encoding('UTF-8');
604 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
605 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
606 _debug("enabling image cache");
609 $rss->set_image_handler('./image.php', 'i');
612 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
613 _debug("feed update interval (sec): " .
614 get_feed_update_interval($link, $feed)*60);
617 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
618 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
619 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
627 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
628 _debug("update_rss_feed: fetch done, parsing...");
630 error_reporting (DEFAULT_ERROR_LEVEL
);
633 $feed = db_escape_string($feed);
635 if ($use_simplepie) {
636 $fetch_ok = !$rss->error();
643 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
644 _debug("update_rss_feed: processing feed data...");
647 // db_query($link, "BEGIN");
649 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
650 FROM ttrss_feeds WHERE id = '$feed'");
652 $registered_title = db_fetch_result($result, 0, "title");
653 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
654 $orig_site_url = db_fetch_result($result, 0, "site_url");
656 $owner_uid = db_fetch_result($result, 0, "owner_uid");
658 if ($use_simplepie) {
659 $site_url = $rss->get_link();
661 $site_url = $rss->channel
["link"];
664 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
665 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
666 _debug("update_rss_feed: checking favicon...");
669 check_feed_favicon($site_url, $feed, $link);
672 if (!$registered_title ||
$registered_title == "[Unknown]") {
674 if ($use_simplepie) {
675 $feed_title = db_escape_string($rss->get_title());
677 $feed_title = db_escape_string($rss->channel
["title"]);
680 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
681 _debug("update_rss_feed: registering title: $feed_title");
684 db_query($link, "UPDATE ttrss_feeds SET
685 title = '$feed_title' WHERE id = '$feed'");
688 // weird, weird Magpie
689 if (!$use_simplepie) {
690 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
693 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
694 db_query($link, "UPDATE ttrss_feeds SET
695 site_url = '$site_url' WHERE id = '$feed'");
698 // print "I: " . $rss->channel["image"]["url"];
700 if (!$use_simplepie) {
701 $icon_url = $rss->image
["url"];
703 $icon_url = $rss->get_image_url();
706 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
707 $icon_url = db_escape_string($icon_url);
708 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
711 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
712 _debug("update_rss_feed: loading filters...");
715 $filters = load_filters($link, $feed, $owner_uid);
717 if ($use_simplepie) {
718 $iterator = $rss->get_items();
720 $iterator = $rss->items
;
721 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
722 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
725 if (!is_array($iterator)) {
726 /* db_query($link, "UPDATE ttrss_feeds
727 SET last_error = 'Parse error: can\'t find any articles.'
728 WHERE id = '$feed'"); */
730 // clear any errors and mark feed as updated if fetched okay
731 // even if it's blank
733 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
734 _debug("update_rss_feed: entry iterator is not an array, no articles?");
737 db_query($link, "UPDATE ttrss_feeds
738 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
740 return; // no articles
743 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
744 _debug("update_rss_feed: processing articles...");
747 foreach ($iterator as $item) {
749 if ($_GET['xdebug']) {
754 if ($use_simplepie) {
755 $entry_guid = $item->get_id();
756 if (!$entry_guid) $entry_guid = $item->get_link();
757 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
761 $entry_guid = $item["id"];
763 if (!$entry_guid) $entry_guid = $item["guid"];
764 if (!$entry_guid) $entry_guid = $item["link"];
765 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
768 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
769 _debug("update_rss_feed: guid $entry_guid");
772 if (!$entry_guid) continue;
774 $entry_timestamp = "";
776 if ($use_simplepie) {
777 $entry_timestamp = strtotime($item->get_date());
779 $rss_2_date = $item['pubdate'];
780 $rss_1_date = $item['dc']['date'];
781 $atom_date = $item['issued'];
782 if (!$atom_date) $atom_date = $item['updated'];
784 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
785 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
786 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
789 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
790 $entry_timestamp = time();
791 $no_orig_date = 'true';
793 $no_orig_date = 'false';
796 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
798 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
799 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
802 if ($use_simplepie) {
803 $entry_title = $item->get_title();
805 $entry_title = trim(strip_tags($item["title"]));
808 if ($use_simplepie) {
809 $entry_link = $item->get_link();
811 // strange Magpie workaround
812 $entry_link = $item["link_"];
813 if (!$entry_link) $entry_link = $item["link"];
816 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
817 _debug("update_rss_feed: title $entry_title");
820 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
822 $entry_link = strip_tags($entry_link);
824 if ($use_simplepie) {
825 $entry_content = $item->get_content();
826 if (!$entry_content) $entry_content = $item->get_description();
828 $entry_content = $item["content:escaped"];
830 if (!$entry_content) $entry_content = $item["content:encoded"];
831 if (!$entry_content) $entry_content = $item["content"]["encoded"];
832 if (!$entry_content) $entry_content = $item["content"];
834 // Magpie bugs are getting ridiculous
835 if (trim($entry_content) == "Array") $entry_content = false;
837 if (!$entry_content) $entry_content = $item["atom_content"];
838 if (!$entry_content) $entry_content = $item["summary"];
840 if (!$entry_content ||
841 strlen($entry_content) < strlen($item["description"])) {
842 $entry_content = $item["description"];
846 if (is_array($entry_content)) {
847 $entry_content = $entry_content["encoded"];
848 if (!$entry_content) $entry_content = $entry_content["escaped"];
852 if ($_GET["xdebug"]) {
853 print "update_rss_feed: content: ";
854 print_r(htmlspecialchars($entry_content));
857 $entry_content_unescaped = $entry_content;
859 if ($use_simplepie) {
860 $entry_comments = strip_tags($item->data
["comments"]);
861 if ($item->get_author()) {
862 $entry_author_item = $item->get_author();
863 $entry_author = $entry_author_item->get_name();
864 if (!$entry_author) $entry_author = $entry_author_item->get_email();
866 $entry_author = db_escape_string($entry_author);
869 $entry_comments = strip_tags($item["comments"]);
871 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
873 if ($item['author']) {
875 if (is_array($item['author'])) {
877 if (!$entry_author) {
878 $entry_author = db_escape_string(strip_tags($item['author']['name']));
881 if (!$entry_author) {
882 $entry_author = db_escape_string(strip_tags($item['author']['email']));
886 if (!$entry_author) {
887 $entry_author = db_escape_string(strip_tags($item['author']));
892 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
894 $entry_guid = db_escape_string(strip_tags($entry_guid));
895 $entry_guid = mb_substr($entry_guid, 0, 250);
897 $result = db_query($link, "SELECT id FROM ttrss_entries
898 WHERE guid = '$entry_guid'");
900 $entry_content = db_escape_string($entry_content);
902 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
904 $entry_title = db_escape_string($entry_title);
905 $entry_link = db_escape_string($entry_link);
906 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
907 $entry_author = mb_substr($entry_author, 0, 250);
909 if ($use_simplepie) {
910 $num_comments = 0; #FIXME#
912 $num_comments = db_escape_string($item["slash"]["comments"]);
915 if (!$num_comments) $num_comments = 0;
917 // parse <category> entries into tags
919 if ($use_simplepie) {
921 $additional_tags = array();
922 $additional_tags_src = $item->get_categories();
924 if (is_array($additional_tags_src)) {
925 foreach ($additional_tags_src as $tobj) {
926 array_push($additional_tags, $tobj->get_term());
930 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
931 _debug("update_rss_feed: category tags:");
932 print_r($additional_tags);
937 $t_ctr = $item['category#'];
939 $additional_tags = false;
942 $additional_tags = false;
943 } else if ($t_ctr > 0) {
944 $additional_tags = array($item['category']);
946 if ($item['category@term']) {
947 array_push($additional_tags, $item['category@term']);
950 for ($i = 0; $i <= $t_ctr; $i++
) {
951 if ($item["category#$i"]) {
952 array_push($additional_tags, $item["category#$i"]);
955 if ($item["category#$i@term"]) {
956 array_push($additional_tags, $item["category#$i@term"]);
961 // parse <dc:subject> elements
963 $t_ctr = $item['dc']['subject#'];
966 $additional_tags = array($item['dc']['subject']);
968 for ($i = 0; $i <= $t_ctr; $i++
) {
969 if ($item['dc']["subject#$i"]) {
970 array_push($additional_tags, $item['dc']["subject#$i"]);
978 $enclosures = array();
980 if ($use_simplepie) {
981 $encs = $item->get_enclosures();
983 if (is_array($encs)) {
984 foreach ($encs as $e) {
986 $e->link
, $e->type
, $e->length
);
988 array_push($enclosures, $e_item);
995 $e_ctr = $item['enclosure#'];
998 $e_item = array($item['enclosure@url'],
999 $item['enclosure@type'],
1000 $item['enclosure@length']);
1002 array_push($enclosures, $e_item);
1004 for ($i = 0; $i <= $e_ctr; $i++
) {
1006 if ($item["enclosure#$i@url"]) {
1007 $e_item = array($item["enclosure#$i@url"],
1008 $item["enclosure#$i@type"],
1009 $item["enclosure#$i@length"]);
1010 array_push($enclosures, $e_item);
1016 // can there be many of those? yes -fox
1018 $m_ctr = $item['media']['content#'];
1021 $e_item = array($item['media']['content@url'],
1022 $item['media']['content@medium'],
1023 $item['media']['content@length']);
1025 array_push($enclosures, $e_item);
1027 for ($i = 0; $i <= $m_ctr; $i++
) {
1029 if ($item["media"]["content#$i@url"]) {
1030 $e_item = array($item["media"]["content#$i@url"],
1031 $item["media"]["content#$i@medium"],
1032 $item["media"]["content#$i@length"]);
1033 array_push($enclosures, $e_item);
1042 $entry_content = sanitize_article_content($entry_content);
1043 $entry_title = sanitize_article_content($entry_title);
1045 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1046 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1049 db_query($link, "BEGIN");
1051 if (db_num_rows($result) == 0) {
1053 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1054 _debug("update_rss_feed: base guid not found");
1057 // base post entry does not exist, create it
1059 $result = db_query($link,
1060 "INSERT INTO ttrss_entries
1076 '$entry_timestamp_fmt',
1085 // we keep encountering the entry in feeds, so we need to
1086 // update date_entered column so that we don't get horrible
1087 // dupes when the entry gets purged and reinserted again e.g.
1088 // in the case of SLOW SLOW OMG SLOW updating feeds
1090 $base_entry_id = db_fetch_result($result, 0, "id");
1092 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1093 WHERE id = '$base_entry_id'");
1096 // now it should exist, if not - bad luck then
1098 $result = db_query($link, "SELECT
1099 id,content_hash,no_orig_date,title,
1100 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1101 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1105 WHERE guid = '$entry_guid'");
1110 if (db_num_rows($result) == 1) {
1112 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1113 _debug("update_rss_feed: base guid found, checking for user record");
1116 // this will be used below in update handler
1117 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1118 $orig_title = db_fetch_result($result, 0, "title");
1119 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1120 $orig_date_entered = strtotime(db_fetch_result($result,
1121 0, "date_entered"));
1123 $ref_id = db_fetch_result($result, 0, "id");
1124 $entry_ref_id = $ref_id;
1126 // check for user post link to main table
1128 // do we allow duplicate posts with same GUID in different feeds?
1129 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1130 $dupcheck_qpart = "AND feed_id = '$feed'";
1132 $dupcheck_qpart = "";
1135 // error_reporting(0);
1137 $article_filters = get_article_filters($filters, $entry_title,
1138 $entry_content, $entry_link, $entry_timestamp);
1140 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1141 _debug("update_rss_feed: article filters: ");
1142 if (count($article_filters) != 0) {
1143 print_r($article_filters);
1147 if (find_article_filter($article_filters, "filter")) {
1148 db_query($link, "COMMIT"); // close transaction in progress
1152 // error_reporting (DEFAULT_ERROR_LEVEL);
1154 $score = calculate_article_score($article_filters);
1156 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1157 _debug("update_rss_feed: initial score: $score");
1160 $result = db_query($link,
1161 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1162 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1165 // okay it doesn't exist - create user entry
1166 if (db_num_rows($result) == 0) {
1168 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1169 _debug("update_rss_feed: user record not found, creating...");
1172 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1174 $last_read_qpart = 'NULL';
1177 $last_read_qpart = 'NOW()';
1180 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1186 if (find_article_filter($article_filters, 'publish')) {
1187 $published = 'true';
1189 $published = 'false';
1192 $result = db_query($link,
1193 "INSERT INTO ttrss_user_entries
1194 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1196 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1197 $last_read_qpart, $marked, $published, '$score')");
1199 $result = db_query($link,
1200 "SELECT int_id FROM ttrss_user_entries WHERE
1201 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1202 feed_id = '$feed' LIMIT 1");
1204 if (db_num_rows($result) == 1) {
1205 $entry_int_id = db_fetch_result($result, 0, "int_id");
1208 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1209 $entry_int_id = db_fetch_result($result, 0, "int_id");
1212 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1213 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1216 $post_needs_update = false;
1218 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1219 ($content_hash != $orig_content_hash)) {
1220 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1221 $post_needs_update = true;
1224 if (db_escape_string($orig_title) != $entry_title) {
1225 $post_needs_update = true;
1228 if ($orig_num_comments != $num_comments) {
1229 $post_needs_update = true;
1232 // this doesn't seem to be very reliable
1234 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1235 // $post_needs_update = true;
1238 // if post needs update, update it and mark all user entries
1239 // linking to this post as updated
1240 if ($post_needs_update) {
1242 if (defined('DAEMON_EXTENDED_DEBUG')) {
1243 _debug("update_rss_feed: post $entry_guid needs update...");
1246 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1248 db_query($link, "UPDATE ttrss_entries
1249 SET title = '$entry_title', content = '$entry_content',
1250 content_hash = '$content_hash',
1251 num_comments = '$num_comments'
1252 WHERE id = '$ref_id'");
1254 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1255 db_query($link, "UPDATE ttrss_user_entries
1256 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1258 db_query($link, "UPDATE ttrss_user_entries
1259 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1265 db_query($link, "COMMIT");
1267 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1268 _debug("update_rss_feed: assigning labels...");
1271 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1274 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1275 _debug("update_rss_feed: looking for enclosures...");
1278 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1279 print_r($enclosures);
1282 db_query($link, "BEGIN");
1284 foreach ($enclosures as $enc) {
1285 $enc_url = db_escape_string($enc[0]);
1286 $enc_type = db_escape_string($enc[1]);
1287 $enc_dur = db_escape_string($enc[2]);
1289 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1290 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1292 if (db_num_rows($result) == 0) {
1293 db_query($link, "INSERT INTO ttrss_enclosures
1294 (content_url, content_type, title, duration, post_id) VALUES
1295 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1299 db_query($link, "COMMIT");
1301 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1302 _debug("update_rss_feed: looking for tags...");
1306 // <a href="..." rel="tag">Xorg</a>, //
1310 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1311 $entry_content_unescaped, $entry_tags);
1313 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1314 print_r($entry_tags);
1315 print "<br/></p>"; */
1317 $entry_tags = $entry_tags[1];
1319 # check for manual tags
1321 $tag_filter = find_article_filter($article_filters, "tag");
1325 $manual_tags = trim_array(split(",", $tag_filter[1]));
1327 foreach ($manual_tags as $tag) {
1328 if (tag_is_valid($tag)) {
1329 array_push($entry_tags, $tag);
1334 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1335 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1337 if ($additional_tags && is_array($additional_tags)) {
1338 foreach ($additional_tags as $tag) {
1339 if (tag_is_valid($tag) &&
1340 array_search($tag, $boring_tags) === FALSE) {
1341 array_push($entry_tags, $tag);
1346 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1348 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1349 print_r($entry_tags);
1352 if (count($entry_tags) > 0) {
1354 db_query($link, "BEGIN");
1356 foreach ($entry_tags as $tag) {
1358 $tag = sanitize_tag($tag);
1359 $tag = db_escape_string($tag);
1361 if (!tag_is_valid($tag)) continue;
1363 $result = db_query($link, "SELECT id FROM ttrss_tags
1364 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1365 owner_uid = '$owner_uid' LIMIT 1");
1367 // print db_fetch_result($result, 0, "id");
1369 if ($result && db_num_rows($result) == 0) {
1371 db_query($link, "INSERT INTO ttrss_tags
1372 (owner_uid,tag_name,post_int_id)
1373 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1377 db_query($link, "COMMIT");
1380 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1381 _debug("update_rss_feed: article processed");
1385 if (!$last_updated) {
1386 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1387 _debug("update_rss_feed: new feed, catching it up...");
1389 catchup_feed($link, $feed, false, $owner_uid);
1393 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1394 _debug("update_rss_feed: updating counters cache...");
1397 // disabled, purge_feed() does that...
1398 //ccache_update($link, $feed, $owner_uid);
1401 purge_feed($link, $feed, 0);
1403 db_query($link, "UPDATE ttrss_feeds
1404 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1406 // db_query($link, "COMMIT");
1410 if ($use_simplepie) {
1411 $error_msg = mb_substr($rss->error(), 0, 250);
1413 $error_msg = mb_substr(magpie_error(), 0, 250);
1416 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1417 _debug("update_rss_feed: error fetching feed: $error_msg");
1420 $error_msg = db_escape_string($error_msg);
1423 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1424 last_updated = NOW() WHERE id = '$feed'");
1427 if ($use_simplepie) {
1431 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1432 _debug("update_rss_feed: done");
1437 function print_select($id, $default, $values, $attributes = "") {
1438 print "<select name=\"$id\" id=\"$id\" $attributes>";
1439 foreach ($values as $v) {
1445 print "<option$sel>$v</option>";
1450 function print_select_hash($id, $default, $values, $attributes = "") {
1451 print "<select name=\"$id\" id='$id' $attributes>";
1452 foreach (array_keys($values) as $v) {
1454 $sel = 'selected="selected"';
1458 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1464 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1467 if ($filters["title"]) {
1468 foreach ($filters["title"] as $filter) {
1469 $reg_exp = $filter["reg_exp"];
1470 $inverse = $filter["inverse"];
1471 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1472 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1474 array_push($matches, array($filter["action"], $filter["action_param"]));
1479 if ($filters["content"]) {
1480 foreach ($filters["content"] as $filter) {
1481 $reg_exp = $filter["reg_exp"];
1482 $inverse = $filter["inverse"];
1484 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1485 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1487 array_push($matches, array($filter["action"], $filter["action_param"]));
1492 if ($filters["both"]) {
1493 foreach ($filters["both"] as $filter) {
1494 $reg_exp = $filter["reg_exp"];
1495 $inverse = $filter["inverse"];
1498 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1499 array_push($matches, array($filter["action"], $filter["action_param"]));
1502 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1503 array_push($matches, array($filter["action"], $filter["action_param"]));
1509 if ($filters["link"]) {
1510 $reg_exp = $filter["reg_exp"];
1511 foreach ($filters["link"] as $filter) {
1512 $reg_exp = $filter["reg_exp"];
1513 $inverse = $filter["inverse"];
1515 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1516 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1518 array_push($matches, array($filter["action"], $filter["action_param"]));
1523 if ($filters["date"]) {
1524 $reg_exp = $filter["reg_exp"];
1525 foreach ($filters["date"] as $filter) {
1526 $date_modifier = $filter["filter_param"];
1527 $inverse = $filter["inverse"];
1528 $check_timestamp = strtotime($filter["reg_exp"]);
1530 # no-op when timestamp doesn't parse to prevent misfires
1532 if ($check_timestamp) {
1535 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1536 $date_modifier == "after" && $timestamp > $check_timestamp) {
1540 if ($inverse) $match_ok = !$match_ok;
1543 array_push($matches, array($filter["action"], $filter["action_param"]));
1552 function find_article_filter($filters, $filter_name) {
1553 foreach ($filters as $f) {
1554 if ($f[0] == $filter_name) {
1561 function calculate_article_score($filters) {
1564 foreach ($filters as $f) {
1565 if ($f[0] == "score") {
1572 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1573 foreach ($filters as $f) {
1574 if ($f[0] == "label") {
1575 label_add_article($link, $id, $f[1], $owner_uid);
1580 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1581 $rtl_content = false, $last_updated = false, $last_error = false,
1582 $fg_content = false, $bg_content = false) {
1584 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1585 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1587 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1591 $rtl_tag = "dir=\"rtl\"";
1593 $rtl_tag = "dir=\"ltr\"";
1596 $error_notify_msg = "";
1599 $link_title = "Error: $last_error ($last_updated)";
1600 $error_notify_msg = "(Error)";
1601 } else if ($last_updated) {
1602 $link_title = "Updated: $last_updated";
1605 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1606 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1608 /* if ($feed_id < -10) {
1609 $bg_color = "#00ccff";
1610 $fg_color = "white";
1613 if ($fg_color || $bg_color) {
1614 $color_str = "<div class='labelColorIndicator'
1615 style='color : $fg_color; background-color : $bg_color'>l</div>";
1618 print $color_str; */
1620 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1621 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1625 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1628 $fctr_class = "class=\"feedCtrHasUnread\"";
1630 $fctr_class = "class=\"feedCtrNoUnread\"";
1633 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1634 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1636 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1637 $total = getFeedArticles($link, $feed_id);
1638 print "<div class=\"feedExtInfo\">
1639 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1646 function getmicrotime() {
1647 list($usec, $sec) = explode(" ",microtime());
1648 return ((float)$usec +
(float)$sec);
1651 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1652 foreach ($values as $v) {
1659 if ($v == $true_is) {
1660 $sel .= " value=\"1\"";
1662 $sel .= " value=\"0\"";
1665 print "<input class=\"noborder\"
1666 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1671 function initialize_user_prefs($link, $uid) {
1673 $uid = db_escape_string($uid);
1675 db_query($link, "BEGIN");
1677 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1679 $u_result = db_query($link, "SELECT pref_name
1680 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1682 $active_prefs = array();
1684 while ($line = db_fetch_assoc($u_result)) {
1685 array_push($active_prefs, $line["pref_name"]);
1688 while ($line = db_fetch_assoc($result)) {
1689 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1690 // print "adding " . $line["pref_name"] . "<br>";
1692 db_query($link, "INSERT INTO ttrss_user_prefs
1693 (owner_uid,pref_name,value) VALUES
1694 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1699 db_query($link, "COMMIT");
1703 function lookup_user_id($link, $user) {
1705 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1708 if (db_num_rows($result) == 1) {
1709 return db_fetch_result($result, 0, "id");
1715 function http_authenticate_user($link) {
1717 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1719 if (!$_SERVER["PHP_AUTH_USER"]) {
1721 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1722 header('HTTP/1.0 401 Unauthorized');
1726 $auth_result = authenticate_user($link,
1727 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1729 if (!$auth_result) {
1730 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1731 header('HTTP/1.0 401 Unauthorized');
1739 function authenticate_user($link, $login, $password, $force_auth = false) {
1741 if (!SINGLE_USER_MODE
) {
1743 $pwd_hash1 = encrypt_password($password);
1744 $pwd_hash2 = encrypt_password($password, $login);
1745 $login = db_escape_string($login);
1747 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1748 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1750 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1752 $query = "SELECT id,login,access_level,pwd_hash
1753 FROM ttrss_users WHERE
1757 $query = "SELECT id,login,access_level,pwd_hash
1758 FROM ttrss_users WHERE
1759 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1760 pwd_hash = '$pwd_hash2')";
1763 $result = db_query($link, $query);
1765 if (db_num_rows($result) == 1) {
1766 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1767 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1768 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1770 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1773 $user_theme = get_user_theme_path($link);
1775 $_SESSION["theme"] = $user_theme;
1776 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1777 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1779 initialize_user_prefs($link, $_SESSION["uid"]);
1788 $_SESSION["uid"] = 1;
1789 $_SESSION["name"] = "admin";
1791 $user_theme = get_user_theme_path($link);
1793 $_SESSION["theme"] = $user_theme;
1794 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1796 initialize_user_prefs($link, $_SESSION["uid"]);
1802 function make_password($length = 8) {
1805 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1809 while ($i < $length) {
1810 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1812 if (!strstr($password, $char)) {
1820 // this is called after user is created to initialize default feeds, labels
1823 // user preferences are checked on every login, not here
1825 function initialize_user($link, $uid) {
1827 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1828 VALUES ('$uid', 'All Articles')");
1830 db_query($link, "INSERT INTO ttrss_filters
1831 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1832 action_id, action_param, filter_param)
1833 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1835 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1836 values ('$uid', 'Tiny Tiny RSS: New Releases',
1837 'http://tt-rss.org/releases.rss')");
1839 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1840 values ('$uid', 'Tiny Tiny RSS: Forum',
1841 'http://tt-rss.org/forum/rss.php')");
1844 function logout_user() {
1846 if (isset($_COOKIE[session_name()])) {
1847 setcookie(session_name(), '', time()-42000, '/');
1851 function get_script_urlpath() {
1852 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1855 function validate_session($link) {
1856 if (SINGLE_USER_MODE
) {
1860 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1861 if ($_SESSION["ip_address"]) {
1862 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1863 $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1869 if ($_SESSION["uid"]) {
1871 $result = db_query($link,
1872 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1874 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1876 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1881 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1883 //print_r($_SESSION);
1885 if (time() > $_SESSION["cookie_lifetime"]) {
1893 function login_sequence($link, $mobile = false) {
1894 if (!SINGLE_USER_MODE
) {
1896 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1897 $swu = db_escape_string($_REQUEST["swu"]);
1899 $_SESSION["prefs_cache"] = false;
1900 return authenticate_user($link, $swu, null, true);
1904 $login_action = $_POST["login_action"];
1906 # try to authenticate user if called from login form
1907 if ($login_action == "do_login") {
1908 $login = $_POST["login"];
1909 $password = $_POST["password"];
1910 $remember_me = $_POST["remember_me"];
1912 if (authenticate_user($link, $login, $password)) {
1913 $_POST["password"] = "";
1915 $_SESSION["language"] = $_POST["language"];
1916 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1918 header("Location: " . $_SERVER["REQUEST_URI"]);
1923 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1927 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1928 render_login_form($link, $mobile);
1929 //header("Location: login.php");
1932 /* bump login timestamp */
1933 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1936 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1937 setcookie("ttrss_lang", $_SESSION["language"],
1938 time() + SESSION_COOKIE_LIFETIME
);
1941 /* bump counters stamp since we're getting reloaded anyway */
1943 $_SESSION["get_all_counters_stamp"] = time();
1947 return authenticate_user($link, "admin", null);
1951 function truncate_string($str, $max_len) {
1952 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1953 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1959 function get_user_theme_path($link) {
1960 $result = db_query($link, "SELECT theme_path
1962 ttrss_themes,ttrss_users
1963 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1964 if (db_num_rows($result) != 0) {
1965 return db_fetch_result($result, 0, "theme_path");
1971 function smart_date_time($timestamp) {
1972 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1973 return date("G:i", $timestamp);
1974 } else if (date("Y", $timestamp) == date("Y")) {
1975 return date("M d, G:i", $timestamp);
1977 return date("Y/m/d, G:i", $timestamp);
1981 function smart_date($timestamp) {
1982 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1984 } else if (date("Y", $timestamp) == date("Y")) {
1985 return date("D m", $timestamp);
1987 return date("Y/m/d", $timestamp);
1991 function sql_bool_to_string($s) {
1992 if ($s == "t" ||
$s == "1") {
1999 function sql_bool_to_bool($s) {
2000 if ($s == "t" ||
$s == "1") {
2007 function bool_to_sql_bool($s) {
2015 function toggleEvenOdd($a) {
2022 function sanity_check($link) {
2027 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2028 $schema_version = db_fetch_result($result, 0, "schema_version");
2030 if ($schema_version != SCHEMA_VERSION
) {
2034 if (DB_TYPE
== "mysql") {
2035 $result = db_query($link, "SELECT true", false);
2036 if (db_num_rows($result) != 1) {
2041 if (db_escape_string("testTEST") != "testTEST") {
2045 error_reporting (DEFAULT_ERROR_LEVEL
);
2047 if ($error_code != 0) {
2048 print_error_xml($error_code);
2055 function file_is_locked($filename) {
2056 if (function_exists('flock')) {
2058 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2059 error_reporting(DEFAULT_ERROR_LEVEL
);
2061 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2062 flock($fp, LOCK_UN
);
2072 return true; // consider the file always locked and skip the test
2075 function make_lockfile($filename) {
2076 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2078 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2085 function make_stampfile($filename) {
2086 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2088 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2089 fwrite($fp, time() . "\n");
2090 flock($fp, LOCK_UN
);
2098 function read_stampfile($filename) {
2101 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2102 error_reporting (DEFAULT_ERROR_LEVEL
);
2105 if (flock($fp, LOCK_EX
)) {
2106 $stamp = fgets($fp);
2107 flock($fp, LOCK_UN
);
2118 function sql_random_function() {
2119 if (DB_TYPE
== "mysql") {
2126 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2128 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2130 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2137 $cat_qpart = "cat_id = '$feed'";
2139 $cat_qpart = "cat_id IS NULL";
2142 $tmp_result = db_query($link, "SELECT id
2143 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2145 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2147 $tmp_feed = $tmp_line["id"];
2149 db_query($link, "UPDATE ttrss_user_entries
2150 SET unread = false,last_read = NOW()
2151 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2153 } else if ($feed == -2) {
2156 db_query($link, "UPDATE ttrss_user_entries
2157 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2158 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2159 AND unread = true AND owner_uid = $owner_uid");
2162 } else if ($feed > 0) {
2164 $tmp_result = db_query($link, "SELECT id
2165 FROM ttrss_feeds WHERE parent_feed = '$feed'
2166 ORDER BY cat_id,title");
2168 $parent_ids = array();
2170 if (db_num_rows($tmp_result) > 0) {
2171 while ($p = db_fetch_assoc($tmp_result)) {
2172 array_push($parent_ids, "feed_id = " . $p["id"]);
2175 $children_qpart = implode(" OR ", $parent_ids);
2177 db_query($link, "UPDATE ttrss_user_entries
2178 SET unread = false,last_read = NOW()
2179 WHERE (feed_id = '$feed' OR $children_qpart)
2180 AND owner_uid = $owner_uid");
2183 db_query($link, "UPDATE ttrss_user_entries
2184 SET unread = false,last_read = NOW()
2185 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2188 } else if ($feed < 0 && $feed > -10) { // special, like starred
2191 db_query($link, "UPDATE ttrss_user_entries
2192 SET unread = false,last_read = NOW()
2193 WHERE marked = true AND owner_uid = $owner_uid");
2197 db_query($link, "UPDATE ttrss_user_entries
2198 SET unread = false,last_read = NOW()
2199 WHERE published = true AND owner_uid = $owner_uid");
2204 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2206 if (DB_TYPE
== "pgsql") {
2207 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2209 $match_part = "updated > DATE_SUB(NOW(),
2210 INTERVAL $intl HOUR) ";
2213 $result = db_query($link, "SELECT id FROM ttrss_entries,
2214 ttrss_user_entries WHERE $match_part AND
2216 ttrss_user_entries.ref_id = ttrss_entries.id AND
2217 owner_uid = $owner_uid");
2219 $affected_ids = array();
2221 while ($line = db_fetch_assoc($result)) {
2222 array_push($affected_ids, $line["id"]);
2225 catchupArticlesById($link, $affected_ids, 0);
2229 db_query($link, "UPDATE ttrss_user_entries
2230 SET unread = false,last_read = NOW()
2231 WHERE owner_uid = $owner_uid");
2234 } else if ($feed < -10) { // label
2236 $label_id = -$feed - 11;
2238 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2239 SET unread = false, last_read = NOW()
2240 WHERE label_id = '$label_id' AND unread = true
2241 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2245 ccache_update($link, $feed, $owner_uid, $cat_view);
2248 db_query($link, "BEGIN");
2250 $tag_name = db_escape_string($feed);
2252 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2253 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2255 while ($line = db_fetch_assoc($result)) {
2256 db_query($link, "UPDATE ttrss_user_entries SET
2257 unread = false, last_read = NOW()
2258 WHERE int_id = " . $line["post_int_id"]);
2260 db_query($link, "COMMIT");
2264 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2268 $cat_qpart = "cat_id = '$feed'";
2270 $cat_qpart = "cat_id IS NULL";
2273 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2274 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2276 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2277 $feed_url = $tmp_line["feed_url"];
2278 $feed_id = $tmp_line["id"];
2279 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2283 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2284 WHERE id = '$feed'");
2285 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2286 update_rss_feed($link, $feed_url, $feed, $force_update);
2290 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2292 if (!$omode) $omode = "flc";
2294 getGlobalCounters($link);
2296 if (strchr($omode, "l")) getLabelCounters($link);
2297 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2298 if (strchr($omode, "t")) getTagCounters($link);
2299 if (strchr($omode, "c")) {
2300 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2301 getCategoryCounters($link);
2306 function getCategoryCounters($link) {
2307 # two special categories are -1 and -2 (all virtuals; all labels)
2309 /* $ctr = getCategoryUnread($link, -1);
2311 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2313 $ctr = getCategoryUnread($link, -2);
2315 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2317 $age_qpart = getMaxAgeSubquery();
2319 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2320 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2321 WHERE ttrss_cat_counters_cache.feed_id = id AND
2322 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2324 while ($line = db_fetch_assoc($result)) {
2325 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2327 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2328 $line["unread"]."\"/>";
2331 /* Special case: NULL category doesn't actually exist in the DB */
2333 print "<counter type=\"category\" id=\"0\" counter=\"".
2334 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2338 function getCategoryUnread($link, $cat, $owner_uid = false) {
2340 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2345 $cat_query = "cat_id = '$cat'";
2347 $cat_query = "cat_id IS NULL";
2350 $age_qpart = getMaxAgeSubquery();
2352 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2354 AND owner_uid = " . $owner_uid);
2356 $cat_feeds = array();
2357 while ($line = db_fetch_assoc($result)) {
2358 array_push($cat_feeds, "feed_id = " . $line["id"]);
2361 if (count($cat_feeds) == 0) return 0;
2363 $match_part = implode(" OR ", $cat_feeds);
2365 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2366 FROM ttrss_user_entries,ttrss_entries
2367 WHERE unread = true AND ($match_part) AND id = ref_id
2368 AND $age_qpart AND owner_uid = " . $owner_uid);
2372 # this needs to be rewritten
2373 while ($line = db_fetch_assoc($result)) {
2374 $unread +
= $line["unread"];
2378 } else if ($cat == -1) {
2379 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2380 } else if ($cat == -2) {
2382 $result = db_query($link, "
2383 SELECT COUNT(unread) AS unread FROM
2384 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2385 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2386 ttrss_labels2.owner_uid = '$owner_uid'
2387 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2388 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2390 $unread = db_fetch_result($result, 0, "unread");
2397 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2398 if (DB_TYPE
== "pgsql") {
2399 return "ttrss_entries.date_entered >
2400 NOW() - INTERVAL '$days days'";
2402 return "ttrss_entries.date_entered >
2403 DATE_SUB(NOW(), INTERVAL $days DAY)";
2407 function getFeedUnread($link, $feed, $is_cat = false) {
2408 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2411 function getLabelUnread($link, $label_id, $owner_uid = false) {
2412 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2414 $result = db_query($link, "
2415 SELECT COUNT(unread) AS unread FROM
2416 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2417 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2418 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2419 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2420 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2422 if (db_num_rows($result) != 0) {
2423 return db_fetch_result($result, 0, "unread");
2429 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2430 $owner_uid = false) {
2432 $n_feed = sprintf("%d", $feed);
2434 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2437 $unread_qpart = "unread = true";
2439 $unread_qpart = "true";
2442 $age_qpart = getMaxAgeSubquery();
2445 return getCategoryUnread($link, $n_feed, $owner_uid);
2446 } else if ($n_feed == -1) {
2447 $match_part = "marked = true";
2448 } else if ($n_feed == -2) {
2449 $match_part = "published = true";
2450 } else if ($n_feed == -3) {
2451 $match_part = "unread = true";
2453 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2455 if (DB_TYPE
== "pgsql") {
2456 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2458 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2460 } else if ($n_feed == -4) {
2461 $match_part = "true";
2462 } else if ($n_feed > 0) {
2464 $result = db_query($link, "SELECT id FROM ttrss_feeds
2465 WHERE parent_feed = '$n_feed'
2467 AND owner_uid = " . $owner_uid);
2469 if (db_num_rows($result) > 0) {
2471 $linked_feeds = array();
2472 while ($line = db_fetch_assoc($result)) {
2473 array_push($linked_feeds, "feed_id = " . $line["id"]);
2476 array_push($linked_feeds, "feed_id = $n_feed");
2478 $match_part = implode(" OR ", $linked_feeds);
2480 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2481 FROM ttrss_user_entries,ttrss_entries
2482 WHERE $unread_qpart AND
2483 ttrss_user_entries.ref_id = ttrss_entries.id AND
2486 owner_uid = " . $owner_uid);
2490 # this needs to be rewritten
2491 while ($line = db_fetch_assoc($result)) {
2492 $unread +
= $line["unread"];
2498 $match_part = "feed_id = '$n_feed'";
2500 } else if ($feed < -10) {
2502 $label_id = -$feed - 11;
2504 return getLabelUnread($link, $label_id, $owner_uid);
2510 $result = db_query($link, "SELECT count(int_id) AS unread
2511 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2512 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2513 ttrss_user_entries.ref_id = ttrss_entries.id AND
2514 ttrss_feeds.hidden = false AND
2516 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2520 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2521 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2522 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2523 AND $unread_qpart AND $age_qpart AND
2524 ttrss_tags.owner_uid = " . $owner_uid);
2527 $unread = db_fetch_result($result, 0, "unread");
2532 function getGlobalUnread($link, $user_id = false) {
2535 $user_id = $_SESSION["uid"];
2538 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2539 WHERE owner_uid = '$user_id' AND feed_id > 0");
2541 $c_id = db_fetch_result($result, 0, "c_id");
2546 function getGlobalCounters($link, $global_unread = -1) {
2547 if ($global_unread == -1) {
2548 $global_unread = getGlobalUnread($link);
2550 print "<counter type=\"global\" id='global-unread'
2551 counter='$global_unread'/>";
2553 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2554 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2556 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2558 print "<counter type=\"global\" id='subscribed-feeds'
2559 counter='$subscribed_feeds'/>";
2563 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2566 if (!$_SESSION["tctr_last_value"]) {
2567 $_SESSION["tctr_last_value"] = array();
2571 $old_counters = $_SESSION["tctr_last_value"];
2573 $tctrs_modified = false;
2575 $age_qpart = getMaxAgeSubquery();
2577 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2578 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2579 AND ref_id = id AND $age_qpart
2580 AND unread = true)) AS count FROM ttrss_tags
2581 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2582 ORDER BY count DESC LIMIT 55");
2586 while ($line = db_fetch_assoc($result)) {
2587 $tags[$line["tag_name"]] +
= $line["count"];
2590 foreach (array_keys($tags) as $tag) {
2591 $unread = $tags[$tag];
2593 $tag = htmlspecialchars($tag);
2595 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2596 $old_counters[$tag] = $unread;
2597 $tctrs_modified = true;
2598 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2603 if ($smart_mode && $tctrs_modified) {
2604 $_SESSION["tctr_last_value"] = $old_counters;
2609 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2611 $age_qpart = getMaxAgeSubquery();
2614 if (!$_SESSION["lctr_last_value"]) {
2615 $_SESSION["lctr_last_value"] = array();
2621 for ($i = -1; $i >= -4; $i--) {
2623 $count = getFeedUnread($link, $i);
2627 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2628 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2633 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2635 $ret_arr[$i]["counter"] = $count;
2636 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2641 $old_counters = $_SESSION["lctr_last_value"];
2642 $lctrs_modified = false;
2645 $owner_uid = $_SESSION["uid"];
2647 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2648 WHERE owner_uid = '$owner_uid'");
2650 while ($line = db_fetch_assoc($result)) {
2652 $id = -$line["id"] - 11;
2654 $label_name = $line["caption"];
2655 $count = getFeedUnread($link, $id);
2657 if (!$smart_mode ||
$old_counters[$id] != $count) {
2658 $old_counters[$id] = $count;
2659 $lctrs_modified = true;
2662 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2663 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2668 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2670 $ret_arr[$id]["counter"] = $count;
2671 $ret_arr[$id]["description"] = $label_name;
2675 error_reporting (DEFAULT_ERROR_LEVEL
);
2678 if ($smart_mode && $lctrs_modified) {
2679 $_SESSION["lctr_last_value"] = $old_counters;
2685 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2687 $age_qpart = getMaxAgeSubquery();
2690 if (!$_SESSION["fctr_last_value"]) {
2691 $_SESSION["fctr_last_value"] = array();
2695 $old_counters = $_SESSION["fctr_last_value"];
2697 $query = "SELECT ttrss_feeds.id,
2699 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2700 last_error, value AS count
2701 FROM ttrss_feeds, ttrss_counters_cache
2702 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2703 AND parent_feed IS NULL
2704 AND ttrss_counters_cache.feed_id = id";
2706 $result = db_query($link, $query);
2707 $fctrs_modified = false;
2709 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2711 while ($line = db_fetch_assoc($result)) {
2714 $count = $line["count"];
2715 $last_error = htmlspecialchars($line["last_error"]);
2717 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2718 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2720 $last_updated = date($short_date, strtotime($line["last_updated"]));
2723 $last_updated = htmlspecialchars($last_updated);
2725 $has_img = feed_has_icon($id);
2727 $tmp_result = db_query($link,
2728 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2729 WHERE parent_feed = '$id' AND feed_id = id");
2731 $count +
= db_fetch_result($tmp_result, 0, "unread");
2733 if (!$smart_mode ||
$old_counters[$id] != $count) {
2734 $old_counters[$id] = $count;
2735 $fctrs_modified = true;
2738 $error_part = "error=\"$last_error\"";
2744 $has_img_part = "hi=\"$has_img\"";
2749 if ($active_feed && $id == $active_feed) {
2750 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2752 $has_title_part = "";
2755 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2756 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2759 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2763 if ($smart_mode && $fctrs_modified) {
2764 $_SESSION["fctr_last_value"] = $old_counters;
2768 function get_script_dt_add() {
2769 /* if (strpos(VERSION, ".99") === false) {
2777 function get_pgsql_version($link) {
2778 $result = db_query($link, "SELECT version() AS version");
2779 $version = split(" ", db_fetch_result($result, 0, "version"));
2783 function print_error_xml($code, $add_msg = "") {
2786 $error_msg = $ERRORS[$code];
2789 $error_msg = "$error_msg; $add_msg";
2792 print "<rpc-reply>";
2793 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2794 print "</rpc-reply>";
2797 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2798 $auth_login = '', $auth_pass = '') {
2800 # check for feed:http://url
2801 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2803 # check for feed://URL
2804 if (strpos($feed_link, "//") === 0) {
2805 $feed_link = "http:$feed_link";
2808 if ($feed_link == "") return;
2810 if ($cat_id == "0" ||
!$cat_id) {
2811 $cat_qpart = "NULL";
2813 $cat_qpart = "'$cat_id'";
2816 $result = db_query($link,
2817 "SELECT id FROM ttrss_feeds
2818 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2820 if (db_num_rows($result) == 0) {
2822 $result = db_query($link,
2823 "INSERT INTO ttrss_feeds
2824 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2825 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2826 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2828 $result = db_query($link,
2829 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2830 AND owner_uid = " . $_SESSION["uid"]);
2832 $feed_id = db_fetch_result($result, 0, "id");
2835 update_rss_feed($link, $feed_link, $feed_id, true);
2844 function print_feed_select($link, $id, $default_id = "",
2845 $attributes = "", $include_all_feeds = true) {
2847 print "<select id=\"$id\" name=\"$id\" $attributes>";
2848 if ($include_all_feeds) {
2849 print "<option value=\"0\">".__('All feeds')."</option>";
2852 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2853 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2855 if (db_num_rows($result) > 0 && $include_all_feeds) {
2856 print "<option disabled>--------</option>";
2859 while ($line = db_fetch_assoc($result)) {
2860 if ($line["id"] == $default_id) {
2861 $is_selected = "selected";
2865 printf("<option $is_selected value='%d'>%s</option>",
2866 $line["id"], htmlspecialchars($line["title"]));
2872 function print_feed_cat_select($link, $id, $default_id = "",
2873 $attributes = "", $include_all_cats = true) {
2875 print "<select id=\"$id\" name=\"$id\" $attributes>";
2877 if ($include_all_cats) {
2878 print "<option value=\"0\">".__('Uncategorized')."</option>";
2881 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2882 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2884 if (db_num_rows($result) > 0 && $include_all_cats) {
2885 print "<option disabled>--------</option>";
2888 while ($line = db_fetch_assoc($result)) {
2889 if ($line["id"] == $default_id) {
2890 $is_selected = "selected";
2894 printf("<option $is_selected value='%d'>%s</option>",
2895 $line["id"], htmlspecialchars($line["title"]));
2901 function checkbox_to_sql_bool($val) {
2902 return ($val == "on") ?
"true" : "false";
2905 function getFeedCatTitle($link, $id) {
2907 return __("Special");
2908 } else if ($id < -10) {
2909 return __("Labels");
2910 } else if ($id > 0) {
2911 $result = db_query($link, "SELECT ttrss_feed_categories.title
2912 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2913 cat_id = ttrss_feed_categories.id");
2914 if (db_num_rows($result) == 1) {
2915 return db_fetch_result($result, 0, "title");
2917 return __("Uncategorized");
2920 return "getFeedCatTitle($id) failed";
2925 function getFeedTitle($link, $id) {
2927 return __("Starred articles");
2928 } else if ($id == -2) {
2929 return __("Published articles");
2930 } else if ($id == -3) {
2931 return __("Fresh articles");
2932 } else if ($id == -4) {
2933 return __("All articles");
2934 } else if ($id < -10) {
2935 $label_id = -$id - 11;
2936 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2937 if (db_num_rows($result) == 1) {
2938 return db_fetch_result($result, 0, "caption");
2940 return "Unknown label ($label_id)";
2943 } else if ($id > 0) {
2944 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2945 if (db_num_rows($result) == 1) {
2946 return db_fetch_result($result, 0, "title");
2948 return "Unknown feed ($id)";
2951 if (preg_match("/^-?[0-9][0-9]*$/", $id)) {
2952 return "getFeedTitle($id) failed";
2960 function get_session_cookie_name() {
2961 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2964 function print_init_params($link) {
2965 print "<init-params>";
2966 if ($_SESSION["stored-params"]) {
2967 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2969 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2970 print "<param key=\"$key\" value=\"$value\"/>";
2975 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2976 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2977 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2978 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2980 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2981 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2983 print "<param key=\"hide_read_feeds\" value=\"" .
2984 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2986 print "<param key=\"enable_feed_cats\" value=\"" .
2987 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2989 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2990 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2992 print "<param key=\"confirm_feed_catchup\" value=\"" .
2993 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2995 print "<param key=\"cdm_auto_catchup\" value=\"" .
2996 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2998 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3000 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3002 print "<param key=\"default_view_mode\" value=\"" .
3003 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3005 print "<param key=\"default_view_limit\" value=\"" .
3006 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3008 print "<param key=\"default_view_order_by\" value=\"" .
3009 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3011 print "<param key=\"prefs_active_tab\" value=\"" .
3012 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3014 print "<param key=\"infobox_disable_overlay\" value=\"" .
3015 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3017 print "<param key=\"icons_location\" value=\"" .
3020 print "<param key=\"hide_read_shows_special\" value=\"" .
3021 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3023 print "<param key=\"hide_feedlist\" value=\"" .
3024 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3026 print "<param key=\"bw_limit\" value=\"".
3027 (int) $_SESSION["bw_limit"]."\"/>";
3029 // print "<param key=\"sync_counters\" value=\"" .
3030 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3032 print "<param key=\"sync_counters\" value=\"1\"/>";
3034 print "<param key=\"offline_enabled\" value=\"".
3035 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3037 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3038 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3040 $num_feeds = db_fetch_result($result, 0, "cf");
3042 print "<param key=\"num_feeds\" value=\"".
3043 (int)$num_feeds. "\"/>";
3045 print "</init-params>";
3048 function print_runtime_info($link) {
3049 print "<runtime-info>";
3051 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3052 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3054 $num_feeds = db_fetch_result($result, 0, "cf");
3056 print "<param key=\"num_feeds\" value=\"".
3057 (int)$num_feeds. "\"/>";
3059 if (ENABLE_UPDATE_DAEMON
) {
3060 print "<param key=\"daemon_is_running\" value=\"".
3061 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3063 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3065 $stamp = (int)read_stampfile("update_daemon.stamp");
3067 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3070 $stamp_delta = time() - $stamp;
3072 if ($stamp_delta > 1800) {
3076 $_SESSION["daemon_stamp_check"] = time();
3079 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3081 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3083 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3088 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3090 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3091 $new_version_details = check_for_update($link);
3093 print "<param key=\"new_version_available\" value=\"".
3094 sprintf("%d", $new_version_details != ""). "\"/>";
3096 $_SESSION["last_version_check"] = time();
3100 // print "<param key=\"new_version_available\" value=\"1\"/>";
3102 print "</runtime-info>";
3105 function getSearchSql($search, $match_on) {
3107 $search_query_part = "";
3109 $keywords = split(" ", $search);
3110 $query_keywords = array();
3112 if ($match_on == "both") {
3114 foreach ($keywords as $k) {
3115 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3116 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3119 $search_query_part = implode("AND", $query_keywords) . " AND ";
3121 } else if ($match_on == "title") {
3123 foreach ($keywords as $k) {
3124 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3127 $search_query_part = implode("AND", $query_keywords) . " AND ";
3129 } else if ($match_on == "content") {
3131 foreach ($keywords as $k) {
3132 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3136 $search_query_part = implode("AND", $query_keywords);
3138 return $search_query_part;
3141 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3143 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3147 $search_query_part = getSearchSql($search, $match_on);
3148 $search_query_part .= " AND ";
3151 $search_query_part = "";
3154 $view_query_part = "";
3156 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3158 $view_query_part = " ";
3159 } else if ($feed != -1) {
3160 $unread = getFeedUnread($link, $feed, $cat_view);
3162 $view_query_part = " unread = true AND ";
3167 if ($view_mode == "marked") {
3168 $view_query_part = " marked = true AND ";
3171 if ($view_mode == "unread") {
3172 $view_query_part = " unread = true AND ";
3175 if ($view_mode == "updated") {
3176 $view_query_part = " (last_read is null and unread = false) AND ";
3180 $limit_query_part = "LIMIT " . $limit;
3183 $vfeed_query_part = "";
3185 // override query strategy and enable feed display when searching globally
3186 if ($search && $search_mode == "all_feeds") {
3187 $query_strategy_part = "ttrss_entries.id > 0";
3188 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3189 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3190 $query_strategy_part = "ttrss_entries.id > 0";
3191 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3192 id = feed_id) as feed_title,";
3193 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3195 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3197 $tmp_result = false;
3200 $tmp_result = db_query($link, "SELECT id
3201 FROM ttrss_feeds WHERE cat_id = '$feed'");
3203 $tmp_result = db_query($link, "SELECT id
3204 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3205 WHERE id = '$feed') AND id != '$feed'");
3208 $cat_siblings = array();
3210 if (db_num_rows($tmp_result) > 0) {
3211 while ($p = db_fetch_assoc($tmp_result)) {
3212 array_push($cat_siblings, "feed_id = " . $p["id"]);
3215 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3216 $feed, implode(" OR ", $cat_siblings));
3219 $query_strategy_part = "ttrss_entries.id > 0";
3222 } else if ($feed >= 0) {
3227 $query_strategy_part = "cat_id = '$feed'";
3229 $query_strategy_part = "cat_id IS NULL";
3232 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3235 $tmp_result = db_query($link, "SELECT id
3236 FROM ttrss_feeds WHERE parent_feed = '$feed'
3237 ORDER BY cat_id,title");
3239 $parent_ids = array();
3241 if (db_num_rows($tmp_result) > 0) {
3242 while ($p = db_fetch_assoc($tmp_result)) {
3243 array_push($parent_ids, "feed_id = " . $p["id"]);
3246 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3247 $feed, implode(" OR ", $parent_ids));
3249 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3251 $query_strategy_part = "feed_id = '$feed'";
3254 } else if ($feed == -1) { // starred virtual feed
3255 $query_strategy_part = "marked = true";
3256 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3257 } else if ($feed == -2) { // published virtual feed OR labels category
3260 $query_strategy_part = "published = true";
3261 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3263 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3265 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3267 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3268 ttrss_user_labels2.article_id = ref_id";
3272 } else if ($feed == -3) { // fresh virtual feed
3273 $query_strategy_part = "unread = true";
3275 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3277 if (DB_TYPE
== "pgsql") {
3278 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3280 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3283 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3284 } else if ($feed == -4) { // all articles virtual feed
3285 $query_strategy_part = "true";
3286 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3287 } else if ($feed <= -10) { // labels
3288 $label_id = -$feed - 11;
3290 $query_strategy_part = "label_id = '$label_id' AND
3291 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3292 ttrss_user_labels2.article_id = ref_id";
3294 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3295 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3298 $query_strategy_part = "id > 0"; // dumb
3301 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3302 $order_by = "updated";
3304 $order_by = "updated DESC";
3307 if ($view_mode != "noscores") {
3308 $order_by = "score DESC, $order_by";
3311 if ($override_order) {
3312 $order_by = $override_order;
3317 if ($search && $search_mode == "all_feeds") {
3318 $feed_title = __("Search results")." ($search)";
3319 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3320 $feed_title = __("Search results")." ($search, $feed)";
3321 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3322 $feed_title = $feed;
3323 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3328 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3329 WHERE id = '$feed' AND owner_uid = $owner_uid");
3330 $feed_title = db_fetch_result($result, 0, "title");
3332 $feed_title = __("Uncategorized");
3336 $feed_title = __("Searched for")." $search ($feed_title)";
3341 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3342 WHERE id = '$feed' AND owner_uid = $owner_uid");
3344 $feed_title = db_fetch_result($result, 0, "title");
3345 $feed_site_url = db_fetch_result($result, 0, "site_url");
3346 $last_error = db_fetch_result($result, 0, "last_error");
3349 $feed_title = __("Searched for") . " $search ($feed_title)";
3353 } else if ($feed == -1) {
3354 $feed_title = __("Starred articles");
3355 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3356 } else if ($feed == -2) {
3358 $feed_title = __("Published articles");
3359 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3361 $feed_title = __("Labels");
3363 } else if ($feed == -3) {
3364 $feed_title = __("Fresh articles");
3365 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3366 } else if ($feed == -4) {
3367 $feed_title = __("All articles");
3368 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3369 } else if ($feed < -10) {
3370 $label_id = -$feed - 11;
3371 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3372 WHERE id = '$label_id'");
3373 $feed_title = db_fetch_result($result, 0, "caption");
3376 $feed_title = __("Searched for") . " $search ($feed_title)";
3382 $content_query_part = "content as content_preview,";
3384 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3387 $feed_kind = "Feeds";
3389 $feed_kind = "Labels";
3392 if ($limit_query_part) {
3393 $offset_query_part = "OFFSET $offset";
3396 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3397 if (!$override_order) {
3398 $order_by = "ttrss_feeds.title, $order_by";
3401 // Special output for Fresh feed
3403 /* if ($feed == -3) {
3404 $group_limit_part = "(select count(*) from
3405 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3406 t1.ref_id = t2.id and t1.owner_uid = 2 and
3407 t1.feed_id = ttrss_user_entries.feed_id and
3408 t2.updated > ttrss_entries.updated) <= 5 AND";
3412 $query = "SELECT DISTINCT
3414 ttrss_entries.id,ttrss_entries.title,
3417 unread,feed_id,marked,published,link,last_read,
3418 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3421 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3424 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3427 ttrss_feeds.hidden = false AND
3428 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3429 ttrss_user_entries.ref_id = ttrss_entries.id AND
3430 ttrss_user_entries.owner_uid = '$owner_uid' AND
3433 $query_strategy_part ORDER BY $order_by
3434 $limit_query_part $offset_query_part";
3436 if ($_GET["debug"]) print $query;
3438 $result = db_query($link, $query);
3443 $feed_kind = "Tags";
3445 $result = db_query($link, "SELECT
3448 ttrss_entries.id as id,title,
3451 marked,link,last_read,
3452 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3455 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3458 ttrss_entries,ttrss_user_entries,ttrss_tags
3460 ref_id = ttrss_entries.id AND
3461 ttrss_user_entries.owner_uid = '$owner_uid' AND
3462 post_int_id = int_id AND tag_name = '$feed' AND
3465 $query_strategy_part ORDER BY $order_by
3466 $limit_query_part");
3469 return array($result, $feed_title, $feed_site_url, $last_error);
3473 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3474 $limit, $search, $search_mode, $match_on) {
3476 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3477 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3478 "margin-bottom : 1em; color : #9a8c59;";
3480 if (!$limit) $limit = 30;
3482 $qfh_ret = queryFeedHeadlines($link, $feed,
3483 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3486 $result = $qfh_ret[0];
3487 $feed_title = htmlspecialchars($qfh_ret[1]);
3488 $feed_site_url = $qfh_ret[2];
3489 $last_error = $qfh_ret[3];
3491 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3493 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3494 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3495 <rss version=\"2.0\">
3497 <title>$feed_title</title>
3498 <link>$feed_site_url</link>
3499 <description>Feed generated by Tiny Tiny RSS</description>";
3501 while ($line = db_fetch_assoc($result)) {
3503 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3504 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3506 $tags = get_article_tags($link, $line["id"], $owner_uid);
3508 foreach ($tags as $tag) {
3509 print "<category>" . htmlspecialchars($tag) . "</category>";
3512 $rfc822_date = date('r', strtotime($line["updated"]));
3514 print "<pubDate>$rfc822_date</pubDate>";
3517 htmlspecialchars($line["title"]) . "</title>";
3519 print "<description><![CDATA[";
3521 if ($line["note"]) {
3522 print "<div style='$note_style'>";
3523 print $line["note"];
3527 print sanitize_rss($link, $line["content_preview"]);
3528 print "]]></description>";
3533 print "</channel></rss>";
3537 function getCategoryTitle($link, $cat_id) {
3539 if ($cat_id == -1) {
3540 return __("Special");
3541 } else if ($cat_id == -2) {
3542 return __("Labels");
3545 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3548 if (db_num_rows($result) == 1) {
3549 return db_fetch_result($result, 0, "title");
3551 return "Uncategorized";
3556 function strip_tags_long($string, $allowed) {
3558 $config = HTMLPurifier_Config
::createDefault();
3560 $config->set('HTML', 'Allowed', $allowed);
3561 $purifier = new HTMLPurifier($config);
3563 return $purifier->purify($string);
3567 // http://ru2.php.net/strip-tags
3569 /* function strip_tags_long($textstring, $allowed){
3570 while($textstring != strip_tags($textstring, $allowed))
3572 while (strlen($textstring) != 0)
3574 if (strlen($textstring) > 1024) {
3577 $otherlen = strlen($textstring);
3579 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3580 $safetext .= $temptext;
3581 $textstring = substr_replace($textstring,'',0,$otherlen);
3583 $textstring = $safetext;
3589 function sanitize_rss($link, $str, $force_strip_tags = false) {
3592 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3594 // $res = strip_tags_long($res,
3595 // "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3597 $res = strip_tags_long($res,
3598 "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4");
3602 if (get_pref($link, "STRIP_IMAGES")) {
3604 $res = preg_replace('/<img[^>]+>/is', '', $res);
3612 * Send by mail a digest of last articles.
3614 * @param mixed $link The database connection.
3615 * @param integer $limit The maximum number of articles by digest.
3616 * @return boolean Return false if digests are not enabled.
3618 function send_headlines_digests($link, $limit = 100) {
3620 if (!DIGEST_ENABLE
) return false;
3622 $user_limit = DIGEST_EMAIL_LIMIT
;
3625 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3627 if (DB_TYPE
== "pgsql") {
3628 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3629 } else if (DB_TYPE
== "mysql") {
3630 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3633 $result = db_query($link, "SELECT id,email FROM ttrss_users
3634 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3636 while ($line = db_fetch_assoc($result)) {
3638 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3639 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3641 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3643 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3644 $digest = $tuple[0];
3645 $headlines_count = $tuple[1];
3646 $affected_ids = $tuple[2];
3647 $digest_text = $tuple[3];
3649 if ($headlines_count > 0) {
3651 $mail = new PHPMailer();
3653 $mail->PluginDir
= "lib/phpmailer/";
3654 $mail->SetLanguage("en", "lib/phpmailer/language/");
3656 $mail->CharSet
= "UTF-8";
3658 $mail->From
= DIGEST_FROM_ADDRESS
;
3659 $mail->FromName
= DIGEST_FROM_NAME
;
3660 $mail->AddAddress($line["email"], $line["login"]);
3662 if (DIGEST_SMTP_HOST
) {
3663 $mail->Host
= DIGEST_SMTP_HOST
;
3664 $mail->Mailer
= "smtp";
3665 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3666 $mail->Username
= DIGEST_SMTP_LOGIN
;
3667 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3670 $mail->IsHTML(true);
3671 $mail->Subject
= DIGEST_SUBJECT
;
3672 $mail->Body
= $digest;
3673 $mail->AltBody
= $digest_text;
3675 $rc = $mail->Send();
3677 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3681 if ($rc && $do_catchup) {
3682 print "Marking affected articles as read...\n";
3683 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3686 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3687 WHERE id = " . $line["id"]);
3689 print "No headlines\n";
3694 print "All done.\n";
3698 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3700 require_once "lib/MiniTemplator.class.php";
3702 $tpl = new MiniTemplator
;
3703 $tpl_t = new MiniTemplator
;
3705 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3706 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3708 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3709 $tpl->setVariable('CUR_TIME', date('G:i'));
3711 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3712 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3714 $affected_ids = array();
3716 if (DB_TYPE
== "pgsql") {
3717 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3718 } else if (DB_TYPE
== "mysql") {
3719 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3722 $result = db_query($link, "SELECT ttrss_entries.title,
3723 ttrss_feeds.title AS feed_title,
3725 ttrss_user_entries.ref_id,
3727 SUBSTRING(content, 1, 120) AS excerpt,
3728 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3730 ttrss_user_entries,ttrss_entries,ttrss_feeds
3732 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3733 AND include_in_digest = true
3736 AND ttrss_user_entries.owner_uid = $user_id
3738 ORDER BY ttrss_feeds.title, date_entered DESC
3741 $cur_feed_title = "";
3743 $headlines_count = db_num_rows($result);
3745 $headlines = array();
3747 while ($line = db_fetch_assoc($result)) {
3748 array_push($headlines, $line);
3751 for ($i = 0; $i < sizeof($headlines); $i++
) {
3753 $line = $headlines[$i];
3755 array_push($affected_ids, $line["ref_id"]);
3757 $updated = smart_date_time(strtotime($line["last_updated"]));
3759 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3760 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3761 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3762 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3763 $tpl->setVariable('ARTICLE_EXCERPT',
3764 truncate_string(strip_tags($line["excerpt"]), 100));
3766 $tpl->addBlock('article');
3768 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3769 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3770 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3771 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3772 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3773 // truncate_string(strip_tags($line["excerpt"]), 100));
3775 $tpl_t->addBlock('article');
3777 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3778 $tpl->addBlock('feed');
3779 $tpl_t->addBlock('feed');
3784 $tpl->addBlock('digest');
3785 $tpl->generateOutputToString($tmp);
3787 $tpl_t->addBlock('digest');
3788 $tpl_t->generateOutputToString($tmp_t);
3790 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3793 function check_for_update($link) {
3794 $releases_feed = "http://tt-rss.org/releases.rss";
3796 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3801 if (ENABLE_SIMPLEPIE
) {
3802 $rss = new SimplePie();
3803 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3804 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3805 $rss->set_feed_url($fetch_url);
3806 $rss->set_output_encoding('UTF-8');
3809 $rss = fetch_rss($releases_feed);
3811 error_reporting (DEFAULT_ERROR_LEVEL
);
3815 if (ENABLE_SIMPLEPIE
) {
3816 $items = $rss->get_items();
3818 $items = $rss->items
;
3820 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3821 if (!$items ||
!is_array($items)) $items = $rss;
3824 if (!is_array($items) ||
count($items) == 0) {
3828 $latest_item = $items[0];
3830 if (ENABLE_SIMPLEPIE
) {
3831 $last_title = $latest_item->get_title();
3833 $last_title = $latest_item["title"];
3836 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3838 if (ENABLE_SIMPLEPIE
) {
3839 $release_url = sanitize_rss($link, $latest_item->get_link());
3840 $content = sanitize_rss($link, $latest_item->get_description());
3842 $release_url = sanitize_rss($link, $latest_item["link"]);
3843 $content = sanitize_rss($link, $latest_item["description"]);
3846 if (version_compare(VERSION
, $latest_version) == -1) {
3847 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3848 $latest_version)."<div class='milestoneDetails'>$content</div>";
3855 function markArticlesById($link, $ids, $cmode) {
3859 foreach ($ids as $id) {
3860 array_push($tmp_ids, "ref_id = '$id'");
3863 $ids_qpart = join(" OR ", $tmp_ids);
3866 db_query($link, "UPDATE ttrss_user_entries SET
3867 marked = false,last_read = NOW()
3868 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3869 } else if ($cmode == 1) {
3870 db_query($link, "UPDATE ttrss_user_entries SET
3872 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3874 db_query($link, "UPDATE ttrss_user_entries SET
3875 marked = NOT marked,last_read = NOW()
3876 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3880 function publishArticlesById($link, $ids, $cmode) {
3884 foreach ($ids as $id) {
3885 array_push($tmp_ids, "ref_id = '$id'");
3888 $ids_qpart = join(" OR ", $tmp_ids);
3891 db_query($link, "UPDATE ttrss_user_entries SET
3892 published = false,last_read = NOW()
3893 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3894 } else if ($cmode == 1) {
3895 db_query($link, "UPDATE ttrss_user_entries SET
3897 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3899 db_query($link, "UPDATE ttrss_user_entries SET
3900 published = NOT published,last_read = NOW()
3901 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3905 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3907 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3911 foreach ($ids as $id) {
3912 array_push($tmp_ids, "ref_id = '$id'");
3915 $ids_qpart = join(" OR ", $tmp_ids);
3918 db_query($link, "UPDATE ttrss_user_entries SET
3919 unread = false,last_read = NOW()
3920 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3921 } else if ($cmode == 1) {
3922 db_query($link, "UPDATE ttrss_user_entries SET
3924 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3926 db_query($link, "UPDATE ttrss_user_entries SET
3927 unread = NOT unread,last_read = NOW()
3928 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3933 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3934 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3936 while ($line = db_fetch_assoc($result)) {
3937 ccache_update($link, $line["feed_id"], $owner_uid);
3941 function catchupArticleById($link, $id, $cmode) {
3944 db_query($link, "UPDATE ttrss_user_entries SET
3945 unread = false,last_read = NOW()
3946 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3947 } else if ($cmode == 1) {
3948 db_query($link, "UPDATE ttrss_user_entries SET
3950 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3952 db_query($link, "UPDATE ttrss_user_entries SET
3953 unread = NOT unread,last_read = NOW()
3954 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3958 function make_guid_from_title($title) {
3959 return preg_replace("/[ \"\',.:;]/", "-",
3960 mb_strtolower(strip_tags($title), 'utf-8'));
3963 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3964 $feed_id, $is_cat, $search, $match_on,
3967 print "<div class=\"headlinesSubToolbar\">";
3969 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3970 $page_next_link = "javascript:viewFeedGoPage(1)";
3971 $page_first_link = "javascript:viewFeedGoPage(0)";
3973 $catchup_page_link = "javascript:catchupPage()";
3974 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3975 $catchup_sel_link = "javascript:catchupSelection()";
3977 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3979 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3980 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3981 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3982 $sel_inv_link = "javascript:invertHeadlineSelection()";
3984 $tog_unread_link = "javascript:selectionToggleUnread()";
3985 $tog_marked_link = "javascript:selectionToggleMarked()";
3986 $tog_published_link = "javascript:selectionTogglePublished()";
3990 $sel_all_link = "javascript:cdmSelectArticles('all')";
3991 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3992 $sel_none_link = "javascript:cdmSelectArticles('none')";
3994 $sel_inv_link = "javascript:invertHeadlineSelection()";
3996 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3997 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3998 $tog_published_link = "javascript:selectionTogglePublished(true)";
4002 print "<div id=\"subtoolbar_ftitle\">";
4004 if ($feed_site_url) {
4006 $target = "target=\"_blank\"";
4008 print "<a $target href=\"$feed_site_url\">".
4009 truncate_string($feed_title,30)."</a>";
4015 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4019 <a target=\"_blank\"
4020 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4021 <img class=\"noborder\"
4022 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4027 print __('Select:')."
4028 <a href=\"$sel_all_link\">".__('All')."</a>,
4029 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4030 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4031 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4033 print " ";
4036 onmouseover=\"enable_selection(false)\"
4037 onmouseout=\"enable_selection(true)\"
4038 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4039 __("Actions...") . " <img width='11' height'7'
4040 src=\"images/down_arrow.png\">
4043 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4045 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4046 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4047 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4048 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4049 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4050 <li class=\"insensitive\">".__('Mark as read:')."</li>
4051 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4053 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4056 //print "<li><span class=\"insensitive\">--------</span></li>";
4057 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4059 print_labels_headlines_dropdown($link, $feed_id);
4066 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4068 $tmp_category = getCategoryTitle($link, $cat_id);
4071 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4072 } else if ($cat_id == 0 ||
$cat_id == -2) {
4073 $cat_unread = getCategoryUnread($link, $cat_id);
4077 $holder_style = "display:none;";
4084 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4087 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4088 $inner_title_class = "catTitle";
4090 $browse_cat_link = "";
4091 $inner_title_class = "catTitleNL";
4094 $cat_class = "feedCat";
4096 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4097 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4098 title=\"".__('Click to collapse category')."\"
4099 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4100 id=\"FCATN-$cat_id\" $browse_cat_link
4101 \">$tmp_category</span>";
4103 print "<span id=\"FCAP-$cat_id\">";
4105 print " <span id=\"FCATCTR-$cat_id\"
4106 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4112 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4116 function outputFeedList($link, $tags = false) {
4118 print "<ul class=\"feedList\" id=\"feedList\">";
4120 $owner_uid = $_SESSION["uid"];
4124 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4126 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4129 $cat_hidden = false;
4132 printCategoryHeader($link, -1, $cat_hidden, false);
4135 $num_starred = getFeedUnread($link, -1);
4136 $num_published = getFeedUnread($link, -2);
4137 $num_fresh = getFeedUnread($link, -3);
4138 $num_total = getFeedUnread($link, -4);
4142 if ($num_total > 0) $class .= "Unread";
4144 printFeedEntry(-4, $class, __("All articles"), $num_total,
4145 "images/tag.png", $link);
4149 if ($num_fresh > 0) $class .= "Unread";
4151 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4152 "images/fresh.png", $link);
4156 if ($num_starred > 0) $class .= "Unread";
4158 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4161 $mark_img_ext = "gif";
4163 $mark_img_ext = "png";
4166 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4167 "images/mark_set.$mark_img_ext", $link);
4171 if ($num_published > 0) $class .= "Unread";
4173 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4174 "images/pub_set.gif", $link);
4176 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4183 $result = db_query($link, "SELECT * FROM
4184 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4186 if (db_num_rows($result) > 0) {
4187 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4189 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4192 $cat_hidden = false;
4195 printCategoryHeader($link, -2, $cat_hidden, true);
4198 print "<li><hr></li>";
4202 while ($line = db_fetch_assoc($result)) {
4204 $label_id = -$line['id'] - 11;
4205 $count = getFeedUnread($link, $label_id);
4213 printFeedEntry($label_id,
4214 $class, $line["caption"],
4215 $count, "images/label.png", $link,
4216 false, false, false,
4217 $line['fg_color'], $line['bg_color']);
4221 if (db_num_rows($result) > 0) {
4222 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4228 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4229 print "<li><hr></li>";
4232 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4233 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4234 $order_by_qpart = "order_id,category,unread DESC,title";
4236 $order_by_qpart = "order_id,category,title";
4239 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4240 $order_by_qpart = "unread DESC,title";
4242 $order_by_qpart = "title";
4246 $age_qpart = getMaxAgeSubquery();
4248 $query = "SELECT ttrss_feeds.*,
4249 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4251 ttrss_feed_categories.title AS category,
4252 ttrss_feed_categories.collapsed,
4254 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4255 ON (ttrss_feed_categories.id = cat_id)
4256 LEFT JOIN ttrss_counters_cache
4258 (ttrss_feeds.id = feed_id)
4260 ttrss_feeds.hidden = false AND
4261 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4262 ORDER BY $order_by_qpart";
4264 $result = db_query($link, $query);
4266 $actid = $_GET["actid"];
4276 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4278 while ($line = db_fetch_assoc($result)) {
4280 $feed = htmlspecialchars(trim($line["title"]));
4282 if (!$feed) $feed = "[Untitled]";
4284 $feed_id = $line["id"];
4285 $unread = $line["unread"];
4287 $subop = $_GET["subop"];
4289 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4290 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4292 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4295 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4298 $rtl_tag = "dir=\"RTL\"";
4303 $tmp_result = db_query($link,
4304 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4305 WHERE parent_feed = '$feed_id' AND feed_id = id");
4307 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4309 $cat_id = $line["cat_id"];
4311 $tmp_category = $line["category"];
4313 if (!$tmp_category) {
4314 $tmp_category = __("Uncategorized");
4317 // $class = ($lnum % 2) ? "even" : "odd";
4319 if ($line["last_error"]) {
4325 if ($unread > 0) $class .= "Unread";
4327 if ($actid == $feed_id) {
4328 $class .= "Selected";
4331 $total_unread +
= $unread;
4333 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4339 $category = $tmp_category;
4341 $collapsed = sql_bool_to_bool($line["collapsed"]);
4343 // workaround for NULL category
4344 if ($category == __("Uncategorized")) {
4345 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4350 $cat_id = sprintf("%d", $cat_id);
4352 printCategoryHeader($link, $cat_id, $collapsed, true);
4356 printFeedEntry($feed_id, $class, $feed, $unread,
4357 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4358 $last_updated, $line["last_error"]);
4363 if (db_num_rows($result) == 0) {
4364 print "<li>".__('No feeds to display.')."</li>";
4371 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4372 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4373 post_int_id = ttrss_user_entries.int_id AND
4374 unread = true AND ref_id = ttrss_entries.id
4375 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4377 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4378 ORDER BY tag_name"); */
4380 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4381 print "<li class=\"feedCat\">".__('Tags')."</li>";
4382 print "<ul class=\"feedCatList\">";
4385 $age_qpart = getMaxAgeSubquery();
4387 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4388 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4389 AND ref_id = id AND $age_qpart
4390 AND unread = true)) AS count FROM ttrss_tags
4391 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4392 ORDER BY count DESC LIMIT 50");
4396 while ($line = db_fetch_assoc($result)) {
4397 $tags[$line["tag_name"]] +
= $line["count"];
4400 foreach (array_keys($tags) as $tag) {
4402 $unread = $tags[$tag];
4410 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4414 if (db_num_rows($result) == 0) {
4415 print "<li>No tags to display.</li>";
4418 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4428 function get_article_tags($link, $id, $owner_uid = 0) {
4430 $a_id = db_escape_string($id);
4432 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4434 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4435 owner_uid as owner FROM
4436 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4437 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4441 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4442 array_push($tags, $tmp_line["tag_name"]);
4448 function trim_value(&$value) {
4449 $value = trim($value);
4452 function trim_array($array) {
4454 array_walk($tmp, 'trim_value');
4458 function tag_is_valid($tag) {
4459 if ($tag == '') return false;
4460 if (preg_match("/^[0-9]*$/", $tag)) return false;
4461 if (mb_strlen($tag) > 250) return false;
4463 if (function_exists('iconv')) {
4464 $tag = iconv("utf-8", "utf-8", $tag);
4467 if (!$tag) return false;
4472 function render_login_form($link, $mobile = false) {
4474 require_once "login_form.php";
4476 require_once "mobile/login_form.php";
4480 // from http://developer.apple.com/internet/safari/faq.html
4481 function no_cache_incantation() {
4482 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4483 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4484 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4485 header("Cache-Control: post-check=0, pre-check=0", false);
4486 header("Pragma: no-cache"); // HTTP/1.0
4489 function format_warning($msg, $id = "") {
4490 return "<div class=\"warning\" id=\"$id\">
4491 <img src=\"images/sign_excl.gif\">$msg</div>";
4494 function format_notice($msg) {
4495 return "<div class=\"notice\">
4496 <img src=\"images/sign_info.gif\">$msg</div>";
4499 function format_error($msg) {
4500 return "<div class=\"error\">
4501 <img src=\"images/sign_excl.gif\">$msg</div>";
4504 function print_notice($msg) {
4505 return print format_notice($msg);
4508 function print_warning($msg) {
4509 return print format_warning($msg);
4512 function print_error($msg) {
4513 return print format_error($msg);
4517 function T_sprintf() {
4518 $args = func_get_args();
4519 return vsprintf(__(array_shift($args)), $args);
4522 function format_inline_player($link, $url, $ctype) {
4526 if (($ctype == __("audio/mpeg")) && (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4528 $entry .= "<object type=\"application/x-shockwave-flash\"
4529 data=\"extras/button/musicplayer.swf?song_url=$url\"
4530 width=\"17\" height=\"17\">
4531 <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object>";
4536 if (substr($ctype,0,6)=="audio/" || $ctype=="application/ogg" || $ctype=="application/x-ogg") {
4537 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4538 if (($ctype == __("audio/mpeg")) &&
4539 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4540 $entry .= "<span><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></span>";
4542 $entry .= "</audio> ";
4543 if (($ctype == __("audio/mpeg")) &&
4544 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4545 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a>";
4546 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
4548 } elseif (substr($ctype,0,6)=="video/") {
4549 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4550 $entry .= "</video>";
4558 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4559 $zoom_mode = false) {
4561 /* we can figure out feed_id from article id anyway, why do we
4562 * pass feed_id here? */
4564 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4565 WHERE ref_id = '$id'");
4567 $feed_id = db_fetch_result($result, 0, "feed_id");
4569 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4571 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4572 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4574 if (db_num_rows($result) == 1) {
4575 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4576 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4578 $rtl_content = false;
4579 $always_display_enclosures = false;
4583 $rtl_tag = "dir=\"RTL\"";
4590 if ($mark_as_read) {
4591 $result = db_query($link, "UPDATE ttrss_user_entries
4592 SET unread = false,last_read = NOW()
4593 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4595 ccache_update($link, $feed_id, $_SESSION["uid"]);
4598 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4599 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4600 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4604 FROM ttrss_entries,ttrss_user_entries
4605 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4611 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4612 $link_target = "target=\"_blank\"";
4615 $line = db_fetch_assoc($result);
4617 if ($line["icon_url"]) {
4618 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4620 $feed_icon = " ";
4623 $num_comments = $line["num_comments"];
4624 $entry_comments = "";
4626 if ($num_comments > 0) {
4627 if ($line["comments"]) {
4628 $comments_url = $line["comments"];
4630 $comments_url = $line["link"];
4632 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4634 if ($line["comments"] && $line["link"] != $line["comments"]) {
4635 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4640 header("Content-Type: text/html");
4642 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4643 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4644 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4649 print "<div class=\"postReply\">";
4651 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4652 onmouseout=\"enable_resize(false)\">";
4654 $entry_author = $line["author"];
4656 if ($entry_author) {
4657 $entry_author = __(" - ") . $entry_author;
4660 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4661 strtotime($line["updated"]));
4663 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4665 if ($line["link"]) {
4666 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4667 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4669 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4672 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4674 if (!$entry_comments) $entry_comments = " "; # placeholder
4676 print "<div style='float : right'>
4677 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'> ";
4680 print "<span id=\"ATSTR-$id\">$tags_str</span>
4681 <a title=\"".__('Edit tags for this article')."\"
4682 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4684 if (defined('_ENABLE_INLINE_VIEW')) {
4686 print "<img src=\"images/art-inline.png\" class='tagsPic'
4687 style=\"cursor : pointer\" style=\"cursor : pointer\"
4688 onclick=\"showOriginalArticleInline($id)\"
4689 alt='Inline' title='".__('Display original article content')."'>";
4693 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4694 style=\"cursor : pointer\" style=\"cursor : pointer\"
4695 onclick=\"zoomToArticle($id)\"
4696 alt='Zoom' title='".__('Show article summary in new window')."'>";
4698 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4700 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4701 style=\"cursor : pointer\" style=\"cursor : pointer\"
4702 onclick=\"publishWithNote($id, '$note_escaped')\"
4703 alt='PubNote' title='".__('Publish article with a note')."'>";
4707 print "<div clear='both'>$entry_comments</div>";
4711 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4713 print "<div class=\"postContent\">";
4715 $article_content = sanitize_rss($link, $line["content"]);
4717 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4718 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4722 print "<div id=\"POSTNOTE-$id\">";
4723 if ($line['note']) {
4724 print format_article_note($id, $line['note']);
4728 print $article_content;
4730 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4731 post_id = '$id' AND content_url != ''");
4733 if (db_num_rows($result) > 0) {
4735 $entries_html = array();
4738 while ($line = db_fetch_assoc($result)) {
4740 $url = $line["content_url"];
4741 $ctype = $line["content_type"];
4743 if (!$ctype) $ctype = __("unknown type");
4745 $filename = substr($url, strrpos($url, "/")+
1);
4747 $entry = format_inline_player($link, $url, $ctype);
4749 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4750 $filename . " (" . $ctype . ")" . "</a>";
4752 array_push($entries_html, $entry);
4756 $entry["type"] = $ctype;
4757 $entry["filename"] = $filename;
4758 $entry["url"] = $url;
4760 array_push($entries, $entry);
4763 print "<div class=\"postEnclosures\">";
4765 if ($always_display_enclosures ||
!preg_match("/<img/i", $article_content)) {
4766 foreach ($entries as $entry) {
4767 if (preg_match("/image/", $entry["type"])) {
4769 alt=\"".htmlspecialchars($entry["filename"])."\"
4770 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4775 print "<div class=\"postEnclosures\">";
4777 if (db_num_rows($result) == 1) {
4778 print __("Attachment:") . " ";
4780 print __("Attachments:") . " ";
4783 print join(", ", $entries_html);
4795 print "]]></article>";
4798 <div style=\"text-align : center\">
4799 <input type=\"submit\" onclick=\"return window.close()\"
4800 value=\"".__("Close this window")."\"></div>";
4801 print "</body></html>";
4807 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4808 $next_unread_feed, $offset, $vgr_last_feed = false,
4809 $override_order = false) {
4811 $disable_cache = false;
4813 $timing_info = getmicrotime();
4815 $topmost_article_ids = array();
4821 if ($subop == "undefined") $subop = "";
4823 $subop_split = split(":", $subop);
4825 if ($subop == "CatchupSelected") {
4826 $ids = split(",", db_escape_string($_GET["ids"]));
4827 $cmode = sprintf("%d", $_GET["cmode"]);
4829 catchupArticlesById($link, $ids, $cmode);
4832 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4833 update_generic_feed($link, $feed, $cat_view, true);
4836 if ($subop == "MarkAllRead") {
4837 catchup_feed($link, $feed, $cat_view);
4839 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4840 if ($next_unread_feed) {
4841 $feed = $next_unread_feed;
4846 if ($subop_split[0] == "MarkAllReadGR") {
4847 catchup_feed($link, $subop_split[1], false);
4852 $result = db_query($link,
4853 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4855 if (db_num_rows($result) == 0) {
4856 print "<div align='center'>".__('Feed not found.')."</div>";
4861 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4863 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4864 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4866 if (db_num_rows($result) == 1) {
4867 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4869 $rtl_content = false;
4873 $rtl_tag = "dir=\"RTL\"";
4879 $rtl_content = false;
4882 $script_dt_add = get_script_dt_add();
4884 /// START /////////////////////////////////////////////////////////////////////////////////
4886 $search = db_escape_string($_GET["query"]);
4889 $disable_cache = true;
4892 $search_mode = db_escape_string($_GET["search_mode"]);
4893 $match_on = db_escape_string($_GET["match_on"]);
4899 $real_offset = $offset * $limit;
4901 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4903 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4904 $search, $search_mode, $match_on, $override_order, $real_offset);
4906 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4908 $result = $qfh_ret[0];
4909 $feed_title = $qfh_ret[1];
4910 $feed_site_url = $qfh_ret[2];
4911 $last_error = $qfh_ret[3];
4913 $vgroup_last_feed = $vgr_last_feed;
4916 $feed_site_url = article_publish_url($link);
4919 /// STOP //////////////////////////////////////////////////////////////////////////////////
4922 print "<div id=\"headlinesContainer\" $rtl_tag>";
4925 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4929 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4930 $feed, $cat_view, $search, $match_on, $search_mode);
4932 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4935 $headlines_count = db_num_rows($result);
4937 if (db_num_rows($result) > 0) {
4939 # print "\{$offset}";
4941 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4942 print "<table class=\"headlinesList\" id=\"headlinesList\"
4943 cellspacing=\"0\">";
4946 $lnum = $limit*$offset;
4948 error_reporting (DEFAULT_ERROR_LEVEL
);
4951 $cur_feed_title = '';
4953 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4955 while ($line = db_fetch_assoc($result)) {
4957 $class = ($lnum %
2) ?
"even" : "odd";
4960 $feed_id = $line["feed_id"];
4962 $labels = get_article_labels($link, $id);
4964 $labels_str = "<span id=\"HLLCTR-$id\">";
4965 $labels_str .= format_article_labels($labels, $id);
4966 $labels_str .= "</span>";
4968 if (count($topmost_article_ids) < 5) {
4969 array_push($topmost_article_ids, $id);
4972 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4974 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4977 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4981 if (sql_bool_to_bool($line["unread"]) &&
4982 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4984 $update_pic = "<img id='FUPDPIC-$id' src=\"images/fresh_sign.png\"
4988 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4996 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4999 $mark_img_ext = "gif";
5001 $mark_img_ext = "png";
5004 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5005 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5007 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5009 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5011 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5014 if ($line["published"] == "t" ||
$line["published"] == "1") {
5015 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5017 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5019 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5021 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5024 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5025 # $line["title"] . "</a>";
5027 # $content_link = "<a
5028 # href=\"" . htmlspecialchars($line["link"]) . "\"
5029 # onclick=\"view($id,$feed_id);\">" .
5030 # $line["title"] . "</a>";
5032 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5033 # $line["title"] . "</a>";
5035 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5036 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5038 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5039 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5042 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5043 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5047 $score = $line["score"];
5049 $score_pic = get_score_pic($score);
5051 /* $score_title = __("(Click to change)");
5052 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5053 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5055 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5060 } else if ($score < -100) {
5066 $entry_author = $line["author"];
5068 if ($entry_author) {
5069 $entry_author = " - $entry_author";
5072 $has_feed_icon = feed_has_icon($feed_id);
5074 if ($has_feed_icon) {
5075 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5077 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5078 $feed_icon_img = "";
5081 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5083 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5084 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5086 $cur_feed_title = $line["feed_title"];
5087 $vgroup_last_feed = $feed_id;
5089 $cur_feed_title = htmlspecialchars($cur_feed_title);
5091 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5093 print "<tr class='feedTitle'><td colspan='7'>".
5094 "<div style=\"float : right\">$feed_icon_img</div>".
5095 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5096 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5100 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5101 onmouseout='postMouseOut($id)'";
5103 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5105 print "<td class='hlUpdPic'>$update_pic</td>";
5107 print "<td class='hlSelectRow'>
5108 <input type=\"checkbox\" onclick=\"tSR(this)\"
5112 print "<td class='hlMarkedPic'>$marked_pic</td>";
5113 print "<td class='hlMarkedPic'>$published_pic</td>";
5115 # if ($line["feed_title"]) {
5116 # print "<td class='hlContent'>$content_link</td>";
5117 # print "<td class='hlFeed'>
5118 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5119 # truncate_string($line["feed_title"],30)."</a> </td>";
5122 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5124 print "<a id=\"RTITLE-$id\"
5125 href=\"" . htmlspecialchars($line["link"]) . "\"
5126 onclick=\"return view($id,$feed_id);\">" .
5129 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5130 if ($content_preview) {
5131 print "<span class=\"contentPreview\"> - $content_preview</span>";
5139 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5140 # $line["feed_title"]."</a>
5142 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5143 if ($line["feed_title"]) {
5144 print "<span class=\"hlFeed\">
5145 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5146 $line["feed_title"]."</a>)
5154 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5156 print "<td class='hlMarkedPic'>$score_pic</td>";
5158 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5159 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5166 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5167 if ($feed_id != $vgroup_last_feed) {
5169 $cur_feed_title = $line["feed_title"];
5170 $vgroup_last_feed = $feed_id;
5172 $cur_feed_title = htmlspecialchars($cur_feed_title);
5174 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5176 $has_feed_icon = feed_has_icon($feed_id);
5178 if ($has_feed_icon) {
5179 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5181 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5184 print "<div class='cdmFeedTitle'>".
5185 "<div style=\"float : right\">$feed_icon_img</div>".
5186 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5187 $line["feed_title"]."</a> $vf_catchup_link</div>";
5192 $add_class = "Unread";
5197 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5198 $show_excerpt = false;
5200 if ($expand_cdm && $score >= -100) {
5202 $show_excerpt = false;
5204 $cdm_cstyle = "style=\"display : none\"";
5205 $show_excerpt = true;
5208 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5209 onmouseout='postMouseOut($id)'";
5211 print "<div class=\"cdmArticle$add_class\"
5213 $mouseover_attrs'>";
5215 print "<div class=\"cdmHeader\">";
5217 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5218 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5221 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5224 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5225 onclick=\"javascript:toggleUnread($id, 0)\"
5226 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5229 print $entry_author;
5231 /* if (!$expand_cdm || $score < -100) {
5232 print " <a id=\"CICH-$id\"
5233 href=\"javascript:cdmExpandArticle($id)\">
5234 (".__('Show article').")</a>";
5239 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5240 if ($line["feed_title"]) {
5241 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5245 print "</span></div>";
5247 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5248 $line["content_preview"] = preg_replace("/href=/i",
5249 "target=\"_blank\" href=", $line["content_preview"]);
5252 if ($show_excerpt) {
5253 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5254 onclick=\"cdmExpandArticle($id)\"
5255 title=\"".__('Click to expand article')."\">";
5257 $content_preview = trim(truncate_string(strip_tags($line["content_preview"]), 100));
5259 if (strlen($content_preview) != 0) {
5260 print $content_preview;
5262 print __('Click to expand article');
5267 print "<div class=\"cdmContent\"
5268 onclick=\"cdmClicked($id)\"
5269 id=\"CICD-$id\" $cdm_cstyle>";
5271 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5273 print "<div id=\"POSTNOTE-$id\">";
5274 if ($line['note']) {
5275 print format_article_note($id, $line['note']);
5279 print sanitize_rss($link, $line["content_preview"]);
5281 $article_content = $line["content_preview"];
5283 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5284 post_id = '$id' AND content_url != ''");
5286 if (db_num_rows($e_result) > 0) {
5288 $entries_html = array();
5291 while ($e_line = db_fetch_assoc($e_result)) {
5293 $url = $e_line["content_url"];
5294 $ctype = $e_line["content_type"];
5295 if (!$ctype) $ctype = __("unknown type");
5297 $filename = substr($url, strrpos($url, "/")+
1);
5299 $entry = format_inline_player($link, $url, $ctype);
5301 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5302 $filename . " (" . $ctype . ")" . "</a>";
5304 array_push($entries_html, $entry);
5308 $entry["type"] = $ctype;
5309 $entry["filename"] = $filename;
5310 $entry["url"] = $url;
5312 array_push($entries, $entry);
5315 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5316 ttrss_feeds WHERE id = ".$line['feed_id']." AND owner_uid = ".$_SESSION["uid"]);
5318 $always_display_enclosures = db_fetch_result($tmp_result, 0, "always_display_enclosures");
5320 if ($always_display_enclosures ||
!preg_match("/img/i", $article_content)) {
5321 foreach ($entries as $entry) {
5322 if (preg_match("/image/", $entry["type"])) {
5324 alt=\"".htmlspecialchars($entry["filename"])."\"
5325 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5330 print "<div class=\"cdmEnclosures\">";
5332 if (db_num_rows($e_result) == 1) {
5333 print __("Attachment:") . " ";
5335 print __("Attachments:") . " ";
5338 print join(", ", $entries_html);
5344 print "<br clear='both'>";
5347 /* if (!$expand_cdm) {
5348 print "<a id=\"CICH-$id\"
5349 href=\"javascript:cdmExpandArticle($id)\">
5355 print "<div class=\"cdmFooter\"><span class='s0'>";
5357 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5359 print __("Select:").
5360 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5361 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5363 print "</span><span class='s1'>$marked_pic ";
5364 print "$published_pic ";
5365 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5366 onclick=\"zoomToArticle($id)\"
5367 style=\"cursor : pointer\"
5369 title='".__('Show article summary in new window')."'> ";
5371 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5373 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5374 style=\"cursor : pointer\" style=\"cursor : pointer\"
5375 onclick=\"publishWithNote($id, '$note_escaped')\"
5376 alt='PubNote' title='".__('Publish article with a note')."'>";
5380 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5382 // print "<img src='images/tag.png' class='markedPic'>";
5384 print "<span class='s1'>
5385 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5386 <span id=\"ATSTR-$id\">$tags_str</span>
5387 <a title=\"".__('Edit tags for this article')."\"
5388 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5392 print "<span class='s2'><a class=\"cdmToggleLink\"
5393 href=\"javascript:toggleUnread($id)\">
5394 ".__('toggle unread')."</a></span>";
5404 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5411 switch ($view_mode) {
5413 $message = __("No unread articles found to display.");
5416 $message = __("No updated articles found to display.");
5419 $message = __("No starred articles found to display.");
5423 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5425 $message = __("No articles found to display.");
5429 if (!$offset) print "<div class='whiteBox'>$message</div>";
5437 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5440 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5442 function printTagCloud($link) {
5444 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5445 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5446 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5448 $result = db_query($link, $query);
5452 while ($line = db_fetch_assoc($result)) {
5453 $tags[$line["tag_name"]] = $line["count"];
5458 $max_size = 32; // max font size in pixels
5459 $min_size = 11; // min font size in pixels
5461 // largest and smallest array values
5462 $max_qty = max(array_values($tags));
5463 $min_qty = min(array_values($tags));
5465 // find the range of values
5466 $spread = $max_qty - $min_qty;
5467 if ($spread == 0) { // we don't want to divide by zero
5471 // set the font-size increment
5472 $step = ($max_size - $min_size) / ($spread);
5474 // loop through the tag array
5475 foreach ($tags as $key => $value) {
5476 // calculate font-size
5477 // find the $value in excess of $min_qty
5478 // multiply by the font-size increment ($size)
5479 // and add the $min_size set above
5480 $size = round($min_size +
(($value - $min_qty) * $step));
5482 $key_escaped = str_replace("'", "\\'", $key);
5484 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5485 $size . "px\" title=\"$value articles tagged with " .
5486 $key . '">' . $key . '</a> ';
5490 function print_checkpoint($n, $s) {
5491 $ts = getmicrotime();
5492 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5496 function sanitize_tag($tag) {
5499 $tag = mb_strtolower($tag, 'utf-8');
5501 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5503 // $tag = str_replace('"', "", $tag);
5504 // $tag = str_replace("+", " ", $tag);
5505 $tag = str_replace("technorati tag: ", "", $tag);
5510 function generate_publish_key() {
5511 return sha1(uniqid(rand(), true));
5514 function article_publish_url($link) {
5519 if ($_SERVER['HTTPS'] != "on") {
5520 $url_path = "http://";
5522 $url_path = "https://";
5525 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5526 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5532 * Purge a feed contents, marked articles excepted.
5534 * @param mixed $link The database connection.
5535 * @param integer $id The id of the feed to purge.
5538 function clear_feed_articles($link, $id) {
5539 $result = db_query($link, "DELETE FROM ttrss_user_entries
5540 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5542 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5543 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5545 ccache_update($link, $id, $_SESSION['uid']);
5546 } // function clear_feed_articles
5549 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5551 * @return string The Mozilla Firefox feed adding URL.
5553 function add_feed_url() {
5554 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5555 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5557 } // function add_feed_url
5560 * Encrypt a password in SHA1.
5562 * @param string $pass The password to encrypt.
5563 * @param string $login A optionnal login.
5564 * @return string The encrypted password.
5566 function encrypt_password($pass, $login = '') {
5568 return "SHA1X:" . sha1("$login:$pass");
5570 return "SHA1:" . sha1($pass);
5572 } // function encrypt_password
5575 * Update a feed batch.
5576 * Used by daemons to update n feeds by run.
5577 * Only update feed needing a update, and not being processed
5578 * by another process.
5580 * @param mixed $link Database link
5581 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5582 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5583 * @param boolean $debug Set to false to disable debug output. Default to true.
5586 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5587 // Process all other feeds using last_updated and interval parameters
5589 // Test if the user has loggued in recently. If not, it does not update its feeds.
5590 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5591 if (DB_TYPE
== "pgsql") {
5592 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5594 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5597 $login_thresh_qpart = "";
5600 // Test if the feed need a update (update interval exceded).
5601 if (DB_TYPE
== "pgsql") {
5602 $update_limit_qpart = "AND ((
5603 ttrss_feeds.update_interval = 0
5604 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5606 ttrss_feeds.update_interval > 0
5607 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5608 ) OR ttrss_feeds.last_updated IS NULL)";
5610 $update_limit_qpart = "AND ((
5611 ttrss_feeds.update_interval = 0
5612 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5614 ttrss_feeds.update_interval > 0
5615 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5616 ) OR ttrss_feeds.last_updated IS NULL)";
5619 // Test if feed is currently being updated by another process.
5620 if (DB_TYPE
== "pgsql") {
5621 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5623 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5626 // Test if there is a limit to number of updated feeds
5628 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5630 $random_qpart = sql_random_function();
5632 // We search for feed needing update.
5633 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5634 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5635 ttrss_feeds.update_interval
5637 ttrss_feeds, ttrss_users, ttrss_user_prefs
5639 ttrss_feeds.owner_uid = ttrss_users.id
5640 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5641 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5642 $login_thresh_qpart $update_limit_qpart
5643 $updstart_thresh_qpart
5644 ORDER BY $random_qpart $query_limit");
5646 $user_prefs_cache = array();
5648 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5650 // Here is a little cache magic in order to minimize risk of double feed updates.
5651 $feeds_to_update = array();
5652 while ($line = db_fetch_assoc($result)) {
5653 $feeds_to_update[$line['id']] = $line;
5656 // We update the feed last update started date before anything else.
5657 // There is no lag due to feed contents downloads
5658 // It prevent an other process to update the same feed.
5659 $feed_ids = array_keys($feeds_to_update);
5661 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5662 WHERE id IN (%s)", implode(',', $feed_ids)));
5665 // For each feed, we call the feed update function.
5666 while ($line = array_pop($feeds_to_update)) {
5668 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5670 // We setup a alarm to alert if the feed take more than 300s to update.
5672 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5673 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5674 // Cancel the alarm (the update went well)
5675 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5677 sleep(1); // prevent flood (FIXME make this an option?)
5680 // Send feed digests by email if needed.
5681 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5683 purge_orphans($link);
5685 } // function update_daemon_common
5687 function sanitize_article_content($text) {
5688 # we don't support CDATA sections in articles, they break our own escaping
5689 $text = preg_replace("/\[\[CDATA/", "", $text);
5690 $text = preg_replace("/\]\]\>/", "", $text);
5694 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5697 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5699 $result = db_query($link, "SELECT reg_exp,
5700 ttrss_filter_types.name AS name,
5701 ttrss_filter_actions.name AS action,
5705 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5708 owner_uid = $owner_uid AND
5709 ttrss_filter_types.id = filter_type AND
5710 ttrss_filter_actions.id = action_id AND
5711 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5713 while ($line = db_fetch_assoc($result)) {
5714 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5715 $filter["reg_exp"] = $line["reg_exp"];
5716 $filter["action"] = $line["action"];
5717 $filter["action_param"] = $line["action_param"];
5718 $filter["filter_param"] = $line["filter_param"];
5719 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5721 array_push($filters[$line["name"]], $filter);
5727 function get_score_pic($score) {
5729 return "score_high.png";
5730 } else if ($score > 0) {
5731 return "score_half_high.png";
5732 } else if ($score < -100) {
5733 return "score_low.png";
5734 } else if ($score < 0) {
5735 return "score_half_low.png";
5737 return "score_neutral.png";
5741 function rounded_table_start($classname, $header = " ") {
5742 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5743 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5744 print "<tr><td class='left'> </td><td class='content'>";
5747 function rounded_table_end($footer = " ") {
5748 print "</td><td class='right'> </td></tr>";
5749 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5753 function feed_has_icon($id) {
5754 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5757 function init_connection($link) {
5758 if (DB_TYPE
== "pgsql") {
5759 pg_query($link, "set client_encoding = 'UTF-8'");
5760 pg_set_client_encoding("UNICODE");
5761 pg_query($link, "set datestyle = 'ISO, european'");
5763 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5764 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5765 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5770 function update_feedbrowser_cache($link) {
5772 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5773 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5774 WHERE tf.feed_url = ttrss_feeds.feed_url
5775 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5776 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5778 db_query($link, "BEGIN");
5780 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5784 while ($line = db_fetch_assoc($result)) {
5785 $subscribers = db_escape_string($line["subscribers"]);
5786 $feed_url = db_escape_string($line["feed_url"]);
5787 $title = db_escape_string($line["title"]);
5789 $tmp_result = db_query($link, "SELECT subscribers FROM
5790 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5792 if (db_num_rows($tmp_result) == 0) {
5794 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5795 (feed_url, title, subscribers) VALUES ('$feed_url',
5796 '$title', '$subscribers')");
5804 db_query($link, "COMMIT");
5810 function ccache_zero($link, $feed_id, $owner_uid) {
5811 db_query($link, "UPDATE ttrss_counters_cache SET
5812 value = 0, updated = NOW() WHERE
5813 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5816 function ccache_zero_all($link, $owner_uid) {
5817 db_query($link, "UPDATE ttrss_counters_cache SET
5818 value = 0 WHERE owner_uid = '$owner_uid'");
5820 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5821 value = 0 WHERE owner_uid = '$owner_uid'");
5824 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5827 $table = "ttrss_counters_cache";
5829 $table = "ttrss_cat_counters_cache";
5832 db_query($link, "DELETE FROM $table WHERE
5833 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5837 function ccache_update_all($link, $owner_uid) {
5839 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5841 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5842 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5844 while ($line = db_fetch_assoc($result)) {
5845 ccache_update($link, $line["feed_id"], $owner_uid, true);
5848 /* We have to manually include category 0 */
5850 ccache_update($link, 0, $owner_uid, true);
5853 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5854 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5856 while ($line = db_fetch_assoc($result)) {
5857 print ccache_update($link, $line["feed_id"], $owner_uid);
5864 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5865 $no_update = false) {
5867 if (!is_numeric($feed_id)) return;
5870 $table = "ttrss_counters_cache";
5872 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5873 WHERE id = '$feed_id'");
5874 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5877 $table = "ttrss_cat_counters_cache";
5880 if (DB_TYPE
== "pgsql") {
5881 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5882 } else if (DB_TYPE
== "mysql") {
5883 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5886 $result = db_query($link, "SELECT value FROM $table
5887 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5890 if (db_num_rows($result) == 1) {
5891 return db_fetch_result($result, 0, "value");
5896 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5902 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5903 $update_pcat = true) {
5905 if (!is_numeric($feed_id)) return;
5907 if (!$is_cat && $feed_id > 0) {
5908 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5909 WHERE id = '$feed_id'");
5910 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5913 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5915 /* When updating a label, all we need to do is recalculate feed counters
5916 * because labels are not cached */
5919 ccache_update_all($link, $owner_uid);
5924 $table = "ttrss_counters_cache";
5926 $table = "ttrss_cat_counters_cache";
5929 if ($is_cat && $feed_id >= 0) {
5930 if ($feed_id != 0) {
5931 $cat_qpart = "cat_id = '$feed_id'";
5933 $cat_qpart = "cat_id IS NULL";
5936 /* Recalculate counters for child feeds */
5938 $result = db_query($link, "SELECT id FROM ttrss_feeds
5939 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5941 while ($line = db_fetch_assoc($result)) {
5942 ccache_update($link, $line["id"], $owner_uid, false, false);
5945 $result = db_query($link, "SELECT SUM(value) AS sv
5946 FROM ttrss_counters_cache, ttrss_feeds
5947 WHERE id = feed_id AND $cat_qpart AND
5948 ttrss_feeds.owner_uid = '$owner_uid'");
5950 $unread = (int) db_fetch_result($result, 0, "sv");
5953 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5956 db_query($link, "BEGIN");
5958 $result = db_query($link, "SELECT feed_id FROM $table
5959 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5961 if (db_num_rows($result) == 1) {
5962 db_query($link, "UPDATE $table SET
5963 value = '$unread', updated = NOW() WHERE
5964 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5967 db_query($link, "INSERT INTO $table
5968 (feed_id, value, owner_uid, updated)
5970 ($feed_id, $unread, $owner_uid, NOW())");
5973 db_query($link, "COMMIT");
5975 if ($feed_id > 0 && $prev_unread != $unread) {
5979 /* Update parent category */
5983 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5984 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5986 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5988 ccache_update($link, $cat_id, $owner_uid, true);
5992 } else if ($feed_id < 0) {
5993 ccache_update_all($link, $owner_uid);
5999 function label_find_id($link, $label, $owner_uid) {
6000 $result = db_query($link,
6001 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6002 AND owner_uid = '$owner_uid' LIMIT 1");
6004 if (db_num_rows($result) == 1) {
6005 return db_fetch_result($result, 0, "id");
6011 function get_article_labels($link, $id) {
6012 $result = db_query($link,
6013 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6014 FROM ttrss_labels2, ttrss_user_labels2
6016 AND article_id = '$id'
6017 AND owner_uid = ".$_SESSION["uid"] . "
6022 while ($line = db_fetch_assoc($result)) {
6023 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6025 array_push($rv, $rk);
6032 function label_find_caption($link, $label, $owner_uid) {
6033 $result = db_query($link,
6034 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6035 AND owner_uid = '$owner_uid' LIMIT 1");
6037 if (db_num_rows($result) == 1) {
6038 return db_fetch_result($result, 0, "caption");
6044 function label_remove_article($link, $id, $label, $owner_uid) {
6046 $label_id = label_find_id($link, $label, $owner_uid);
6048 if (!$label_id) return;
6050 $result = db_query($link,
6051 "DELETE FROM ttrss_user_labels2
6053 label_id = '$label_id' AND
6054 article_id = '$id'");
6057 function label_add_article($link, $id, $label, $owner_uid) {
6059 $label_id = label_find_id($link, $label, $owner_uid);
6061 if (!$label_id) return;
6063 $result = db_query($link,
6065 article_id FROM ttrss_labels2, ttrss_user_labels2
6068 label_id = '$label_id' AND
6069 article_id = '$id' AND owner_uid = '$owner_uid'
6072 if (db_num_rows($result) == 0) {
6073 db_query($link, "INSERT INTO ttrss_user_labels2
6074 (label_id, article_id) VALUES ('$label_id', '$id')");
6078 function label_remove($link, $id, $owner_uid) {
6080 db_query($link, "BEGIN");
6082 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6085 $caption = db_fetch_result($result, 0, "caption");
6087 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6088 AND owner_uid = " . $_SESSION["uid"]);
6090 if (db_affected_rows($link, $result) != 0 && $caption) {
6092 /* Disable filters that reference label being removed */
6094 db_query($link, "UPDATE ttrss_filters SET
6095 enabled = false WHERE action_param = '$caption'
6097 AND owner_uid = " . $_SESSION["uid"]);
6100 db_query($link, "COMMIT");
6103 function label_create($link, $caption) {
6105 db_query($link, "BEGIN");
6109 $result = db_query($link, "SELECT id FROM ttrss_labels2
6110 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6112 if (db_num_rows($result) == 0) {
6113 $result = db_query($link,
6114 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6115 VALUES ('$caption', '".$_SESSION["uid"]."')");
6117 $result = db_affected_rows($link, $result) != 0;
6120 db_query($link, "COMMIT");
6125 function print_labels_headlines_dropdown($link, $feed_id) {
6126 print "<li onclick=\"javascript:addLabel()\">
6127 ".__("Create label...")."</li>";
6129 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6130 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6132 while ($line = db_fetch_assoc($result)) {
6134 $label_id = $line["id"];
6135 $label_caption = $line["caption"];
6137 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6138 print "<li id=\"LHDL-$id\"
6139 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6140 $label_caption ".__('(remove)')."</li>";
6142 print "<li id=\"LHDL-$id\"
6143 onclick=\"javascript:selectionAssignLabel($label_id)\">
6144 $label_caption</li>";
6149 function format_tags_string($tags, $id) {
6152 $tags_nolinks_str = "";
6156 if ($_SESSION["theme"] == "3pane") {
6162 $formatted_tags = array();
6164 foreach ($tags as $tag) {
6166 $tag_escaped = str_replace("'", "\\'", $tag);
6168 if (mb_strlen($tag) > 30) {
6169 $tag = truncate_string($tag, 30);
6172 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6174 array_push($formatted_tags, $tag_str);
6176 $tmp_tags_str = implode(", ", $formatted_tags);
6178 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6183 $tags_str = implode(", ", $formatted_tags);
6185 if ($num_tags < count($tags)) {
6186 $tags_str .= ", …";
6189 if ($num_tags == 0) {
6190 $tags_str = __("no tags");
6197 function format_article_labels($labels, $id) {
6201 foreach ($labels as $l) {
6202 $labels_str .= sprintf("<span class='hlLabelRef'
6203 style='color : %s; background-color : %s'>%s</span>",
6204 $l[2], $l[3], $l[1]);
6211 function format_article_note($id, $note) {
6213 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6215 $str = "<div class='articleNote'>";
6217 $str .= "<div class='articleNoteOps'>";
6218 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6219 __('edit note')."</a>";