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",
30 "fr_FR" => "Français",
31 "hu_HU" => "Magyar (Hungarian)",
32 "it_IT" => "Italiano",
33 "ja_JP" => "日本語 (Japanese)",
34 "nb_NO" => "Norwegian bokmål",
36 "pt_BR" => "Portuguese/Brazil",
37 "zh_CN" => "Simplified Chinese");
42 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
43 require_once "accept-to-gettext.php";
44 require_once "lib/gettext/gettext.inc";
46 function startup_gettext() {
48 # Get locale from Accept-Language header
49 $lang = al2gt(array_keys(get_translations()), "text/html");
51 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
52 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
55 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
56 $lang = $_COOKIE["ttrss_lang"];
59 /* In login action of mobile version */
60 if ($_POST["language"] && defined('MOBILE_VERSION')) {
61 $lang = $_POST["language"];
62 $_COOKIE["ttrss_lang"] = $lang;
66 if (defined('LC_MESSAGES')) {
67 _setlocale(LC_MESSAGES
, $lang);
68 } else if (defined('LC_ALL')) {
69 _setlocale(LC_ALL
, $lang);
71 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
77 _bindtextdomain("messages", "locale");
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
87 } else { // If translations are enabled.
91 function startup_gettext() {
95 } // If translations are enabled.
97 require_once 'db-prefs.php';
98 require_once 'compat.php';
99 require_once 'errors.php';
100 require_once 'version.php';
102 require_once 'lib/phpmailer/class.phpmailer.php';
104 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
105 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
106 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
108 require_once "lib/simplepie/simplepie.inc";
109 require_once "lib/magpierss/rss_fetch.inc";
110 require_once 'lib/magpierss/rss_utils.inc';
111 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
114 * Print a timestamped debug message.
116 * @param string $msg The debug message.
119 function _debug($msg) {
120 $ts = strftime("%H:%M:%S", time());
121 if (function_exists('posix_getpid')) {
122 $ts = "$ts/" . posix_getpid();
124 print "[$ts] $msg\n";
128 * Purge a feed old posts.
130 * @param mixed $link A database connection.
131 * @param mixed $feed_id The id of the purged feed.
132 * @param mixed $purge_interval Olderness of purged posts.
133 * @param boolean $debug Set to True to enable the debug. False by default.
137 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
139 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
143 $result = db_query($link,
144 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
148 if (db_num_rows($result) == 1) {
149 $owner_uid = db_fetch_result($result, 0, "owner_uid");
152 if ($purge_interval == -1 ||
!$purge_interval) {
154 ccache_update($link, $feed_id, $owner_uid);
159 if (!$owner_uid) return;
161 if (FORCE_ARTICLE_PURGE
== 0) {
162 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
165 $purge_unread = true;
166 $purge_interval = FORCE_ARTICLE_PURGE
;
169 if (!$purge_unread) $query_limit = " unread = false AND ";
171 if (DB_TYPE
== "pgsql") {
172 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
173 marked = false AND feed_id = '$feed_id' AND
174 (SELECT date_entered FROM ttrss_entries WHERE
175 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
177 $pg_version = get_pgsql_version($link);
179 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
181 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
182 ttrss_entries.id = ref_id AND
184 feed_id = '$feed_id' AND
186 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
190 $result = db_query($link, "DELETE FROM ttrss_user_entries
192 WHERE ttrss_entries.id = ref_id AND
194 feed_id = '$feed_id' AND
196 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
199 $rows = pg_affected_rows($result);
203 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
204 marked = false AND feed_id = '$feed_id' AND
205 (SELECT date_entered FROM ttrss_entries WHERE
206 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
208 $result = db_query($link, "DELETE FROM ttrss_user_entries
209 USING ttrss_user_entries, ttrss_entries
210 WHERE ttrss_entries.id = ref_id AND
212 feed_id = '$feed_id' AND
214 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
216 $rows = mysql_affected_rows($link);
220 ccache_update($link, $feed_id, $owner_uid);
223 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
225 } // function purge_feed
228 * Purge old posts from old feeds.
230 * @param mixed $link A database connection
231 * @param boolean $do_output Set to true to enable printed output, false by default.
232 * @param integer $limit The maximal number of removed posts.
236 function global_purge_old_posts($link, $do_output = false, $limit = false) {
238 $random_qpart = sql_random_function();
241 $limit_qpart = "LIMIT $limit";
246 $result = db_query($link,
247 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
248 ORDER BY $random_qpart $limit_qpart");
250 while ($line = db_fetch_assoc($result)) {
252 $feed_id = $line["id"];
253 $purge_interval = $line["purge_interval"];
254 $owner_uid = $line["owner_uid"];
256 if ($purge_interval == 0) {
258 $tmp_result = db_query($link,
259 "SELECT value FROM ttrss_user_prefs WHERE
260 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
262 if (db_num_rows($tmp_result) != 0) {
263 $purge_interval = db_fetch_result($tmp_result, 0, "value");
268 // print "Feed $feed_id: purge interval = $purge_interval\n";
271 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
272 purge_feed($link, $feed_id, $purge_interval, $do_output);
276 // purge orphaned posts in main content table
277 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
278 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
281 $rows = db_affected_rows($link, $result);
282 _debug("Purged $rows orphaned posts.");
285 } // function global_purge_old_posts
287 function feed_purge_interval($link, $feed_id) {
289 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
290 WHERE id = '$feed_id'");
292 if (db_num_rows($result) == 1) {
293 $purge_interval = db_fetch_result($result, 0, "purge_interval");
294 $owner_uid = db_fetch_result($result, 0, "owner_uid");
296 if ($purge_interval == 0) $purge_interval = get_pref($link,
297 'PURGE_OLD_DAYS', $owner_uid);
299 return $purge_interval;
306 function purge_old_posts($link) {
308 $user_id = $_SESSION["uid"];
310 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
311 WHERE owner_uid = '$user_id'");
313 while ($line = db_fetch_assoc($result)) {
315 $feed_id = $line["id"];
316 $purge_interval = $line["purge_interval"];
318 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
320 if ($purge_interval > 0) {
321 purge_feed($link, $feed_id, $purge_interval);
325 purge_orphans($link);
328 function purge_orphans($link) {
329 // purge orphaned posts in main content table
330 db_query($link, "DELETE FROM ttrss_entries WHERE
331 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
334 function get_feed_update_interval($link, $feed_id) {
335 $result = db_query($link, "SELECT owner_uid, update_interval FROM
336 ttrss_feeds WHERE id = '$feed_id'");
338 if (db_num_rows($result) == 1) {
339 $update_interval = db_fetch_result($result, 0, "update_interval");
340 $owner_uid = db_fetch_result($result, 0, "owner_uid");
342 if ($update_interval != 0) {
343 return $update_interval;
345 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
353 function fetch_file_contents($url) {
354 if (USE_CURL_FOR_ICONS
) {
355 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
357 $ch = curl_init($url);
358 $fp = fopen($tmpfile, "w");
361 curl_setopt($ch, CURLOPT_FILE
, $fp);
362 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
363 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
369 $contents = file_get_contents($tmpfile);
375 return file_get_contents($url);
381 * Try to determine the favicon URL for a feed.
382 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
383 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
385 * @param string $url A feed or page URL
387 * @return mixed The favicon URL, or false if none was found.
389 function get_favicon_url($url) {
391 if ($html = @fetch_file_contents
($url)) {
393 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
394 // Attempt to grab a favicon link from their webpage url
395 $linkUrl = html_entity_decode($matches[1]);
397 if (substr($linkUrl, 0, 1) == '/') {
398 $urlParts = parse_url($url);
399 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
400 } else if (substr($linkUrl, 0, 7) == 'http://') {
401 $faviconURL = $linkUrl;
403 $pos = strrpos($url, "/");
404 // no "/" in url or "/" is part of "://"
405 if ($pos === false ||
$pos == (strpos($url, "://")+
2)) {
406 $faviconURL = $url.'/'.$linkUrl;
408 $faviconURL = substr($url, 0, $pos+
1).$linkUrl;
413 // If unsuccessful, attempt to "guess" the favicon location
414 $urlParts = parse_url($url);
415 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
419 // Run a test to see if what we have attempted to get actually exists.
420 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
425 } // function get_favicon_url
428 * Check if a link is a valid and working URL.
430 * @param mixed $link A URL to check
432 * @return boolean True if the URL is valid, false otherwise.
434 function url_validate($link) {
436 $url_parts = @parse_url
($link);
438 if ( empty( $url_parts["host"] ) )
441 if ( !empty( $url_parts["path"] ) ) {
442 $documentpath = $url_parts["path"];
447 if ( !empty( $url_parts["query"] ) )
448 $documentpath .= "?" . $url_parts["query"];
450 $host = $url_parts["host"];
451 $port = $url_parts["port"];
456 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
461 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
463 $http_response = fgets( $socket, 22 );
465 $responses = "/(200 OK)|(30[123])/";
466 if ( preg_match($responses, $http_response) ) {
473 } // function url_validate
475 function check_feed_favicon($site_url, $feed, $link) {
476 $favicon_url = get_favicon_url($site_url);
478 # print "FAVICON [$site_url]: $favicon_url\n";
482 $icon_file = ICONS_DIR
. "/$feed.ico";
484 if ($favicon_url && !file_exists($icon_file)) {
485 $contents = fetch_file_contents($favicon_url);
487 $fp = fopen($icon_file, "w");
490 fwrite($fp, $contents);
492 chmod($icon_file, 0644);
496 error_reporting(DEFAULT_ERROR_LEVEL
);
500 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
502 if (!$_GET["daemon"] && !$ignore_daemon) {
506 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
507 _debug("update_rss_feed: start");
510 if (!$ignore_daemon) {
512 if (DB_TYPE
== "pgsql") {
513 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
515 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
518 $result = db_query($link, "SELECT id,update_interval,auth_login,
519 auth_pass,cache_images,update_method
520 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
524 $result = db_query($link, "SELECT id,update_interval,auth_login,
525 auth_pass,cache_images,update_method,hidden,last_updated
526 FROM ttrss_feeds WHERE id = '$feed'");
530 if (db_num_rows($result) == 0) {
531 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
532 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
537 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
538 $update_method = db_fetch_result($result, 0, "update_method");
539 $last_updated = db_fetch_result($result, 0, "last_updated");
541 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
542 WHERE id = '$feed'");
544 $auth_login = db_fetch_result($result, 0, "auth_login");
545 $auth_pass = db_fetch_result($result, 0, "auth_pass");
547 if (ALLOW_SELECT_UPDATE_METHOD
) {
548 if (ENABLE_SIMPLEPIE
) {
549 $use_simplepie = $update_method != 1;
551 $use_simplepie = $update_method == 2;
554 $use_simplepie = ENABLE_SIMPLEPIE
;
557 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
558 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
561 if (!$use_simplepie) {
562 $auth_login = urlencode($auth_login);
563 $auth_pass = urlencode($auth_pass);
566 $update_interval = db_fetch_result($result, 0, "update_interval");
567 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
569 if ($update_interval < 0) { return; }
571 $feed = db_escape_string($feed);
573 $fetch_url = $feed_url;
575 if ($auth_login && $auth_pass) {
576 $url_parts = array();
577 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
579 if ($url_parts[1] && $url_parts[2]) {
580 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
585 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
586 _debug("update_rss_feed: fetching [$fetch_url]...");
589 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
593 if (!$use_simplepie) {
594 $rss = fetch_rss($fetch_url);
596 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
597 mkdir(SIMPLEPIE_CACHE_DIR
);
600 $rss = new SimplePie();
601 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
602 # $rss->set_timeout(10);
603 $rss->set_feed_url($fetch_url);
604 $rss->set_output_encoding('UTF-8');
606 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
607 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
608 _debug("enabling image cache");
611 $rss->set_image_handler('./image.php', 'i');
614 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
615 _debug("feed update interval (sec): " .
616 get_feed_update_interval($link, $feed)*60);
619 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
620 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
621 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
629 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
630 _debug("update_rss_feed: fetch done, parsing...");
632 error_reporting (DEFAULT_ERROR_LEVEL
);
635 $feed = db_escape_string($feed);
637 if ($use_simplepie) {
638 $fetch_ok = !$rss->error();
645 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
646 _debug("update_rss_feed: processing feed data...");
649 // db_query($link, "BEGIN");
651 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
652 FROM ttrss_feeds WHERE id = '$feed'");
654 $registered_title = db_fetch_result($result, 0, "title");
655 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
656 $orig_site_url = db_fetch_result($result, 0, "site_url");
658 $owner_uid = db_fetch_result($result, 0, "owner_uid");
660 if ($use_simplepie) {
661 $site_url = $rss->get_link();
663 $site_url = $rss->channel
["link"];
666 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
667 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
668 _debug("update_rss_feed: checking favicon...");
671 check_feed_favicon($site_url, $feed, $link);
674 if (!$registered_title ||
$registered_title == "[Unknown]") {
676 if ($use_simplepie) {
677 $feed_title = db_escape_string($rss->get_title());
679 $feed_title = db_escape_string($rss->channel
["title"]);
682 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
683 _debug("update_rss_feed: registering title: $feed_title");
686 db_query($link, "UPDATE ttrss_feeds SET
687 title = '$feed_title' WHERE id = '$feed'");
690 // weird, weird Magpie
691 if (!$use_simplepie) {
692 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
695 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
696 db_query($link, "UPDATE ttrss_feeds SET
697 site_url = '$site_url' WHERE id = '$feed'");
700 // print "I: " . $rss->channel["image"]["url"];
702 if (!$use_simplepie) {
703 $icon_url = $rss->image
["url"];
705 $icon_url = $rss->get_image_url();
708 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
709 $icon_url = db_escape_string($icon_url);
710 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
713 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
714 _debug("update_rss_feed: loading filters...");
717 $filters = load_filters($link, $feed, $owner_uid);
719 if ($use_simplepie) {
720 $iterator = $rss->get_items();
722 $iterator = $rss->items
;
723 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
724 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
727 if (!is_array($iterator)) {
728 /* db_query($link, "UPDATE ttrss_feeds
729 SET last_error = 'Parse error: can\'t find any articles.'
730 WHERE id = '$feed'"); */
732 // clear any errors and mark feed as updated if fetched okay
733 // even if it's blank
735 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
736 _debug("update_rss_feed: entry iterator is not an array, no articles?");
739 db_query($link, "UPDATE ttrss_feeds
740 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
742 return; // no articles
745 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
746 _debug("update_rss_feed: processing articles...");
749 foreach ($iterator as $item) {
751 if ($_GET['xdebug']) {
756 if ($use_simplepie) {
757 $entry_guid = $item->get_id();
758 if (!$entry_guid) $entry_guid = $item->get_link();
759 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
763 $entry_guid = $item["id"];
765 if (!$entry_guid) $entry_guid = $item["guid"];
766 if (!$entry_guid) $entry_guid = $item["link"];
767 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
770 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
771 _debug("update_rss_feed: guid $entry_guid");
774 if (!$entry_guid) continue;
776 $entry_timestamp = "";
778 if ($use_simplepie) {
779 $entry_timestamp = strtotime($item->get_date());
781 $rss_2_date = $item['pubdate'];
782 $rss_1_date = $item['dc']['date'];
783 $atom_date = $item['issued'];
784 if (!$atom_date) $atom_date = $item['updated'];
786 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
787 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
788 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
791 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
792 $entry_timestamp = time();
793 $no_orig_date = 'true';
795 $no_orig_date = 'false';
798 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
800 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
801 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
804 if ($use_simplepie) {
805 $entry_title = $item->get_title();
807 $entry_title = trim(strip_tags($item["title"]));
810 if ($use_simplepie) {
811 $entry_link = $item->get_link();
813 // strange Magpie workaround
814 $entry_link = $item["link_"];
815 if (!$entry_link) $entry_link = $item["link"];
818 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
819 _debug("update_rss_feed: title $entry_title");
822 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
824 $entry_link = strip_tags($entry_link);
826 if ($use_simplepie) {
827 $entry_content = $item->get_content();
828 if (!$entry_content) $entry_content = $item->get_description();
830 $entry_content = $item["content:escaped"];
832 if (!$entry_content) $entry_content = $item["content:encoded"];
833 if (!$entry_content) $entry_content = $item["content"]["encoded"];
834 if (!$entry_content) $entry_content = $item["content"];
836 // Magpie bugs are getting ridiculous
837 if (trim($entry_content) == "Array") $entry_content = false;
839 if (!$entry_content) $entry_content = $item["atom_content"];
840 if (!$entry_content) $entry_content = $item["summary"];
842 if (!$entry_content ||
843 strlen($entry_content) < strlen($item["description"])) {
844 $entry_content = $item["description"];
848 if (is_array($entry_content)) {
849 $entry_content = $entry_content["encoded"];
850 if (!$entry_content) $entry_content = $entry_content["escaped"];
854 if ($_GET["xdebug"]) {
855 print "update_rss_feed: content: ";
856 print_r(htmlspecialchars($entry_content));
859 $entry_content_unescaped = $entry_content;
861 if ($use_simplepie) {
862 $entry_comments = strip_tags($item->data
["comments"]);
863 if ($item->get_author()) {
864 $entry_author_item = $item->get_author();
865 $entry_author = $entry_author_item->get_name();
866 if (!$entry_author) $entry_author = $entry_author_item->get_email();
868 $entry_author = db_escape_string($entry_author);
871 $entry_comments = strip_tags($item["comments"]);
873 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
875 if ($item['author']) {
877 if (is_array($item['author'])) {
879 if (!$entry_author) {
880 $entry_author = db_escape_string(strip_tags($item['author']['name']));
883 if (!$entry_author) {
884 $entry_author = db_escape_string(strip_tags($item['author']['email']));
888 if (!$entry_author) {
889 $entry_author = db_escape_string(strip_tags($item['author']));
894 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
896 $entry_guid = db_escape_string(strip_tags($entry_guid));
897 $entry_guid = mb_substr($entry_guid, 0, 250);
899 $result = db_query($link, "SELECT id FROM ttrss_entries
900 WHERE guid = '$entry_guid'");
902 $entry_content = db_escape_string($entry_content);
904 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
906 $entry_title = db_escape_string($entry_title);
907 $entry_link = db_escape_string($entry_link);
908 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
909 $entry_author = mb_substr($entry_author, 0, 250);
911 if ($use_simplepie) {
912 $num_comments = 0; #FIXME#
914 $num_comments = db_escape_string($item["slash"]["comments"]);
917 if (!$num_comments) $num_comments = 0;
919 // parse <category> entries into tags
921 if ($use_simplepie) {
923 $additional_tags = array();
924 $additional_tags_src = $item->get_categories();
926 if (is_array($additional_tags_src)) {
927 foreach ($additional_tags_src as $tobj) {
928 array_push($additional_tags, $tobj->get_term());
932 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
933 _debug("update_rss_feed: category tags:");
934 print_r($additional_tags);
939 $t_ctr = $item['category#'];
941 $additional_tags = false;
944 $additional_tags = false;
945 } else if ($t_ctr > 0) {
946 $additional_tags = array($item['category']);
948 if ($item['category@term']) {
949 array_push($additional_tags, $item['category@term']);
952 for ($i = 0; $i <= $t_ctr; $i++
) {
953 if ($item["category#$i"]) {
954 array_push($additional_tags, $item["category#$i"]);
957 if ($item["category#$i@term"]) {
958 array_push($additional_tags, $item["category#$i@term"]);
963 // parse <dc:subject> elements
965 $t_ctr = $item['dc']['subject#'];
968 $additional_tags = array($item['dc']['subject']);
970 for ($i = 0; $i <= $t_ctr; $i++
) {
971 if ($item['dc']["subject#$i"]) {
972 array_push($additional_tags, $item['dc']["subject#$i"]);
980 $enclosures = array();
982 if ($use_simplepie) {
983 $encs = $item->get_enclosures();
985 if (is_array($encs)) {
986 foreach ($encs as $e) {
988 $e->link
, $e->type
, $e->length
);
990 array_push($enclosures, $e_item);
997 $e_ctr = $item['enclosure#'];
1000 $e_item = array($item['enclosure@url'],
1001 $item['enclosure@type'],
1002 $item['enclosure@length']);
1004 array_push($enclosures, $e_item);
1006 for ($i = 0; $i <= $e_ctr; $i++
) {
1008 if ($item["enclosure#$i@url"]) {
1009 $e_item = array($item["enclosure#$i@url"],
1010 $item["enclosure#$i@type"],
1011 $item["enclosure#$i@length"]);
1012 array_push($enclosures, $e_item);
1018 // can there be many of those? yes -fox
1020 $m_ctr = $item['media']['content#'];
1023 $e_item = array($item['media']['content@url'],
1024 $item['media']['content@medium'],
1025 $item['media']['content@length']);
1027 array_push($enclosures, $e_item);
1029 for ($i = 0; $i <= $m_ctr; $i++
) {
1031 if ($item["media"]["content#$i@url"]) {
1032 $e_item = array($item["media"]["content#$i@url"],
1033 $item["media"]["content#$i@medium"],
1034 $item["media"]["content#$i@length"]);
1035 array_push($enclosures, $e_item);
1044 $entry_content = sanitize_article_content($entry_content);
1045 $entry_title = sanitize_article_content($entry_title);
1047 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1048 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1051 db_query($link, "BEGIN");
1053 if (db_num_rows($result) == 0) {
1055 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1056 _debug("update_rss_feed: base guid not found");
1059 // base post entry does not exist, create it
1061 $result = db_query($link,
1062 "INSERT INTO ttrss_entries
1078 '$entry_timestamp_fmt',
1087 // we keep encountering the entry in feeds, so we need to
1088 // update date_entered column so that we don't get horrible
1089 // dupes when the entry gets purged and reinserted again e.g.
1090 // in the case of SLOW SLOW OMG SLOW updating feeds
1092 $base_entry_id = db_fetch_result($result, 0, "id");
1094 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1095 WHERE id = '$base_entry_id'");
1098 // now it should exist, if not - bad luck then
1100 $result = db_query($link, "SELECT
1101 id,content_hash,no_orig_date,title,
1102 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1103 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1107 WHERE guid = '$entry_guid'");
1112 if (db_num_rows($result) == 1) {
1114 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1115 _debug("update_rss_feed: base guid found, checking for user record");
1118 // this will be used below in update handler
1119 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1120 $orig_title = db_fetch_result($result, 0, "title");
1121 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1122 $orig_date_entered = strtotime(db_fetch_result($result,
1123 0, "date_entered"));
1125 $ref_id = db_fetch_result($result, 0, "id");
1126 $entry_ref_id = $ref_id;
1128 // check for user post link to main table
1130 // do we allow duplicate posts with same GUID in different feeds?
1131 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1132 $dupcheck_qpart = "AND feed_id = '$feed'";
1134 $dupcheck_qpart = "";
1137 // error_reporting(0);
1139 $article_filters = get_article_filters($filters, $entry_title,
1140 $entry_content, $entry_link, $entry_timestamp);
1142 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1143 _debug("update_rss_feed: article filters: ");
1144 if (count($article_filters) != 0) {
1145 print_r($article_filters);
1149 if (find_article_filter($article_filters, "filter")) {
1150 db_query($link, "COMMIT"); // close transaction in progress
1154 // error_reporting (DEFAULT_ERROR_LEVEL);
1156 $score = calculate_article_score($article_filters);
1158 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1159 _debug("update_rss_feed: initial score: $score");
1162 $result = db_query($link,
1163 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1164 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1167 // okay it doesn't exist - create user entry
1168 if (db_num_rows($result) == 0) {
1170 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1171 _debug("update_rss_feed: user record not found, creating...");
1174 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1176 $last_read_qpart = 'NULL';
1179 $last_read_qpart = 'NOW()';
1182 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1188 if (find_article_filter($article_filters, 'publish')) {
1189 $published = 'true';
1191 $published = 'false';
1194 $result = db_query($link,
1195 "INSERT INTO ttrss_user_entries
1196 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1198 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1199 $last_read_qpart, $marked, $published, '$score')");
1201 $result = db_query($link,
1202 "SELECT int_id FROM ttrss_user_entries WHERE
1203 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1204 feed_id = '$feed' LIMIT 1");
1206 if (db_num_rows($result) == 1) {
1207 $entry_int_id = db_fetch_result($result, 0, "int_id");
1210 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1211 $entry_int_id = db_fetch_result($result, 0, "int_id");
1214 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1215 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1218 $post_needs_update = false;
1220 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1221 ($content_hash != $orig_content_hash)) {
1222 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1223 $post_needs_update = true;
1226 if (db_escape_string($orig_title) != $entry_title) {
1227 $post_needs_update = true;
1230 if ($orig_num_comments != $num_comments) {
1231 $post_needs_update = true;
1234 // this doesn't seem to be very reliable
1236 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1237 // $post_needs_update = true;
1240 // if post needs update, update it and mark all user entries
1241 // linking to this post as updated
1242 if ($post_needs_update) {
1244 if (defined('DAEMON_EXTENDED_DEBUG')) {
1245 _debug("update_rss_feed: post $entry_guid needs update...");
1248 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1250 db_query($link, "UPDATE ttrss_entries
1251 SET title = '$entry_title', content = '$entry_content',
1252 content_hash = '$content_hash',
1253 num_comments = '$num_comments'
1254 WHERE id = '$ref_id'");
1256 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1257 db_query($link, "UPDATE ttrss_user_entries
1258 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1260 db_query($link, "UPDATE ttrss_user_entries
1261 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1267 db_query($link, "COMMIT");
1269 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1270 _debug("update_rss_feed: assigning labels...");
1273 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1276 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1277 _debug("update_rss_feed: looking for enclosures...");
1280 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1281 print_r($enclosures);
1284 db_query($link, "BEGIN");
1286 foreach ($enclosures as $enc) {
1287 $enc_url = db_escape_string($enc[0]);
1288 $enc_type = db_escape_string($enc[1]);
1289 $enc_dur = db_escape_string($enc[2]);
1291 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1292 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1294 if (db_num_rows($result) == 0) {
1295 db_query($link, "INSERT INTO ttrss_enclosures
1296 (content_url, content_type, title, duration, post_id) VALUES
1297 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1301 db_query($link, "COMMIT");
1303 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1304 _debug("update_rss_feed: looking for tags...");
1308 // <a href="..." rel="tag">Xorg</a>, //
1312 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1313 $entry_content_unescaped, $entry_tags);
1315 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1316 print_r($entry_tags);
1317 print "<br/></p>"; */
1319 $entry_tags = $entry_tags[1];
1321 # check for manual tags
1323 $tag_filter = find_article_filter($article_filters, "tag");
1327 $manual_tags = trim_array(split(",", $tag_filter[1]));
1329 foreach ($manual_tags as $tag) {
1330 if (tag_is_valid($tag)) {
1331 array_push($entry_tags, $tag);
1336 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1337 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1339 if ($additional_tags && is_array($additional_tags)) {
1340 foreach ($additional_tags as $tag) {
1341 if (tag_is_valid($tag) &&
1342 array_search($tag, $boring_tags) === FALSE) {
1343 array_push($entry_tags, $tag);
1348 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1350 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1351 print_r($entry_tags);
1354 if (count($entry_tags) > 0) {
1356 db_query($link, "BEGIN");
1358 foreach ($entry_tags as $tag) {
1360 $tag = sanitize_tag($tag);
1361 $tag = db_escape_string($tag);
1363 if (!tag_is_valid($tag)) continue;
1365 $result = db_query($link, "SELECT id FROM ttrss_tags
1366 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1367 owner_uid = '$owner_uid' LIMIT 1");
1369 // print db_fetch_result($result, 0, "id");
1371 if ($result && db_num_rows($result) == 0) {
1373 db_query($link, "INSERT INTO ttrss_tags
1374 (owner_uid,tag_name,post_int_id)
1375 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1379 db_query($link, "COMMIT");
1382 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1383 _debug("update_rss_feed: article processed");
1387 if (!$last_updated) {
1388 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1389 _debug("update_rss_feed: new feed, catching it up...");
1391 catchup_feed($link, $feed, false, $owner_uid);
1395 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1396 _debug("update_rss_feed: updating counters cache...");
1399 // disabled, purge_feed() does that...
1400 //ccache_update($link, $feed, $owner_uid);
1403 purge_feed($link, $feed, 0);
1405 db_query($link, "UPDATE ttrss_feeds
1406 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1408 // db_query($link, "COMMIT");
1412 if ($use_simplepie) {
1413 $error_msg = mb_substr($rss->error(), 0, 250);
1415 $error_msg = mb_substr(magpie_error(), 0, 250);
1418 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1419 _debug("update_rss_feed: error fetching feed: $error_msg");
1422 $error_msg = db_escape_string($error_msg);
1425 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1426 last_updated = NOW() WHERE id = '$feed'");
1429 if ($use_simplepie) {
1433 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1434 _debug("update_rss_feed: done");
1439 function print_select($id, $default, $values, $attributes = "") {
1440 print "<select name=\"$id\" id=\"$id\" $attributes>";
1441 foreach ($values as $v) {
1447 print "<option$sel>$v</option>";
1452 function print_select_hash($id, $default, $values, $attributes = "") {
1453 print "<select name=\"$id\" id='$id' $attributes>";
1454 foreach (array_keys($values) as $v) {
1456 $sel = 'selected="selected"';
1460 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1466 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1469 if ($filters["title"]) {
1470 foreach ($filters["title"] as $filter) {
1471 $reg_exp = $filter["reg_exp"];
1472 $inverse = $filter["inverse"];
1473 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1474 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1476 array_push($matches, array($filter["action"], $filter["action_param"]));
1481 if ($filters["content"]) {
1482 foreach ($filters["content"] as $filter) {
1483 $reg_exp = $filter["reg_exp"];
1484 $inverse = $filter["inverse"];
1486 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1487 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1489 array_push($matches, array($filter["action"], $filter["action_param"]));
1494 if ($filters["both"]) {
1495 foreach ($filters["both"] as $filter) {
1496 $reg_exp = $filter["reg_exp"];
1497 $inverse = $filter["inverse"];
1500 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1501 array_push($matches, array($filter["action"], $filter["action_param"]));
1504 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1505 array_push($matches, array($filter["action"], $filter["action_param"]));
1511 if ($filters["link"]) {
1512 $reg_exp = $filter["reg_exp"];
1513 foreach ($filters["link"] as $filter) {
1514 $reg_exp = $filter["reg_exp"];
1515 $inverse = $filter["inverse"];
1517 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1518 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1520 array_push($matches, array($filter["action"], $filter["action_param"]));
1525 if ($filters["date"]) {
1526 $reg_exp = $filter["reg_exp"];
1527 foreach ($filters["date"] as $filter) {
1528 $date_modifier = $filter["filter_param"];
1529 $inverse = $filter["inverse"];
1530 $check_timestamp = strtotime($filter["reg_exp"]);
1532 # no-op when timestamp doesn't parse to prevent misfires
1534 if ($check_timestamp) {
1537 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1538 $date_modifier == "after" && $timestamp > $check_timestamp) {
1542 if ($inverse) $match_ok = !$match_ok;
1545 array_push($matches, array($filter["action"], $filter["action_param"]));
1554 function find_article_filter($filters, $filter_name) {
1555 foreach ($filters as $f) {
1556 if ($f[0] == $filter_name) {
1563 function calculate_article_score($filters) {
1566 foreach ($filters as $f) {
1567 if ($f[0] == "score") {
1574 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1575 foreach ($filters as $f) {
1576 if ($f[0] == "label") {
1577 label_add_article($link, $id, $f[1], $owner_uid);
1582 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1583 $rtl_content = false, $last_updated = false, $last_error = false,
1584 $fg_content = false, $bg_content = false) {
1586 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1587 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1589 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1593 $rtl_tag = "dir=\"rtl\"";
1595 $rtl_tag = "dir=\"ltr\"";
1598 $error_notify_msg = "";
1601 $link_title = "Error: $last_error ($last_updated)";
1602 $error_notify_msg = "(Error)";
1603 } else if ($last_updated) {
1604 $link_title = "Updated: $last_updated";
1607 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1608 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1610 /* if ($feed_id < -10) {
1611 $bg_color = "#00ccff";
1612 $fg_color = "white";
1615 if ($fg_color || $bg_color) {
1616 $color_str = "<div class='labelColorIndicator'
1617 style='color : $fg_color; background-color : $bg_color'>l</div>";
1620 print $color_str; */
1622 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1623 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1627 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1630 $fctr_class = "class=\"feedCtrHasUnread\"";
1632 $fctr_class = "class=\"feedCtrNoUnread\"";
1635 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1636 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1638 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1639 $total = getFeedArticles($link, $feed_id);
1640 print "<div class=\"feedExtInfo\">
1641 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1648 function getmicrotime() {
1649 list($usec, $sec) = explode(" ",microtime());
1650 return ((float)$usec +
(float)$sec);
1653 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1654 foreach ($values as $v) {
1661 if ($v == $true_is) {
1662 $sel .= " value=\"1\"";
1664 $sel .= " value=\"0\"";
1667 print "<input class=\"noborder\"
1668 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1673 function initialize_user_prefs($link, $uid) {
1675 $uid = db_escape_string($uid);
1677 db_query($link, "BEGIN");
1679 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1681 $u_result = db_query($link, "SELECT pref_name
1682 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1684 $active_prefs = array();
1686 while ($line = db_fetch_assoc($u_result)) {
1687 array_push($active_prefs, $line["pref_name"]);
1690 while ($line = db_fetch_assoc($result)) {
1691 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1692 // print "adding " . $line["pref_name"] . "<br>";
1694 db_query($link, "INSERT INTO ttrss_user_prefs
1695 (owner_uid,pref_name,value) VALUES
1696 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1701 db_query($link, "COMMIT");
1705 function lookup_user_id($link, $user) {
1707 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1710 if (db_num_rows($result) == 1) {
1711 return db_fetch_result($result, 0, "id");
1717 function http_authenticate_user($link) {
1719 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1721 if (!$_SERVER["PHP_AUTH_USER"]) {
1723 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1724 header('HTTP/1.0 401 Unauthorized');
1728 $auth_result = authenticate_user($link,
1729 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1731 if (!$auth_result) {
1732 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1733 header('HTTP/1.0 401 Unauthorized');
1741 function authenticate_user($link, $login, $password, $force_auth = false) {
1743 if (!SINGLE_USER_MODE
) {
1745 $pwd_hash1 = encrypt_password($password);
1746 $pwd_hash2 = encrypt_password($password, $login);
1747 $login = db_escape_string($login);
1749 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1750 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1752 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1754 $query = "SELECT id,login,access_level,pwd_hash
1755 FROM ttrss_users WHERE
1759 $query = "SELECT id,login,access_level,pwd_hash
1760 FROM ttrss_users WHERE
1761 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1762 pwd_hash = '$pwd_hash2')";
1765 $result = db_query($link, $query);
1767 if (db_num_rows($result) == 1) {
1768 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1769 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1770 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1772 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1775 $user_theme = get_user_theme_path($link);
1777 $_SESSION["theme"] = $user_theme;
1778 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1779 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1781 initialize_user_prefs($link, $_SESSION["uid"]);
1790 $_SESSION["uid"] = 1;
1791 $_SESSION["name"] = "admin";
1793 $user_theme = get_user_theme_path($link);
1795 $_SESSION["theme"] = $user_theme;
1796 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1798 initialize_user_prefs($link, $_SESSION["uid"]);
1804 function make_password($length = 8) {
1807 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1811 while ($i < $length) {
1812 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1814 if (!strstr($password, $char)) {
1822 // this is called after user is created to initialize default feeds, labels
1825 // user preferences are checked on every login, not here
1827 function initialize_user($link, $uid) {
1829 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1830 VALUES ('$uid', 'All Articles')");
1832 db_query($link, "INSERT INTO ttrss_filters
1833 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1834 action_id, action_param, filter_param)
1835 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1837 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1838 values ('$uid', 'Tiny Tiny RSS: New Releases',
1839 'http://tt-rss.org/releases.rss')");
1841 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1842 values ('$uid', 'Tiny Tiny RSS: Forum',
1843 'http://tt-rss.org/forum/rss.php')");
1846 function logout_user() {
1848 if (isset($_COOKIE[session_name()])) {
1849 setcookie(session_name(), '', time()-42000, '/');
1853 function get_script_urlpath() {
1854 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1857 function validate_session($link) {
1858 if (SINGLE_USER_MODE
) {
1862 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1863 if ($_SESSION["ip_address"]) {
1864 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1865 $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1871 if ($_SESSION["uid"]) {
1873 $result = db_query($link,
1874 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1876 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1878 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1883 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1885 //print_r($_SESSION);
1887 if (time() > $_SESSION["cookie_lifetime"]) {
1895 function login_sequence($link, $mobile = false) {
1896 if (!SINGLE_USER_MODE
) {
1898 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1899 $swu = db_escape_string($_REQUEST["swu"]);
1901 $_SESSION["prefs_cache"] = false;
1902 return authenticate_user($link, $swu, null, true);
1906 $login_action = $_POST["login_action"];
1908 # try to authenticate user if called from login form
1909 if ($login_action == "do_login") {
1910 $login = $_POST["login"];
1911 $password = $_POST["password"];
1912 $remember_me = $_POST["remember_me"];
1914 if (authenticate_user($link, $login, $password)) {
1915 $_POST["password"] = "";
1917 $_SESSION["language"] = $_POST["language"];
1918 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1920 header("Location: " . $_SERVER["REQUEST_URI"]);
1925 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1929 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1930 render_login_form($link, $mobile);
1931 //header("Location: login.php");
1934 /* bump login timestamp */
1935 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1938 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1939 setcookie("ttrss_lang", $_SESSION["language"],
1940 time() + SESSION_COOKIE_LIFETIME
);
1943 /* bump counters stamp since we're getting reloaded anyway */
1945 $_SESSION["get_all_counters_stamp"] = time();
1949 return authenticate_user($link, "admin", null);
1953 function truncate_string($str, $max_len) {
1954 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1955 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1961 function get_user_theme_path($link) {
1962 $result = db_query($link, "SELECT theme_path
1964 ttrss_themes,ttrss_users
1965 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1966 if (db_num_rows($result) != 0) {
1967 return db_fetch_result($result, 0, "theme_path");
1973 function smart_date_time($timestamp) {
1974 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1975 return date("G:i", $timestamp);
1976 } else if (date("Y", $timestamp) == date("Y")) {
1977 return date("M d, G:i", $timestamp);
1979 return date("Y/m/d, G:i", $timestamp);
1983 function smart_date($timestamp) {
1984 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1986 } else if (date("Y", $timestamp) == date("Y")) {
1987 return date("D m", $timestamp);
1989 return date("Y/m/d", $timestamp);
1993 function sql_bool_to_string($s) {
1994 if ($s == "t" ||
$s == "1") {
2001 function sql_bool_to_bool($s) {
2002 if ($s == "t" ||
$s == "1") {
2009 function bool_to_sql_bool($s) {
2017 function toggleEvenOdd($a) {
2024 function sanity_check($link) {
2029 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2030 $schema_version = db_fetch_result($result, 0, "schema_version");
2032 if ($schema_version != SCHEMA_VERSION
) {
2036 if (DB_TYPE
== "mysql") {
2037 $result = db_query($link, "SELECT true", false);
2038 if (db_num_rows($result) != 1) {
2043 if (db_escape_string("testTEST") != "testTEST") {
2047 error_reporting (DEFAULT_ERROR_LEVEL
);
2049 if ($error_code != 0) {
2050 print_error_xml($error_code);
2057 function file_is_locked($filename) {
2058 if (function_exists('flock')) {
2060 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2061 error_reporting(DEFAULT_ERROR_LEVEL
);
2063 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2064 flock($fp, LOCK_UN
);
2074 return true; // consider the file always locked and skip the test
2077 function make_lockfile($filename) {
2078 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2080 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2087 function make_stampfile($filename) {
2088 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2090 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2091 fwrite($fp, time() . "\n");
2092 flock($fp, LOCK_UN
);
2100 function read_stampfile($filename) {
2103 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2104 error_reporting (DEFAULT_ERROR_LEVEL
);
2107 if (flock($fp, LOCK_EX
)) {
2108 $stamp = fgets($fp);
2109 flock($fp, LOCK_UN
);
2120 function sql_random_function() {
2121 if (DB_TYPE
== "mysql") {
2128 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2130 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2132 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2139 $cat_qpart = "cat_id = '$feed'";
2141 $cat_qpart = "cat_id IS NULL";
2144 $tmp_result = db_query($link, "SELECT id
2145 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2147 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2149 $tmp_feed = $tmp_line["id"];
2151 db_query($link, "UPDATE ttrss_user_entries
2152 SET unread = false,last_read = NOW()
2153 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2155 } else if ($feed == -2) {
2158 db_query($link, "UPDATE ttrss_user_entries
2159 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2160 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2161 AND unread = true AND owner_uid = $owner_uid");
2164 } else if ($feed > 0) {
2166 $tmp_result = db_query($link, "SELECT id
2167 FROM ttrss_feeds WHERE parent_feed = '$feed'
2168 ORDER BY cat_id,title");
2170 $parent_ids = array();
2172 if (db_num_rows($tmp_result) > 0) {
2173 while ($p = db_fetch_assoc($tmp_result)) {
2174 array_push($parent_ids, "feed_id = " . $p["id"]);
2177 $children_qpart = implode(" OR ", $parent_ids);
2179 db_query($link, "UPDATE ttrss_user_entries
2180 SET unread = false,last_read = NOW()
2181 WHERE (feed_id = '$feed' OR $children_qpart)
2182 AND owner_uid = $owner_uid");
2185 db_query($link, "UPDATE ttrss_user_entries
2186 SET unread = false,last_read = NOW()
2187 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2190 } else if ($feed < 0 && $feed > -10) { // special, like starred
2193 db_query($link, "UPDATE ttrss_user_entries
2194 SET unread = false,last_read = NOW()
2195 WHERE marked = true AND owner_uid = $owner_uid");
2199 db_query($link, "UPDATE ttrss_user_entries
2200 SET unread = false,last_read = NOW()
2201 WHERE published = true AND owner_uid = $owner_uid");
2206 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2208 if (DB_TYPE
== "pgsql") {
2209 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2211 $match_part = "updated > DATE_SUB(NOW(),
2212 INTERVAL $intl HOUR) ";
2215 $result = db_query($link, "SELECT id FROM ttrss_entries,
2216 ttrss_user_entries WHERE $match_part AND
2218 ttrss_user_entries.ref_id = ttrss_entries.id AND
2219 owner_uid = $owner_uid");
2221 $affected_ids = array();
2223 while ($line = db_fetch_assoc($result)) {
2224 array_push($affected_ids, $line["id"]);
2227 catchupArticlesById($link, $affected_ids, 0);
2231 db_query($link, "UPDATE ttrss_user_entries
2232 SET unread = false,last_read = NOW()
2233 WHERE owner_uid = $owner_uid");
2236 } else if ($feed < -10) { // label
2238 $label_id = -$feed - 11;
2240 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2241 SET unread = false, last_read = NOW()
2242 WHERE label_id = '$label_id' AND unread = true
2243 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2247 ccache_update($link, $feed, $owner_uid, $cat_view);
2250 db_query($link, "BEGIN");
2252 $tag_name = db_escape_string($feed);
2254 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2255 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2257 while ($line = db_fetch_assoc($result)) {
2258 db_query($link, "UPDATE ttrss_user_entries SET
2259 unread = false, last_read = NOW()
2260 WHERE int_id = " . $line["post_int_id"]);
2262 db_query($link, "COMMIT");
2266 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2270 $cat_qpart = "cat_id = '$feed'";
2272 $cat_qpart = "cat_id IS NULL";
2275 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2276 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2278 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2279 $feed_url = $tmp_line["feed_url"];
2280 $feed_id = $tmp_line["id"];
2281 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2285 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2286 WHERE id = '$feed'");
2287 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2288 update_rss_feed($link, $feed_url, $feed, $force_update);
2292 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2294 if (!$omode) $omode = "flc";
2296 getGlobalCounters($link);
2298 if (strchr($omode, "l")) getLabelCounters($link);
2299 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2300 if (strchr($omode, "t")) getTagCounters($link);
2301 if (strchr($omode, "c")) {
2302 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2303 getCategoryCounters($link);
2308 function getCategoryCounters($link) {
2309 # two special categories are -1 and -2 (all virtuals; all labels)
2311 /* $ctr = getCategoryUnread($link, -1);
2313 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2315 $ctr = getCategoryUnread($link, -2);
2317 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2319 $age_qpart = getMaxAgeSubquery();
2321 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2322 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2323 WHERE ttrss_cat_counters_cache.feed_id = id AND
2324 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2326 while ($line = db_fetch_assoc($result)) {
2327 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2329 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2330 $line["unread"]."\"/>";
2333 /* Special case: NULL category doesn't actually exist in the DB */
2335 print "<counter type=\"category\" id=\"0\" counter=\"".
2336 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2340 function getCategoryUnread($link, $cat, $owner_uid = false) {
2342 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2347 $cat_query = "cat_id = '$cat'";
2349 $cat_query = "cat_id IS NULL";
2352 $age_qpart = getMaxAgeSubquery();
2354 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2356 AND owner_uid = " . $owner_uid);
2358 $cat_feeds = array();
2359 while ($line = db_fetch_assoc($result)) {
2360 array_push($cat_feeds, "feed_id = " . $line["id"]);
2363 if (count($cat_feeds) == 0) return 0;
2365 $match_part = implode(" OR ", $cat_feeds);
2367 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2368 FROM ttrss_user_entries,ttrss_entries
2369 WHERE unread = true AND ($match_part) AND id = ref_id
2370 AND $age_qpart AND owner_uid = " . $owner_uid);
2374 # this needs to be rewritten
2375 while ($line = db_fetch_assoc($result)) {
2376 $unread +
= $line["unread"];
2380 } else if ($cat == -1) {
2381 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2382 } else if ($cat == -2) {
2384 $result = db_query($link, "
2385 SELECT COUNT(unread) AS unread FROM
2386 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2387 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2388 ttrss_labels2.owner_uid = '$owner_uid'
2389 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2390 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2392 $unread = db_fetch_result($result, 0, "unread");
2399 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2400 if (DB_TYPE
== "pgsql") {
2401 return "ttrss_entries.date_entered >
2402 NOW() - INTERVAL '$days days'";
2404 return "ttrss_entries.date_entered >
2405 DATE_SUB(NOW(), INTERVAL $days DAY)";
2409 function getFeedUnread($link, $feed, $is_cat = false) {
2410 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2413 function getLabelUnread($link, $label_id, $owner_uid = false) {
2414 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2416 $result = db_query($link, "
2417 SELECT COUNT(unread) AS unread FROM
2418 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2419 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2420 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2421 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2422 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2424 if (db_num_rows($result) != 0) {
2425 return db_fetch_result($result, 0, "unread");
2431 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2432 $owner_uid = false) {
2434 $n_feed = sprintf("%d", $feed);
2436 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2439 $unread_qpart = "unread = true";
2441 $unread_qpart = "true";
2444 $age_qpart = getMaxAgeSubquery();
2447 return getCategoryUnread($link, $n_feed, $owner_uid);
2448 } else if ($n_feed == -1) {
2449 $match_part = "marked = true";
2450 } else if ($n_feed == -2) {
2451 $match_part = "published = true";
2452 } else if ($n_feed == -3) {
2453 $match_part = "unread = true";
2455 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2457 if (DB_TYPE
== "pgsql") {
2458 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2460 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2462 } else if ($n_feed == -4) {
2463 $match_part = "true";
2464 } else if ($n_feed > 0) {
2466 $result = db_query($link, "SELECT id FROM ttrss_feeds
2467 WHERE parent_feed = '$n_feed'
2469 AND owner_uid = " . $owner_uid);
2471 if (db_num_rows($result) > 0) {
2473 $linked_feeds = array();
2474 while ($line = db_fetch_assoc($result)) {
2475 array_push($linked_feeds, "feed_id = " . $line["id"]);
2478 array_push($linked_feeds, "feed_id = $n_feed");
2480 $match_part = implode(" OR ", $linked_feeds);
2482 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2483 FROM ttrss_user_entries,ttrss_entries
2484 WHERE $unread_qpart AND
2485 ttrss_user_entries.ref_id = ttrss_entries.id AND
2488 owner_uid = " . $owner_uid);
2492 # this needs to be rewritten
2493 while ($line = db_fetch_assoc($result)) {
2494 $unread +
= $line["unread"];
2500 $match_part = "feed_id = '$n_feed'";
2502 } else if ($feed < -10) {
2504 $label_id = -$feed - 11;
2506 return getLabelUnread($link, $label_id, $owner_uid);
2512 $result = db_query($link, "SELECT count(int_id) AS unread
2513 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2514 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2515 ttrss_user_entries.ref_id = ttrss_entries.id AND
2516 ttrss_feeds.hidden = false AND
2518 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2522 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2523 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2524 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2525 AND $unread_qpart AND $age_qpart AND
2526 ttrss_tags.owner_uid = " . $owner_uid);
2529 $unread = db_fetch_result($result, 0, "unread");
2534 function getGlobalUnread($link, $user_id = false) {
2537 $user_id = $_SESSION["uid"];
2540 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2541 WHERE owner_uid = '$user_id' AND feed_id > 0");
2543 $c_id = db_fetch_result($result, 0, "c_id");
2548 function getGlobalCounters($link, $global_unread = -1) {
2549 if ($global_unread == -1) {
2550 $global_unread = getGlobalUnread($link);
2552 print "<counter type=\"global\" id='global-unread'
2553 counter='$global_unread'/>";
2555 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2556 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2558 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2560 print "<counter type=\"global\" id='subscribed-feeds'
2561 counter='$subscribed_feeds'/>";
2565 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2568 if (!$_SESSION["tctr_last_value"]) {
2569 $_SESSION["tctr_last_value"] = array();
2573 $old_counters = $_SESSION["tctr_last_value"];
2575 $tctrs_modified = false;
2577 $age_qpart = getMaxAgeSubquery();
2579 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2580 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2581 AND ref_id = id AND $age_qpart
2582 AND unread = true)) AS count FROM ttrss_tags
2583 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2584 ORDER BY count DESC LIMIT 55");
2588 while ($line = db_fetch_assoc($result)) {
2589 $tags[$line["tag_name"]] +
= $line["count"];
2592 foreach (array_keys($tags) as $tag) {
2593 $unread = $tags[$tag];
2595 $tag = htmlspecialchars($tag);
2597 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2598 $old_counters[$tag] = $unread;
2599 $tctrs_modified = true;
2600 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2605 if ($smart_mode && $tctrs_modified) {
2606 $_SESSION["tctr_last_value"] = $old_counters;
2611 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2613 $age_qpart = getMaxAgeSubquery();
2616 if (!$_SESSION["lctr_last_value"]) {
2617 $_SESSION["lctr_last_value"] = array();
2623 for ($i = -1; $i >= -4; $i--) {
2625 $count = getFeedUnread($link, $i);
2629 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2630 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2635 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2637 $ret_arr[$i]["counter"] = $count;
2638 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2643 $old_counters = $_SESSION["lctr_last_value"];
2644 $lctrs_modified = false;
2647 $owner_uid = $_SESSION["uid"];
2649 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2650 WHERE owner_uid = '$owner_uid'");
2652 while ($line = db_fetch_assoc($result)) {
2654 $id = -$line["id"] - 11;
2656 $label_name = $line["caption"];
2657 $count = getFeedUnread($link, $id);
2659 if (!$smart_mode ||
$old_counters[$id] != $count) {
2660 $old_counters[$id] = $count;
2661 $lctrs_modified = true;
2664 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2665 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2670 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2672 $ret_arr[$id]["counter"] = $count;
2673 $ret_arr[$id]["description"] = $label_name;
2677 error_reporting (DEFAULT_ERROR_LEVEL
);
2680 if ($smart_mode && $lctrs_modified) {
2681 $_SESSION["lctr_last_value"] = $old_counters;
2687 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2689 $age_qpart = getMaxAgeSubquery();
2692 if (!$_SESSION["fctr_last_value"]) {
2693 $_SESSION["fctr_last_value"] = array();
2697 $old_counters = $_SESSION["fctr_last_value"];
2699 $query = "SELECT ttrss_feeds.id,
2701 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2702 last_error, value AS count
2703 FROM ttrss_feeds, ttrss_counters_cache
2704 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2705 AND parent_feed IS NULL
2706 AND ttrss_counters_cache.feed_id = id";
2708 $result = db_query($link, $query);
2709 $fctrs_modified = false;
2711 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2713 while ($line = db_fetch_assoc($result)) {
2716 $count = $line["count"];
2717 $last_error = htmlspecialchars($line["last_error"]);
2719 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2720 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2722 $last_updated = date($short_date, strtotime($line["last_updated"]));
2725 $last_updated = htmlspecialchars($last_updated);
2727 $has_img = feed_has_icon($id);
2729 $tmp_result = db_query($link,
2730 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2731 WHERE parent_feed = '$id' AND feed_id = id");
2733 $count +
= db_fetch_result($tmp_result, 0, "unread");
2735 if (!$smart_mode ||
$old_counters[$id] != $count) {
2736 $old_counters[$id] = $count;
2737 $fctrs_modified = true;
2740 $error_part = "error=\"$last_error\"";
2746 $has_img_part = "hi=\"$has_img\"";
2751 if ($active_feed && $id == $active_feed) {
2752 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2754 $has_title_part = "";
2757 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2758 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2761 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2765 if ($smart_mode && $fctrs_modified) {
2766 $_SESSION["fctr_last_value"] = $old_counters;
2770 function get_script_dt_add() {
2771 /* if (strpos(VERSION, ".99") === false) {
2779 function get_pgsql_version($link) {
2780 $result = db_query($link, "SELECT version() AS version");
2781 $version = split(" ", db_fetch_result($result, 0, "version"));
2785 function print_error_xml($code, $add_msg = "") {
2788 $error_msg = $ERRORS[$code];
2791 $error_msg = "$error_msg; $add_msg";
2794 print "<rpc-reply>";
2795 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2796 print "</rpc-reply>";
2799 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2800 $auth_login = '', $auth_pass = '') {
2802 # check for feed:http://url
2803 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2805 # check for feed://URL
2806 if (strpos($feed_link, "//") === 0) {
2807 $feed_link = "http:$feed_link";
2810 if ($feed_link == "") return;
2812 if ($cat_id == "0" ||
!$cat_id) {
2813 $cat_qpart = "NULL";
2815 $cat_qpart = "'$cat_id'";
2818 $result = db_query($link,
2819 "SELECT id FROM ttrss_feeds
2820 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2822 if (db_num_rows($result) == 0) {
2824 $result = db_query($link,
2825 "INSERT INTO ttrss_feeds
2826 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2827 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2828 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2830 $result = db_query($link,
2831 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2832 AND owner_uid = " . $_SESSION["uid"]);
2834 $feed_id = db_fetch_result($result, 0, "id");
2837 update_rss_feed($link, $feed_link, $feed_id, true);
2846 function print_feed_select($link, $id, $default_id = "",
2847 $attributes = "", $include_all_feeds = true) {
2849 print "<select id=\"$id\" name=\"$id\" $attributes>";
2850 if ($include_all_feeds) {
2851 print "<option value=\"0\">".__('All feeds')."</option>";
2854 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2855 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2857 if (db_num_rows($result) > 0 && $include_all_feeds) {
2858 print "<option disabled>--------</option>";
2861 while ($line = db_fetch_assoc($result)) {
2862 if ($line["id"] == $default_id) {
2863 $is_selected = "selected";
2868 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2870 printf("<option $is_selected value='%d'>%s</option>",
2871 $line["id"], $title);
2877 function print_feed_cat_select($link, $id, $default_id = "",
2878 $attributes = "", $include_all_cats = true) {
2880 print "<select id=\"$id\" name=\"$id\" $attributes>";
2882 if ($include_all_cats) {
2883 print "<option value=\"0\">".__('Uncategorized')."</option>";
2886 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2887 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2889 if (db_num_rows($result) > 0 && $include_all_cats) {
2890 print "<option disabled>--------</option>";
2893 while ($line = db_fetch_assoc($result)) {
2894 if ($line["id"] == $default_id) {
2895 $is_selected = "selected";
2899 printf("<option $is_selected value='%d'>%s</option>",
2900 $line["id"], htmlspecialchars($line["title"]));
2906 function checkbox_to_sql_bool($val) {
2907 return ($val == "on") ?
"true" : "false";
2910 function getFeedCatTitle($link, $id) {
2912 return __("Special");
2913 } else if ($id < -10) {
2914 return __("Labels");
2915 } else if ($id > 0) {
2916 $result = db_query($link, "SELECT ttrss_feed_categories.title
2917 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2918 cat_id = ttrss_feed_categories.id");
2919 if (db_num_rows($result) == 1) {
2920 return db_fetch_result($result, 0, "title");
2922 return __("Uncategorized");
2925 return "getFeedCatTitle($id) failed";
2930 function getFeedTitle($link, $id) {
2932 return __("Starred articles");
2933 } else if ($id == -2) {
2934 return __("Published articles");
2935 } else if ($id == -3) {
2936 return __("Fresh articles");
2937 } else if ($id == -4) {
2938 return __("All articles");
2939 } else if ($id < -10) {
2940 $label_id = -$id - 11;
2941 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2942 if (db_num_rows($result) == 1) {
2943 return db_fetch_result($result, 0, "caption");
2945 return "Unknown label ($label_id)";
2948 } else if ($id > 0) {
2949 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2950 if (db_num_rows($result) == 1) {
2951 return db_fetch_result($result, 0, "title");
2953 return "Unknown feed ($id)";
2956 if (preg_match("/^-?[0-9][0-9]*$/", $id)) {
2957 return "getFeedTitle($id) failed";
2965 function get_session_cookie_name() {
2966 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2969 function print_init_params($link) {
2970 print "<init-params>";
2971 if ($_SESSION["stored-params"]) {
2972 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2974 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2975 print "<param key=\"$key\" value=\"$value\"/>";
2980 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2981 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2982 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2983 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2985 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2986 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2988 print "<param key=\"hide_read_feeds\" value=\"" .
2989 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2991 print "<param key=\"enable_feed_cats\" value=\"" .
2992 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2994 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2995 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2997 print "<param key=\"confirm_feed_catchup\" value=\"" .
2998 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3000 print "<param key=\"cdm_auto_catchup\" value=\"" .
3001 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3003 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3005 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3007 print "<param key=\"default_view_mode\" value=\"" .
3008 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3010 print "<param key=\"default_view_limit\" value=\"" .
3011 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3013 print "<param key=\"default_view_order_by\" value=\"" .
3014 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3016 print "<param key=\"prefs_active_tab\" value=\"" .
3017 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3019 print "<param key=\"infobox_disable_overlay\" value=\"" .
3020 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3022 print "<param key=\"icons_location\" value=\"" .
3025 print "<param key=\"hide_read_shows_special\" value=\"" .
3026 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3028 print "<param key=\"hide_feedlist\" value=\"" .
3029 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3031 print "<param key=\"bw_limit\" value=\"".
3032 (int) $_SESSION["bw_limit"]."\"/>";
3034 // print "<param key=\"sync_counters\" value=\"" .
3035 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3037 print "<param key=\"sync_counters\" value=\"1\"/>";
3039 print "<param key=\"offline_enabled\" value=\"".
3040 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3042 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3043 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3045 $num_feeds = db_fetch_result($result, 0, "cf");
3047 print "<param key=\"num_feeds\" value=\"".
3048 (int)$num_feeds. "\"/>";
3050 print "</init-params>";
3053 function print_runtime_info($link) {
3054 print "<runtime-info>";
3056 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3057 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3059 $num_feeds = db_fetch_result($result, 0, "cf");
3061 print "<param key=\"num_feeds\" value=\"".
3062 (int)$num_feeds. "\"/>";
3064 if (ENABLE_UPDATE_DAEMON
) {
3065 print "<param key=\"daemon_is_running\" value=\"".
3066 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3068 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3070 $stamp = (int)read_stampfile("update_daemon.stamp");
3072 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3075 $stamp_delta = time() - $stamp;
3077 if ($stamp_delta > 1800) {
3081 $_SESSION["daemon_stamp_check"] = time();
3084 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3086 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3088 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3093 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3095 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3096 $new_version_details = check_for_update($link);
3098 print "<param key=\"new_version_available\" value=\"".
3099 sprintf("%d", $new_version_details != ""). "\"/>";
3101 $_SESSION["last_version_check"] = time();
3105 // print "<param key=\"new_version_available\" value=\"1\"/>";
3107 print "</runtime-info>";
3110 function getSearchSql($search, $match_on) {
3112 $search_query_part = "";
3114 $keywords = split(" ", $search);
3115 $query_keywords = array();
3117 if ($match_on == "both") {
3119 foreach ($keywords as $k) {
3120 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3121 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3124 $search_query_part = implode("AND", $query_keywords) . " AND ";
3126 } else if ($match_on == "title") {
3128 foreach ($keywords as $k) {
3129 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3132 $search_query_part = implode("AND", $query_keywords) . " AND ";
3134 } else if ($match_on == "content") {
3136 foreach ($keywords as $k) {
3137 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3141 $search_query_part = implode("AND", $query_keywords);
3143 return $search_query_part;
3146 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3148 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3152 $search_query_part = getSearchSql($search, $match_on);
3153 $search_query_part .= " AND ";
3156 $search_query_part = "";
3159 $view_query_part = "";
3161 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3163 $view_query_part = " ";
3164 } else if ($feed != -1) {
3165 $unread = getFeedUnread($link, $feed, $cat_view);
3167 $view_query_part = " unread = true AND ";
3172 if ($view_mode == "marked") {
3173 $view_query_part = " marked = true AND ";
3176 if ($view_mode == "unread") {
3177 $view_query_part = " unread = true AND ";
3180 if ($view_mode == "updated") {
3181 $view_query_part = " (last_read is null and unread = false) AND ";
3185 $limit_query_part = "LIMIT " . $limit;
3188 $vfeed_query_part = "";
3190 // override query strategy and enable feed display when searching globally
3191 if ($search && $search_mode == "all_feeds") {
3192 $query_strategy_part = "ttrss_entries.id > 0";
3193 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3194 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3195 $query_strategy_part = "ttrss_entries.id > 0";
3196 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3197 id = feed_id) as feed_title,";
3198 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3200 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3202 $tmp_result = false;
3205 $tmp_result = db_query($link, "SELECT id
3206 FROM ttrss_feeds WHERE cat_id = '$feed'");
3208 $tmp_result = db_query($link, "SELECT id
3209 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3210 WHERE id = '$feed') AND id != '$feed'");
3213 $cat_siblings = array();
3215 if (db_num_rows($tmp_result) > 0) {
3216 while ($p = db_fetch_assoc($tmp_result)) {
3217 array_push($cat_siblings, "feed_id = " . $p["id"]);
3220 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3221 $feed, implode(" OR ", $cat_siblings));
3224 $query_strategy_part = "ttrss_entries.id > 0";
3227 } else if ($feed >= 0) {
3232 $query_strategy_part = "cat_id = '$feed'";
3234 $query_strategy_part = "cat_id IS NULL";
3237 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3240 $tmp_result = db_query($link, "SELECT id
3241 FROM ttrss_feeds WHERE parent_feed = '$feed'
3242 ORDER BY cat_id,title");
3244 $parent_ids = array();
3246 if (db_num_rows($tmp_result) > 0) {
3247 while ($p = db_fetch_assoc($tmp_result)) {
3248 array_push($parent_ids, "feed_id = " . $p["id"]);
3251 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3252 $feed, implode(" OR ", $parent_ids));
3254 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3256 $query_strategy_part = "feed_id = '$feed'";
3259 } else if ($feed == -1) { // starred virtual feed
3260 $query_strategy_part = "marked = true";
3261 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3262 } else if ($feed == -2) { // published virtual feed OR labels category
3265 $query_strategy_part = "published = true";
3266 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3270 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3272 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3273 ttrss_user_labels2.article_id = ref_id";
3277 } else if ($feed == -3) { // fresh virtual feed
3278 $query_strategy_part = "unread = true";
3280 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3282 if (DB_TYPE
== "pgsql") {
3283 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3285 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3288 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3289 } else if ($feed == -4) { // all articles virtual feed
3290 $query_strategy_part = "true";
3291 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3292 } else if ($feed <= -10) { // labels
3293 $label_id = -$feed - 11;
3295 $query_strategy_part = "label_id = '$label_id' AND
3296 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3297 ttrss_user_labels2.article_id = ref_id";
3299 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3300 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3303 $query_strategy_part = "id > 0"; // dumb
3306 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3307 $order_by = "updated";
3309 $order_by = "updated DESC";
3312 if ($view_mode != "noscores") {
3313 $order_by = "score DESC, $order_by";
3316 if ($override_order) {
3317 $order_by = $override_order;
3322 if ($search && $search_mode == "all_feeds") {
3323 $feed_title = __("Search results")." ($search)";
3324 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3325 $feed_title = __("Search results")." ($search, $feed)";
3326 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3327 $feed_title = $feed;
3328 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3333 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3334 WHERE id = '$feed' AND owner_uid = $owner_uid");
3335 $feed_title = db_fetch_result($result, 0, "title");
3337 $feed_title = __("Uncategorized");
3341 $feed_title = __("Searched for")." $search ($feed_title)";
3346 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3347 WHERE id = '$feed' AND owner_uid = $owner_uid");
3349 $feed_title = db_fetch_result($result, 0, "title");
3350 $feed_site_url = db_fetch_result($result, 0, "site_url");
3351 $last_error = db_fetch_result($result, 0, "last_error");
3354 $feed_title = __("Searched for") . " $search ($feed_title)";
3358 } else if ($feed == -1) {
3359 $feed_title = __("Starred articles");
3360 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3361 } else if ($feed == -2) {
3363 $feed_title = __("Published articles");
3364 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3366 $feed_title = __("Labels");
3368 } else if ($feed == -3) {
3369 $feed_title = __("Fresh articles");
3370 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3371 } else if ($feed == -4) {
3372 $feed_title = __("All articles");
3373 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3374 } else if ($feed < -10) {
3375 $label_id = -$feed - 11;
3376 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3377 WHERE id = '$label_id'");
3378 $feed_title = db_fetch_result($result, 0, "caption");
3381 $feed_title = __("Searched for") . " $search ($feed_title)";
3387 $content_query_part = "content as content_preview,";
3389 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3392 $feed_kind = "Feeds";
3394 $feed_kind = "Labels";
3397 if ($limit_query_part) {
3398 $offset_query_part = "OFFSET $offset";
3401 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3402 if (!$override_order) {
3403 $order_by = "ttrss_feeds.title, $order_by";
3406 // Special output for Fresh feed
3408 /* if ($feed == -3) {
3409 $group_limit_part = "(select count(*) from
3410 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3411 t1.ref_id = t2.id and t1.owner_uid = 2 and
3412 t1.feed_id = ttrss_user_entries.feed_id and
3413 t2.updated > ttrss_entries.updated) <= 5 AND";
3417 $query = "SELECT DISTINCT
3419 ttrss_entries.id,ttrss_entries.title,
3422 unread,feed_id,marked,published,link,last_read,
3423 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3426 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3429 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3432 ttrss_feeds.hidden = false AND
3433 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3434 ttrss_user_entries.ref_id = ttrss_entries.id AND
3435 ttrss_user_entries.owner_uid = '$owner_uid' AND
3438 $query_strategy_part ORDER BY $order_by
3439 $limit_query_part $offset_query_part";
3441 if ($_GET["debug"]) print $query;
3443 $result = db_query($link, $query);
3448 $feed_kind = "Tags";
3450 $result = db_query($link, "SELECT
3453 ttrss_entries.id as id,title,
3456 marked,link,last_read,
3457 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3460 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3463 ttrss_entries,ttrss_user_entries,ttrss_tags
3465 ref_id = ttrss_entries.id AND
3466 ttrss_user_entries.owner_uid = '$owner_uid' AND
3467 post_int_id = int_id AND tag_name = '$feed' AND
3470 $query_strategy_part ORDER BY $order_by
3471 $limit_query_part");
3474 return array($result, $feed_title, $feed_site_url, $last_error);
3478 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3479 $limit, $search, $search_mode, $match_on) {
3481 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3482 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3483 "margin-bottom : 1em; color : #9a8c59;";
3485 if (!$limit) $limit = 30;
3487 $qfh_ret = queryFeedHeadlines($link, $feed,
3488 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3491 $result = $qfh_ret[0];
3492 $feed_title = htmlspecialchars($qfh_ret[1]);
3493 $feed_site_url = $qfh_ret[2];
3494 $last_error = $qfh_ret[3];
3496 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3498 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3499 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3500 <rss version=\"2.0\">
3502 <title>$feed_title</title>
3503 <link>$feed_site_url</link>
3504 <description>Feed generated by Tiny Tiny RSS</description>";
3506 while ($line = db_fetch_assoc($result)) {
3508 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3509 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3511 $tags = get_article_tags($link, $line["id"], $owner_uid);
3513 foreach ($tags as $tag) {
3514 print "<category>" . htmlspecialchars($tag) . "</category>";
3517 $rfc822_date = date('r', strtotime($line["updated"]));
3519 print "<pubDate>$rfc822_date</pubDate>";
3522 htmlspecialchars($line["title"]) . "</title>";
3524 print "<description><![CDATA[";
3526 if ($line["note"]) {
3527 print "<div style='$note_style'>";
3528 print $line["note"];
3532 print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3533 print "]]></description>";
3538 print "</channel></rss>";
3542 function getCategoryTitle($link, $cat_id) {
3544 if ($cat_id == -1) {
3545 return __("Special");
3546 } else if ($cat_id == -2) {
3547 return __("Labels");
3550 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3553 if (db_num_rows($result) == 1) {
3554 return db_fetch_result($result, 0, "title");
3556 return "Uncategorized";
3561 function strip_tags_long($string, $allowed) {
3563 $config = HTMLPurifier_Config
::createDefault();
3565 $config->set('HTML', 'Allowed', $allowed);
3566 $purifier = new HTMLPurifier($config);
3568 return $purifier->purify($string);
3572 // http://ru2.php.net/strip-tags
3574 /* function strip_tags_long($textstring, $allowed){
3575 while($textstring != strip_tags($textstring, $allowed))
3577 while (strlen($textstring) != 0)
3579 if (strlen($textstring) > 1024) {
3582 $otherlen = strlen($textstring);
3584 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3585 $safetext .= $temptext;
3586 $textstring = substr_replace($textstring,'',0,$otherlen);
3588 $textstring = $safetext;
3594 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false) {
3597 if (!$owner) $owner = $_SESSION["uid"];
3599 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) ||
$force_strip_tags) {
3601 // $res = strip_tags_long($res,
3602 // "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3604 $res = strip_tags_long($res,
3605 "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4");
3609 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3611 $res = preg_replace('/<img[^>]+>/is', '', $res);
3619 * Send by mail a digest of last articles.
3621 * @param mixed $link The database connection.
3622 * @param integer $limit The maximum number of articles by digest.
3623 * @return boolean Return false if digests are not enabled.
3625 function send_headlines_digests($link, $limit = 100) {
3627 if (!DIGEST_ENABLE
) return false;
3629 $user_limit = DIGEST_EMAIL_LIMIT
;
3632 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3634 if (DB_TYPE
== "pgsql") {
3635 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3636 } else if (DB_TYPE
== "mysql") {
3637 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3640 $result = db_query($link, "SELECT id,email FROM ttrss_users
3641 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3643 while ($line = db_fetch_assoc($result)) {
3645 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3646 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3648 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3650 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3651 $digest = $tuple[0];
3652 $headlines_count = $tuple[1];
3653 $affected_ids = $tuple[2];
3654 $digest_text = $tuple[3];
3656 if ($headlines_count > 0) {
3658 $mail = new PHPMailer();
3660 $mail->PluginDir
= "lib/phpmailer/";
3661 $mail->SetLanguage("en", "lib/phpmailer/language/");
3663 $mail->CharSet
= "UTF-8";
3665 $mail->From
= DIGEST_FROM_ADDRESS
;
3666 $mail->FromName
= DIGEST_FROM_NAME
;
3667 $mail->AddAddress($line["email"], $line["login"]);
3669 if (DIGEST_SMTP_HOST
) {
3670 $mail->Host
= DIGEST_SMTP_HOST
;
3671 $mail->Mailer
= "smtp";
3672 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3673 $mail->Username
= DIGEST_SMTP_LOGIN
;
3674 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3677 $mail->IsHTML(true);
3678 $mail->Subject
= DIGEST_SUBJECT
;
3679 $mail->Body
= $digest;
3680 $mail->AltBody
= $digest_text;
3682 $rc = $mail->Send();
3684 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3688 if ($rc && $do_catchup) {
3689 print "Marking affected articles as read...\n";
3690 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3693 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3694 WHERE id = " . $line["id"]);
3696 print "No headlines\n";
3701 print "All done.\n";
3705 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3707 require_once "lib/MiniTemplator.class.php";
3709 $tpl = new MiniTemplator
;
3710 $tpl_t = new MiniTemplator
;
3712 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3713 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3715 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3716 $tpl->setVariable('CUR_TIME', date('G:i'));
3718 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3719 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3721 $affected_ids = array();
3723 if (DB_TYPE
== "pgsql") {
3724 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3725 } else if (DB_TYPE
== "mysql") {
3726 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3729 $result = db_query($link, "SELECT ttrss_entries.title,
3730 ttrss_feeds.title AS feed_title,
3732 ttrss_user_entries.ref_id,
3734 SUBSTRING(content, 1, 120) AS excerpt,
3735 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3737 ttrss_user_entries,ttrss_entries,ttrss_feeds
3739 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3740 AND include_in_digest = true
3743 AND ttrss_user_entries.owner_uid = $user_id
3745 ORDER BY ttrss_feeds.title, date_entered DESC
3748 $cur_feed_title = "";
3750 $headlines_count = db_num_rows($result);
3752 $headlines = array();
3754 while ($line = db_fetch_assoc($result)) {
3755 array_push($headlines, $line);
3758 for ($i = 0; $i < sizeof($headlines); $i++
) {
3760 $line = $headlines[$i];
3762 array_push($affected_ids, $line["ref_id"]);
3764 $updated = smart_date_time(strtotime($line["last_updated"]));
3766 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3767 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3768 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3769 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3770 $tpl->setVariable('ARTICLE_EXCERPT',
3771 truncate_string(strip_tags($line["excerpt"]), 100));
3773 $tpl->addBlock('article');
3775 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3776 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3777 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3778 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3779 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3780 // truncate_string(strip_tags($line["excerpt"]), 100));
3782 $tpl_t->addBlock('article');
3784 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3785 $tpl->addBlock('feed');
3786 $tpl_t->addBlock('feed');
3791 $tpl->addBlock('digest');
3792 $tpl->generateOutputToString($tmp);
3794 $tpl_t->addBlock('digest');
3795 $tpl_t->generateOutputToString($tmp_t);
3797 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3800 function check_for_update($link) {
3801 $releases_feed = "http://tt-rss.org/releases.rss";
3803 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3808 if (ENABLE_SIMPLEPIE
) {
3809 $rss = new SimplePie();
3810 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3811 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3812 $rss->set_feed_url($fetch_url);
3813 $rss->set_output_encoding('UTF-8');
3816 $rss = fetch_rss($releases_feed);
3818 error_reporting (DEFAULT_ERROR_LEVEL
);
3822 if (ENABLE_SIMPLEPIE
) {
3823 $items = $rss->get_items();
3825 $items = $rss->items
;
3827 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3828 if (!$items ||
!is_array($items)) $items = $rss;
3831 if (!is_array($items) ||
count($items) == 0) {
3835 $latest_item = $items[0];
3837 if (ENABLE_SIMPLEPIE
) {
3838 $last_title = $latest_item->get_title();
3840 $last_title = $latest_item["title"];
3843 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3845 if (ENABLE_SIMPLEPIE
) {
3846 $release_url = sanitize_rss($link, $latest_item->get_link());
3847 $content = sanitize_rss($link, $latest_item->get_description());
3849 $release_url = sanitize_rss($link, $latest_item["link"]);
3850 $content = sanitize_rss($link, $latest_item["description"]);
3853 if (version_compare(VERSION
, $latest_version) == -1) {
3854 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3855 $latest_version)."<div class='milestoneDetails'>$content</div>";
3862 function markArticlesById($link, $ids, $cmode) {
3866 foreach ($ids as $id) {
3867 array_push($tmp_ids, "ref_id = '$id'");
3870 $ids_qpart = join(" OR ", $tmp_ids);
3873 db_query($link, "UPDATE ttrss_user_entries SET
3874 marked = false,last_read = NOW()
3875 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3876 } else if ($cmode == 1) {
3877 db_query($link, "UPDATE ttrss_user_entries SET
3879 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3881 db_query($link, "UPDATE ttrss_user_entries SET
3882 marked = NOT marked,last_read = NOW()
3883 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3887 function publishArticlesById($link, $ids, $cmode) {
3891 foreach ($ids as $id) {
3892 array_push($tmp_ids, "ref_id = '$id'");
3895 $ids_qpart = join(" OR ", $tmp_ids);
3898 db_query($link, "UPDATE ttrss_user_entries SET
3899 published = false,last_read = NOW()
3900 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3901 } else if ($cmode == 1) {
3902 db_query($link, "UPDATE ttrss_user_entries SET
3904 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3906 db_query($link, "UPDATE ttrss_user_entries SET
3907 published = NOT published,last_read = NOW()
3908 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3912 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3914 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3918 foreach ($ids as $id) {
3919 array_push($tmp_ids, "ref_id = '$id'");
3922 $ids_qpart = join(" OR ", $tmp_ids);
3925 db_query($link, "UPDATE ttrss_user_entries SET
3926 unread = false,last_read = NOW()
3927 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3928 } else if ($cmode == 1) {
3929 db_query($link, "UPDATE ttrss_user_entries SET
3931 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3933 db_query($link, "UPDATE ttrss_user_entries SET
3934 unread = NOT unread,last_read = NOW()
3935 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3940 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3941 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3943 while ($line = db_fetch_assoc($result)) {
3944 ccache_update($link, $line["feed_id"], $owner_uid);
3948 function catchupArticleById($link, $id, $cmode) {
3951 db_query($link, "UPDATE ttrss_user_entries SET
3952 unread = false,last_read = NOW()
3953 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3954 } else if ($cmode == 1) {
3955 db_query($link, "UPDATE ttrss_user_entries SET
3957 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3959 db_query($link, "UPDATE ttrss_user_entries SET
3960 unread = NOT unread,last_read = NOW()
3961 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3965 function make_guid_from_title($title) {
3966 return preg_replace("/[ \"\',.:;]/", "-",
3967 mb_strtolower(strip_tags($title), 'utf-8'));
3970 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3971 $feed_id, $is_cat, $search, $match_on,
3974 print "<div class=\"headlinesSubToolbar\">";
3976 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3977 $page_next_link = "javascript:viewFeedGoPage(1)";
3978 $page_first_link = "javascript:viewFeedGoPage(0)";
3980 $catchup_page_link = "javascript:catchupPage()";
3981 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3982 $catchup_sel_link = "javascript:catchupSelection()";
3984 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3986 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3987 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3988 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3989 $sel_inv_link = "javascript:invertHeadlineSelection()";
3991 $tog_unread_link = "javascript:selectionToggleUnread()";
3992 $tog_marked_link = "javascript:selectionToggleMarked()";
3993 $tog_published_link = "javascript:selectionTogglePublished()";
3997 $sel_all_link = "javascript:cdmSelectArticles('all')";
3998 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3999 $sel_none_link = "javascript:cdmSelectArticles('none')";
4001 $sel_inv_link = "javascript:invertHeadlineSelection()";
4003 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4004 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4005 $tog_published_link = "javascript:selectionTogglePublished(true)";
4009 print "<div id=\"subtoolbar_ftitle\">";
4011 if ($feed_site_url) {
4013 $target = "target=\"_blank\"";
4015 print "<a $target href=\"$feed_site_url\">".
4016 truncate_string($feed_title,30)."</a>";
4022 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4026 <a target=\"_blank\"
4027 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4028 <img class=\"noborder\"
4029 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4034 print __('Select:')."
4035 <a href=\"$sel_all_link\">".__('All')."</a>,
4036 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4037 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4038 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4040 print " ";
4043 onmouseover=\"enable_selection(false)\"
4044 onmouseout=\"enable_selection(true)\"
4045 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4046 __("Actions...") . " <img width='11' height'7'
4047 src=\"images/down_arrow.png\">
4050 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4052 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4053 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4054 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4055 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4056 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4057 <li class=\"insensitive\">".__('Mark as read:')."</li>
4058 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4060 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4063 //print "<li><span class=\"insensitive\">--------</span></li>";
4064 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4066 print_labels_headlines_dropdown($link, $feed_id);
4073 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4075 $tmp_category = getCategoryTitle($link, $cat_id);
4078 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4079 } else if ($cat_id == 0 ||
$cat_id == -2) {
4080 $cat_unread = getCategoryUnread($link, $cat_id);
4084 $holder_style = "display:none;";
4091 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4094 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4095 $inner_title_class = "catTitle";
4097 $browse_cat_link = "";
4098 $inner_title_class = "catTitleNL";
4101 $cat_class = "feedCat";
4103 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4104 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4105 title=\"".__('Click to collapse category')."\"
4106 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4107 id=\"FCATN-$cat_id\" $browse_cat_link
4108 \">$tmp_category</span>";
4110 print "<span id=\"FCAP-$cat_id\">";
4112 print " <span id=\"FCATCTR-$cat_id\"
4113 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4119 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4123 function outputFeedList($link, $tags = false) {
4125 print "<ul class=\"feedList\" id=\"feedList\">";
4127 $owner_uid = $_SESSION["uid"];
4131 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4133 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4136 $cat_hidden = false;
4139 printCategoryHeader($link, -1, $cat_hidden, false);
4142 $num_starred = getFeedUnread($link, -1);
4143 $num_published = getFeedUnread($link, -2);
4144 $num_fresh = getFeedUnread($link, -3);
4145 $num_total = getFeedUnread($link, -4);
4149 if ($num_total > 0) $class .= "Unread";
4151 printFeedEntry(-4, $class, __("All articles"), $num_total,
4152 "images/tag.png", $link);
4156 if ($num_fresh > 0) $class .= "Unread";
4158 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4159 "images/fresh.png", $link);
4163 if ($num_starred > 0) $class .= "Unread";
4165 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4168 $mark_img_ext = "gif";
4170 $mark_img_ext = "png";
4173 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4174 "images/mark_set.$mark_img_ext", $link);
4178 if ($num_published > 0) $class .= "Unread";
4180 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4181 "images/pub_set.gif", $link);
4183 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4190 $result = db_query($link, "SELECT * FROM
4191 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4193 if (db_num_rows($result) > 0) {
4194 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4196 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4199 $cat_hidden = false;
4202 printCategoryHeader($link, -2, $cat_hidden, true);
4205 print "<li><hr></li>";
4209 while ($line = db_fetch_assoc($result)) {
4211 $label_id = -$line['id'] - 11;
4212 $count = getFeedUnread($link, $label_id);
4220 printFeedEntry($label_id,
4221 $class, $line["caption"],
4222 $count, "images/label.png", $link,
4223 false, false, false,
4224 $line['fg_color'], $line['bg_color']);
4228 if (db_num_rows($result) > 0) {
4229 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4235 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4236 print "<li><hr></li>";
4239 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4240 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4241 $order_by_qpart = "order_id,category,unread DESC,title";
4243 $order_by_qpart = "order_id,category,title";
4246 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4247 $order_by_qpart = "unread DESC,title";
4249 $order_by_qpart = "title";
4253 $age_qpart = getMaxAgeSubquery();
4255 $query = "SELECT ttrss_feeds.*,
4256 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4258 ttrss_feed_categories.title AS category,
4259 ttrss_feed_categories.collapsed,
4261 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4262 ON (ttrss_feed_categories.id = cat_id)
4263 LEFT JOIN ttrss_counters_cache
4265 (ttrss_feeds.id = feed_id)
4267 ttrss_feeds.hidden = false AND
4268 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4269 ORDER BY $order_by_qpart";
4271 $result = db_query($link, $query);
4273 $actid = $_GET["actid"];
4283 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4285 while ($line = db_fetch_assoc($result)) {
4287 $feed = htmlspecialchars(trim($line["title"]));
4289 if (!$feed) $feed = "[Untitled]";
4291 $feed_id = $line["id"];
4292 $unread = $line["unread"];
4294 $subop = $_GET["subop"];
4296 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4297 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4299 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4302 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4305 $rtl_tag = "dir=\"RTL\"";
4310 $tmp_result = db_query($link,
4311 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4312 WHERE parent_feed = '$feed_id' AND feed_id = id");
4314 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4316 $cat_id = $line["cat_id"];
4318 $tmp_category = $line["category"];
4320 if (!$tmp_category) {
4321 $tmp_category = __("Uncategorized");
4324 // $class = ($lnum % 2) ? "even" : "odd";
4326 if ($line["last_error"]) {
4332 if ($unread > 0) $class .= "Unread";
4334 if ($actid == $feed_id) {
4335 $class .= "Selected";
4338 $total_unread +
= $unread;
4340 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4346 $category = $tmp_category;
4348 $collapsed = sql_bool_to_bool($line["collapsed"]);
4350 // workaround for NULL category
4351 if ($category == __("Uncategorized")) {
4352 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4357 $cat_id = sprintf("%d", $cat_id);
4359 printCategoryHeader($link, $cat_id, $collapsed, true);
4363 printFeedEntry($feed_id, $class, $feed, $unread,
4364 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4365 $last_updated, $line["last_error"]);
4370 if (db_num_rows($result) == 0) {
4371 print "<li>".__('No feeds to display.')."</li>";
4378 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4379 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4380 post_int_id = ttrss_user_entries.int_id AND
4381 unread = true AND ref_id = ttrss_entries.id
4382 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4384 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4385 ORDER BY tag_name"); */
4387 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4388 print "<li class=\"feedCat\">".__('Tags')."</li>";
4389 print "<ul class=\"feedCatList\">";
4392 $age_qpart = getMaxAgeSubquery();
4394 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4395 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4396 AND ref_id = id AND $age_qpart
4397 AND unread = true)) AS count FROM ttrss_tags
4398 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4399 ORDER BY count DESC LIMIT 50");
4403 while ($line = db_fetch_assoc($result)) {
4404 $tags[$line["tag_name"]] +
= $line["count"];
4407 foreach (array_keys($tags) as $tag) {
4409 $unread = $tags[$tag];
4417 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4421 if (db_num_rows($result) == 0) {
4422 print "<li>No tags to display.</li>";
4425 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4435 function get_article_tags($link, $id, $owner_uid = 0) {
4437 $a_id = db_escape_string($id);
4439 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4441 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4442 owner_uid as owner FROM
4443 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4444 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4448 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4449 array_push($tags, $tmp_line["tag_name"]);
4455 function trim_value(&$value) {
4456 $value = trim($value);
4459 function trim_array($array) {
4461 array_walk($tmp, 'trim_value');
4465 function tag_is_valid($tag) {
4466 if ($tag == '') return false;
4467 if (preg_match("/^[0-9]*$/", $tag)) return false;
4468 if (mb_strlen($tag) > 250) return false;
4470 if (function_exists('iconv')) {
4471 $tag = iconv("utf-8", "utf-8", $tag);
4474 if (!$tag) return false;
4479 function render_login_form($link, $mobile = false) {
4481 require_once "login_form.php";
4483 require_once "mobile/login_form.php";
4487 // from http://developer.apple.com/internet/safari/faq.html
4488 function no_cache_incantation() {
4489 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4490 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4491 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4492 header("Cache-Control: post-check=0, pre-check=0", false);
4493 header("Pragma: no-cache"); // HTTP/1.0
4496 function format_warning($msg, $id = "") {
4497 return "<div class=\"warning\" id=\"$id\">
4498 <img src=\"images/sign_excl.gif\">$msg</div>";
4501 function format_notice($msg) {
4502 return "<div class=\"notice\">
4503 <img src=\"images/sign_info.gif\">$msg</div>";
4506 function format_error($msg) {
4507 return "<div class=\"error\">
4508 <img src=\"images/sign_excl.gif\">$msg</div>";
4511 function print_notice($msg) {
4512 return print format_notice($msg);
4515 function print_warning($msg) {
4516 return print format_warning($msg);
4519 function print_error($msg) {
4520 return print format_error($msg);
4524 function T_sprintf() {
4525 $args = func_get_args();
4526 return vsprintf(__(array_shift($args)), $args);
4529 function format_inline_player($link, $url, $ctype) {
4533 if (($ctype == __("audio/mpeg")) && (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4535 $entry .= "<object type=\"application/x-shockwave-flash\"
4536 data=\"extras/button/musicplayer.swf?song_url=$url\"
4537 width=\"17\" height=\"17\">
4538 <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object>";
4543 if (substr($ctype,0,6)=="audio/" || $ctype=="application/ogg" || $ctype=="application/x-ogg") {
4544 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4545 if (($ctype == __("audio/mpeg")) &&
4546 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4547 $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>";
4549 $entry .= "</audio> ";
4550 if (($ctype == __("audio/mpeg")) &&
4551 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4552 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a>";
4553 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
4555 } elseif (substr($ctype,0,6)=="video/") {
4556 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4557 $entry .= "</video>";
4565 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4566 $zoom_mode = false) {
4568 /* we can figure out feed_id from article id anyway, why do we
4569 * pass feed_id here? */
4571 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4572 WHERE ref_id = '$id'");
4574 $feed_id = db_fetch_result($result, 0, "feed_id");
4576 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4578 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4579 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4581 if (db_num_rows($result) == 1) {
4582 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4583 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4585 $rtl_content = false;
4586 $always_display_enclosures = false;
4590 $rtl_tag = "dir=\"RTL\"";
4597 if ($mark_as_read) {
4598 $result = db_query($link, "UPDATE ttrss_user_entries
4599 SET unread = false,last_read = NOW()
4600 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4602 ccache_update($link, $feed_id, $_SESSION["uid"]);
4605 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4606 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4607 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4611 FROM ttrss_entries,ttrss_user_entries
4612 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4618 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4619 $link_target = "target=\"_blank\"";
4622 $line = db_fetch_assoc($result);
4624 if ($line["icon_url"]) {
4625 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4627 $feed_icon = " ";
4630 $num_comments = $line["num_comments"];
4631 $entry_comments = "";
4633 if ($num_comments > 0) {
4634 if ($line["comments"]) {
4635 $comments_url = $line["comments"];
4637 $comments_url = $line["link"];
4639 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4641 if ($line["comments"] && $line["link"] != $line["comments"]) {
4642 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4647 header("Content-Type: text/html");
4649 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4650 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4651 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4656 print "<div class=\"postReply\">";
4658 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4659 onmouseout=\"enable_resize(false)\">";
4661 $entry_author = $line["author"];
4663 if ($entry_author) {
4664 $entry_author = __(" - ") . $entry_author;
4667 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4668 strtotime($line["updated"]));
4670 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4672 if ($line["link"]) {
4673 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4674 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4676 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4679 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4681 if (!$entry_comments) $entry_comments = " "; # placeholder
4683 print "<div style='float : right'>
4684 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'> ";
4687 print "<span id=\"ATSTR-$id\">$tags_str</span>
4688 <a title=\"".__('Edit tags for this article')."\"
4689 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4691 if (defined('_ENABLE_INLINE_VIEW')) {
4693 print "<img src=\"images/art-inline.png\" class='tagsPic'
4694 style=\"cursor : pointer\" style=\"cursor : pointer\"
4695 onclick=\"showOriginalArticleInline($id)\"
4696 alt='Inline' title='".__('Display original article content')."'>";
4700 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4701 style=\"cursor : pointer\" style=\"cursor : pointer\"
4702 onclick=\"zoomToArticle($id)\"
4703 alt='Zoom' title='".__('Show article summary in new window')."'>";
4705 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4707 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4708 style=\"cursor : pointer\" style=\"cursor : pointer\"
4709 onclick=\"publishWithNote($id, '$note_escaped')\"
4710 alt='PubNote' title='".__('Publish article with a note')."'>";
4713 $tags_str = strip_tags($tags_str);
4714 print "<span id=\"ATSTR-$id\">$tags_str</span>";
4717 print "<div clear='both'>$entry_comments</div>";
4721 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4723 print "<div class=\"postContent\">";
4725 $article_content = sanitize_rss($link, $line["content"]);
4727 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4728 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4732 print "<div id=\"POSTNOTE-$id\">";
4733 if ($line['note']) {
4734 print format_article_note($id, $line['note']);
4738 print $article_content;
4740 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4741 post_id = '$id' AND content_url != ''");
4743 if (db_num_rows($result) > 0) {
4745 $entries_html = array();
4748 while ($line = db_fetch_assoc($result)) {
4750 $url = $line["content_url"];
4751 $ctype = $line["content_type"];
4753 if (!$ctype) $ctype = __("unknown type");
4755 $filename = substr($url, strrpos($url, "/")+
1);
4757 $entry = format_inline_player($link, $url, $ctype);
4759 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4760 $filename . " (" . $ctype . ")" . "</a>";
4762 array_push($entries_html, $entry);
4766 $entry["type"] = $ctype;
4767 $entry["filename"] = $filename;
4768 $entry["url"] = $url;
4770 array_push($entries, $entry);
4773 print "<div class=\"postEnclosures\">";
4775 if ($always_display_enclosures ||
!preg_match("/<img/i", $article_content)) {
4776 foreach ($entries as $entry) {
4777 if (preg_match("/image/", $entry["type"])) {
4779 alt=\"".htmlspecialchars($entry["filename"])."\"
4780 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4785 print "<div class=\"postEnclosures\">";
4787 if (db_num_rows($result) == 1) {
4788 print __("Attachment:") . " ";
4790 print __("Attachments:") . " ";
4793 print join(", ", $entries_html);
4805 print "]]></article>";
4808 <div style=\"text-align : center\">
4809 <input type=\"submit\" onclick=\"return window.close()\"
4810 value=\"".__("Close this window")."\"></div>";
4811 print "</body></html>";
4817 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4818 $next_unread_feed, $offset, $vgr_last_feed = false,
4819 $override_order = false) {
4821 $disable_cache = false;
4823 $timing_info = getmicrotime();
4825 $topmost_article_ids = array();
4831 if ($subop == "undefined") $subop = "";
4833 $subop_split = split(":", $subop);
4835 if ($subop == "CatchupSelected") {
4836 $ids = split(",", db_escape_string($_GET["ids"]));
4837 $cmode = sprintf("%d", $_GET["cmode"]);
4839 catchupArticlesById($link, $ids, $cmode);
4842 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4843 update_generic_feed($link, $feed, $cat_view, true);
4846 if ($subop == "MarkAllRead") {
4847 catchup_feed($link, $feed, $cat_view);
4849 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4850 if ($next_unread_feed) {
4851 $feed = $next_unread_feed;
4856 if ($subop_split[0] == "MarkAllReadGR") {
4857 catchup_feed($link, $subop_split[1], false);
4862 $result = db_query($link,
4863 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4865 if (db_num_rows($result) == 0) {
4866 print "<div align='center'>".__('Feed not found.')."</div>";
4871 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4873 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4874 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4876 if (db_num_rows($result) == 1) {
4877 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4879 $rtl_content = false;
4883 $rtl_tag = "dir=\"RTL\"";
4889 $rtl_content = false;
4892 $script_dt_add = get_script_dt_add();
4894 /// START /////////////////////////////////////////////////////////////////////////////////
4896 $search = db_escape_string($_GET["query"]);
4899 $disable_cache = true;
4902 $search_mode = db_escape_string($_GET["search_mode"]);
4903 $match_on = db_escape_string($_GET["match_on"]);
4909 $real_offset = $offset * $limit;
4911 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4913 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4914 $search, $search_mode, $match_on, $override_order, $real_offset);
4916 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4918 $result = $qfh_ret[0];
4919 $feed_title = $qfh_ret[1];
4920 $feed_site_url = $qfh_ret[2];
4921 $last_error = $qfh_ret[3];
4923 $vgroup_last_feed = $vgr_last_feed;
4926 $feed_site_url = article_publish_url($link);
4929 /// STOP //////////////////////////////////////////////////////////////////////////////////
4932 print "<div id=\"headlinesContainer\" $rtl_tag>";
4935 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4939 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4940 $feed, $cat_view, $search, $match_on, $search_mode);
4942 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4945 $headlines_count = db_num_rows($result);
4947 if (db_num_rows($result) > 0) {
4949 # print "\{$offset}";
4951 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4952 print "<table class=\"headlinesList\" id=\"headlinesList\"
4953 cellspacing=\"0\">";
4956 $lnum = $limit*$offset;
4958 error_reporting (DEFAULT_ERROR_LEVEL
);
4961 $cur_feed_title = '';
4963 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4965 while ($line = db_fetch_assoc($result)) {
4967 $class = ($lnum %
2) ?
"even" : "odd";
4970 $feed_id = $line["feed_id"];
4972 $labels = get_article_labels($link, $id);
4974 $labels_str = "<span id=\"HLLCTR-$id\">";
4975 $labels_str .= format_article_labels($labels, $id);
4976 $labels_str .= "</span>";
4978 if (count($topmost_article_ids) < 5) {
4979 array_push($topmost_article_ids, $id);
4982 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4984 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4987 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4991 if (sql_bool_to_bool($line["unread"]) &&
4992 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4994 $update_pic = "<img id='FUPDPIC-$id' src=\"images/fresh_sign.png\"
4998 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5006 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5009 $mark_img_ext = "gif";
5011 $mark_img_ext = "png";
5014 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5015 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5017 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5019 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5021 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5024 if ($line["published"] == "t" ||
$line["published"] == "1") {
5025 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5027 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5029 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5031 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5034 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5035 # $line["title"] . "</a>";
5037 # $content_link = "<a
5038 # href=\"" . htmlspecialchars($line["link"]) . "\"
5039 # onclick=\"view($id,$feed_id);\">" .
5040 # $line["title"] . "</a>";
5042 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5043 # $line["title"] . "</a>";
5045 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5046 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5048 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5049 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5052 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5053 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5057 $score = $line["score"];
5059 $score_pic = get_score_pic($score);
5061 /* $score_title = __("(Click to change)");
5062 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5063 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5065 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5070 } else if ($score < -100) {
5076 $entry_author = $line["author"];
5078 if ($entry_author) {
5079 $entry_author = " - $entry_author";
5082 $has_feed_icon = feed_has_icon($feed_id);
5084 if ($has_feed_icon) {
5085 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5087 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5088 $feed_icon_img = "";
5091 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5093 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5094 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5096 $cur_feed_title = $line["feed_title"];
5097 $vgroup_last_feed = $feed_id;
5099 $cur_feed_title = htmlspecialchars($cur_feed_title);
5101 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5103 print "<tr class='feedTitle'><td colspan='7'>".
5104 "<div style=\"float : right\">$feed_icon_img</div>".
5105 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5106 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5110 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5111 onmouseout='postMouseOut($id)'";
5113 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5115 print "<td class='hlUpdPic'>$update_pic</td>";
5117 print "<td class='hlSelectRow'>
5118 <input type=\"checkbox\" onclick=\"tSR(this)\"
5122 print "<td class='hlMarkedPic'>$marked_pic</td>";
5123 print "<td class='hlMarkedPic'>$published_pic</td>";
5125 # if ($line["feed_title"]) {
5126 # print "<td class='hlContent'>$content_link</td>";
5127 # print "<td class='hlFeed'>
5128 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5129 # truncate_string($line["feed_title"],30)."</a> </td>";
5132 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle' id='HLC-$id'>";
5134 print "<a id=\"RTITLE-$id\"
5135 href=\"" . htmlspecialchars($line["link"]) . "\"
5136 onclick=\"return false\">" .
5139 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5140 if ($content_preview) {
5141 print "<span class=\"contentPreview\"> - $content_preview</span>";
5149 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5150 # $line["feed_title"]."</a>
5152 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5153 if ($line["feed_title"]) {
5154 print "<span class=\"hlFeed\">
5155 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5156 $line["feed_title"]."</a>)
5161 // print "<img id='HLL-$id' class='hlLoading'
5162 // src='images/indicator_tiny.gif' style='display : none'>";
5168 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5170 print "<td class='hlMarkedPic'>$score_pic</td>";
5172 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5173 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5180 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5181 if ($feed_id != $vgroup_last_feed) {
5183 $cur_feed_title = $line["feed_title"];
5184 $vgroup_last_feed = $feed_id;
5186 $cur_feed_title = htmlspecialchars($cur_feed_title);
5188 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5190 $has_feed_icon = feed_has_icon($feed_id);
5192 if ($has_feed_icon) {
5193 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5195 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5198 print "<div class='cdmFeedTitle'>".
5199 "<div style=\"float : right\">$feed_icon_img</div>".
5200 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5201 $line["feed_title"]."</a> $vf_catchup_link</div>";
5206 $add_class = "Unread";
5211 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5212 $show_excerpt = false;
5214 if ($expand_cdm && $score >= -100) {
5216 $show_excerpt = false;
5218 $cdm_cstyle = "style=\"display : none\"";
5219 $show_excerpt = true;
5222 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5223 onmouseout='postMouseOut($id)'";
5225 print "<div class=\"cdmArticle$add_class\"
5227 $mouseover_attrs'>";
5229 print "<div class=\"cdmHeader\">";
5231 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5232 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5235 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5238 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5239 onclick=\"javascript:toggleUnread($id, 0)\"
5240 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5243 print $entry_author;
5245 /* if (!$expand_cdm || $score < -100) {
5246 print " <a id=\"CICH-$id\"
5247 href=\"javascript:cdmExpandArticle($id)\">
5248 (".__('Show article').")</a>";
5253 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5254 if ($line["feed_title"]) {
5255 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5259 print "</span></div>";
5261 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5262 $line["content_preview"] = preg_replace("/href=/i",
5263 "target=\"_blank\" href=", $line["content_preview"]);
5266 if ($show_excerpt) {
5267 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5268 onclick=\"cdmExpandArticle($id)\"
5269 title=\"".__('Click to expand article')."\">";
5271 $content_preview = trim(truncate_string(strip_tags($line["content_preview"]), 100));
5273 if (strlen($content_preview) != 0) {
5274 print $content_preview;
5276 print __('Click to expand article');
5281 print "<div class=\"cdmContent\"
5282 onclick=\"cdmClicked($id)\"
5283 id=\"CICD-$id\" $cdm_cstyle>";
5285 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5287 print "<div id=\"POSTNOTE-$id\">";
5288 if ($line['note']) {
5289 print format_article_note($id, $line['note']);
5293 print sanitize_rss($link, $line["content_preview"]);
5295 $article_content = $line["content_preview"];
5297 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5298 post_id = '$id' AND content_url != ''");
5300 if (db_num_rows($e_result) > 0) {
5302 $entries_html = array();
5305 while ($e_line = db_fetch_assoc($e_result)) {
5307 $url = $e_line["content_url"];
5308 $ctype = $e_line["content_type"];
5309 if (!$ctype) $ctype = __("unknown type");
5311 $filename = substr($url, strrpos($url, "/")+
1);
5313 $entry = format_inline_player($link, $url, $ctype);
5315 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5316 $filename . " (" . $ctype . ")" . "</a>";
5318 array_push($entries_html, $entry);
5322 $entry["type"] = $ctype;
5323 $entry["filename"] = $filename;
5324 $entry["url"] = $url;
5326 array_push($entries, $entry);
5329 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5330 ttrss_feeds WHERE id = ".$line['feed_id']." AND owner_uid = ".$_SESSION["uid"]);
5332 $always_display_enclosures = db_fetch_result($tmp_result, 0, "always_display_enclosures");
5334 if ($always_display_enclosures ||
!preg_match("/img/i", $article_content)) {
5335 foreach ($entries as $entry) {
5336 if (preg_match("/image/", $entry["type"])) {
5338 alt=\"".htmlspecialchars($entry["filename"])."\"
5339 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5344 print "<div class=\"cdmEnclosures\">";
5346 if (db_num_rows($e_result) == 1) {
5347 print __("Attachment:") . " ";
5349 print __("Attachments:") . " ";
5352 print join(", ", $entries_html);
5358 print "<br clear='both'>";
5361 /* if (!$expand_cdm) {
5362 print "<a id=\"CICH-$id\"
5363 href=\"javascript:cdmExpandArticle($id)\">
5369 print "<div class=\"cdmFooter\"><span class='s0'>";
5371 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5373 print __("Select:").
5374 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5375 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5377 print "</span><span class='s1'>$marked_pic ";
5378 print "$published_pic ";
5379 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5380 onclick=\"zoomToArticle($id)\"
5381 style=\"cursor : pointer\"
5383 title='".__('Show article summary in new window')."'> ";
5385 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5387 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5388 style=\"cursor : pointer\" style=\"cursor : pointer\"
5389 onclick=\"publishWithNote($id, '$note_escaped')\"
5390 alt='PubNote' title='".__('Publish article with a note')."'>";
5394 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5396 // print "<img src='images/tag.png' class='markedPic'>";
5398 print "<span class='s1'>
5399 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5400 <span id=\"ATSTR-$id\">$tags_str</span>
5401 <a title=\"".__('Edit tags for this article')."\"
5402 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5406 print "<span class='s2'><a class=\"cdmToggleLink\"
5407 href=\"javascript:toggleUnread($id)\">
5408 ".__('toggle unread')."</a></span>";
5418 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5425 switch ($view_mode) {
5427 $message = __("No unread articles found to display.");
5430 $message = __("No updated articles found to display.");
5433 $message = __("No starred articles found to display.");
5437 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5439 $message = __("No articles found to display.");
5443 if (!$offset) print "<div class='whiteBox'>$message</div>";
5451 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5454 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5456 function printTagCloud($link) {
5458 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5459 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5460 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5462 $result = db_query($link, $query);
5466 while ($line = db_fetch_assoc($result)) {
5467 $tags[$line["tag_name"]] = $line["count"];
5472 $max_size = 32; // max font size in pixels
5473 $min_size = 11; // min font size in pixels
5475 // largest and smallest array values
5476 $max_qty = max(array_values($tags));
5477 $min_qty = min(array_values($tags));
5479 // find the range of values
5480 $spread = $max_qty - $min_qty;
5481 if ($spread == 0) { // we don't want to divide by zero
5485 // set the font-size increment
5486 $step = ($max_size - $min_size) / ($spread);
5488 // loop through the tag array
5489 foreach ($tags as $key => $value) {
5490 // calculate font-size
5491 // find the $value in excess of $min_qty
5492 // multiply by the font-size increment ($size)
5493 // and add the $min_size set above
5494 $size = round($min_size +
(($value - $min_qty) * $step));
5496 $key_escaped = str_replace("'", "\\'", $key);
5498 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5499 $size . "px\" title=\"$value articles tagged with " .
5500 $key . '">' . $key . '</a> ';
5504 function print_checkpoint($n, $s) {
5505 $ts = getmicrotime();
5506 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5510 function sanitize_tag($tag) {
5513 $tag = mb_strtolower($tag, 'utf-8');
5515 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5517 // $tag = str_replace('"', "", $tag);
5518 // $tag = str_replace("+", " ", $tag);
5519 $tag = str_replace("technorati tag: ", "", $tag);
5524 function generate_publish_key() {
5525 return sha1(uniqid(rand(), true));
5528 function article_publish_url($link) {
5533 if ($_SERVER['HTTPS'] != "on") {
5534 $url_path = "http://";
5536 $url_path = "https://";
5539 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5540 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5546 * Purge a feed contents, marked articles excepted.
5548 * @param mixed $link The database connection.
5549 * @param integer $id The id of the feed to purge.
5552 function clear_feed_articles($link, $id) {
5553 $result = db_query($link, "DELETE FROM ttrss_user_entries
5554 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5556 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5557 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5559 ccache_update($link, $id, $_SESSION['uid']);
5560 } // function clear_feed_articles
5563 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5565 * @return string The Mozilla Firefox feed adding URL.
5567 function add_feed_url() {
5568 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5569 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5571 } // function add_feed_url
5574 * Encrypt a password in SHA1.
5576 * @param string $pass The password to encrypt.
5577 * @param string $login A optionnal login.
5578 * @return string The encrypted password.
5580 function encrypt_password($pass, $login = '') {
5582 return "SHA1X:" . sha1("$login:$pass");
5584 return "SHA1:" . sha1($pass);
5586 } // function encrypt_password
5589 * Update a feed batch.
5590 * Used by daemons to update n feeds by run.
5591 * Only update feed needing a update, and not being processed
5592 * by another process.
5594 * @param mixed $link Database link
5595 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5596 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5597 * @param boolean $debug Set to false to disable debug output. Default to true.
5600 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5601 // Process all other feeds using last_updated and interval parameters
5603 // Test if the user has loggued in recently. If not, it does not update its feeds.
5604 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5605 if (DB_TYPE
== "pgsql") {
5606 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5608 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5611 $login_thresh_qpart = "";
5614 // Test if the feed need a update (update interval exceded).
5615 if (DB_TYPE
== "pgsql") {
5616 $update_limit_qpart = "AND ((
5617 ttrss_feeds.update_interval = 0
5618 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5620 ttrss_feeds.update_interval > 0
5621 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5622 ) OR ttrss_feeds.last_updated IS NULL)";
5624 $update_limit_qpart = "AND ((
5625 ttrss_feeds.update_interval = 0
5626 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5628 ttrss_feeds.update_interval > 0
5629 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5630 ) OR ttrss_feeds.last_updated IS NULL)";
5633 // Test if feed is currently being updated by another process.
5634 if (DB_TYPE
== "pgsql") {
5635 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5637 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5640 // Test if there is a limit to number of updated feeds
5642 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5644 $random_qpart = sql_random_function();
5646 // We search for feed needing update.
5647 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5648 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5649 ttrss_feeds.update_interval
5651 ttrss_feeds, ttrss_users, ttrss_user_prefs
5653 ttrss_feeds.owner_uid = ttrss_users.id
5654 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5655 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5656 $login_thresh_qpart $update_limit_qpart
5657 $updstart_thresh_qpart
5658 ORDER BY $random_qpart $query_limit");
5660 $user_prefs_cache = array();
5662 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5664 // Here is a little cache magic in order to minimize risk of double feed updates.
5665 $feeds_to_update = array();
5666 while ($line = db_fetch_assoc($result)) {
5667 $feeds_to_update[$line['id']] = $line;
5670 // We update the feed last update started date before anything else.
5671 // There is no lag due to feed contents downloads
5672 // It prevent an other process to update the same feed.
5673 $feed_ids = array_keys($feeds_to_update);
5675 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5676 WHERE id IN (%s)", implode(',', $feed_ids)));
5679 // For each feed, we call the feed update function.
5680 while ($line = array_pop($feeds_to_update)) {
5682 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5684 // We setup a alarm to alert if the feed take more than 300s to update.
5686 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5687 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5688 // Cancel the alarm (the update went well)
5689 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5691 sleep(1); // prevent flood (FIXME make this an option?)
5694 // Send feed digests by email if needed.
5695 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5697 purge_orphans($link);
5699 } // function update_daemon_common
5701 function sanitize_article_content($text) {
5702 # we don't support CDATA sections in articles, they break our own escaping
5703 $text = preg_replace("/\[\[CDATA/", "", $text);
5704 $text = preg_replace("/\]\]\>/", "", $text);
5708 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5711 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5713 $result = db_query($link, "SELECT reg_exp,
5714 ttrss_filter_types.name AS name,
5715 ttrss_filter_actions.name AS action,
5719 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5722 owner_uid = $owner_uid AND
5723 ttrss_filter_types.id = filter_type AND
5724 ttrss_filter_actions.id = action_id AND
5725 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5727 while ($line = db_fetch_assoc($result)) {
5728 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5729 $filter["reg_exp"] = $line["reg_exp"];
5730 $filter["action"] = $line["action"];
5731 $filter["action_param"] = $line["action_param"];
5732 $filter["filter_param"] = $line["filter_param"];
5733 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5735 array_push($filters[$line["name"]], $filter);
5741 function get_score_pic($score) {
5743 return "score_high.png";
5744 } else if ($score > 0) {
5745 return "score_half_high.png";
5746 } else if ($score < -100) {
5747 return "score_low.png";
5748 } else if ($score < 0) {
5749 return "score_half_low.png";
5751 return "score_neutral.png";
5755 function rounded_table_start($classname, $header = " ") {
5756 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5757 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5758 print "<tr><td class='left'> </td><td class='content'>";
5761 function rounded_table_end($footer = " ") {
5762 print "</td><td class='right'> </td></tr>";
5763 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5767 function feed_has_icon($id) {
5768 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5771 function init_connection($link) {
5772 if (DB_TYPE
== "pgsql") {
5773 pg_query($link, "set client_encoding = 'UTF-8'");
5774 pg_set_client_encoding("UNICODE");
5775 pg_query($link, "set datestyle = 'ISO, european'");
5777 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5778 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5779 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5784 function update_feedbrowser_cache($link) {
5786 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5787 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5788 WHERE tf.feed_url = ttrss_feeds.feed_url
5789 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5790 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5792 db_query($link, "BEGIN");
5794 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5798 while ($line = db_fetch_assoc($result)) {
5799 $subscribers = db_escape_string($line["subscribers"]);
5800 $feed_url = db_escape_string($line["feed_url"]);
5801 $title = db_escape_string($line["title"]);
5803 $tmp_result = db_query($link, "SELECT subscribers FROM
5804 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5806 if (db_num_rows($tmp_result) == 0) {
5808 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5809 (feed_url, title, subscribers) VALUES ('$feed_url',
5810 '$title', '$subscribers')");
5818 db_query($link, "COMMIT");
5824 function ccache_zero($link, $feed_id, $owner_uid) {
5825 db_query($link, "UPDATE ttrss_counters_cache SET
5826 value = 0, updated = NOW() WHERE
5827 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5830 function ccache_zero_all($link, $owner_uid) {
5831 db_query($link, "UPDATE ttrss_counters_cache SET
5832 value = 0 WHERE owner_uid = '$owner_uid'");
5834 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5835 value = 0 WHERE owner_uid = '$owner_uid'");
5838 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5841 $table = "ttrss_counters_cache";
5843 $table = "ttrss_cat_counters_cache";
5846 db_query($link, "DELETE FROM $table WHERE
5847 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5851 function ccache_update_all($link, $owner_uid) {
5853 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5855 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5856 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5858 while ($line = db_fetch_assoc($result)) {
5859 ccache_update($link, $line["feed_id"], $owner_uid, true);
5862 /* We have to manually include category 0 */
5864 ccache_update($link, 0, $owner_uid, true);
5867 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5868 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5870 while ($line = db_fetch_assoc($result)) {
5871 print ccache_update($link, $line["feed_id"], $owner_uid);
5878 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5879 $no_update = false) {
5881 if (!is_numeric($feed_id)) return;
5884 $table = "ttrss_counters_cache";
5886 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5887 WHERE id = '$feed_id'");
5888 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5891 $table = "ttrss_cat_counters_cache";
5894 if (DB_TYPE
== "pgsql") {
5895 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5896 } else if (DB_TYPE
== "mysql") {
5897 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5900 $result = db_query($link, "SELECT value FROM $table
5901 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5904 if (db_num_rows($result) == 1) {
5905 return db_fetch_result($result, 0, "value");
5910 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5916 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5917 $update_pcat = true) {
5919 if (!is_numeric($feed_id)) return;
5921 if (!$is_cat && $feed_id > 0) {
5922 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5923 WHERE id = '$feed_id'");
5924 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5927 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5929 /* When updating a label, all we need to do is recalculate feed counters
5930 * because labels are not cached */
5933 ccache_update_all($link, $owner_uid);
5938 $table = "ttrss_counters_cache";
5940 $table = "ttrss_cat_counters_cache";
5943 if ($is_cat && $feed_id >= 0) {
5944 if ($feed_id != 0) {
5945 $cat_qpart = "cat_id = '$feed_id'";
5947 $cat_qpart = "cat_id IS NULL";
5950 /* Recalculate counters for child feeds */
5952 $result = db_query($link, "SELECT id FROM ttrss_feeds
5953 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5955 while ($line = db_fetch_assoc($result)) {
5956 ccache_update($link, $line["id"], $owner_uid, false, false);
5959 $result = db_query($link, "SELECT SUM(value) AS sv
5960 FROM ttrss_counters_cache, ttrss_feeds
5961 WHERE id = feed_id AND $cat_qpart AND
5962 ttrss_feeds.owner_uid = '$owner_uid'");
5964 $unread = (int) db_fetch_result($result, 0, "sv");
5967 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5970 db_query($link, "BEGIN");
5972 $result = db_query($link, "SELECT feed_id FROM $table
5973 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5975 if (db_num_rows($result) == 1) {
5976 db_query($link, "UPDATE $table SET
5977 value = '$unread', updated = NOW() WHERE
5978 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5981 db_query($link, "INSERT INTO $table
5982 (feed_id, value, owner_uid, updated)
5984 ($feed_id, $unread, $owner_uid, NOW())");
5987 db_query($link, "COMMIT");
5989 if ($feed_id > 0 && $prev_unread != $unread) {
5993 /* Update parent category */
5997 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5998 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6000 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6002 ccache_update($link, $cat_id, $owner_uid, true);
6006 } else if ($feed_id < 0) {
6007 ccache_update_all($link, $owner_uid);
6013 function label_find_id($link, $label, $owner_uid) {
6014 $result = db_query($link,
6015 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6016 AND owner_uid = '$owner_uid' LIMIT 1");
6018 if (db_num_rows($result) == 1) {
6019 return db_fetch_result($result, 0, "id");
6025 function get_article_labels($link, $id) {
6026 $result = db_query($link,
6027 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6028 FROM ttrss_labels2, ttrss_user_labels2
6030 AND article_id = '$id'
6031 AND owner_uid = ".$_SESSION["uid"] . "
6036 while ($line = db_fetch_assoc($result)) {
6037 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6039 array_push($rv, $rk);
6046 function label_find_caption($link, $label, $owner_uid) {
6047 $result = db_query($link,
6048 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6049 AND owner_uid = '$owner_uid' LIMIT 1");
6051 if (db_num_rows($result) == 1) {
6052 return db_fetch_result($result, 0, "caption");
6058 function label_remove_article($link, $id, $label, $owner_uid) {
6060 $label_id = label_find_id($link, $label, $owner_uid);
6062 if (!$label_id) return;
6064 $result = db_query($link,
6065 "DELETE FROM ttrss_user_labels2
6067 label_id = '$label_id' AND
6068 article_id = '$id'");
6071 function label_add_article($link, $id, $label, $owner_uid) {
6073 $label_id = label_find_id($link, $label, $owner_uid);
6075 if (!$label_id) return;
6077 $result = db_query($link,
6079 article_id FROM ttrss_labels2, ttrss_user_labels2
6082 label_id = '$label_id' AND
6083 article_id = '$id' AND owner_uid = '$owner_uid'
6086 if (db_num_rows($result) == 0) {
6087 db_query($link, "INSERT INTO ttrss_user_labels2
6088 (label_id, article_id) VALUES ('$label_id', '$id')");
6092 function label_remove($link, $id, $owner_uid) {
6094 db_query($link, "BEGIN");
6096 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6099 $caption = db_fetch_result($result, 0, "caption");
6101 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6102 AND owner_uid = " . $_SESSION["uid"]);
6104 if (db_affected_rows($link, $result) != 0 && $caption) {
6106 /* Disable filters that reference label being removed */
6108 db_query($link, "UPDATE ttrss_filters SET
6109 enabled = false WHERE action_param = '$caption'
6111 AND owner_uid = " . $_SESSION["uid"]);
6114 db_query($link, "COMMIT");
6117 function label_create($link, $caption) {
6119 db_query($link, "BEGIN");
6123 $result = db_query($link, "SELECT id FROM ttrss_labels2
6124 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6126 if (db_num_rows($result) == 0) {
6127 $result = db_query($link,
6128 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6129 VALUES ('$caption', '".$_SESSION["uid"]."')");
6131 $result = db_affected_rows($link, $result) != 0;
6134 db_query($link, "COMMIT");
6139 function print_labels_headlines_dropdown($link, $feed_id) {
6140 print "<li onclick=\"javascript:addLabel()\">
6141 ".__("Create label...")."</li>";
6143 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6144 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6146 while ($line = db_fetch_assoc($result)) {
6148 $label_id = $line["id"];
6149 $label_caption = $line["caption"];
6151 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6152 print "<li id=\"LHDL-$id\"
6153 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6154 $label_caption ".__('(remove)')."</li>";
6156 print "<li id=\"LHDL-$id\"
6157 onclick=\"javascript:selectionAssignLabel($label_id)\">
6158 $label_caption</li>";
6163 function format_tags_string($tags, $id) {
6166 $tags_nolinks_str = "";
6170 if ($_SESSION["theme"] == "3pane") {
6176 $formatted_tags = array();
6178 foreach ($tags as $tag) {
6180 $tag_escaped = str_replace("'", "\\'", $tag);
6182 if (mb_strlen($tag) > 30) {
6183 $tag = truncate_string($tag, 30);
6186 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6188 array_push($formatted_tags, $tag_str);
6190 $tmp_tags_str = implode(", ", $formatted_tags);
6192 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6197 $tags_str = implode(", ", $formatted_tags);
6199 if ($num_tags < count($tags)) {
6200 $tags_str .= ", …";
6203 if ($num_tags == 0) {
6204 $tags_str = __("no tags");
6211 function format_article_labels($labels, $id) {
6215 foreach ($labels as $l) {
6216 $labels_str .= sprintf("<span class='hlLabelRef'
6217 style='color : %s; background-color : %s'>%s</span>",
6218 $l[2], $l[3], $l[1]);
6225 function format_article_note($id, $note) {
6227 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6229 $str = "<div class='articleNote'>";
6231 $str .= "<div class='articleNoteOps'>";
6232 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6233 __('edit note')."</a>";