3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "lib/gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'lib/phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "lib/simplepie/simplepie.inc";
106 require_once "lib/magpierss/rss_fetch.inc";
107 require_once 'lib/magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if ($purge_interval == -1 ||
!$purge_interval) {
150 ccache_update($link, $feed_id, $owner_uid);
155 if (!$owner_uid) return;
157 if (FORCE_ARTICLE_PURGE
== 0) {
158 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
161 $purge_unread = true;
162 $purge_interval = FORCE_ARTICLE_PURGE
;
165 if (!$purge_unread) $query_limit = " unread = false AND ";
167 if (DB_TYPE
== "pgsql") {
168 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
169 marked = false AND feed_id = '$feed_id' AND
170 (SELECT date_entered FROM ttrss_entries WHERE
171 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
173 $pg_version = get_pgsql_version($link);
175 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
177 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
178 ttrss_entries.id = ref_id AND
180 feed_id = '$feed_id' AND
182 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
186 $result = db_query($link, "DELETE FROM ttrss_user_entries
188 WHERE ttrss_entries.id = ref_id AND
190 feed_id = '$feed_id' AND
192 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
195 $rows = pg_affected_rows($result);
199 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
200 marked = false AND feed_id = '$feed_id' AND
201 (SELECT date_entered FROM ttrss_entries WHERE
202 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
204 $result = db_query($link, "DELETE FROM ttrss_user_entries
205 USING ttrss_user_entries, ttrss_entries
206 WHERE ttrss_entries.id = ref_id AND
208 feed_id = '$feed_id' AND
210 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
212 $rows = mysql_affected_rows($link);
216 ccache_update($link, $feed_id, $owner_uid);
219 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
221 } // function purge_feed
224 * Purge old posts from old feeds.
226 * @param mixed $link A database connection
227 * @param boolean $do_output Set to true to enable printed output, false by default.
228 * @param integer $limit The maximal number of removed posts.
232 function global_purge_old_posts($link, $do_output = false, $limit = false) {
234 $random_qpart = sql_random_function();
237 $limit_qpart = "LIMIT $limit";
242 $result = db_query($link,
243 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
244 ORDER BY $random_qpart $limit_qpart");
246 while ($line = db_fetch_assoc($result)) {
248 $feed_id = $line["id"];
249 $purge_interval = $line["purge_interval"];
250 $owner_uid = $line["owner_uid"];
252 if ($purge_interval == 0) {
254 $tmp_result = db_query($link,
255 "SELECT value FROM ttrss_user_prefs WHERE
256 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
258 if (db_num_rows($tmp_result) != 0) {
259 $purge_interval = db_fetch_result($tmp_result, 0, "value");
264 // print "Feed $feed_id: purge interval = $purge_interval\n";
267 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
268 purge_feed($link, $feed_id, $purge_interval, $do_output);
272 // purge orphaned posts in main content table
273 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
274 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
277 $rows = db_affected_rows($link, $result);
278 _debug("Purged $rows orphaned posts.");
281 } // function global_purge_old_posts
283 function feed_purge_interval($link, $feed_id) {
285 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
286 WHERE id = '$feed_id'");
288 if (db_num_rows($result) == 1) {
289 $purge_interval = db_fetch_result($result, 0, "purge_interval");
290 $owner_uid = db_fetch_result($result, 0, "owner_uid");
292 if ($purge_interval == 0) $purge_interval = get_pref($link,
293 'PURGE_OLD_DAYS', $owner_uid);
295 return $purge_interval;
302 function purge_old_posts($link) {
304 $user_id = $_SESSION["uid"];
306 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
307 WHERE owner_uid = '$user_id'");
309 while ($line = db_fetch_assoc($result)) {
311 $feed_id = $line["id"];
312 $purge_interval = $line["purge_interval"];
314 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
316 if ($purge_interval > 0) {
317 purge_feed($link, $feed_id, $purge_interval);
321 purge_orphans($link);
324 function purge_orphans($link) {
325 // purge orphaned posts in main content table
326 db_query($link, "DELETE FROM ttrss_entries WHERE
327 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
330 function get_feed_update_interval($link, $feed_id) {
331 $result = db_query($link, "SELECT owner_uid, update_interval FROM
332 ttrss_feeds WHERE id = '$feed_id'");
334 if (db_num_rows($result) == 1) {
335 $update_interval = db_fetch_result($result, 0, "update_interval");
336 $owner_uid = db_fetch_result($result, 0, "owner_uid");
338 if ($update_interval != 0) {
339 return $update_interval;
341 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
349 function fetch_file_contents($url) {
350 if (USE_CURL_FOR_ICONS
) {
351 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
353 $ch = curl_init($url);
354 $fp = fopen($tmpfile, "w");
357 curl_setopt($ch, CURLOPT_FILE
, $fp);
358 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
359 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
365 $contents = file_get_contents($tmpfile);
371 return file_get_contents($url);
377 * Try to determine the favicon URL for a feed.
378 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
379 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
381 * @param string $url A feed or page URL
383 * @return mixed The favicon URL, or false if none was found.
385 function get_favicon_url($url) {
387 if ($html = @fetch_file_contents
($url)) {
389 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
390 // Attempt to grab a favicon link from their webpage url
391 $linkUrl = html_entity_decode($matches[1]);
393 if (substr($linkUrl, 0, 1) == '/') {
394 $urlParts = parse_url($url);
395 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
396 } else if (substr($linkUrl, 0, 7) == 'http://') {
397 $faviconURL = $linkUrl;
399 $pos = strrpos($url, "/");
400 // no "/" in url or "/" is part of "://"
401 if ($pos === false ||
$pos == (strpos($url, "://")+
2)) {
402 $faviconURL = $url.'/'.$linkUrl;
404 $faviconURL = substr($url, 0, $pos+
1).$linkUrl;
409 // If unsuccessful, attempt to "guess" the favicon location
410 $urlParts = parse_url($url);
411 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
415 // Run a test to see if what we have attempted to get actually exists.
416 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
421 } // function get_favicon_url
424 * Check if a link is a valid and working URL.
426 * @param mixed $link A URL to check
428 * @return boolean True if the URL is valid, false otherwise.
430 function url_validate($link) {
432 $url_parts = @parse_url
($link);
434 if ( empty( $url_parts["host"] ) )
437 if ( !empty( $url_parts["path"] ) ) {
438 $documentpath = $url_parts["path"];
443 if ( !empty( $url_parts["query"] ) )
444 $documentpath .= "?" . $url_parts["query"];
446 $host = $url_parts["host"];
447 $port = $url_parts["port"];
452 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
457 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
459 $http_response = fgets( $socket, 22 );
461 $responses = "/(200 OK)|(30[123])/";
462 if ( preg_match($responses, $http_response) ) {
469 } // function url_validate
471 function check_feed_favicon($site_url, $feed, $link) {
472 $favicon_url = get_favicon_url($site_url);
474 # print "FAVICON [$site_url]: $favicon_url\n";
478 $icon_file = ICONS_DIR
. "/$feed.ico";
480 if ($favicon_url && !file_exists($icon_file)) {
481 $contents = fetch_file_contents($favicon_url);
483 $fp = fopen($icon_file, "w");
486 fwrite($fp, $contents);
488 chmod($icon_file, 0644);
492 error_reporting(DEFAULT_ERROR_LEVEL
);
496 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
498 if (!$_GET["daemon"] && !$ignore_daemon) {
502 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
503 _debug("update_rss_feed: start");
506 if (!$ignore_daemon) {
508 if (DB_TYPE
== "pgsql") {
509 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
511 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
514 $result = db_query($link, "SELECT id,update_interval,auth_login,
515 auth_pass,cache_images,update_method
516 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
520 $result = db_query($link, "SELECT id,update_interval,auth_login,
521 auth_pass,cache_images,update_method,hidden,last_updated
522 FROM ttrss_feeds WHERE id = '$feed'");
526 if (db_num_rows($result) == 0) {
527 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
528 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
533 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
534 $update_method = db_fetch_result($result, 0, "update_method");
535 $last_updated = db_fetch_result($result, 0, "last_updated");
537 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
538 WHERE id = '$feed'");
540 $auth_login = db_fetch_result($result, 0, "auth_login");
541 $auth_pass = db_fetch_result($result, 0, "auth_pass");
543 if (ALLOW_SELECT_UPDATE_METHOD
) {
544 if (ENABLE_SIMPLEPIE
) {
545 $use_simplepie = $update_method != 1;
547 $use_simplepie = $update_method == 2;
550 $use_simplepie = ENABLE_SIMPLEPIE
;
553 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
554 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
557 if (!$use_simplepie) {
558 $auth_login = urlencode($auth_login);
559 $auth_pass = urlencode($auth_pass);
562 $update_interval = db_fetch_result($result, 0, "update_interval");
563 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
565 if ($update_interval < 0) { return; }
567 $feed = db_escape_string($feed);
569 $fetch_url = $feed_url;
571 if ($auth_login && $auth_pass) {
572 $url_parts = array();
573 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
575 if ($url_parts[1] && $url_parts[2]) {
576 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
581 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
582 _debug("update_rss_feed: fetching [$fetch_url]...");
585 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
589 if (!$use_simplepie) {
590 $rss = fetch_rss($fetch_url);
592 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
593 mkdir(SIMPLEPIE_CACHE_DIR
);
596 $rss = new SimplePie();
597 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
598 # $rss->set_timeout(10);
599 $rss->set_feed_url($fetch_url);
600 $rss->set_output_encoding('UTF-8');
602 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
603 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
604 _debug("enabling image cache");
607 $rss->set_image_handler('./image.php', 'i');
610 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
611 _debug("feed update interval (sec): " .
612 get_feed_update_interval($link, $feed)*60);
615 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
616 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
617 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
625 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
626 _debug("update_rss_feed: fetch done, parsing...");
628 error_reporting (DEFAULT_ERROR_LEVEL
);
631 $feed = db_escape_string($feed);
633 if ($use_simplepie) {
634 $fetch_ok = !$rss->error();
641 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
642 _debug("update_rss_feed: processing feed data...");
645 // db_query($link, "BEGIN");
647 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
648 FROM ttrss_feeds WHERE id = '$feed'");
650 $registered_title = db_fetch_result($result, 0, "title");
651 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
652 $orig_site_url = db_fetch_result($result, 0, "site_url");
654 $owner_uid = db_fetch_result($result, 0, "owner_uid");
656 if ($use_simplepie) {
657 $site_url = $rss->get_link();
659 $site_url = $rss->channel
["link"];
662 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
663 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
664 _debug("update_rss_feed: checking favicon...");
667 check_feed_favicon($site_url, $feed, $link);
670 if (!$registered_title ||
$registered_title == "[Unknown]") {
672 if ($use_simplepie) {
673 $feed_title = db_escape_string($rss->get_title());
675 $feed_title = db_escape_string($rss->channel
["title"]);
678 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
679 _debug("update_rss_feed: registering title: $feed_title");
682 db_query($link, "UPDATE ttrss_feeds SET
683 title = '$feed_title' WHERE id = '$feed'");
686 // weird, weird Magpie
687 if (!$use_simplepie) {
688 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
691 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
692 db_query($link, "UPDATE ttrss_feeds SET
693 site_url = '$site_url' WHERE id = '$feed'");
696 // print "I: " . $rss->channel["image"]["url"];
698 if (!$use_simplepie) {
699 $icon_url = $rss->image
["url"];
701 $icon_url = $rss->get_image_url();
704 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
705 $icon_url = db_escape_string($icon_url);
706 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
709 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
710 _debug("update_rss_feed: loading filters...");
713 $filters = load_filters($link, $feed, $owner_uid);
715 if ($use_simplepie) {
716 $iterator = $rss->get_items();
718 $iterator = $rss->items
;
719 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
720 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
723 if (!is_array($iterator)) {
724 /* db_query($link, "UPDATE ttrss_feeds
725 SET last_error = 'Parse error: can\'t find any articles.'
726 WHERE id = '$feed'"); */
728 // clear any errors and mark feed as updated if fetched okay
729 // even if it's blank
731 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
732 _debug("update_rss_feed: entry iterator is not an array, no articles?");
735 db_query($link, "UPDATE ttrss_feeds
736 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
738 return; // no articles
741 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
742 _debug("update_rss_feed: processing articles...");
745 foreach ($iterator as $item) {
747 if ($_GET['xdebug']) {
752 if ($use_simplepie) {
753 $entry_guid = $item->get_id();
754 if (!$entry_guid) $entry_guid = $item->get_link();
755 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
759 $entry_guid = $item["id"];
761 if (!$entry_guid) $entry_guid = $item["guid"];
762 if (!$entry_guid) $entry_guid = $item["link"];
763 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
766 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
767 _debug("update_rss_feed: guid $entry_guid");
770 if (!$entry_guid) continue;
772 $entry_timestamp = "";
774 if ($use_simplepie) {
775 $entry_timestamp = strtotime($item->get_date());
777 $rss_2_date = $item['pubdate'];
778 $rss_1_date = $item['dc']['date'];
779 $atom_date = $item['issued'];
780 if (!$atom_date) $atom_date = $item['updated'];
782 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
783 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
784 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
787 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
788 $entry_timestamp = time();
789 $no_orig_date = 'true';
791 $no_orig_date = 'false';
794 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
796 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
797 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
800 if ($use_simplepie) {
801 $entry_title = $item->get_title();
803 $entry_title = trim(strip_tags($item["title"]));
806 if ($use_simplepie) {
807 $entry_link = $item->get_link();
809 // strange Magpie workaround
810 $entry_link = $item["link_"];
811 if (!$entry_link) $entry_link = $item["link"];
814 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
815 _debug("update_rss_feed: title $entry_title");
818 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
820 $entry_link = strip_tags($entry_link);
822 if ($use_simplepie) {
823 $entry_content = $item->get_content();
824 if (!$entry_content) $entry_content = $item->get_description();
826 $entry_content = $item["content:escaped"];
828 if (!$entry_content) $entry_content = $item["content:encoded"];
829 if (!$entry_content) $entry_content = $item["content"]["encoded"];
830 if (!$entry_content) $entry_content = $item["content"];
832 // Magpie bugs are getting ridiculous
833 if (trim($entry_content) == "Array") $entry_content = false;
835 if (!$entry_content) $entry_content = $item["atom_content"];
836 if (!$entry_content) $entry_content = $item["summary"];
838 if (!$entry_content ||
839 strlen($entry_content) < strlen($item["description"])) {
840 $entry_content = $item["description"];
844 if (is_array($entry_content)) {
845 $entry_content = $entry_content["encoded"];
846 if (!$entry_content) $entry_content = $entry_content["escaped"];
850 if ($_GET["xdebug"]) {
851 print "update_rss_feed: content: ";
852 print_r(htmlspecialchars($entry_content));
855 $entry_content_unescaped = $entry_content;
857 if ($use_simplepie) {
858 $entry_comments = strip_tags($item->data
["comments"]);
859 if ($item->get_author()) {
860 $entry_author_item = $item->get_author();
861 $entry_author = $entry_author_item->get_name();
862 if (!$entry_author) $entry_author = $entry_author_item->get_email();
864 $entry_author = db_escape_string($entry_author);
867 $entry_comments = strip_tags($item["comments"]);
869 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
871 if ($item['author']) {
873 if (is_array($item['author'])) {
875 if (!$entry_author) {
876 $entry_author = db_escape_string(strip_tags($item['author']['name']));
879 if (!$entry_author) {
880 $entry_author = db_escape_string(strip_tags($item['author']['email']));
884 if (!$entry_author) {
885 $entry_author = db_escape_string(strip_tags($item['author']));
890 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
892 $entry_guid = db_escape_string(strip_tags($entry_guid));
893 $entry_guid = mb_substr($entry_guid, 0, 250);
895 $result = db_query($link, "SELECT id FROM ttrss_entries
896 WHERE guid = '$entry_guid'");
898 $entry_content = db_escape_string($entry_content);
900 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
902 $entry_title = db_escape_string($entry_title);
903 $entry_link = db_escape_string($entry_link);
904 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
905 $entry_author = mb_substr($entry_author, 0, 250);
907 if ($use_simplepie) {
908 $num_comments = 0; #FIXME#
910 $num_comments = db_escape_string($item["slash"]["comments"]);
913 if (!$num_comments) $num_comments = 0;
915 // parse <category> entries into tags
917 if ($use_simplepie) {
919 $additional_tags = array();
920 $additional_tags_src = $item->get_categories();
922 if (is_array($additional_tags_src)) {
923 foreach ($additional_tags_src as $tobj) {
924 array_push($additional_tags, $tobj->get_term());
928 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
929 _debug("update_rss_feed: category tags:");
930 print_r($additional_tags);
935 $t_ctr = $item['category#'];
937 $additional_tags = false;
940 $additional_tags = false;
941 } else if ($t_ctr > 0) {
942 $additional_tags = array($item['category']);
944 if ($item['category@term']) {
945 array_push($additional_tags, $item['category@term']);
948 for ($i = 0; $i <= $t_ctr; $i++
) {
949 if ($item["category#$i"]) {
950 array_push($additional_tags, $item["category#$i"]);
953 if ($item["category#$i@term"]) {
954 array_push($additional_tags, $item["category#$i@term"]);
959 // parse <dc:subject> elements
961 $t_ctr = $item['dc']['subject#'];
964 $additional_tags = array($item['dc']['subject']);
966 for ($i = 0; $i <= $t_ctr; $i++
) {
967 if ($item['dc']["subject#$i"]) {
968 array_push($additional_tags, $item['dc']["subject#$i"]);
976 $enclosures = array();
978 if ($use_simplepie) {
979 $encs = $item->get_enclosures();
981 if (is_array($encs)) {
982 foreach ($encs as $e) {
984 $e->link
, $e->type
, $e->length
);
986 array_push($enclosures, $e_item);
993 $e_ctr = $item['enclosure#'];
996 $e_item = array($item['enclosure@url'],
997 $item['enclosure@type'],
998 $item['enclosure@length']);
1000 array_push($enclosures, $e_item);
1002 for ($i = 0; $i <= $e_ctr; $i++
) {
1004 if ($item["enclosure#$i@url"]) {
1005 $e_item = array($item["enclosure#$i@url"],
1006 $item["enclosure#$i@type"],
1007 $item["enclosure#$i@length"]);
1008 array_push($enclosures, $e_item);
1014 // can there be many of those? yes -fox
1016 $m_ctr = $item['media']['content#'];
1019 $e_item = array($item['media']['content@url'],
1020 $item['media']['content@medium'],
1021 $item['media']['content@length']);
1023 array_push($enclosures, $e_item);
1025 for ($i = 0; $i <= $m_ctr; $i++
) {
1027 if ($item["media"]["content#$i@url"]) {
1028 $e_item = array($item["media"]["content#$i@url"],
1029 $item["media"]["content#$i@medium"],
1030 $item["media"]["content#$i@length"]);
1031 array_push($enclosures, $e_item);
1040 $entry_content = sanitize_article_content($entry_content);
1041 $entry_title = sanitize_article_content($entry_title);
1043 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1044 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1047 db_query($link, "BEGIN");
1049 if (db_num_rows($result) == 0) {
1051 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1052 _debug("update_rss_feed: base guid not found");
1055 // base post entry does not exist, create it
1057 $result = db_query($link,
1058 "INSERT INTO ttrss_entries
1074 '$entry_timestamp_fmt',
1083 // we keep encountering the entry in feeds, so we need to
1084 // update date_entered column so that we don't get horrible
1085 // dupes when the entry gets purged and reinserted again e.g.
1086 // in the case of SLOW SLOW OMG SLOW updating feeds
1088 $base_entry_id = db_fetch_result($result, 0, "id");
1090 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1091 WHERE id = '$base_entry_id'");
1094 // now it should exist, if not - bad luck then
1096 $result = db_query($link, "SELECT
1097 id,content_hash,no_orig_date,title,
1098 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1099 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1103 WHERE guid = '$entry_guid'");
1108 if (db_num_rows($result) == 1) {
1110 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1111 _debug("update_rss_feed: base guid found, checking for user record");
1114 // this will be used below in update handler
1115 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1116 $orig_title = db_fetch_result($result, 0, "title");
1117 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1118 $orig_date_entered = strtotime(db_fetch_result($result,
1119 0, "date_entered"));
1121 $ref_id = db_fetch_result($result, 0, "id");
1122 $entry_ref_id = $ref_id;
1124 // check for user post link to main table
1126 // do we allow duplicate posts with same GUID in different feeds?
1127 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1128 $dupcheck_qpart = "AND feed_id = '$feed'";
1130 $dupcheck_qpart = "";
1133 // error_reporting(0);
1135 $article_filters = get_article_filters($filters, $entry_title,
1136 $entry_content, $entry_link, $entry_timestamp);
1138 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1139 _debug("update_rss_feed: article filters: ");
1140 if (count($article_filters) != 0) {
1141 print_r($article_filters);
1145 if (find_article_filter($article_filters, "filter")) {
1146 db_query($link, "COMMIT"); // close transaction in progress
1150 // error_reporting (DEFAULT_ERROR_LEVEL);
1152 $score = calculate_article_score($article_filters);
1154 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1155 _debug("update_rss_feed: initial score: $score");
1158 $result = db_query($link,
1159 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1160 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1163 // okay it doesn't exist - create user entry
1164 if (db_num_rows($result) == 0) {
1166 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1167 _debug("update_rss_feed: user record not found, creating...");
1170 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1172 $last_read_qpart = 'NULL';
1175 $last_read_qpart = 'NOW()';
1178 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1184 if (find_article_filter($article_filters, 'publish')) {
1185 $published = 'true';
1187 $published = 'false';
1190 $result = db_query($link,
1191 "INSERT INTO ttrss_user_entries
1192 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1194 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1195 $last_read_qpart, $marked, $published, '$score')");
1197 $result = db_query($link,
1198 "SELECT int_id FROM ttrss_user_entries WHERE
1199 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1200 feed_id = '$feed' LIMIT 1");
1202 if (db_num_rows($result) == 1) {
1203 $entry_int_id = db_fetch_result($result, 0, "int_id");
1206 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1207 $entry_int_id = db_fetch_result($result, 0, "int_id");
1210 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1211 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1214 $post_needs_update = false;
1216 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1217 ($content_hash != $orig_content_hash)) {
1218 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1219 $post_needs_update = true;
1222 if (db_escape_string($orig_title) != $entry_title) {
1223 $post_needs_update = true;
1226 if ($orig_num_comments != $num_comments) {
1227 $post_needs_update = true;
1230 // this doesn't seem to be very reliable
1232 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1233 // $post_needs_update = true;
1236 // if post needs update, update it and mark all user entries
1237 // linking to this post as updated
1238 if ($post_needs_update) {
1240 if (defined('DAEMON_EXTENDED_DEBUG')) {
1241 _debug("update_rss_feed: post $entry_guid needs update...");
1244 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1246 db_query($link, "UPDATE ttrss_entries
1247 SET title = '$entry_title', content = '$entry_content',
1248 content_hash = '$content_hash',
1249 num_comments = '$num_comments'
1250 WHERE id = '$ref_id'");
1252 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1253 db_query($link, "UPDATE ttrss_user_entries
1254 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1256 db_query($link, "UPDATE ttrss_user_entries
1257 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1263 db_query($link, "COMMIT");
1265 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1266 _debug("update_rss_feed: assigning labels...");
1269 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1272 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1273 _debug("update_rss_feed: looking for enclosures...");
1276 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1277 print_r($enclosures);
1280 db_query($link, "BEGIN");
1282 foreach ($enclosures as $enc) {
1283 $enc_url = db_escape_string($enc[0]);
1284 $enc_type = db_escape_string($enc[1]);
1285 $enc_dur = db_escape_string($enc[2]);
1287 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1288 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1290 if (db_num_rows($result) == 0) {
1291 db_query($link, "INSERT INTO ttrss_enclosures
1292 (content_url, content_type, title, duration, post_id) VALUES
1293 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1297 db_query($link, "COMMIT");
1299 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1300 _debug("update_rss_feed: looking for tags...");
1304 // <a href="..." rel="tag">Xorg</a>, //
1308 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1309 $entry_content_unescaped, $entry_tags);
1311 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1312 print_r($entry_tags);
1313 print "<br/></p>"; */
1315 $entry_tags = $entry_tags[1];
1317 # check for manual tags
1319 $tag_filter = find_article_filter($article_filters, "tag");
1323 $manual_tags = trim_array(split(",", $tag_filter[1]));
1325 foreach ($manual_tags as $tag) {
1326 if (tag_is_valid($tag)) {
1327 array_push($entry_tags, $tag);
1332 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1333 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1335 if ($additional_tags && is_array($additional_tags)) {
1336 foreach ($additional_tags as $tag) {
1337 if (tag_is_valid($tag) &&
1338 array_search($tag, $boring_tags) === FALSE) {
1339 array_push($entry_tags, $tag);
1344 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1346 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1347 print_r($entry_tags);
1350 if (count($entry_tags) > 0) {
1352 db_query($link, "BEGIN");
1354 foreach ($entry_tags as $tag) {
1356 $tag = sanitize_tag($tag);
1357 $tag = db_escape_string($tag);
1359 if (!tag_is_valid($tag)) continue;
1361 $result = db_query($link, "SELECT id FROM ttrss_tags
1362 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1363 owner_uid = '$owner_uid' LIMIT 1");
1365 // print db_fetch_result($result, 0, "id");
1367 if ($result && db_num_rows($result) == 0) {
1369 db_query($link, "INSERT INTO ttrss_tags
1370 (owner_uid,tag_name,post_int_id)
1371 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1375 db_query($link, "COMMIT");
1378 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1379 _debug("update_rss_feed: article processed");
1383 if (!$last_updated) {
1384 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1385 _debug("update_rss_feed: new feed, catching it up...");
1387 catchup_feed($link, $feed, false, $owner_uid);
1391 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1392 _debug("update_rss_feed: updating counters cache...");
1395 // disabled, purge_feed() does that...
1396 //ccache_update($link, $feed, $owner_uid);
1399 purge_feed($link, $feed, 0);
1401 db_query($link, "UPDATE ttrss_feeds
1402 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1404 // db_query($link, "COMMIT");
1408 if ($use_simplepie) {
1409 $error_msg = mb_substr($rss->error(), 0, 250);
1411 $error_msg = mb_substr(magpie_error(), 0, 250);
1414 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1415 _debug("update_rss_feed: error fetching feed: $error_msg");
1418 $error_msg = db_escape_string($error_msg);
1421 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1422 last_updated = NOW() WHERE id = '$feed'");
1425 if ($use_simplepie) {
1429 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1430 _debug("update_rss_feed: done");
1435 function print_select($id, $default, $values, $attributes = "") {
1436 print "<select name=\"$id\" id=\"$id\" $attributes>";
1437 foreach ($values as $v) {
1443 print "<option$sel>$v</option>";
1448 function print_select_hash($id, $default, $values, $attributes = "") {
1449 print "<select name=\"$id\" id='$id' $attributes>";
1450 foreach (array_keys($values) as $v) {
1452 $sel = 'selected="selected"';
1456 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1462 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1465 if ($filters["title"]) {
1466 foreach ($filters["title"] as $filter) {
1467 $reg_exp = $filter["reg_exp"];
1468 $inverse = $filter["inverse"];
1469 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1470 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1472 array_push($matches, array($filter["action"], $filter["action_param"]));
1477 if ($filters["content"]) {
1478 foreach ($filters["content"] as $filter) {
1479 $reg_exp = $filter["reg_exp"];
1480 $inverse = $filter["inverse"];
1482 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1483 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1485 array_push($matches, array($filter["action"], $filter["action_param"]));
1490 if ($filters["both"]) {
1491 foreach ($filters["both"] as $filter) {
1492 $reg_exp = $filter["reg_exp"];
1493 $inverse = $filter["inverse"];
1496 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1497 array_push($matches, array($filter["action"], $filter["action_param"]));
1500 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1501 array_push($matches, array($filter["action"], $filter["action_param"]));
1507 if ($filters["link"]) {
1508 $reg_exp = $filter["reg_exp"];
1509 foreach ($filters["link"] as $filter) {
1510 $reg_exp = $filter["reg_exp"];
1511 $inverse = $filter["inverse"];
1513 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1514 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1516 array_push($matches, array($filter["action"], $filter["action_param"]));
1521 if ($filters["date"]) {
1522 $reg_exp = $filter["reg_exp"];
1523 foreach ($filters["date"] as $filter) {
1524 $date_modifier = $filter["filter_param"];
1525 $inverse = $filter["inverse"];
1526 $check_timestamp = strtotime($filter["reg_exp"]);
1528 # no-op when timestamp doesn't parse to prevent misfires
1530 if ($check_timestamp) {
1533 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1534 $date_modifier == "after" && $timestamp > $check_timestamp) {
1538 if ($inverse) $match_ok = !$match_ok;
1541 array_push($matches, array($filter["action"], $filter["action_param"]));
1550 function find_article_filter($filters, $filter_name) {
1551 foreach ($filters as $f) {
1552 if ($f[0] == $filter_name) {
1559 function calculate_article_score($filters) {
1562 foreach ($filters as $f) {
1563 if ($f[0] == "score") {
1570 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1571 foreach ($filters as $f) {
1572 if ($f[0] == "label") {
1573 label_add_article($link, $id, $f[1], $owner_uid);
1578 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1579 $rtl_content = false, $last_updated = false, $last_error = false,
1580 $fg_content = false, $bg_content = false) {
1582 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1583 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1585 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1589 $rtl_tag = "dir=\"rtl\"";
1591 $rtl_tag = "dir=\"ltr\"";
1594 $error_notify_msg = "";
1597 $link_title = "Error: $last_error ($last_updated)";
1598 $error_notify_msg = "(Error)";
1599 } else if ($last_updated) {
1600 $link_title = "Updated: $last_updated";
1603 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1604 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1606 /* if ($feed_id < -10) {
1607 $bg_color = "#00ccff";
1608 $fg_color = "white";
1611 if ($fg_color || $bg_color) {
1612 $color_str = "<div class='labelColorIndicator'
1613 style='color : $fg_color; background-color : $bg_color'>l</div>";
1616 print $color_str; */
1618 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1619 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1623 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1626 $fctr_class = "class=\"feedCtrHasUnread\"";
1628 $fctr_class = "class=\"feedCtrNoUnread\"";
1631 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1632 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1634 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1635 $total = getFeedArticles($link, $feed_id);
1636 print "<div class=\"feedExtInfo\">
1637 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1644 function getmicrotime() {
1645 list($usec, $sec) = explode(" ",microtime());
1646 return ((float)$usec +
(float)$sec);
1649 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1650 foreach ($values as $v) {
1657 if ($v == $true_is) {
1658 $sel .= " value=\"1\"";
1660 $sel .= " value=\"0\"";
1663 print "<input class=\"noborder\"
1664 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1669 function initialize_user_prefs($link, $uid) {
1671 $uid = db_escape_string($uid);
1673 db_query($link, "BEGIN");
1675 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1677 $u_result = db_query($link, "SELECT pref_name
1678 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1680 $active_prefs = array();
1682 while ($line = db_fetch_assoc($u_result)) {
1683 array_push($active_prefs, $line["pref_name"]);
1686 while ($line = db_fetch_assoc($result)) {
1687 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1688 // print "adding " . $line["pref_name"] . "<br>";
1690 db_query($link, "INSERT INTO ttrss_user_prefs
1691 (owner_uid,pref_name,value) VALUES
1692 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1697 db_query($link, "COMMIT");
1701 function lookup_user_id($link, $user) {
1703 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1706 if (db_num_rows($result) == 1) {
1707 return db_fetch_result($result, 0, "id");
1713 function http_authenticate_user($link) {
1715 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1717 if (!$_SERVER["PHP_AUTH_USER"]) {
1719 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1720 header('HTTP/1.0 401 Unauthorized');
1724 $auth_result = authenticate_user($link,
1725 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1727 if (!$auth_result) {
1728 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1729 header('HTTP/1.0 401 Unauthorized');
1737 function authenticate_user($link, $login, $password, $force_auth = false) {
1739 if (!SINGLE_USER_MODE
) {
1741 $pwd_hash1 = encrypt_password($password);
1742 $pwd_hash2 = encrypt_password($password, $login);
1744 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1745 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1747 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1749 $query = "SELECT id,login,access_level,pwd_hash
1750 FROM ttrss_users WHERE
1754 $query = "SELECT id,login,access_level,pwd_hash
1755 FROM ttrss_users WHERE
1756 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1757 pwd_hash = '$pwd_hash2')";
1760 $result = db_query($link, $query);
1762 if (db_num_rows($result) == 1) {
1763 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1764 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1765 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1767 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1770 $user_theme = get_user_theme_path($link);
1772 $_SESSION["theme"] = $user_theme;
1773 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1774 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1776 initialize_user_prefs($link, $_SESSION["uid"]);
1785 $_SESSION["uid"] = 1;
1786 $_SESSION["name"] = "admin";
1788 $user_theme = get_user_theme_path($link);
1790 $_SESSION["theme"] = $user_theme;
1791 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1793 initialize_user_prefs($link, $_SESSION["uid"]);
1799 function make_password($length = 8) {
1802 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1806 while ($i < $length) {
1807 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1809 if (!strstr($password, $char)) {
1817 // this is called after user is created to initialize default feeds, labels
1820 // user preferences are checked on every login, not here
1822 function initialize_user($link, $uid) {
1824 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1825 VALUES ('$uid', 'All Articles')");
1827 db_query($link, "INSERT INTO ttrss_filters
1828 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1829 action_id, action_param, filter_param)
1830 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1832 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1833 values ('$uid', 'Tiny Tiny RSS: New Releases',
1834 'http://tt-rss.org/releases.rss')");
1836 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1837 values ('$uid', 'Tiny Tiny RSS: Forum',
1838 'http://tt-rss.org/forum/rss.php')");
1841 function logout_user() {
1843 if (isset($_COOKIE[session_name()])) {
1844 setcookie(session_name(), '', time()-42000, '/');
1848 function get_script_urlpath() {
1849 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1852 function validate_session($link) {
1853 if (SINGLE_USER_MODE
) {
1857 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1858 if ($_SESSION["ip_address"]) {
1859 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1860 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1866 if ($_SESSION["uid"]) {
1868 $result = db_query($link,
1869 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1871 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1873 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1878 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1880 //print_r($_SESSION);
1882 if (time() > $_SESSION["cookie_lifetime"]) {
1890 function login_sequence($link, $mobile = false) {
1891 if (!SINGLE_USER_MODE
) {
1893 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1894 $swu = db_escape_string($_REQUEST["swu"]);
1896 $_SESSION["prefs_cache"] = false;
1897 return authenticate_user($link, $swu, null, true);
1901 $login_action = $_POST["login_action"];
1903 # try to authenticate user if called from login form
1904 if ($login_action == "do_login") {
1905 $login = $_POST["login"];
1906 $password = $_POST["password"];
1907 $remember_me = $_POST["remember_me"];
1909 if (authenticate_user($link, $login, $password)) {
1910 $_POST["password"] = "";
1912 $_SESSION["language"] = $_POST["language"];
1913 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1915 header("Location: " . $_SERVER["REQUEST_URI"]);
1920 $_SESSION["login_error_msg"] = "Incorrect username or password";
1924 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1925 render_login_form($link, $mobile);
1926 //header("Location: login.php");
1929 /* bump login timestamp */
1930 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1933 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1934 setcookie("ttrss_lang", $_SESSION["language"],
1935 time() + SESSION_COOKIE_LIFETIME
);
1938 /* bump counters stamp since we're getting reloaded anyway */
1940 $_SESSION["get_all_counters_stamp"] = time();
1944 return authenticate_user($link, "admin", null);
1948 function truncate_string($str, $max_len) {
1949 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1950 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1956 function get_user_theme_path($link) {
1957 $result = db_query($link, "SELECT theme_path
1959 ttrss_themes,ttrss_users
1960 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1961 if (db_num_rows($result) != 0) {
1962 return db_fetch_result($result, 0, "theme_path");
1968 function smart_date_time($timestamp) {
1969 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1970 return date("G:i", $timestamp);
1971 } else if (date("Y", $timestamp) == date("Y")) {
1972 return date("M d, G:i", $timestamp);
1974 return date("Y/m/d, G:i", $timestamp);
1978 function smart_date($timestamp) {
1979 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1981 } else if (date("Y", $timestamp) == date("Y")) {
1982 return date("D m", $timestamp);
1984 return date("Y/m/d", $timestamp);
1988 function sql_bool_to_string($s) {
1989 if ($s == "t" ||
$s == "1") {
1996 function sql_bool_to_bool($s) {
1997 if ($s == "t" ||
$s == "1") {
2004 function bool_to_sql_bool($s) {
2012 function toggleEvenOdd($a) {
2019 function sanity_check($link) {
2024 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2025 $schema_version = db_fetch_result($result, 0, "schema_version");
2027 if ($schema_version != SCHEMA_VERSION
) {
2031 if (DB_TYPE
== "mysql") {
2032 $result = db_query($link, "SELECT true", false);
2033 if (db_num_rows($result) != 1) {
2038 if (db_escape_string("testTEST") != "testTEST") {
2042 error_reporting (DEFAULT_ERROR_LEVEL
);
2044 if ($error_code != 0) {
2045 print_error_xml($error_code);
2052 function file_is_locked($filename) {
2053 if (function_exists('flock')) {
2055 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2056 error_reporting(DEFAULT_ERROR_LEVEL
);
2058 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2059 flock($fp, LOCK_UN
);
2069 return true; // consider the file always locked and skip the test
2072 function make_lockfile($filename) {
2073 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2075 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2082 function make_stampfile($filename) {
2083 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2085 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2086 fwrite($fp, time() . "\n");
2087 flock($fp, LOCK_UN
);
2095 function read_stampfile($filename) {
2098 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2099 error_reporting (DEFAULT_ERROR_LEVEL
);
2102 if (flock($fp, LOCK_EX
)) {
2103 $stamp = fgets($fp);
2104 flock($fp, LOCK_UN
);
2115 function sql_random_function() {
2116 if (DB_TYPE
== "mysql") {
2123 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2125 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2127 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2134 $cat_qpart = "cat_id = '$feed'";
2136 $cat_qpart = "cat_id IS NULL";
2139 $tmp_result = db_query($link, "SELECT id
2140 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2142 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2144 $tmp_feed = $tmp_line["id"];
2146 db_query($link, "UPDATE ttrss_user_entries
2147 SET unread = false,last_read = NOW()
2148 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2150 } else if ($feed == -2) {
2153 db_query($link, "UPDATE ttrss_user_entries
2154 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2155 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2156 AND unread = true AND owner_uid = $owner_uid");
2159 } else if ($feed > 0) {
2161 $tmp_result = db_query($link, "SELECT id
2162 FROM ttrss_feeds WHERE parent_feed = '$feed'
2163 ORDER BY cat_id,title");
2165 $parent_ids = array();
2167 if (db_num_rows($tmp_result) > 0) {
2168 while ($p = db_fetch_assoc($tmp_result)) {
2169 array_push($parent_ids, "feed_id = " . $p["id"]);
2172 $children_qpart = implode(" OR ", $parent_ids);
2174 db_query($link, "UPDATE ttrss_user_entries
2175 SET unread = false,last_read = NOW()
2176 WHERE (feed_id = '$feed' OR $children_qpart)
2177 AND owner_uid = $owner_uid");
2180 db_query($link, "UPDATE ttrss_user_entries
2181 SET unread = false,last_read = NOW()
2182 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2185 } else if ($feed < 0 && $feed > -10) { // special, like starred
2188 db_query($link, "UPDATE ttrss_user_entries
2189 SET unread = false,last_read = NOW()
2190 WHERE marked = true AND owner_uid = $owner_uid");
2194 db_query($link, "UPDATE ttrss_user_entries
2195 SET unread = false,last_read = NOW()
2196 WHERE published = true AND owner_uid = $owner_uid");
2201 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2203 if (DB_TYPE
== "pgsql") {
2204 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2206 $match_part = "updated > DATE_SUB(NOW(),
2207 INTERVAL $intl HOUR) ";
2210 $result = db_query($link, "SELECT id FROM ttrss_entries,
2211 ttrss_user_entries WHERE $match_part AND
2213 ttrss_user_entries.ref_id = ttrss_entries.id AND
2214 owner_uid = $owner_uid");
2216 $affected_ids = array();
2218 while ($line = db_fetch_assoc($result)) {
2219 array_push($affected_ids, $line["id"]);
2222 catchupArticlesById($link, $affected_ids, 0);
2226 db_query($link, "UPDATE ttrss_user_entries
2227 SET unread = false,last_read = NOW()
2228 WHERE owner_uid = $owner_uid");
2231 } else if ($feed < -10) { // label
2233 $label_id = -$feed - 11;
2235 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2236 SET unread = false, last_read = NOW()
2237 WHERE label_id = '$label_id' AND unread = true
2238 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2242 ccache_update($link, $feed, $owner_uid, $cat_view);
2245 db_query($link, "BEGIN");
2247 $tag_name = db_escape_string($feed);
2249 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2250 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2252 while ($line = db_fetch_assoc($result)) {
2253 db_query($link, "UPDATE ttrss_user_entries SET
2254 unread = false, last_read = NOW()
2255 WHERE int_id = " . $line["post_int_id"]);
2257 db_query($link, "COMMIT");
2261 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2265 $cat_qpart = "cat_id = '$feed'";
2267 $cat_qpart = "cat_id IS NULL";
2270 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2271 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2273 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2274 $feed_url = $tmp_line["feed_url"];
2275 $feed_id = $tmp_line["id"];
2276 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2280 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2281 WHERE id = '$feed'");
2282 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2283 update_rss_feed($link, $feed_url, $feed, $force_update);
2287 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2289 if (!$omode) $omode = "flc";
2291 getGlobalCounters($link);
2293 if (strchr($omode, "l")) getLabelCounters($link);
2294 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2295 if (strchr($omode, "t")) getTagCounters($link);
2296 if (strchr($omode, "c")) {
2297 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2298 getCategoryCounters($link);
2303 function getCategoryCounters($link) {
2304 # two special categories are -1 and -2 (all virtuals; all labels)
2306 /* $ctr = getCategoryUnread($link, -1);
2308 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2310 $ctr = getCategoryUnread($link, -2);
2312 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2314 $age_qpart = getMaxAgeSubquery();
2316 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2317 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2318 WHERE ttrss_cat_counters_cache.feed_id = id AND
2319 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2321 while ($line = db_fetch_assoc($result)) {
2322 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2324 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2325 $line["unread"]."\"/>";
2328 /* Special case: NULL category doesn't actually exist in the DB */
2330 print "<counter type=\"category\" id=\"0\" counter=\"".
2331 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2335 function getCategoryUnread($link, $cat, $owner_uid = false) {
2337 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2342 $cat_query = "cat_id = '$cat'";
2344 $cat_query = "cat_id IS NULL";
2347 $age_qpart = getMaxAgeSubquery();
2349 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2351 AND owner_uid = " . $owner_uid);
2353 $cat_feeds = array();
2354 while ($line = db_fetch_assoc($result)) {
2355 array_push($cat_feeds, "feed_id = " . $line["id"]);
2358 if (count($cat_feeds) == 0) return 0;
2360 $match_part = implode(" OR ", $cat_feeds);
2362 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2363 FROM ttrss_user_entries,ttrss_entries
2364 WHERE unread = true AND ($match_part) AND id = ref_id
2365 AND $age_qpart AND owner_uid = " . $owner_uid);
2369 # this needs to be rewritten
2370 while ($line = db_fetch_assoc($result)) {
2371 $unread +
= $line["unread"];
2375 } else if ($cat == -1) {
2376 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2377 } else if ($cat == -2) {
2379 $result = db_query($link, "
2380 SELECT COUNT(unread) AS unread FROM
2381 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2382 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2383 ttrss_labels2.owner_uid = '$owner_uid'
2384 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2385 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2387 $unread = db_fetch_result($result, 0, "unread");
2394 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2395 if (DB_TYPE
== "pgsql") {
2396 return "ttrss_entries.date_entered >
2397 NOW() - INTERVAL '$days days'";
2399 return "ttrss_entries.date_entered >
2400 DATE_SUB(NOW(), INTERVAL $days DAY)";
2404 function getFeedUnread($link, $feed, $is_cat = false) {
2405 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2408 function getLabelUnread($link, $label_id, $owner_uid = false) {
2409 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2411 $result = db_query($link, "
2412 SELECT COUNT(unread) AS unread FROM
2413 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2414 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2415 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2416 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2417 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2419 if (db_num_rows($result) != 0) {
2420 return db_fetch_result($result, 0, "unread");
2426 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2427 $owner_uid = false) {
2429 $n_feed = sprintf("%d", $feed);
2431 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2434 $unread_qpart = "unread = true";
2436 $unread_qpart = "true";
2439 $age_qpart = getMaxAgeSubquery();
2442 return getCategoryUnread($link, $n_feed, $owner_uid);
2443 } else if ($n_feed == -1) {
2444 $match_part = "marked = true";
2445 } else if ($n_feed == -2) {
2446 $match_part = "published = true";
2447 } else if ($n_feed == -3) {
2448 $match_part = "unread = true";
2450 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2452 if (DB_TYPE
== "pgsql") {
2453 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2455 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2457 } else if ($n_feed == -4) {
2458 $match_part = "true";
2459 } else if ($n_feed > 0) {
2461 $result = db_query($link, "SELECT id FROM ttrss_feeds
2462 WHERE parent_feed = '$n_feed'
2464 AND owner_uid = " . $owner_uid);
2466 if (db_num_rows($result) > 0) {
2468 $linked_feeds = array();
2469 while ($line = db_fetch_assoc($result)) {
2470 array_push($linked_feeds, "feed_id = " . $line["id"]);
2473 array_push($linked_feeds, "feed_id = $n_feed");
2475 $match_part = implode(" OR ", $linked_feeds);
2477 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2478 FROM ttrss_user_entries,ttrss_entries
2479 WHERE $unread_qpart AND
2480 ttrss_user_entries.ref_id = ttrss_entries.id AND
2483 owner_uid = " . $owner_uid);
2487 # this needs to be rewritten
2488 while ($line = db_fetch_assoc($result)) {
2489 $unread +
= $line["unread"];
2495 $match_part = "feed_id = '$n_feed'";
2497 } else if ($feed < -10) {
2499 $label_id = -$feed - 11;
2501 return getLabelUnread($link, $label_id, $owner_uid);
2507 $result = db_query($link, "SELECT count(int_id) AS unread
2508 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2509 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2510 ttrss_user_entries.ref_id = ttrss_entries.id AND
2511 ttrss_feeds.hidden = false AND
2513 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2517 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2518 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2519 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2520 AND $unread_qpart AND $age_qpart AND
2521 ttrss_tags.owner_uid = " . $owner_uid);
2524 $unread = db_fetch_result($result, 0, "unread");
2529 function getGlobalUnread($link, $user_id = false) {
2532 $user_id = $_SESSION["uid"];
2535 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2536 WHERE owner_uid = '$user_id' AND feed_id > 0");
2538 $c_id = db_fetch_result($result, 0, "c_id");
2543 function getGlobalCounters($link, $global_unread = -1) {
2544 if ($global_unread == -1) {
2545 $global_unread = getGlobalUnread($link);
2547 print "<counter type=\"global\" id='global-unread'
2548 counter='$global_unread'/>";
2550 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2551 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2553 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2555 print "<counter type=\"global\" id='subscribed-feeds'
2556 counter='$subscribed_feeds'/>";
2560 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2563 if (!$_SESSION["tctr_last_value"]) {
2564 $_SESSION["tctr_last_value"] = array();
2568 $old_counters = $_SESSION["tctr_last_value"];
2570 $tctrs_modified = false;
2572 $age_qpart = getMaxAgeSubquery();
2574 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2575 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2576 AND ref_id = id AND $age_qpart
2577 AND unread = true)) AS count FROM ttrss_tags
2578 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2579 ORDER BY count DESC LIMIT 55");
2583 while ($line = db_fetch_assoc($result)) {
2584 $tags[$line["tag_name"]] +
= $line["count"];
2587 foreach (array_keys($tags) as $tag) {
2588 $unread = $tags[$tag];
2590 $tag = htmlspecialchars($tag);
2592 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2593 $old_counters[$tag] = $unread;
2594 $tctrs_modified = true;
2595 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2600 if ($smart_mode && $tctrs_modified) {
2601 $_SESSION["tctr_last_value"] = $old_counters;
2606 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2608 $age_qpart = getMaxAgeSubquery();
2611 if (!$_SESSION["lctr_last_value"]) {
2612 $_SESSION["lctr_last_value"] = array();
2618 for ($i = -1; $i >= -4; $i--) {
2620 $count = getFeedUnread($link, $i);
2624 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2625 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2630 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2632 $ret_arr[$i]["counter"] = $count;
2633 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2638 $old_counters = $_SESSION["lctr_last_value"];
2639 $lctrs_modified = false;
2642 $owner_uid = $_SESSION["uid"];
2644 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2645 WHERE owner_uid = '$owner_uid'");
2647 while ($line = db_fetch_assoc($result)) {
2649 $id = -$line["id"] - 11;
2651 $label_name = $line["caption"];
2652 $count = getFeedUnread($link, $id);
2654 if (!$smart_mode ||
$old_counters[$id] != $count) {
2655 $old_counters[$id] = $count;
2656 $lctrs_modified = true;
2659 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2660 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2665 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2667 $ret_arr[$id]["counter"] = $count;
2668 $ret_arr[$id]["description"] = $label_name;
2672 error_reporting (DEFAULT_ERROR_LEVEL
);
2675 if ($smart_mode && $lctrs_modified) {
2676 $_SESSION["lctr_last_value"] = $old_counters;
2682 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2684 $age_qpart = getMaxAgeSubquery();
2687 if (!$_SESSION["fctr_last_value"]) {
2688 $_SESSION["fctr_last_value"] = array();
2692 $old_counters = $_SESSION["fctr_last_value"];
2694 $query = "SELECT ttrss_feeds.id,
2696 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2697 last_error, value AS count
2698 FROM ttrss_feeds, ttrss_counters_cache
2699 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2700 AND parent_feed IS NULL
2701 AND ttrss_counters_cache.feed_id = id";
2703 $result = db_query($link, $query);
2704 $fctrs_modified = false;
2706 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2708 while ($line = db_fetch_assoc($result)) {
2711 $count = $line["count"];
2712 $last_error = htmlspecialchars($line["last_error"]);
2714 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2715 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2717 $last_updated = date($short_date, strtotime($line["last_updated"]));
2720 $last_updated = htmlspecialchars($last_updated);
2722 $has_img = feed_has_icon($id);
2724 $tmp_result = db_query($link,
2725 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2726 WHERE parent_feed = '$id' AND feed_id = id");
2728 $count +
= db_fetch_result($tmp_result, 0, "unread");
2730 if (!$smart_mode ||
$old_counters[$id] != $count) {
2731 $old_counters[$id] = $count;
2732 $fctrs_modified = true;
2735 $error_part = "error=\"$last_error\"";
2741 $has_img_part = "hi=\"$has_img\"";
2746 if ($active_feed && $id == $active_feed) {
2747 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2749 $has_title_part = "";
2752 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2753 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2756 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2760 if ($smart_mode && $fctrs_modified) {
2761 $_SESSION["fctr_last_value"] = $old_counters;
2765 function get_script_dt_add() {
2766 /* if (strpos(VERSION, ".99") === false) {
2774 function get_pgsql_version($link) {
2775 $result = db_query($link, "SELECT version() AS version");
2776 $version = split(" ", db_fetch_result($result, 0, "version"));
2780 function print_error_xml($code, $add_msg = "") {
2783 $error_msg = $ERRORS[$code];
2786 $error_msg = "$error_msg; $add_msg";
2789 print "<rpc-reply>";
2790 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2791 print "</rpc-reply>";
2794 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2795 $auth_login = '', $auth_pass = '') {
2797 # check for feed:http://url
2798 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2800 # check for feed://URL
2801 if (strpos($feed_link, "//") === 0) {
2802 $feed_link = "http:$feed_link";
2805 if ($feed_link == "") return;
2807 if ($cat_id == "0" ||
!$cat_id) {
2808 $cat_qpart = "NULL";
2810 $cat_qpart = "'$cat_id'";
2813 $result = db_query($link,
2814 "SELECT id FROM ttrss_feeds
2815 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2817 if (db_num_rows($result) == 0) {
2819 $result = db_query($link,
2820 "INSERT INTO ttrss_feeds
2821 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2822 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2823 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2825 $result = db_query($link,
2826 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2827 AND owner_uid = " . $_SESSION["uid"]);
2829 $feed_id = db_fetch_result($result, 0, "id");
2832 update_rss_feed($link, $feed_link, $feed_id, true);
2841 function print_feed_select($link, $id, $default_id = "",
2842 $attributes = "", $include_all_feeds = true) {
2844 print "<select id=\"$id\" name=\"$id\" $attributes>";
2845 if ($include_all_feeds) {
2846 print "<option value=\"0\">".__('All feeds')."</option>";
2849 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2850 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2852 if (db_num_rows($result) > 0 && $include_all_feeds) {
2853 print "<option disabled>--------</option>";
2856 while ($line = db_fetch_assoc($result)) {
2857 if ($line["id"] == $default_id) {
2858 $is_selected = "selected";
2862 printf("<option $is_selected value='%d'>%s</option>",
2863 $line["id"], htmlspecialchars($line["title"]));
2869 function print_feed_cat_select($link, $id, $default_id = "",
2870 $attributes = "", $include_all_cats = true) {
2872 print "<select id=\"$id\" name=\"$id\" $attributes>";
2874 if ($include_all_cats) {
2875 print "<option value=\"0\">".__('Uncategorized')."</option>";
2878 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2879 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2881 if (db_num_rows($result) > 0 && $include_all_cats) {
2882 print "<option disabled>--------</option>";
2885 while ($line = db_fetch_assoc($result)) {
2886 if ($line["id"] == $default_id) {
2887 $is_selected = "selected";
2891 printf("<option $is_selected value='%d'>%s</option>",
2892 $line["id"], htmlspecialchars($line["title"]));
2898 function checkbox_to_sql_bool($val) {
2899 return ($val == "on") ?
"true" : "false";
2902 function getFeedCatTitle($link, $id) {
2904 return __("Special");
2905 } else if ($id < -10) {
2906 return __("Labels");
2907 } else if ($id > 0) {
2908 $result = db_query($link, "SELECT ttrss_feed_categories.title
2909 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2910 cat_id = ttrss_feed_categories.id");
2911 if (db_num_rows($result) == 1) {
2912 return db_fetch_result($result, 0, "title");
2914 return __("Uncategorized");
2917 return "getFeedCatTitle($id) failed";
2922 function getFeedTitle($link, $id) {
2924 return __("Starred articles");
2925 } else if ($id == -2) {
2926 return __("Published articles");
2927 } else if ($id == -3) {
2928 return __("Fresh articles");
2929 } else if ($id == -4) {
2930 return __("All articles");
2931 } else if ($id < -10) {
2932 $label_id = -$id - 11;
2933 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2934 if (db_num_rows($result) == 1) {
2935 return db_fetch_result($result, 0, "caption");
2937 return "Unknown label ($label_id)";
2940 } else if ($id > 0) {
2941 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2942 if (db_num_rows($result) == 1) {
2943 return db_fetch_result($result, 0, "title");
2945 return "Unknown feed ($id)";
2948 return "getFeedTitle($id) failed";
2953 function get_session_cookie_name() {
2954 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2957 function print_init_params($link) {
2958 print "<init-params>";
2959 if ($_SESSION["stored-params"]) {
2960 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2962 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2963 print "<param key=\"$key\" value=\"$value\"/>";
2968 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2969 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2970 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2971 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2973 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2974 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2976 print "<param key=\"hide_read_feeds\" value=\"" .
2977 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2979 print "<param key=\"enable_feed_cats\" value=\"" .
2980 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2982 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2983 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2985 print "<param key=\"confirm_feed_catchup\" value=\"" .
2986 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2988 print "<param key=\"cdm_auto_catchup\" value=\"" .
2989 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2991 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2993 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2995 print "<param key=\"default_view_mode\" value=\"" .
2996 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2998 print "<param key=\"default_view_limit\" value=\"" .
2999 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3001 print "<param key=\"default_view_order_by\" value=\"" .
3002 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3004 print "<param key=\"prefs_active_tab\" value=\"" .
3005 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3007 print "<param key=\"infobox_disable_overlay\" value=\"" .
3008 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3010 print "<param key=\"icons_location\" value=\"" .
3013 print "<param key=\"hide_read_shows_special\" value=\"" .
3014 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3016 print "<param key=\"hide_feedlist\" value=\"" .
3017 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3019 print "<param key=\"bw_limit\" value=\"".
3020 (int) $_SESSION["bw_limit"]."\"/>";
3022 // print "<param key=\"sync_counters\" value=\"" .
3023 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3025 print "<param key=\"sync_counters\" value=\"1\"/>";
3027 print "<param key=\"offline_enabled\" value=\"".
3028 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3030 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3031 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3033 $num_feeds = db_fetch_result($result, 0, "cf");
3035 print "<param key=\"num_feeds\" value=\"".
3036 (int)$num_feeds. "\"/>";
3038 print "</init-params>";
3041 function print_runtime_info($link) {
3042 print "<runtime-info>";
3044 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3045 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3047 $num_feeds = db_fetch_result($result, 0, "cf");
3049 print "<param key=\"num_feeds\" value=\"".
3050 (int)$num_feeds. "\"/>";
3052 if (ENABLE_UPDATE_DAEMON
) {
3053 print "<param key=\"daemon_is_running\" value=\"".
3054 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3056 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3058 $stamp = (int)read_stampfile("update_daemon.stamp");
3060 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3063 $stamp_delta = time() - $stamp;
3065 if ($stamp_delta > 1800) {
3069 $_SESSION["daemon_stamp_check"] = time();
3072 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3074 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3076 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3081 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3083 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3084 $new_version_details = check_for_update($link);
3086 print "<param key=\"new_version_available\" value=\"".
3087 sprintf("%d", $new_version_details != ""). "\"/>";
3089 $_SESSION["last_version_check"] = time();
3093 // print "<param key=\"new_version_available\" value=\"1\"/>";
3095 print "</runtime-info>";
3098 function getSearchSql($search, $match_on) {
3100 $search_query_part = "";
3102 $keywords = split(" ", $search);
3103 $query_keywords = array();
3105 if ($match_on == "both") {
3107 foreach ($keywords as $k) {
3108 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3109 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3112 $search_query_part = implode("AND", $query_keywords) . " AND ";
3114 } else if ($match_on == "title") {
3116 foreach ($keywords as $k) {
3117 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3120 $search_query_part = implode("AND", $query_keywords) . " AND ";
3122 } else if ($match_on == "content") {
3124 foreach ($keywords as $k) {
3125 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3129 $search_query_part = implode("AND", $query_keywords);
3131 return $search_query_part;
3134 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3136 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3140 $search_query_part = getSearchSql($search, $match_on);
3141 $search_query_part .= " AND ";
3144 $search_query_part = "";
3147 $view_query_part = "";
3149 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3151 $view_query_part = " ";
3152 } else if ($feed != -1) {
3153 $unread = getFeedUnread($link, $feed, $cat_view);
3155 $view_query_part = " unread = true AND ";
3160 if ($view_mode == "marked") {
3161 $view_query_part = " marked = true AND ";
3164 if ($view_mode == "unread") {
3165 $view_query_part = " unread = true AND ";
3168 if ($view_mode == "updated") {
3169 $view_query_part = " (last_read is null and unread = false) AND ";
3173 $limit_query_part = "LIMIT " . $limit;
3176 $vfeed_query_part = "";
3178 // override query strategy and enable feed display when searching globally
3179 if ($search && $search_mode == "all_feeds") {
3180 $query_strategy_part = "ttrss_entries.id > 0";
3181 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3182 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3183 $query_strategy_part = "ttrss_entries.id > 0";
3184 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3185 id = feed_id) as feed_title,";
3186 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3188 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3190 $tmp_result = false;
3193 $tmp_result = db_query($link, "SELECT id
3194 FROM ttrss_feeds WHERE cat_id = '$feed'");
3196 $tmp_result = db_query($link, "SELECT id
3197 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3198 WHERE id = '$feed') AND id != '$feed'");
3201 $cat_siblings = array();
3203 if (db_num_rows($tmp_result) > 0) {
3204 while ($p = db_fetch_assoc($tmp_result)) {
3205 array_push($cat_siblings, "feed_id = " . $p["id"]);
3208 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3209 $feed, implode(" OR ", $cat_siblings));
3212 $query_strategy_part = "ttrss_entries.id > 0";
3215 } else if ($feed >= 0) {
3220 $query_strategy_part = "cat_id = '$feed'";
3222 $query_strategy_part = "cat_id IS NULL";
3225 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3228 $tmp_result = db_query($link, "SELECT id
3229 FROM ttrss_feeds WHERE parent_feed = '$feed'
3230 ORDER BY cat_id,title");
3232 $parent_ids = array();
3234 if (db_num_rows($tmp_result) > 0) {
3235 while ($p = db_fetch_assoc($tmp_result)) {
3236 array_push($parent_ids, "feed_id = " . $p["id"]);
3239 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3240 $feed, implode(" OR ", $parent_ids));
3242 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3244 $query_strategy_part = "feed_id = '$feed'";
3247 } else if ($feed == -1) { // starred virtual feed
3248 $query_strategy_part = "marked = true";
3249 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3250 } else if ($feed == -2) { // published virtual feed OR labels category
3253 $query_strategy_part = "published = true";
3254 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3256 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3258 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3260 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3261 ttrss_user_labels2.article_id = ref_id";
3265 } else if ($feed == -3) { // fresh virtual feed
3266 $query_strategy_part = "unread = true";
3268 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3270 if (DB_TYPE
== "pgsql") {
3271 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3273 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3276 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3277 } else if ($feed == -4) { // all articles virtual feed
3278 $query_strategy_part = "true";
3279 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3280 } else if ($feed <= -10) { // labels
3281 $label_id = -$feed - 11;
3283 $query_strategy_part = "label_id = '$label_id' AND
3284 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3285 ttrss_user_labels2.article_id = ref_id";
3287 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3288 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3291 $query_strategy_part = "id > 0"; // dumb
3294 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3295 $order_by = "updated";
3297 $order_by = "updated DESC";
3300 if ($view_mode != "noscores") {
3301 $order_by = "score DESC, $order_by";
3304 if ($override_order) {
3305 $order_by = $override_order;
3310 if ($search && $search_mode == "all_feeds") {
3311 $feed_title = __("Search results")." ($search)";
3312 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3313 $feed_title = __("Search results")." ($search, $feed)";
3314 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3315 $feed_title = $feed;
3316 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3321 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3322 WHERE id = '$feed' AND owner_uid = $owner_uid");
3323 $feed_title = db_fetch_result($result, 0, "title");
3325 $feed_title = __("Uncategorized");
3329 $feed_title = __("Searched for")." $search ($feed_title)";
3334 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3335 WHERE id = '$feed' AND owner_uid = $owner_uid");
3337 $feed_title = db_fetch_result($result, 0, "title");
3338 $feed_site_url = db_fetch_result($result, 0, "site_url");
3339 $last_error = db_fetch_result($result, 0, "last_error");
3342 $feed_title = __("Searched for") . " $search ($feed_title)";
3346 } else if ($feed == -1) {
3347 $feed_title = __("Starred articles");
3348 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3349 } else if ($feed == -2) {
3351 $feed_title = __("Published articles");
3352 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3354 $feed_title = __("Labels");
3356 } else if ($feed == -3) {
3357 $feed_title = __("Fresh articles");
3358 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3359 } else if ($feed == -4) {
3360 $feed_title = __("All articles");
3361 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3362 } else if ($feed < -10) {
3363 $label_id = -$feed - 11;
3364 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3365 WHERE id = '$label_id'");
3366 $feed_title = db_fetch_result($result, 0, "caption");
3369 $feed_title = __("Searched for") . " $search ($feed_title)";
3375 $content_query_part = "content as content_preview,";
3377 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3380 $feed_kind = "Feeds";
3382 $feed_kind = "Labels";
3385 if ($limit_query_part) {
3386 $offset_query_part = "OFFSET $offset";
3389 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3390 if (!$override_order) {
3391 $order_by = "ttrss_feeds.title, $order_by";
3394 // Special output for Fresh feed
3396 /* if ($feed == -3) {
3397 $group_limit_part = "(select count(*) from
3398 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3399 t1.ref_id = t2.id and t1.owner_uid = 2 and
3400 t1.feed_id = ttrss_user_entries.feed_id and
3401 t2.updated > ttrss_entries.updated) <= 5 AND";
3405 $query = "SELECT DISTINCT
3407 ttrss_entries.id,ttrss_entries.title,
3410 unread,feed_id,marked,published,link,last_read,
3411 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3414 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3417 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3420 ttrss_feeds.hidden = false AND
3421 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3422 ttrss_user_entries.ref_id = ttrss_entries.id AND
3423 ttrss_user_entries.owner_uid = '$owner_uid' AND
3426 $query_strategy_part ORDER BY $order_by
3427 $limit_query_part $offset_query_part";
3429 if ($_GET["debug"]) print $query;
3431 $result = db_query($link, $query);
3436 $feed_kind = "Tags";
3438 $result = db_query($link, "SELECT
3441 ttrss_entries.id as id,title,
3444 marked,link,last_read,
3445 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3448 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3451 ttrss_entries,ttrss_user_entries,ttrss_tags
3453 ref_id = ttrss_entries.id AND
3454 ttrss_user_entries.owner_uid = '$owner_uid' AND
3455 post_int_id = int_id AND tag_name = '$feed' AND
3458 $query_strategy_part ORDER BY $order_by
3459 $limit_query_part");
3462 return array($result, $feed_title, $feed_site_url, $last_error);
3466 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3467 $limit, $search, $search_mode, $match_on) {
3469 $note_style = "background-color : #fff7d5; border-width : 1px; ".
3470 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3471 "margin-top : 5px; color : #9a8c59;";
3473 if (!$limit) $limit = 30;
3475 $qfh_ret = queryFeedHeadlines($link, $feed,
3476 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3479 $result = $qfh_ret[0];
3480 $feed_title = htmlspecialchars($qfh_ret[1]);
3481 $feed_site_url = $qfh_ret[2];
3482 $last_error = $qfh_ret[3];
3484 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3486 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3487 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3488 <rss version=\"2.0\">
3490 <title>$feed_title</title>
3491 <link>$feed_site_url</link>
3492 <description>Feed generated by Tiny Tiny RSS</description>";
3494 while ($line = db_fetch_assoc($result)) {
3496 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3497 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3499 $tags = get_article_tags($link, $line["id"], $owner_uid);
3501 foreach ($tags as $tag) {
3502 print "<category>" . htmlspecialchars($tag) . "</category>";
3505 $rfc822_date = date('r', strtotime($line["updated"]));
3507 print "<pubDate>$rfc822_date</pubDate>";
3510 htmlspecialchars($line["title"]) . "</title>";
3512 print "<description><![CDATA[";
3513 print $line["content_preview"];
3514 if ($line["note"]) {
3515 print "<div style='$note_style'>";
3516 print $line["note"];
3519 print "]]></description>";
3524 print "</channel></rss>";
3528 function getCategoryTitle($link, $cat_id) {
3530 if ($cat_id == -1) {
3531 return __("Special");
3532 } else if ($cat_id == -2) {
3533 return __("Labels");
3536 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3539 if (db_num_rows($result) == 1) {
3540 return db_fetch_result($result, 0, "title");
3542 return "Uncategorized";
3547 // http://ru2.php.net/strip-tags
3549 function strip_tags_long($textstring, $allowed){
3550 while($textstring != strip_tags($textstring, $allowed))
3552 while (strlen($textstring) != 0)
3554 if (strlen($textstring) > 1024) {
3557 $otherlen = strlen($textstring);
3559 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3560 $safetext .= $temptext;
3561 $textstring = substr_replace($textstring,'',0,$otherlen);
3563 $textstring = $safetext;
3569 function sanitize_rss($link, $str, $force_strip_tags = false) {
3572 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3574 $res = strip_tags_long($res,
3575 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3577 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3578 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3581 if (get_pref($link, "STRIP_IMAGES")) {
3583 $res = preg_replace('/<img[^>]+>/is', '', $res);
3591 * Send by mail a digest of last articles.
3593 * @param mixed $link The database connection.
3594 * @param integer $limit The maximum number of articles by digest.
3595 * @return boolean Return false if digests are not enabled.
3597 function send_headlines_digests($link, $limit = 100) {
3599 if (!DIGEST_ENABLE
) return false;
3601 $user_limit = DIGEST_EMAIL_LIMIT
;
3604 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3606 if (DB_TYPE
== "pgsql") {
3607 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3608 } else if (DB_TYPE
== "mysql") {
3609 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3612 $result = db_query($link, "SELECT id,email FROM ttrss_users
3613 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3615 while ($line = db_fetch_assoc($result)) {
3617 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3618 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3620 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3622 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3623 $digest = $tuple[0];
3624 $headlines_count = $tuple[1];
3625 $affected_ids = $tuple[2];
3626 $digest_text = $tuple[3];
3628 if ($headlines_count > 0) {
3630 $mail = new PHPMailer();
3632 $mail->PluginDir
= "lib/phpmailer/";
3633 $mail->SetLanguage("en", "lib/phpmailer/language/");
3635 $mail->CharSet
= "UTF-8";
3637 $mail->From
= DIGEST_FROM_ADDRESS
;
3638 $mail->FromName
= DIGEST_FROM_NAME
;
3639 $mail->AddAddress($line["email"], $line["login"]);
3641 if (DIGEST_SMTP_HOST
) {
3642 $mail->Host
= DIGEST_SMTP_HOST
;
3643 $mail->Mailer
= "smtp";
3644 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3645 $mail->Username
= DIGEST_SMTP_LOGIN
;
3646 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3649 $mail->IsHTML(true);
3650 $mail->Subject
= DIGEST_SUBJECT
;
3651 $mail->Body
= $digest;
3652 $mail->AltBody
= $digest_text;
3654 $rc = $mail->Send();
3656 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3660 if ($rc && $do_catchup) {
3661 print "Marking affected articles as read...\n";
3662 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3665 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3666 WHERE id = " . $line["id"]);
3668 print "No headlines\n";
3673 print "All done.\n";
3677 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3679 require_once "lib/MiniTemplator.class.php";
3681 $tpl = new MiniTemplator
;
3682 $tpl_t = new MiniTemplator
;
3684 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3685 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3687 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3688 $tpl->setVariable('CUR_TIME', date('G:i'));
3690 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3691 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3693 $affected_ids = array();
3695 if (DB_TYPE
== "pgsql") {
3696 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3697 } else if (DB_TYPE
== "mysql") {
3698 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3701 $result = db_query($link, "SELECT ttrss_entries.title,
3702 ttrss_feeds.title AS feed_title,
3704 ttrss_user_entries.ref_id,
3706 SUBSTRING(content, 1, 120) AS excerpt,
3707 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3709 ttrss_user_entries,ttrss_entries,ttrss_feeds
3711 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3712 AND include_in_digest = true
3715 AND ttrss_user_entries.owner_uid = $user_id
3717 ORDER BY ttrss_feeds.title, date_entered DESC
3720 $cur_feed_title = "";
3722 $headlines_count = db_num_rows($result);
3724 $headlines = array();
3726 while ($line = db_fetch_assoc($result)) {
3727 array_push($headlines, $line);
3730 for ($i = 0; $i < sizeof($headlines); $i++
) {
3732 $line = $headlines[$i];
3734 array_push($affected_ids, $line["ref_id"]);
3736 $updated = smart_date_time(strtotime($line["last_updated"]));
3738 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3739 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3740 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3741 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3742 $tpl->setVariable('ARTICLE_EXCERPT',
3743 truncate_string(strip_tags($line["excerpt"]), 100));
3745 $tpl->addBlock('article');
3747 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3748 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3749 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3750 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3751 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3752 // truncate_string(strip_tags($line["excerpt"]), 100));
3754 $tpl_t->addBlock('article');
3756 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3757 $tpl->addBlock('feed');
3758 $tpl_t->addBlock('feed');
3763 $tpl->addBlock('digest');
3764 $tpl->generateOutputToString($tmp);
3766 $tpl_t->addBlock('digest');
3767 $tpl_t->generateOutputToString($tmp_t);
3769 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3772 function check_for_update($link) {
3773 $releases_feed = "http://tt-rss.org/releases.rss";
3775 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3780 if (ENABLE_SIMPLEPIE
) {
3781 $rss = new SimplePie();
3782 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3783 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3784 $rss->set_feed_url($fetch_url);
3785 $rss->set_output_encoding('UTF-8');
3788 $rss = fetch_rss($releases_feed);
3790 error_reporting (DEFAULT_ERROR_LEVEL
);
3794 if (ENABLE_SIMPLEPIE
) {
3795 $items = $rss->get_items();
3797 $items = $rss->items
;
3799 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3800 if (!$items ||
!is_array($items)) $items = $rss;
3803 if (!is_array($items) ||
count($items) == 0) {
3807 $latest_item = $items[0];
3809 if (ENABLE_SIMPLEPIE
) {
3810 $last_title = $latest_item->get_title();
3812 $last_title = $latest_item["title"];
3815 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3817 if (ENABLE_SIMPLEPIE
) {
3818 $release_url = sanitize_rss($link, $latest_item->get_link());
3819 $content = sanitize_rss($link, $latest_item->get_description());
3821 $release_url = sanitize_rss($link, $latest_item["link"]);
3822 $content = sanitize_rss($link, $latest_item["description"]);
3825 if (version_compare(VERSION
, $latest_version) == -1) {
3826 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3827 $latest_version)."<div class='milestoneDetails'>$content</div>";
3834 function markArticlesById($link, $ids, $cmode) {
3838 foreach ($ids as $id) {
3839 array_push($tmp_ids, "ref_id = '$id'");
3842 $ids_qpart = join(" OR ", $tmp_ids);
3845 db_query($link, "UPDATE ttrss_user_entries SET
3846 marked = false,last_read = NOW()
3847 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3848 } else if ($cmode == 1) {
3849 db_query($link, "UPDATE ttrss_user_entries SET
3851 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3853 db_query($link, "UPDATE ttrss_user_entries SET
3854 marked = NOT marked,last_read = NOW()
3855 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3859 function publishArticlesById($link, $ids, $cmode) {
3863 foreach ($ids as $id) {
3864 array_push($tmp_ids, "ref_id = '$id'");
3867 $ids_qpart = join(" OR ", $tmp_ids);
3870 db_query($link, "UPDATE ttrss_user_entries SET
3871 published = false,last_read = NOW()
3872 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3873 } else if ($cmode == 1) {
3874 db_query($link, "UPDATE ttrss_user_entries SET
3876 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3878 db_query($link, "UPDATE ttrss_user_entries SET
3879 published = NOT published,last_read = NOW()
3880 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3884 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3886 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3890 foreach ($ids as $id) {
3891 array_push($tmp_ids, "ref_id = '$id'");
3894 $ids_qpart = join(" OR ", $tmp_ids);
3897 db_query($link, "UPDATE ttrss_user_entries SET
3898 unread = false,last_read = NOW()
3899 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3900 } else if ($cmode == 1) {
3901 db_query($link, "UPDATE ttrss_user_entries SET
3903 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3905 db_query($link, "UPDATE ttrss_user_entries SET
3906 unread = NOT unread,last_read = NOW()
3907 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3912 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3913 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3915 while ($line = db_fetch_assoc($result)) {
3916 ccache_update($link, $line["feed_id"], $owner_uid);
3920 function catchupArticleById($link, $id, $cmode) {
3923 db_query($link, "UPDATE ttrss_user_entries SET
3924 unread = false,last_read = NOW()
3925 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3926 } else if ($cmode == 1) {
3927 db_query($link, "UPDATE ttrss_user_entries SET
3929 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3931 db_query($link, "UPDATE ttrss_user_entries SET
3932 unread = NOT unread,last_read = NOW()
3933 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3937 function make_guid_from_title($title) {
3938 return preg_replace("/[ \"\',.:;]/", "-",
3939 mb_strtolower(strip_tags($title), 'utf-8'));
3942 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3943 $feed_id, $is_cat, $search, $match_on,
3946 print "<div class=\"headlinesSubToolbar\">";
3948 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3949 $page_next_link = "javascript:viewFeedGoPage(1)";
3950 $page_first_link = "javascript:viewFeedGoPage(0)";
3952 $catchup_page_link = "javascript:catchupPage()";
3953 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3954 $catchup_sel_link = "javascript:catchupSelection()";
3956 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3958 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3959 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3960 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3961 $sel_inv_link = "javascript:invertHeadlineSelection()";
3963 $tog_unread_link = "javascript:selectionToggleUnread()";
3964 $tog_marked_link = "javascript:selectionToggleMarked()";
3965 $tog_published_link = "javascript:selectionTogglePublished()";
3969 $sel_all_link = "javascript:cdmSelectArticles('all')";
3970 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3971 $sel_none_link = "javascript:cdmSelectArticles('none')";
3973 $sel_inv_link = "javascript:invertHeadlineSelection()";
3975 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3976 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3977 $tog_published_link = "javascript:selectionTogglePublished(true)";
3981 print "<div id=\"subtoolbar_ftitle\">";
3983 if ($feed_site_url) {
3985 $target = "target=\"_blank\"";
3987 print "<a $target href=\"$feed_site_url\">".
3988 truncate_string($feed_title,30)."</a>";
3994 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3998 <a target=\"_blank\"
3999 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4000 <img class=\"noborder\"
4001 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4006 print __('Select:')."
4007 <a href=\"$sel_all_link\">".__('All')."</a>,
4008 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4009 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4010 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4012 print " ";
4015 onmouseover=\"enable_selection(false)\"
4016 onmouseout=\"enable_selection(true)\"
4017 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4018 __("Actions...") . " <img src=\"images/down_arrow.png\">
4021 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4023 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4024 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4025 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4026 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4027 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4028 <li class=\"insensitive\">".__('Mark as read:')."</li>
4029 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4031 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4034 //print "<li><span class=\"insensitive\">--------</span></li>";
4035 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4037 print_labels_headlines_dropdown($link, $feed_id);
4044 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4046 $tmp_category = getCategoryTitle($link, $cat_id);
4049 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4050 } else if ($cat_id == 0 ||
$cat_id == -2) {
4051 $cat_unread = getCategoryUnread($link, $cat_id);
4055 $holder_style = "display:none;";
4062 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4065 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4066 $inner_title_class = "catTitle";
4068 $browse_cat_link = "";
4069 $inner_title_class = "catTitleNL";
4072 $cat_class = "feedCat";
4074 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4075 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4076 title=\"".__('Click to collapse category')."\"
4077 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4078 id=\"FCATN-$cat_id\" $browse_cat_link
4079 \">$tmp_category</span>";
4081 print "<span id=\"FCAP-$cat_id\">";
4083 print " <span id=\"FCATCTR-$cat_id\"
4084 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4090 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4094 function outputFeedList($link, $tags = false) {
4096 print "<ul class=\"feedList\" id=\"feedList\">";
4098 $owner_uid = $_SESSION["uid"];
4102 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4104 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4107 $cat_hidden = false;
4110 printCategoryHeader($link, -1, $cat_hidden, false);
4113 $num_starred = getFeedUnread($link, -1);
4114 $num_published = getFeedUnread($link, -2);
4115 $num_fresh = getFeedUnread($link, -3);
4116 $num_total = getFeedUnread($link, -4);
4120 if ($num_total > 0) $class .= "Unread";
4122 printFeedEntry(-4, $class, __("All articles"), $num_total,
4123 "images/tag.png", $link);
4127 if ($num_fresh > 0) $class .= "Unread";
4129 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4130 "images/fresh.png", $link);
4134 if ($num_starred > 0) $class .= "Unread";
4136 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4139 $mark_img_ext = "gif";
4141 $mark_img_ext = "png";
4144 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4145 "images/mark_set.$mark_img_ext", $link);
4149 if ($num_published > 0) $class .= "Unread";
4151 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4152 "images/pub_set.gif", $link);
4154 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4161 $result = db_query($link, "SELECT * FROM
4162 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4164 if (db_num_rows($result) > 0) {
4165 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4167 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4170 $cat_hidden = false;
4173 printCategoryHeader($link, -2, $cat_hidden, true);
4176 print "<li><hr></li>";
4180 while ($line = db_fetch_assoc($result)) {
4182 $label_id = -$line['id'] - 11;
4183 $count = getFeedUnread($link, $label_id);
4191 printFeedEntry($label_id,
4192 $class, $line["caption"],
4193 $count, "images/label.png", $link,
4194 false, false, false,
4195 $line['fg_color'], $line['bg_color']);
4199 if (db_num_rows($result) > 0) {
4200 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4206 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4207 print "<li><hr></li>";
4210 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4211 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4212 $order_by_qpart = "order_id,category,unread DESC,title";
4214 $order_by_qpart = "order_id,category,title";
4217 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4218 $order_by_qpart = "unread DESC,title";
4220 $order_by_qpart = "title";
4224 $age_qpart = getMaxAgeSubquery();
4226 $query = "SELECT ttrss_feeds.*,
4227 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4229 ttrss_feed_categories.title AS category,
4230 ttrss_feed_categories.collapsed,
4232 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4233 ON (ttrss_feed_categories.id = cat_id)
4234 LEFT JOIN ttrss_counters_cache
4236 (ttrss_feeds.id = feed_id)
4238 ttrss_feeds.hidden = false AND
4239 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4240 ORDER BY $order_by_qpart";
4242 $result = db_query($link, $query);
4244 $actid = $_GET["actid"];
4254 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4256 while ($line = db_fetch_assoc($result)) {
4258 $feed = trim($line["title"]);
4260 if (!$feed) $feed = "[Untitled]";
4262 $feed_id = $line["id"];
4263 $unread = $line["unread"];
4265 $subop = $_GET["subop"];
4267 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4268 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4270 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4273 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4276 $rtl_tag = "dir=\"RTL\"";
4281 $tmp_result = db_query($link,
4282 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4283 WHERE parent_feed = '$feed_id' AND feed_id = id");
4285 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4287 $cat_id = $line["cat_id"];
4289 $tmp_category = $line["category"];
4291 if (!$tmp_category) {
4292 $tmp_category = __("Uncategorized");
4295 // $class = ($lnum % 2) ? "even" : "odd";
4297 if ($line["last_error"]) {
4303 if ($unread > 0) $class .= "Unread";
4305 if ($actid == $feed_id) {
4306 $class .= "Selected";
4309 $total_unread +
= $unread;
4311 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4317 $category = $tmp_category;
4319 $collapsed = sql_bool_to_bool($line["collapsed"]);
4321 // workaround for NULL category
4322 if ($category == __("Uncategorized")) {
4323 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4328 $cat_id = sprintf("%d", $cat_id);
4330 printCategoryHeader($link, $cat_id, $collapsed, true);
4334 printFeedEntry($feed_id, $class, $feed, $unread,
4335 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4336 $last_updated, $line["last_error"]);
4341 if (db_num_rows($result) == 0) {
4342 print "<li>".__('No feeds to display.')."</li>";
4349 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4350 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4351 post_int_id = ttrss_user_entries.int_id AND
4352 unread = true AND ref_id = ttrss_entries.id
4353 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4355 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4356 ORDER BY tag_name"); */
4358 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4359 print "<li class=\"feedCat\">".__('Tags')."</li>";
4360 print "<ul class=\"feedCatList\">";
4363 $age_qpart = getMaxAgeSubquery();
4365 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4366 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4367 AND ref_id = id AND $age_qpart
4368 AND unread = true)) AS count FROM ttrss_tags
4369 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4370 ORDER BY count DESC LIMIT 50");
4374 while ($line = db_fetch_assoc($result)) {
4375 $tags[$line["tag_name"]] +
= $line["count"];
4378 foreach (array_keys($tags) as $tag) {
4380 $unread = $tags[$tag];
4388 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4392 if (db_num_rows($result) == 0) {
4393 print "<li>No tags to display.</li>";
4396 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4406 function get_article_tags($link, $id, $owner_uid = 0) {
4408 $a_id = db_escape_string($id);
4410 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4412 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4413 owner_uid as owner FROM
4414 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4415 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4419 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4420 array_push($tags, $tmp_line["tag_name"]);
4426 function trim_value(&$value) {
4427 $value = trim($value);
4430 function trim_array($array) {
4432 array_walk($tmp, 'trim_value');
4436 function tag_is_valid($tag) {
4437 if ($tag == '') return false;
4438 if (preg_match("/^[0-9]*$/", $tag)) return false;
4440 if (function_exists('iconv')) {
4441 $tag = iconv("utf-8", "utf-8", $tag);
4444 if (!$tag) return false;
4449 function render_login_form($link, $mobile = false) {
4451 require_once "login_form.php";
4453 require_once "mobile/login_form.php";
4457 // from http://developer.apple.com/internet/safari/faq.html
4458 function no_cache_incantation() {
4459 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4460 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4461 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4462 header("Cache-Control: post-check=0, pre-check=0", false);
4463 header("Pragma: no-cache"); // HTTP/1.0
4466 function format_warning($msg, $id = "") {
4467 return "<div class=\"warning\" id=\"$id\">
4468 <img src=\"images/sign_excl.gif\">$msg</div>";
4471 function format_notice($msg) {
4472 return "<div class=\"notice\">
4473 <img src=\"images/sign_info.gif\">$msg</div>";
4476 function format_error($msg) {
4477 return "<div class=\"error\">
4478 <img src=\"images/sign_excl.gif\">$msg</div>";
4481 function print_notice($msg) {
4482 return print format_notice($msg);
4485 function print_warning($msg) {
4486 return print format_warning($msg);
4489 function print_error($msg) {
4490 return print format_error($msg);
4494 function T_sprintf() {
4495 $args = func_get_args();
4496 return vsprintf(__(array_shift($args)), $args);
4499 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4500 $zoom_mode = false) {
4502 /* we can figure out feed_id from article id anyway, why do we
4503 * pass feed_id here? */
4505 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4506 WHERE ref_id = '$id'");
4508 $feed_id = db_fetch_result($result, 0, "feed_id");
4510 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4512 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4513 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4515 if (db_num_rows($result) == 1) {
4516 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4518 $rtl_content = false;
4522 $rtl_tag = "dir=\"RTL\"";
4529 if ($mark_as_read) {
4530 $result = db_query($link, "UPDATE ttrss_user_entries
4531 SET unread = false,last_read = NOW()
4532 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4534 ccache_update($link, $feed_id, $_SESSION["uid"]);
4537 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4538 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4539 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4543 FROM ttrss_entries,ttrss_user_entries
4544 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4550 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4551 $link_target = "target=\"_blank\"";
4554 $line = db_fetch_assoc($result);
4556 if ($line["icon_url"]) {
4557 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4559 $feed_icon = " ";
4562 $num_comments = $line["num_comments"];
4563 $entry_comments = "";
4565 if ($num_comments > 0) {
4566 if ($line["comments"]) {
4567 $comments_url = $line["comments"];
4569 $comments_url = $line["link"];
4571 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4573 if ($line["comments"] && $line["link"] != $line["comments"]) {
4574 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4579 header("Content-Type: text/html");
4581 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4582 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4583 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4588 print "<div class=\"postReply\">";
4590 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4591 onmouseout=\"enable_resize(false)\">";
4593 $entry_author = $line["author"];
4595 if ($entry_author) {
4596 $entry_author = __(" - ") . $entry_author;
4599 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4600 strtotime($line["updated"]));
4602 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4604 if ($line["link"]) {
4605 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4606 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4608 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4611 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4613 if (!$entry_comments) $entry_comments = " "; # placeholder
4615 print "<div style='float : right'>
4616 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'> ";
4619 print "<span id=\"ATSTR-$id\">$tags_str</span>
4620 <a title=\"".__('Edit tags for this article')."\"
4621 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4623 if (defined('_ENABLE_INLINE_VIEW')) {
4625 print "<img src=\"images/art-inline.png\" class='tagsPic'
4626 style=\"cursor : pointer\" style=\"cursor : pointer\"
4627 onclick=\"showOriginalArticleInline($id)\"
4628 alt='Inline' title='".__('Display original article content')."'>";
4632 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4633 style=\"cursor : pointer\" style=\"cursor : pointer\"
4634 onclick=\"zoomToArticle($id)\"
4635 alt='Zoom' title='".__('Show article summary in new window')."'>";
4637 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4639 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4640 style=\"cursor : pointer\" style=\"cursor : pointer\"
4641 onclick=\"publishWithNote($id, '$note_escaped')\"
4642 alt='PubNote' title='".__('Publish article with a note')."'>";
4646 print "<div clear='both'>$entry_comments</div>";
4650 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4652 print "<div class=\"postContent\">";
4654 $article_content = sanitize_rss($link, $line["content"]);
4656 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4657 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4661 print $article_content;
4663 print "<div id=\"POSTNOTE-$id\">";
4664 if ($line['note']) {
4665 print format_article_note($id, $line['note']);
4669 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4670 post_id = '$id' AND content_url != ''");
4672 if (db_num_rows($result) > 0) {
4674 $entries_html = array();
4677 while ($line = db_fetch_assoc($result)) {
4679 $url = $line["content_url"];
4680 $ctype = $line["content_type"];
4682 if (!$ctype) $ctype = __("unknown type");
4684 $filename = substr($url, strrpos($url, "/")+
1);
4688 if (($ctype == __("audio/mpeg")) &&
4689 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4691 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
4695 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4696 $filename . " (" . $ctype . ")" . "</a>";
4698 array_push($entries_html, $entry);
4702 $entry["type"] = $ctype;
4703 $entry["filename"] = $filename;
4704 $entry["url"] = $url;
4706 array_push($entries, $entry);
4709 print "<div class=\"postEnclosures\">";
4711 if (!preg_match("/<img/i", $article_content)) {
4712 foreach ($entries as $entry) {
4713 if (preg_match("/image/", $entry["type"])) {
4715 alt=\"".htmlspecialchars($entry["filename"])."\"
4716 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4721 print "<div class=\"postEnclosures\">";
4723 if (db_num_rows($result) == 1) {
4724 print __("Attachment:") . " ";
4726 print __("Attachments:") . " ";
4729 print join(", ", $entries_html);
4741 print "]]></article>";
4744 <div style=\"text-align : center\">
4745 <input type=\"submit\" onclick=\"return window.close()\"
4746 value=\"".__("Close this window")."\"></div>";
4747 print "</body></html>";
4753 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4754 $next_unread_feed, $offset, $vgr_last_feed = false,
4755 $override_order = false) {
4757 $disable_cache = false;
4759 $timing_info = getmicrotime();
4761 $topmost_article_ids = array();
4767 if ($subop == "undefined") $subop = "";
4769 $subop_split = split(":", $subop);
4771 if ($subop == "CatchupSelected") {
4772 $ids = split(",", db_escape_string($_GET["ids"]));
4773 $cmode = sprintf("%d", $_GET["cmode"]);
4775 catchupArticlesById($link, $ids, $cmode);
4778 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4779 update_generic_feed($link, $feed, $cat_view, true);
4782 if ($subop == "MarkAllRead") {
4783 catchup_feed($link, $feed, $cat_view);
4785 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4786 if ($next_unread_feed) {
4787 $feed = $next_unread_feed;
4792 if ($subop_split[0] == "MarkAllReadGR") {
4793 catchup_feed($link, $subop_split[1], false);
4798 $result = db_query($link,
4799 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4801 if (db_num_rows($result) == 0) {
4802 print "<div align='center'>".__('Feed not found.')."</div>";
4807 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4809 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4810 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4812 if (db_num_rows($result) == 1) {
4813 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4815 $rtl_content = false;
4819 $rtl_tag = "dir=\"RTL\"";
4825 $rtl_content = false;
4828 $script_dt_add = get_script_dt_add();
4830 /// START /////////////////////////////////////////////////////////////////////////////////
4832 $search = db_escape_string($_GET["query"]);
4835 $disable_cache = true;
4838 $search_mode = db_escape_string($_GET["search_mode"]);
4839 $match_on = db_escape_string($_GET["match_on"]);
4845 $real_offset = $offset * $limit;
4847 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4849 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4850 $search, $search_mode, $match_on, $override_order, $real_offset);
4852 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4854 $result = $qfh_ret[0];
4855 $feed_title = $qfh_ret[1];
4856 $feed_site_url = $qfh_ret[2];
4857 $last_error = $qfh_ret[3];
4859 $vgroup_last_feed = $vgr_last_feed;
4862 $feed_site_url = article_publish_url($link);
4865 /// STOP //////////////////////////////////////////////////////////////////////////////////
4868 print "<div id=\"headlinesContainer\" $rtl_tag>";
4871 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4875 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4876 $feed, $cat_view, $search, $match_on, $search_mode);
4878 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4881 $headlines_count = db_num_rows($result);
4883 if (db_num_rows($result) > 0) {
4885 # print "\{$offset}";
4887 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4888 print "<table class=\"headlinesList\" id=\"headlinesList\"
4889 cellspacing=\"0\">";
4892 $lnum = $limit*$offset;
4894 error_reporting (DEFAULT_ERROR_LEVEL
);
4897 $cur_feed_title = '';
4899 while ($line = db_fetch_assoc($result)) {
4901 $class = ($lnum %
2) ?
"even" : "odd";
4904 $feed_id = $line["feed_id"];
4906 $labels = get_article_labels($link, $id);
4908 $labels_str = "<span id=\"HLLCTR-$id\">";
4909 $labels_str .= format_article_labels($labels, $id);
4910 $labels_str .= "</span>";
4912 if (count($topmost_article_ids) < 5) {
4913 array_push($topmost_article_ids, $id);
4916 if ($line["last_read"] == "" &&
4917 ($line["unread"] != "t" && $line["unread"] != "1")) {
4919 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4922 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4926 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4934 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4937 $mark_img_ext = "gif";
4939 $mark_img_ext = "png";
4942 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4943 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4945 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4947 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4949 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4952 if ($line["published"] == "t" ||
$line["published"] == "1") {
4953 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4955 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4957 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4959 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4962 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4963 # $line["title"] . "</a>";
4965 # $content_link = "<a
4966 # href=\"" . htmlspecialchars($line["link"]) . "\"
4967 # onclick=\"view($id,$feed_id);\">" .
4968 # $line["title"] . "</a>";
4970 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4971 # $line["title"] . "</a>";
4973 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4974 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4976 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4977 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4980 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4981 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4985 $score = $line["score"];
4987 $score_pic = get_score_pic($score);
4989 /* $score_title = __("(Click to change)");
4990 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4991 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4993 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4998 } else if ($score < -100) {
5004 $entry_author = $line["author"];
5006 if ($entry_author) {
5007 $entry_author = " - $entry_author";
5010 $has_feed_icon = feed_has_icon($feed_id);
5012 if ($has_feed_icon) {
5013 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5015 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5016 $feed_icon_img = "";
5019 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5021 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5022 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5024 $cur_feed_title = $line["feed_title"];
5025 $vgroup_last_feed = $feed_id;
5027 $cur_feed_title = htmlspecialchars($cur_feed_title);
5029 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5031 print "<tr class='feedTitle'><td colspan='7'>".
5032 "<div style=\"float : right\">$feed_icon_img</div>".
5033 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5034 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5038 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5039 onmouseout='postMouseOut($id)'";
5041 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5043 print "<td class='hlUpdPic'>$update_pic</td>";
5045 print "<td class='hlSelectRow'>
5046 <input type=\"checkbox\" onclick=\"tSR(this)\"
5050 print "<td class='hlMarkedPic'>$marked_pic</td>";
5051 print "<td class='hlMarkedPic'>$published_pic</td>";
5053 # if ($line["feed_title"]) {
5054 # print "<td class='hlContent'>$content_link</td>";
5055 # print "<td class='hlFeed'>
5056 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5057 # truncate_string($line["feed_title"],30)."</a> </td>";
5060 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5062 print "<a id=\"RTITLE-$id\"
5063 href=\"" . htmlspecialchars($line["link"]) . "\"
5064 onclick=\"return view($id,$feed_id);\">" .
5067 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5068 if ($content_preview) {
5069 print "<span class=\"contentPreview\"> - $content_preview</span>";
5077 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5078 # $line["feed_title"]."</a>
5080 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5081 if ($line["feed_title"]) {
5082 print "<span class=\"hlFeed\">
5083 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5084 $line["feed_title"]."</a>)
5092 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5094 print "<td class='hlMarkedPic'>$score_pic</td>";
5096 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5097 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5104 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5105 if ($feed_id != $vgroup_last_feed) {
5107 $cur_feed_title = $line["feed_title"];
5108 $vgroup_last_feed = $feed_id;
5110 $cur_feed_title = htmlspecialchars($cur_feed_title);
5112 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5114 $has_feed_icon = feed_has_icon($feed_id);
5116 if ($has_feed_icon) {
5117 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5119 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5122 print "<div class='cdmFeedTitle'>".
5123 "<div style=\"float : right\">$feed_icon_img</div>".
5124 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5125 $line["feed_title"]."</a> $vf_catchup_link</div>";
5130 $add_class = "Unread";
5135 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5136 $show_excerpt = false;
5138 if ($expand_cdm && $score >= -100) {
5140 $show_excerpt = false;
5142 $cdm_cstyle = "style=\"display : none\"";
5143 $show_excerpt = true;
5146 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5147 onmouseout='postMouseOut($id)'";
5149 print "<div class=\"cdmArticle$add_class\"
5151 $mouseover_attrs'>";
5153 print "<div class=\"cdmHeader\">";
5155 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5156 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5159 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5162 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5163 onclick=\"javascript:toggleUnread($id, 0)\"
5164 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5167 print $entry_author;
5169 /* if (!$expand_cdm || $score < -100) {
5170 print " <a id=\"CICH-$id\"
5171 href=\"javascript:cdmExpandArticle($id)\">
5172 (".__('Show article').")</a>";
5177 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5178 if ($line["feed_title"]) {
5179 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5183 print "</span></div>";
5185 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5186 $line["content_preview"] = preg_replace("/href=/i",
5187 "target=\"_blank\" href=", $line["content_preview"]);
5190 if ($show_excerpt) {
5191 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5192 onclick=\"cdmExpandArticle($id)\"
5193 title=\"".__('Click to expand article')."\">";
5194 print truncate_string(strip_tags($line["content_preview"]), 100);
5198 print "<div class=\"cdmContent\"
5199 onclick=\"cdmClicked($id)\"
5200 id=\"CICD-$id\" $cdm_cstyle>";
5202 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5204 print sanitize_rss($link, $line["content_preview"]);
5206 print "<div id=\"POSTNOTE-$id\">";
5207 if ($line['note']) {
5208 print format_article_note($id, $line['note']);
5212 $article_content = $line["content_preview"];
5214 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5215 post_id = '$id' AND content_url != ''");
5217 if (db_num_rows($e_result) > 0) {
5219 $entries_html = array();
5222 while ($e_line = db_fetch_assoc($e_result)) {
5224 $url = $e_line["content_url"];
5225 $ctype = $e_line["content_type"];
5226 if (!$ctype) $ctype = __("unknown type");
5228 $filename = substr($url, strrpos($url, "/")+
1);
5232 if (($ctype == __("audio/mpeg")) &&
5233 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5235 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
5239 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5240 $filename . " (" . $ctype . ")" . "</a>";
5242 array_push($entries_html, $entry);
5246 $entry["type"] = $ctype;
5247 $entry["filename"] = $filename;
5248 $entry["url"] = $url;
5250 array_push($entries, $entry);
5253 if (!preg_match("/img/i", $article_content)) {
5254 foreach ($entries as $entry) {
5255 if (preg_match("/image/", $entry["type"])) {
5257 alt=\"".htmlspecialchars($entry["filename"])."\"
5258 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5263 print "<div class=\"cdmEnclosures\">";
5265 if (db_num_rows($e_result) == 1) {
5266 print __("Attachment:") . " ";
5268 print __("Attachments:") . " ";
5271 print join(", ", $entries_html);
5277 print "<br clear='both'>";
5280 /* if (!$expand_cdm) {
5281 print "<a id=\"CICH-$id\"
5282 href=\"javascript:cdmExpandArticle($id)\">
5288 print "<div class=\"cdmFooter\"><span class='s0'>";
5290 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5292 print __("Select:").
5293 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5294 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5296 print "</span><span class='s1'>$marked_pic ";
5297 print "$published_pic ";
5298 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5299 onclick=\"zoomToArticle($id)\"
5300 style=\"cursor : pointer\"
5302 title='".__('Show article summary in new window')."'> ";
5304 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5306 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5307 style=\"cursor : pointer\" style=\"cursor : pointer\"
5308 onclick=\"publishWithNote($id, '$note_escaped')\"
5309 alt='PubNote' title='".__('Publish article with a note')."'>";
5313 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5315 // print "<img src='images/tag.png' class='markedPic'>";
5317 print "<span class='s1'>
5318 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5319 <span id=\"ATSTR-$id\">$tags_str</span>
5320 <a title=\"".__('Edit tags for this article')."\"
5321 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5325 print "<span class='s2'><a class=\"cdmToggleLink\"
5326 href=\"javascript:toggleUnread($id)\">
5327 ".__('toggle unread')."</a></span>";
5337 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5344 switch ($view_mode) {
5346 $message = __("No unread articles found to display.");
5349 $message = __("No updated articles found to display.");
5352 $message = __("No starred articles found to display.");
5356 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5358 $message = __("No articles found to display.");
5362 if (!$offset) print "<div class='whiteBox'>$message</div>";
5370 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5373 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5375 function printTagCloud($link) {
5377 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5378 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5379 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5381 $result = db_query($link, $query);
5385 while ($line = db_fetch_assoc($result)) {
5386 $tags[$line["tag_name"]] = $line["count"];
5391 $max_size = 32; // max font size in pixels
5392 $min_size = 11; // min font size in pixels
5394 // largest and smallest array values
5395 $max_qty = max(array_values($tags));
5396 $min_qty = min(array_values($tags));
5398 // find the range of values
5399 $spread = $max_qty - $min_qty;
5400 if ($spread == 0) { // we don't want to divide by zero
5404 // set the font-size increment
5405 $step = ($max_size - $min_size) / ($spread);
5407 // loop through the tag array
5408 foreach ($tags as $key => $value) {
5409 // calculate font-size
5410 // find the $value in excess of $min_qty
5411 // multiply by the font-size increment ($size)
5412 // and add the $min_size set above
5413 $size = round($min_size +
(($value - $min_qty) * $step));
5415 $key_escaped = str_replace("'", "\\'", $key);
5417 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5418 $size . "px\" title=\"$value articles tagged with " .
5419 $key . '">' . $key . '</a> ';
5423 function print_checkpoint($n, $s) {
5424 $ts = getmicrotime();
5425 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5429 function sanitize_tag($tag) {
5432 $tag = mb_strtolower($tag, 'utf-8');
5434 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5436 // $tag = str_replace('"', "", $tag);
5437 // $tag = str_replace("+", " ", $tag);
5438 $tag = str_replace("technorati tag: ", "", $tag);
5443 function generate_publish_key() {
5444 return sha1(uniqid(rand(), true));
5447 function article_publish_url($link) {
5452 if ($_SERVER['HTTPS'] != "on") {
5453 $url_path = "http://";
5455 $url_path = "https://";
5458 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5459 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5465 * Purge a feed contents, marked articles excepted.
5467 * @param mixed $link The database connection.
5468 * @param integer $id The id of the feed to purge.
5471 function clear_feed_articles($link, $id) {
5472 $result = db_query($link, "DELETE FROM ttrss_user_entries
5473 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5475 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5476 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5478 ccache_update($link, $id, $_SESSION['uid']);
5479 } // function clear_feed_articles
5482 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5484 * @return string The Mozilla Firefox feed adding URL.
5486 function add_feed_url() {
5487 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5488 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5490 } // function add_feed_url
5493 * Encrypt a password in SHA1.
5495 * @param string $pass The password to encrypt.
5496 * @param string $login A optionnal login.
5497 * @return string The encrypted password.
5499 function encrypt_password($pass, $login = '') {
5501 return "SHA1X:" . sha1("$login:$pass");
5503 return "SHA1:" . sha1($pass);
5505 } // function encrypt_password
5508 * Update a feed batch.
5509 * Used by daemons to update n feeds by run.
5510 * Only update feed needing a update, and not being processed
5511 * by another process.
5513 * @param mixed $link Database link
5514 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5515 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5516 * @param boolean $debug Set to false to disable debug output. Default to true.
5519 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5520 // Process all other feeds using last_updated and interval parameters
5522 // Test if the user has loggued in recently. If not, it does not update its feeds.
5523 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5524 if (DB_TYPE
== "pgsql") {
5525 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5527 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5530 $login_thresh_qpart = "";
5533 // Test if the feed need a update (update interval exceded).
5534 if (DB_TYPE
== "pgsql") {
5535 $update_limit_qpart = "AND ((
5536 ttrss_feeds.update_interval = 0
5537 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5539 ttrss_feeds.update_interval > 0
5540 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5541 ) OR ttrss_feeds.last_updated IS NULL)";
5543 $update_limit_qpart = "AND ((
5544 ttrss_feeds.update_interval = 0
5545 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5547 ttrss_feeds.update_interval > 0
5548 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5549 ) OR ttrss_feeds.last_updated IS NULL)";
5552 // Test if feed is currently being updated by another process.
5553 if (DB_TYPE
== "pgsql") {
5554 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5556 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5559 // Test if there is a limit to number of updated feeds
5561 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5563 $random_qpart = sql_random_function();
5565 // We search for feed needing update.
5566 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5567 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5568 ttrss_feeds.update_interval
5570 ttrss_feeds, ttrss_users, ttrss_user_prefs
5572 ttrss_feeds.owner_uid = ttrss_users.id
5573 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5574 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5575 $login_thresh_qpart $update_limit_qpart
5576 $updstart_thresh_qpart
5577 ORDER BY $random_qpart $query_limit");
5579 $user_prefs_cache = array();
5581 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5583 // Here is a little cache magic in order to minimize risk of double feed updates.
5584 $feeds_to_update = array();
5585 while ($line = db_fetch_assoc($result)) {
5586 $feeds_to_update[$line['id']] = $line;
5589 // We update the feed last update started date before anything else.
5590 // There is no lag due to feed contents downloads
5591 // It prevent an other process to update the same feed.
5592 $feed_ids = array_keys($feeds_to_update);
5594 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5595 WHERE id IN (%s)", implode(',', $feed_ids)));
5598 // For each feed, we call the feed update function.
5599 while ($line = array_pop($feeds_to_update)) {
5601 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5603 // We setup a alarm to alert if the feed take more than 300s to update.
5605 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5606 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5607 // Cancel the alarm (the update went well)
5608 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5610 sleep(1); // prevent flood (FIXME make this an option?)
5613 // Send feed digests by email if needed.
5614 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5616 purge_orphans($link);
5618 } // function update_daemon_common
5620 function sanitize_article_content($text) {
5621 # we don't support CDATA sections in articles, they break our own escaping
5622 $text = preg_replace("/\[\[CDATA/", "", $text);
5623 $text = preg_replace("/\]\]\>/", "", $text);
5627 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5630 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5632 $result = db_query($link, "SELECT reg_exp,
5633 ttrss_filter_types.name AS name,
5634 ttrss_filter_actions.name AS action,
5638 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5641 owner_uid = $owner_uid AND
5642 ttrss_filter_types.id = filter_type AND
5643 ttrss_filter_actions.id = action_id AND
5644 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5646 while ($line = db_fetch_assoc($result)) {
5647 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5648 $filter["reg_exp"] = $line["reg_exp"];
5649 $filter["action"] = $line["action"];
5650 $filter["action_param"] = $line["action_param"];
5651 $filter["filter_param"] = $line["filter_param"];
5652 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5654 array_push($filters[$line["name"]], $filter);
5660 function get_score_pic($score) {
5662 return "score_high.png";
5663 } else if ($score > 0) {
5664 return "score_half_high.png";
5665 } else if ($score < -100) {
5666 return "score_low.png";
5667 } else if ($score < 0) {
5668 return "score_half_low.png";
5670 return "score_neutral.png";
5674 function rounded_table_start($classname, $header = " ") {
5675 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5676 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5677 print "<tr><td class='left'> </td><td class='content'>";
5680 function rounded_table_end($footer = " ") {
5681 print "</td><td class='right'> </td></tr>";
5682 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5686 function feed_has_icon($id) {
5687 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5690 function init_connection($link) {
5691 if (DB_TYPE
== "pgsql") {
5692 pg_query($link, "set client_encoding = 'UTF-8'");
5693 pg_set_client_encoding("UNICODE");
5694 pg_query($link, "set datestyle = 'ISO, european'");
5696 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5697 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5698 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5703 function update_feedbrowser_cache($link) {
5705 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5706 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5707 WHERE tf.feed_url = ttrss_feeds.feed_url
5708 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5709 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5711 db_query($link, "BEGIN");
5713 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5717 while ($line = db_fetch_assoc($result)) {
5718 $subscribers = db_escape_string($line["subscribers"]);
5719 $feed_url = db_escape_string($line["feed_url"]);
5720 $title = db_escape_string($line["title"]);
5722 $tmp_result = db_query($link, "SELECT subscribers FROM
5723 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5725 if (db_num_rows($tmp_result) == 0) {
5727 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5728 (feed_url, title, subscribers) VALUES ('$feed_url',
5729 '$title', '$subscribers')");
5737 db_query($link, "COMMIT");
5743 function ccache_zero($link, $feed_id, $owner_uid) {
5744 db_query($link, "UPDATE ttrss_counters_cache SET
5745 value = 0, updated = NOW() WHERE
5746 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5749 function ccache_zero_all($link, $owner_uid) {
5750 db_query($link, "UPDATE ttrss_counters_cache SET
5751 value = 0 WHERE owner_uid = '$owner_uid'");
5753 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5754 value = 0 WHERE owner_uid = '$owner_uid'");
5757 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5760 $table = "ttrss_counters_cache";
5762 $table = "ttrss_cat_counters_cache";
5765 db_query($link, "DELETE FROM $table WHERE
5766 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5770 function ccache_update_all($link, $owner_uid) {
5772 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5774 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5775 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5777 while ($line = db_fetch_assoc($result)) {
5778 ccache_update($link, $line["feed_id"], $owner_uid, true);
5781 /* We have to manually include category 0 */
5783 ccache_update($link, 0, $owner_uid, true);
5786 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5787 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5789 while ($line = db_fetch_assoc($result)) {
5790 print ccache_update($link, $line["feed_id"], $owner_uid);
5797 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5798 $no_update = false) {
5800 if (!is_numeric($feed_id)) return;
5803 $table = "ttrss_counters_cache";
5805 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5806 WHERE id = '$feed_id'");
5807 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5810 $table = "ttrss_cat_counters_cache";
5813 if (DB_TYPE
== "pgsql") {
5814 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5815 } else if (DB_TYPE
== "mysql") {
5816 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5819 $result = db_query($link, "SELECT value FROM $table
5820 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5823 if (db_num_rows($result) == 1) {
5824 return db_fetch_result($result, 0, "value");
5829 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5835 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5836 $update_pcat = true) {
5838 if (!is_numeric($feed_id)) return;
5840 if (!$is_cat && $feed_id > 0) {
5841 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5842 WHERE id = '$feed_id'");
5843 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5846 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5848 /* When updating a label, all we need to do is recalculate feed counters
5849 * because labels are not cached */
5852 ccache_update_all($link, $owner_uid);
5857 $table = "ttrss_counters_cache";
5859 $table = "ttrss_cat_counters_cache";
5862 if ($is_cat && $feed_id >= 0) {
5863 if ($feed_id != 0) {
5864 $cat_qpart = "cat_id = '$feed_id'";
5866 $cat_qpart = "cat_id IS NULL";
5869 /* Recalculate counters for child feeds */
5871 $result = db_query($link, "SELECT id FROM ttrss_feeds
5872 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5874 while ($line = db_fetch_assoc($result)) {
5875 ccache_update($link, $line["id"], $owner_uid, false, false);
5878 $result = db_query($link, "SELECT SUM(value) AS sv
5879 FROM ttrss_counters_cache, ttrss_feeds
5880 WHERE id = feed_id AND $cat_qpart AND
5881 ttrss_feeds.owner_uid = '$owner_uid'");
5883 $unread = (int) db_fetch_result($result, 0, "sv");
5886 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5889 db_query($link, "BEGIN");
5891 $result = db_query($link, "SELECT feed_id FROM $table
5892 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5894 if (db_num_rows($result) == 1) {
5895 db_query($link, "UPDATE $table SET
5896 value = '$unread', updated = NOW() WHERE
5897 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5900 db_query($link, "INSERT INTO $table
5901 (feed_id, value, owner_uid, updated)
5903 ($feed_id, $unread, $owner_uid, NOW())");
5906 db_query($link, "COMMIT");
5908 if ($feed_id > 0 && $prev_unread != $unread) {
5912 /* Update parent category */
5916 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5917 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5919 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5921 ccache_update($link, $cat_id, $owner_uid, true);
5925 } else if ($feed_id < 0) {
5926 ccache_update_all($link, $owner_uid);
5932 function label_find_id($link, $label, $owner_uid) {
5933 $result = db_query($link,
5934 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5935 AND owner_uid = '$owner_uid' LIMIT 1");
5937 if (db_num_rows($result) == 1) {
5938 return db_fetch_result($result, 0, "id");
5944 function get_article_labels($link, $id) {
5945 $result = db_query($link,
5946 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5947 FROM ttrss_labels2, ttrss_user_labels2
5949 AND article_id = '$id'
5950 AND owner_uid = ".$_SESSION["uid"] . "
5955 while ($line = db_fetch_assoc($result)) {
5956 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5958 array_push($rv, $rk);
5965 function label_find_caption($link, $label, $owner_uid) {
5966 $result = db_query($link,
5967 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5968 AND owner_uid = '$owner_uid' LIMIT 1");
5970 if (db_num_rows($result) == 1) {
5971 return db_fetch_result($result, 0, "caption");
5977 function label_remove_article($link, $id, $label, $owner_uid) {
5979 $label_id = label_find_id($link, $label, $owner_uid);
5981 if (!$label_id) return;
5983 $result = db_query($link,
5984 "DELETE FROM ttrss_user_labels2
5986 label_id = '$label_id' AND
5987 article_id = '$id'");
5990 function label_add_article($link, $id, $label, $owner_uid) {
5992 $label_id = label_find_id($link, $label, $owner_uid);
5994 if (!$label_id) return;
5996 $result = db_query($link,
5998 article_id FROM ttrss_labels2, ttrss_user_labels2
6001 label_id = '$label_id' AND
6002 article_id = '$id' AND owner_uid = '$owner_uid'
6005 if (db_num_rows($result) == 0) {
6006 db_query($link, "INSERT INTO ttrss_user_labels2
6007 (label_id, article_id) VALUES ('$label_id', '$id')");
6011 function label_remove($link, $id, $owner_uid) {
6013 db_query($link, "BEGIN");
6015 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6018 $caption = db_fetch_result($result, 0, "caption");
6020 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6021 AND owner_uid = " . $_SESSION["uid"]);
6023 if (db_affected_rows($link, $result) != 0 && $caption) {
6025 /* Disable filters that reference label being removed */
6027 db_query($link, "UPDATE ttrss_filters SET
6028 enabled = false WHERE action_param = '$caption'
6030 AND owner_uid = " . $_SESSION["uid"]);
6033 db_query($link, "COMMIT");
6036 function label_create($link, $caption) {
6038 db_query($link, "BEGIN");
6042 $result = db_query($link, "SELECT id FROM ttrss_labels2
6043 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6045 if (db_num_rows($result) == 0) {
6046 $result = db_query($link,
6047 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6048 VALUES ('$caption', '".$_SESSION["uid"]."')");
6050 $result = db_affected_rows($link, $result) != 0;
6053 db_query($link, "COMMIT");
6058 function print_labels_headlines_dropdown($link, $feed_id) {
6059 print "<li onclick=\"javascript:addLabel()\">
6060 ".__("Create label...")."</li>";
6062 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6063 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6065 while ($line = db_fetch_assoc($result)) {
6067 $label_id = $line["id"];
6068 $label_caption = $line["caption"];
6070 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6071 print "<li id=\"LHDL-$id\"
6072 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6073 $label_caption ".__('(remove)')."</li>";
6075 print "<li id=\"LHDL-$id\"
6076 onclick=\"javascript:selectionAssignLabel($label_id)\">
6077 $label_caption</li>";
6082 function format_tags_string($tags, $id) {
6085 $tags_nolinks_str = "";
6089 if ($_SESSION["theme"] == "3pane") {
6095 $formatted_tags = array();
6097 foreach ($tags as $tag) {
6099 $tag_escaped = str_replace("'", "\\'", $tag);
6101 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6103 array_push($formatted_tags, $tag_str);
6105 if ($num_tags == $tag_limit) {
6110 $tags_str = implode(", ", $formatted_tags);
6112 if ($num_tags < count($tags)) {
6113 $tags_str .= ", …";
6116 if ($num_tags == 0) {
6117 $tags_str = __("no tags");
6124 function format_article_labels($labels, $id) {
6128 foreach ($labels as $l) {
6129 $labels_str .= sprintf("<span class='hlLabelRef'
6130 style='color : %s; background-color : %s'>%s</span>",
6131 $l[2], $l[3], $l[1]);
6138 function format_article_note($id, $note) {
6140 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6142 $str = "<div class='articleNote'>";
6143 $str .= "<div class='articleNoteOps'>";
6144 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6145 __('edit note')."</a>";