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;
398 } else if (substr($url, -1, 1) == '/') {
399 $faviconURL = $url.$linkUrl;
401 $faviconURL = $url.'/'.$linkUrl;
405 // If unsuccessful, attempt to "guess" the favicon location
406 $urlParts = parse_url($url);
407 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
411 // Run a test to see if what we have attempted to get actually exists.
412 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
417 } // function get_favicon_url
420 * Check if a link is a valid and working URL.
422 * @param mixed $link A URL to check
424 * @return boolean True if the URL is valid, false otherwise.
426 function url_validate($link) {
428 $url_parts = @parse_url
($link);
430 if ( empty( $url_parts["host"] ) )
433 if ( !empty( $url_parts["path"] ) ) {
434 $documentpath = $url_parts["path"];
439 if ( !empty( $url_parts["query"] ) )
440 $documentpath .= "?" . $url_parts["query"];
442 $host = $url_parts["host"];
443 $port = $url_parts["port"];
448 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
453 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
455 $http_response = fgets( $socket, 22 );
457 $responses = "/(200 OK)|(30[0-9] Moved)/";
458 if ( preg_match($responses, $http_response) ) {
465 } // function url_validate
467 function check_feed_favicon($site_url, $feed, $link) {
468 $favicon_url = get_favicon_url($site_url);
470 # print "FAVICON [$site_url]: $favicon_url\n";
474 $icon_file = ICONS_DIR
. "/$feed.ico";
476 if ($favicon_url && !file_exists($icon_file)) {
477 $contents = fetch_file_contents($favicon_url);
479 $fp = fopen($icon_file, "w");
482 fwrite($fp, $contents);
484 chmod($icon_file, 0644);
488 error_reporting(DEFAULT_ERROR_LEVEL
);
492 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
494 if (!$_GET["daemon"] && !$ignore_daemon) {
498 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
499 _debug("update_rss_feed: start");
502 if (!$ignore_daemon) {
504 if (DB_TYPE
== "pgsql") {
505 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
507 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
510 $result = db_query($link, "SELECT id,update_interval,auth_login,
511 auth_pass,cache_images,update_method
512 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
516 $result = db_query($link, "SELECT id,update_interval,auth_login,
517 auth_pass,cache_images,update_method,hidden,last_updated
518 FROM ttrss_feeds WHERE id = '$feed'");
522 if (db_num_rows($result) == 0) {
523 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
524 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
529 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
530 $update_method = db_fetch_result($result, 0, "update_method");
531 $last_updated = db_fetch_result($result, 0, "last_updated");
533 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
534 WHERE id = '$feed'");
536 $auth_login = db_fetch_result($result, 0, "auth_login");
537 $auth_pass = db_fetch_result($result, 0, "auth_pass");
539 if (ALLOW_SELECT_UPDATE_METHOD
) {
540 if (ENABLE_SIMPLEPIE
) {
541 $use_simplepie = $update_method != 1;
543 $use_simplepie = $update_method == 2;
546 $use_simplepie = ENABLE_SIMPLEPIE
;
549 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
550 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
553 if (!$use_simplepie) {
554 $auth_login = urlencode($auth_login);
555 $auth_pass = urlencode($auth_pass);
558 $update_interval = db_fetch_result($result, 0, "update_interval");
559 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
561 if ($update_interval < 0) { return; }
563 $feed = db_escape_string($feed);
565 $fetch_url = $feed_url;
567 if ($auth_login && $auth_pass) {
568 $url_parts = array();
569 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
571 if ($url_parts[1] && $url_parts[2]) {
572 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
577 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
578 _debug("update_rss_feed: fetching [$fetch_url]...");
581 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
585 if (!$use_simplepie) {
586 $rss = fetch_rss($fetch_url);
588 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
589 mkdir(SIMPLEPIE_CACHE_DIR
);
592 $rss = new SimplePie();
593 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
594 # $rss->set_timeout(10);
595 $rss->set_feed_url($fetch_url);
596 $rss->set_output_encoding('UTF-8');
598 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
599 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
600 _debug("enabling image cache");
603 $rss->set_image_handler('./image.php', 'i');
606 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
607 _debug("feed update interval (sec): " .
608 get_feed_update_interval($link, $feed)*60);
611 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
612 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
613 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
621 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
622 _debug("update_rss_feed: fetch done, parsing...");
624 error_reporting (DEFAULT_ERROR_LEVEL
);
627 $feed = db_escape_string($feed);
629 if ($use_simplepie) {
630 $fetch_ok = !$rss->error();
637 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
638 _debug("update_rss_feed: processing feed data...");
641 // db_query($link, "BEGIN");
643 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
644 FROM ttrss_feeds WHERE id = '$feed'");
646 $registered_title = db_fetch_result($result, 0, "title");
647 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
648 $orig_site_url = db_fetch_result($result, 0, "site_url");
650 $owner_uid = db_fetch_result($result, 0, "owner_uid");
652 if ($use_simplepie) {
653 $site_url = $rss->get_link();
655 $site_url = $rss->channel
["link"];
658 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
659 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
660 _debug("update_rss_feed: checking favicon...");
663 check_feed_favicon($site_url, $feed, $link);
666 if (!$registered_title ||
$registered_title == "[Unknown]") {
668 if ($use_simplepie) {
669 $feed_title = db_escape_string($rss->get_title());
671 $feed_title = db_escape_string($rss->channel
["title"]);
674 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
675 _debug("update_rss_feed: registering title: $feed_title");
678 db_query($link, "UPDATE ttrss_feeds SET
679 title = '$feed_title' WHERE id = '$feed'");
682 // weird, weird Magpie
683 if (!$use_simplepie) {
684 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
687 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
688 db_query($link, "UPDATE ttrss_feeds SET
689 site_url = '$site_url' WHERE id = '$feed'");
692 // print "I: " . $rss->channel["image"]["url"];
694 if (!$use_simplepie) {
695 $icon_url = $rss->image
["url"];
697 $icon_url = $rss->get_image_url();
700 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
701 $icon_url = db_escape_string($icon_url);
702 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
705 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
706 _debug("update_rss_feed: loading filters...");
709 $filters = load_filters($link, $feed, $owner_uid);
711 if ($use_simplepie) {
712 $iterator = $rss->get_items();
714 $iterator = $rss->items
;
715 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
716 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
719 if (!is_array($iterator)) {
720 /* db_query($link, "UPDATE ttrss_feeds
721 SET last_error = 'Parse error: can\'t find any articles.'
722 WHERE id = '$feed'"); */
724 // clear any errors and mark feed as updated if fetched okay
725 // even if it's blank
727 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
728 _debug("update_rss_feed: entry iterator is not an array, no articles?");
731 db_query($link, "UPDATE ttrss_feeds
732 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
734 return; // no articles
737 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
738 _debug("update_rss_feed: processing articles...");
741 foreach ($iterator as $item) {
743 if ($_GET['xdebug']) {
748 if ($use_simplepie) {
749 $entry_guid = $item->get_id();
750 if (!$entry_guid) $entry_guid = $item->get_link();
751 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
755 $entry_guid = $item["id"];
757 if (!$entry_guid) $entry_guid = $item["guid"];
758 if (!$entry_guid) $entry_guid = $item["link"];
759 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
762 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
763 _debug("update_rss_feed: guid $entry_guid");
766 if (!$entry_guid) continue;
768 $entry_timestamp = "";
770 if ($use_simplepie) {
771 $entry_timestamp = strtotime($item->get_date());
773 $rss_2_date = $item['pubdate'];
774 $rss_1_date = $item['dc']['date'];
775 $atom_date = $item['issued'];
776 if (!$atom_date) $atom_date = $item['updated'];
778 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
779 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
780 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
783 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
784 $entry_timestamp = time();
785 $no_orig_date = 'true';
787 $no_orig_date = 'false';
790 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
792 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
793 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
796 if ($use_simplepie) {
797 $entry_title = $item->get_title();
799 $entry_title = trim(strip_tags($item["title"]));
802 if ($use_simplepie) {
803 $entry_link = $item->get_link();
805 // strange Magpie workaround
806 $entry_link = $item["link_"];
807 if (!$entry_link) $entry_link = $item["link"];
810 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
811 _debug("update_rss_feed: title $entry_title");
814 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
816 $entry_link = strip_tags($entry_link);
818 if ($use_simplepie) {
819 $entry_content = $item->get_content();
820 if (!$entry_content) $entry_content = $item->get_description();
822 $entry_content = $item["content:escaped"];
824 if (!$entry_content) $entry_content = $item["content:encoded"];
825 if (!$entry_content) $entry_content = $item["content"]["encoded"];
826 if (!$entry_content) $entry_content = $item["content"];
828 // Magpie bugs are getting ridiculous
829 if (trim($entry_content) == "Array") $entry_content = false;
831 if (!$entry_content) $entry_content = $item["atom_content"];
832 if (!$entry_content) $entry_content = $item["summary"];
834 if (!$entry_content ||
835 strlen($entry_content) < strlen($item["description"])) {
836 $entry_content = $item["description"];
840 if (is_array($entry_content)) {
841 $entry_content = $entry_content["encoded"];
842 if (!$entry_content) $entry_content = $entry_content["escaped"];
846 if ($_GET["xdebug"]) {
847 print "update_rss_feed: content: ";
848 print_r(htmlspecialchars($entry_content));
851 $entry_content_unescaped = $entry_content;
853 if ($use_simplepie) {
854 $entry_comments = strip_tags($item->data
["comments"]);
855 if ($item->get_author()) {
856 $entry_author_item = $item->get_author();
857 $entry_author = $entry_author_item->get_name();
858 if (!$entry_author) $entry_author = $entry_author_item->get_email();
860 $entry_author = db_escape_string($entry_author);
863 $entry_comments = strip_tags($item["comments"]);
865 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
867 if ($item['author']) {
869 if (is_array($item['author'])) {
871 if (!$entry_author) {
872 $entry_author = db_escape_string(strip_tags($item['author']['name']));
875 if (!$entry_author) {
876 $entry_author = db_escape_string(strip_tags($item['author']['email']));
880 if (!$entry_author) {
881 $entry_author = db_escape_string(strip_tags($item['author']));
886 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
888 $entry_guid = db_escape_string(strip_tags($entry_guid));
889 $entry_guid = mb_substr($entry_guid, 0, 250);
891 $result = db_query($link, "SELECT id FROM ttrss_entries
892 WHERE guid = '$entry_guid'");
894 $entry_content = db_escape_string($entry_content);
896 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
898 $entry_title = db_escape_string($entry_title);
899 $entry_link = db_escape_string($entry_link);
900 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
901 $entry_author = mb_substr($entry_author, 0, 250);
903 if ($use_simplepie) {
904 $num_comments = 0; #FIXME#
906 $num_comments = db_escape_string($item["slash"]["comments"]);
909 if (!$num_comments) $num_comments = 0;
911 // parse <category> entries into tags
913 if ($use_simplepie) {
915 $additional_tags = array();
916 $additional_tags_src = $item->get_categories();
918 if (is_array($additional_tags_src)) {
919 foreach ($additional_tags_src as $tobj) {
920 array_push($additional_tags, $tobj->get_term());
924 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
925 _debug("update_rss_feed: category tags:");
926 print_r($additional_tags);
931 $t_ctr = $item['category#'];
933 $additional_tags = false;
936 $additional_tags = false;
937 } else if ($t_ctr > 0) {
938 $additional_tags = array($item['category']);
940 if ($item['category@term']) {
941 array_push($additional_tags, $item['category@term']);
944 for ($i = 0; $i <= $t_ctr; $i++
) {
945 if ($item["category#$i"]) {
946 array_push($additional_tags, $item["category#$i"]);
949 if ($item["category#$i@term"]) {
950 array_push($additional_tags, $item["category#$i@term"]);
955 // parse <dc:subject> elements
957 $t_ctr = $item['dc']['subject#'];
960 $additional_tags = array($item['dc']['subject']);
962 for ($i = 0; $i <= $t_ctr; $i++
) {
963 if ($item['dc']["subject#$i"]) {
964 array_push($additional_tags, $item['dc']["subject#$i"]);
972 $enclosures = array();
974 if ($use_simplepie) {
975 $encs = $item->get_enclosures();
977 if (is_array($encs)) {
978 foreach ($encs as $e) {
980 $e->link
, $e->type
, $e->length
);
982 array_push($enclosures, $e_item);
989 $e_ctr = $item['enclosure#'];
992 $e_item = array($item['enclosure@url'],
993 $item['enclosure@type'],
994 $item['enclosure@length']);
996 array_push($enclosures, $e_item);
998 for ($i = 0; $i <= $e_ctr; $i++
) {
1000 if ($item["enclosure#$i@url"]) {
1001 $e_item = array($item["enclosure#$i@url"],
1002 $item["enclosure#$i@type"],
1003 $item["enclosure#$i@length"]);
1004 array_push($enclosures, $e_item);
1010 // can there be many of those? yes -fox
1012 $m_ctr = $item['media']['content#'];
1015 $e_item = array($item['media']['content@url'],
1016 $item['media']['content@medium'],
1017 $item['media']['content@length']);
1019 array_push($enclosures, $e_item);
1021 for ($i = 0; $i <= $m_ctr; $i++
) {
1023 if ($item["media"]["content#$i@url"]) {
1024 $e_item = array($item["media"]["content#$i@url"],
1025 $item["media"]["content#$i@medium"],
1026 $item["media"]["content#$i@length"]);
1027 array_push($enclosures, $e_item);
1036 $entry_content = sanitize_article_content($entry_content);
1037 $entry_title = sanitize_article_content($entry_title);
1039 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1040 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1043 db_query($link, "BEGIN");
1045 if (db_num_rows($result) == 0) {
1047 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1048 _debug("update_rss_feed: base guid not found");
1051 // base post entry does not exist, create it
1053 $result = db_query($link,
1054 "INSERT INTO ttrss_entries
1070 '$entry_timestamp_fmt',
1079 // we keep encountering the entry in feeds, so we need to
1080 // update date_entered column so that we don't get horrible
1081 // dupes when the entry gets purged and reinserted again e.g.
1082 // in the case of SLOW SLOW OMG SLOW updating feeds
1084 $base_entry_id = db_fetch_result($result, 0, "id");
1086 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1087 WHERE id = '$base_entry_id'");
1090 // now it should exist, if not - bad luck then
1092 $result = db_query($link, "SELECT
1093 id,content_hash,no_orig_date,title,
1094 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1095 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1099 WHERE guid = '$entry_guid'");
1104 if (db_num_rows($result) == 1) {
1106 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1107 _debug("update_rss_feed: base guid found, checking for user record");
1110 // this will be used below in update handler
1111 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1112 $orig_title = db_fetch_result($result, 0, "title");
1113 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1114 $orig_date_entered = strtotime(db_fetch_result($result,
1115 0, "date_entered"));
1117 $ref_id = db_fetch_result($result, 0, "id");
1118 $entry_ref_id = $ref_id;
1120 // check for user post link to main table
1122 // do we allow duplicate posts with same GUID in different feeds?
1123 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1124 $dupcheck_qpart = "AND feed_id = '$feed'";
1126 $dupcheck_qpart = "";
1129 // error_reporting(0);
1131 $article_filters = get_article_filters($filters, $entry_title,
1132 $entry_content, $entry_link, $entry_timestamp);
1134 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1135 _debug("update_rss_feed: article filters: ");
1136 if (count($article_filters) != 0) {
1137 print_r($article_filters);
1141 if (find_article_filter($article_filters, "filter")) {
1142 db_query($link, "COMMIT"); // close transaction in progress
1146 // error_reporting (DEFAULT_ERROR_LEVEL);
1148 $score = calculate_article_score($article_filters);
1150 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1151 _debug("update_rss_feed: initial score: $score");
1154 $result = db_query($link,
1155 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1156 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1159 // okay it doesn't exist - create user entry
1160 if (db_num_rows($result) == 0) {
1162 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1163 _debug("update_rss_feed: user record not found, creating...");
1166 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1168 $last_read_qpart = 'NULL';
1171 $last_read_qpart = 'NOW()';
1174 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1180 if (find_article_filter($article_filters, 'publish')) {
1181 $published = 'true';
1183 $published = 'false';
1186 $result = db_query($link,
1187 "INSERT INTO ttrss_user_entries
1188 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1190 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1191 $last_read_qpart, $marked, $published, '$score')");
1193 $result = db_query($link,
1194 "SELECT int_id FROM ttrss_user_entries WHERE
1195 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1196 feed_id = '$feed' LIMIT 1");
1198 if (db_num_rows($result) == 1) {
1199 $entry_int_id = db_fetch_result($result, 0, "int_id");
1202 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1203 $entry_int_id = db_fetch_result($result, 0, "int_id");
1206 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1207 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1210 $post_needs_update = false;
1212 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1213 ($content_hash != $orig_content_hash)) {
1214 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1215 $post_needs_update = true;
1218 if (db_escape_string($orig_title) != $entry_title) {
1219 $post_needs_update = true;
1222 if ($orig_num_comments != $num_comments) {
1223 $post_needs_update = true;
1226 // this doesn't seem to be very reliable
1228 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1229 // $post_needs_update = true;
1232 // if post needs update, update it and mark all user entries
1233 // linking to this post as updated
1234 if ($post_needs_update) {
1236 if (defined('DAEMON_EXTENDED_DEBUG')) {
1237 _debug("update_rss_feed: post $entry_guid needs update...");
1240 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1242 db_query($link, "UPDATE ttrss_entries
1243 SET title = '$entry_title', content = '$entry_content',
1244 content_hash = '$content_hash',
1245 num_comments = '$num_comments'
1246 WHERE id = '$ref_id'");
1248 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1249 db_query($link, "UPDATE ttrss_user_entries
1250 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1252 db_query($link, "UPDATE ttrss_user_entries
1253 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1259 db_query($link, "COMMIT");
1261 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1262 _debug("update_rss_feed: assigning labels...");
1265 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1268 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1269 _debug("update_rss_feed: looking for enclosures...");
1272 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1273 print_r($enclosures);
1276 db_query($link, "BEGIN");
1278 foreach ($enclosures as $enc) {
1279 $enc_url = db_escape_string($enc[0]);
1280 $enc_type = db_escape_string($enc[1]);
1281 $enc_dur = db_escape_string($enc[2]);
1283 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1284 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1286 if (db_num_rows($result) == 0) {
1287 db_query($link, "INSERT INTO ttrss_enclosures
1288 (content_url, content_type, title, duration, post_id) VALUES
1289 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1293 db_query($link, "COMMIT");
1295 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1296 _debug("update_rss_feed: looking for tags...");
1300 // <a href="..." rel="tag">Xorg</a>, //
1304 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1305 $entry_content_unescaped, $entry_tags);
1307 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1308 print_r($entry_tags);
1309 print "<br/></p>"; */
1311 $entry_tags = $entry_tags[1];
1313 # check for manual tags
1315 $tag_filter = find_article_filter($article_filters, "tag");
1319 $manual_tags = trim_array(split(",", $tag_filter[1]));
1321 foreach ($manual_tags as $tag) {
1322 if (tag_is_valid($tag)) {
1323 array_push($entry_tags, $tag);
1328 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1329 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1331 if ($additional_tags && is_array($additional_tags)) {
1332 foreach ($additional_tags as $tag) {
1333 if (tag_is_valid($tag) &&
1334 array_search($tag, $boring_tags) === FALSE) {
1335 array_push($entry_tags, $tag);
1340 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1342 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1343 print_r($entry_tags);
1346 if (count($entry_tags) > 0) {
1348 db_query($link, "BEGIN");
1350 foreach ($entry_tags as $tag) {
1352 $tag = sanitize_tag($tag);
1353 $tag = db_escape_string($tag);
1355 if (!tag_is_valid($tag)) continue;
1357 $result = db_query($link, "SELECT id FROM ttrss_tags
1358 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1359 owner_uid = '$owner_uid' LIMIT 1");
1361 // print db_fetch_result($result, 0, "id");
1363 if ($result && db_num_rows($result) == 0) {
1365 db_query($link, "INSERT INTO ttrss_tags
1366 (owner_uid,tag_name,post_int_id)
1367 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1371 db_query($link, "COMMIT");
1374 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1375 _debug("update_rss_feed: article processed");
1379 if (!$last_updated) {
1380 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1381 _debug("update_rss_feed: new feed, catching it up...");
1383 catchup_feed($link, $feed, false);
1387 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1388 _debug("update_rss_feed: updating counters cache...");
1391 // disabled, purge_feed() does that...
1392 //ccache_update($link, $feed, $owner_uid);
1395 purge_feed($link, $feed, 0);
1397 db_query($link, "UPDATE ttrss_feeds
1398 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1400 // db_query($link, "COMMIT");
1404 if ($use_simplepie) {
1405 $error_msg = mb_substr($rss->error(), 0, 250);
1407 $error_msg = mb_substr(magpie_error(), 0, 250);
1410 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1411 _debug("update_rss_feed: error fetching feed: $error_msg");
1414 $error_msg = db_escape_string($error_msg);
1417 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1418 last_updated = NOW() WHERE id = '$feed'");
1421 if ($use_simplepie) {
1425 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1426 _debug("update_rss_feed: done");
1431 function print_select($id, $default, $values, $attributes = "") {
1432 print "<select name=\"$id\" id=\"$id\" $attributes>";
1433 foreach ($values as $v) {
1439 print "<option$sel>$v</option>";
1444 function print_select_hash($id, $default, $values, $attributes = "") {
1445 print "<select name=\"$id\" id='$id' $attributes>";
1446 foreach (array_keys($values) as $v) {
1448 $sel = 'selected="selected"';
1452 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1458 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1461 if ($filters["title"]) {
1462 foreach ($filters["title"] as $filter) {
1463 $reg_exp = $filter["reg_exp"];
1464 $inverse = $filter["inverse"];
1465 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1466 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1468 array_push($matches, array($filter["action"], $filter["action_param"]));
1473 if ($filters["content"]) {
1474 foreach ($filters["content"] as $filter) {
1475 $reg_exp = $filter["reg_exp"];
1476 $inverse = $filter["inverse"];
1478 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1479 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1481 array_push($matches, array($filter["action"], $filter["action_param"]));
1486 if ($filters["both"]) {
1487 foreach ($filters["both"] as $filter) {
1488 $reg_exp = $filter["reg_exp"];
1489 $inverse = $filter["inverse"];
1492 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1493 array_push($matches, array($filter["action"], $filter["action_param"]));
1496 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1497 array_push($matches, array($filter["action"], $filter["action_param"]));
1503 if ($filters["link"]) {
1504 $reg_exp = $filter["reg_exp"];
1505 foreach ($filters["link"] as $filter) {
1506 $reg_exp = $filter["reg_exp"];
1507 $inverse = $filter["inverse"];
1509 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1510 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1512 array_push($matches, array($filter["action"], $filter["action_param"]));
1517 if ($filters["date"]) {
1518 $reg_exp = $filter["reg_exp"];
1519 foreach ($filters["date"] as $filter) {
1520 $date_modifier = $filter["filter_param"];
1521 $inverse = $filter["inverse"];
1522 $check_timestamp = strtotime($filter["reg_exp"]);
1524 # no-op when timestamp doesn't parse to prevent misfires
1526 if ($check_timestamp) {
1529 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1530 $date_modifier == "after" && $timestamp > $check_timestamp) {
1534 if ($inverse) $match_ok = !$match_ok;
1537 array_push($matches, array($filter["action"], $filter["action_param"]));
1546 function find_article_filter($filters, $filter_name) {
1547 foreach ($filters as $f) {
1548 if ($f[0] == $filter_name) {
1555 function calculate_article_score($filters) {
1558 foreach ($filters as $f) {
1559 if ($f[0] == "score") {
1566 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1567 foreach ($filters as $f) {
1568 if ($f[0] == "label") {
1569 label_add_article($link, $id, $f[1], $owner_uid);
1574 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1575 $rtl_content = false, $last_updated = false, $last_error = false) {
1577 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1578 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1580 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1584 $rtl_tag = "dir=\"rtl\"";
1586 $rtl_tag = "dir=\"ltr\"";
1589 $error_notify_msg = "";
1592 $link_title = "Error: $last_error ($last_updated)";
1593 $error_notify_msg = "(Error)";
1594 } else if ($last_updated) {
1595 $link_title = "Updated: $last_updated";
1598 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1599 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1601 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1602 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1606 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1609 $fctr_class = "class=\"feedCtrHasUnread\"";
1611 $fctr_class = "class=\"feedCtrNoUnread\"";
1614 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1615 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1617 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1618 $total = getFeedArticles($link, $feed_id);
1619 print "<div class=\"feedExtInfo\">
1620 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1627 function getmicrotime() {
1628 list($usec, $sec) = explode(" ",microtime());
1629 return ((float)$usec +
(float)$sec);
1632 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1633 foreach ($values as $v) {
1640 if ($v == $true_is) {
1641 $sel .= " value=\"1\"";
1643 $sel .= " value=\"0\"";
1646 print "<input class=\"noborder\"
1647 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1652 function initialize_user_prefs($link, $uid) {
1654 $uid = db_escape_string($uid);
1656 db_query($link, "BEGIN");
1658 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1660 $u_result = db_query($link, "SELECT pref_name
1661 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1663 $active_prefs = array();
1665 while ($line = db_fetch_assoc($u_result)) {
1666 array_push($active_prefs, $line["pref_name"]);
1669 while ($line = db_fetch_assoc($result)) {
1670 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1671 // print "adding " . $line["pref_name"] . "<br>";
1673 db_query($link, "INSERT INTO ttrss_user_prefs
1674 (owner_uid,pref_name,value) VALUES
1675 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1680 db_query($link, "COMMIT");
1684 function lookup_user_id($link, $user) {
1686 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1689 if (db_num_rows($result) == 1) {
1690 return db_fetch_result($result, 0, "id");
1696 function http_authenticate_user($link) {
1698 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1700 if (!$_SERVER["PHP_AUTH_USER"]) {
1702 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1703 header('HTTP/1.0 401 Unauthorized');
1707 $auth_result = authenticate_user($link,
1708 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1710 if (!$auth_result) {
1711 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1712 header('HTTP/1.0 401 Unauthorized');
1720 function authenticate_user($link, $login, $password, $force_auth = false) {
1722 if (!SINGLE_USER_MODE
) {
1724 $pwd_hash1 = encrypt_password($password);
1725 $pwd_hash2 = encrypt_password($password, $login);
1727 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1728 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1730 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1732 $query = "SELECT id,login,access_level,pwd_hash
1733 FROM ttrss_users WHERE
1737 $query = "SELECT id,login,access_level,pwd_hash
1738 FROM ttrss_users WHERE
1739 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1740 pwd_hash = '$pwd_hash2')";
1743 $result = db_query($link, $query);
1745 if (db_num_rows($result) == 1) {
1746 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1747 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1748 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1750 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1753 $user_theme = get_user_theme_path($link);
1755 $_SESSION["theme"] = $user_theme;
1756 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1757 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1759 initialize_user_prefs($link, $_SESSION["uid"]);
1768 $_SESSION["uid"] = 1;
1769 $_SESSION["name"] = "admin";
1771 $user_theme = get_user_theme_path($link);
1773 $_SESSION["theme"] = $user_theme;
1774 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1776 initialize_user_prefs($link, $_SESSION["uid"]);
1782 function make_password($length = 8) {
1785 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1789 while ($i < $length) {
1790 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1792 if (!strstr($password, $char)) {
1800 // this is called after user is created to initialize default feeds, labels
1803 // user preferences are checked on every login, not here
1805 function initialize_user($link, $uid) {
1807 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1808 VALUES ('$uid', 'All Articles')");
1810 db_query($link, "INSERT INTO ttrss_filters
1811 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1812 action_id, action_param, filter_param)
1813 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1815 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1816 values ('$uid', 'Tiny Tiny RSS: New Releases',
1817 'http://tt-rss.org/releases.rss')");
1819 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1820 values ('$uid', 'Tiny Tiny RSS: Forum',
1821 'http://tt-rss.org/forum/rss.php')");
1824 function logout_user() {
1826 if (isset($_COOKIE[session_name()])) {
1827 setcookie(session_name(), '', time()-42000, '/');
1831 function get_script_urlpath() {
1832 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1835 function validate_session($link) {
1836 if (SINGLE_USER_MODE
) {
1840 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1841 if ($_SESSION["ip_address"]) {
1842 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1843 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1849 if ($_SESSION["uid"]) {
1851 $result = db_query($link,
1852 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1854 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1856 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1861 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1863 //print_r($_SESSION);
1865 if (time() > $_SESSION["cookie_lifetime"]) {
1873 function login_sequence($link, $mobile = false) {
1874 if (!SINGLE_USER_MODE
) {
1876 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1877 $swu = db_escape_string($_REQUEST["swu"]);
1879 $_SESSION["prefs_cache"] = false;
1880 return authenticate_user($link, $swu, null, true);
1884 $login_action = $_POST["login_action"];
1886 # try to authenticate user if called from login form
1887 if ($login_action == "do_login") {
1888 $login = $_POST["login"];
1889 $password = $_POST["password"];
1890 $remember_me = $_POST["remember_me"];
1892 if (authenticate_user($link, $login, $password)) {
1893 $_POST["password"] = "";
1895 $_SESSION["language"] = $_POST["language"];
1896 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1898 header("Location: " . $_SERVER["REQUEST_URI"]);
1903 $_SESSION["login_error_msg"] = "Incorrect username or password";
1907 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1908 render_login_form($link, $mobile);
1911 /* bump login timestamp */
1912 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1915 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1916 setcookie("ttrss_lang", $_SESSION["language"],
1917 time() + SESSION_COOKIE_LIFETIME
);
1920 /* bump counters stamp since we're getting reloaded anyway */
1922 $_SESSION["get_all_counters_stamp"] = time();
1926 return authenticate_user($link, "admin", null);
1930 function truncate_string($str, $max_len) {
1931 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1932 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1938 function get_user_theme_path($link) {
1939 $result = db_query($link, "SELECT theme_path
1941 ttrss_themes,ttrss_users
1942 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1943 if (db_num_rows($result) != 0) {
1944 return db_fetch_result($result, 0, "theme_path");
1950 function smart_date_time($timestamp) {
1951 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1952 return date("G:i", $timestamp);
1953 } else if (date("Y", $timestamp) == date("Y")) {
1954 return date("M d, G:i", $timestamp);
1956 return date("Y/m/d, G:i", $timestamp);
1960 function smart_date($timestamp) {
1961 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1963 } else if (date("Y", $timestamp) == date("Y")) {
1964 return date("D m", $timestamp);
1966 return date("Y/m/d", $timestamp);
1970 function sql_bool_to_string($s) {
1971 if ($s == "t" ||
$s == "1") {
1978 function sql_bool_to_bool($s) {
1979 if ($s == "t" ||
$s == "1") {
1987 function toggleEvenOdd($a) {
1994 function sanity_check($link) {
1999 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2000 $schema_version = db_fetch_result($result, 0, "schema_version");
2002 if ($schema_version != SCHEMA_VERSION
) {
2006 if (DB_TYPE
== "mysql") {
2007 $result = db_query($link, "SELECT true", false);
2008 if (db_num_rows($result) != 1) {
2013 if (db_escape_string("testTEST") != "testTEST") {
2017 error_reporting (DEFAULT_ERROR_LEVEL
);
2019 if ($error_code != 0) {
2020 print_error_xml($error_code);
2027 function file_is_locked($filename) {
2028 if (function_exists('flock')) {
2030 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2031 error_reporting(DEFAULT_ERROR_LEVEL
);
2033 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2034 flock($fp, LOCK_UN
);
2044 return true; // consider the file always locked and skip the test
2047 function make_lockfile($filename) {
2048 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2050 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2057 function make_stampfile($filename) {
2058 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2060 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2061 fwrite($fp, time() . "\n");
2062 flock($fp, LOCK_UN
);
2070 function read_stampfile($filename) {
2073 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2074 error_reporting (DEFAULT_ERROR_LEVEL
);
2077 if (flock($fp, LOCK_EX
)) {
2078 $stamp = fgets($fp);
2079 flock($fp, LOCK_UN
);
2090 function sql_random_function() {
2091 if (DB_TYPE
== "mysql") {
2098 function catchup_feed($link, $feed, $cat_view) {
2100 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2105 $cat_qpart = "cat_id = '$feed'";
2107 $cat_qpart = "cat_id IS NULL";
2110 $tmp_result = db_query($link, "SELECT id
2111 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2114 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2116 $tmp_feed = $tmp_line["id"];
2118 db_query($link, "UPDATE ttrss_user_entries
2119 SET unread = false,last_read = NOW()
2120 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2123 } else if ($feed > 0) {
2125 $tmp_result = db_query($link, "SELECT id
2126 FROM ttrss_feeds WHERE parent_feed = '$feed'
2127 ORDER BY cat_id,title");
2129 $parent_ids = array();
2131 if (db_num_rows($tmp_result) > 0) {
2132 while ($p = db_fetch_assoc($tmp_result)) {
2133 array_push($parent_ids, "feed_id = " . $p["id"]);
2136 $children_qpart = implode(" OR ", $parent_ids);
2138 db_query($link, "UPDATE ttrss_user_entries
2139 SET unread = false,last_read = NOW()
2140 WHERE (feed_id = '$feed' OR $children_qpart)
2141 AND owner_uid = " . $_SESSION["uid"]);
2144 db_query($link, "UPDATE ttrss_user_entries
2145 SET unread = false,last_read = NOW()
2146 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2149 } else if ($feed < 0 && $feed > -10) { // special, like starred
2152 db_query($link, "UPDATE ttrss_user_entries
2153 SET unread = false,last_read = NOW()
2154 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2158 db_query($link, "UPDATE ttrss_user_entries
2159 SET unread = false,last_read = NOW()
2160 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2165 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2167 if (DB_TYPE
== "pgsql") {
2168 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2170 $match_part = "updated > DATE_SUB(NOW(),
2171 INTERVAL $intl HOUR) ";
2174 $result = db_query($link, "SELECT id FROM ttrss_entries,
2175 ttrss_user_entries WHERE $match_part AND
2177 ttrss_user_entries.ref_id = ttrss_entries.id AND
2178 owner_uid = ".$_SESSION["uid"]);
2180 $affected_ids = array();
2182 while ($line = db_fetch_assoc($result)) {
2183 array_push($affected_ids, $line["id"]);
2186 catchupArticlesById($link, $affected_ids, 0);
2190 db_query($link, "UPDATE ttrss_user_entries
2191 SET unread = false,last_read = NOW()
2192 WHERE owner_uid = ".$_SESSION["uid"]);
2195 } else if ($feed < -10) { // label
2197 $label_id = -$feed - 11;
2199 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2200 SET unread = false WHERE label_id = '$label_id' AND unread = true
2201 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2205 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2208 db_query($link, "BEGIN");
2210 $tag_name = db_escape_string($feed);
2212 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2213 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2215 while ($line = db_fetch_assoc($result)) {
2216 db_query($link, "UPDATE ttrss_user_entries SET
2217 unread = false, last_read = NOW()
2218 WHERE int_id = " . $line["post_int_id"]);
2220 db_query($link, "COMMIT");
2224 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2228 $cat_qpart = "cat_id = '$feed'";
2230 $cat_qpart = "cat_id IS NULL";
2233 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2234 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2236 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2237 $feed_url = $tmp_line["feed_url"];
2238 $feed_id = $tmp_line["id"];
2239 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2243 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2244 WHERE id = '$feed'");
2245 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2246 update_rss_feed($link, $feed_url, $feed, $force_update);
2250 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2252 if (!$omode) $omode = "flc";
2254 getGlobalCounters($link);
2256 if (strchr($omode, "l")) getLabelCounters($link);
2257 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2258 if (strchr($omode, "t")) getTagCounters($link);
2259 if (strchr($omode, "c")) {
2260 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2261 getCategoryCounters($link);
2266 function getCategoryCounters($link) {
2267 # two special categories are -1 and -2 (all virtuals; all labels)
2269 /* $ctr = getCategoryUnread($link, -1);
2271 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2273 $ctr = getCategoryUnread($link, -2);
2275 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2277 $age_qpart = getMaxAgeSubquery();
2279 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2280 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2281 WHERE ttrss_cat_counters_cache.feed_id = id AND
2282 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2284 while ($line = db_fetch_assoc($result)) {
2285 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2287 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2288 $line["unread"]."\"/>";
2291 /* Special case: NULL category doesn't actually exist in the DB */
2293 print "<counter type=\"category\" id=\"0\" counter=\"".
2294 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2298 function getCategoryUnread($link, $cat, $owner_uid = false) {
2300 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2305 $cat_query = "cat_id = '$cat'";
2307 $cat_query = "cat_id IS NULL";
2310 $age_qpart = getMaxAgeSubquery();
2312 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2314 AND owner_uid = " . $owner_uid);
2316 $cat_feeds = array();
2317 while ($line = db_fetch_assoc($result)) {
2318 array_push($cat_feeds, "feed_id = " . $line["id"]);
2321 if (count($cat_feeds) == 0) return 0;
2323 $match_part = implode(" OR ", $cat_feeds);
2325 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2326 FROM ttrss_user_entries,ttrss_entries
2327 WHERE unread = true AND ($match_part) AND id = ref_id
2328 AND $age_qpart AND owner_uid = " . $owner_uid);
2332 # this needs to be rewritten
2333 while ($line = db_fetch_assoc($result)) {
2334 $unread +
= $line["unread"];
2338 } else if ($cat == -1) {
2339 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2340 } else if ($cat == -2) {
2342 $result = db_query($link, "
2343 SELECT COUNT(unread) AS unread FROM
2344 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2345 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2346 ttrss_labels2.owner_uid = '$owner_uid'
2347 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2348 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2350 $unread = db_fetch_result($result, 0, "unread");
2357 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2358 if (DB_TYPE
== "pgsql") {
2359 return "ttrss_entries.date_entered >
2360 NOW() - INTERVAL '$days days'";
2362 return "ttrss_entries.date_entered >
2363 DATE_SUB(NOW(), INTERVAL $days DAY)";
2367 function getFeedUnread($link, $feed, $is_cat = false) {
2368 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2371 function getLabelUnread($link, $label_id, $owner_uid = false) {
2372 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2374 $result = db_query($link, "
2375 SELECT COUNT(unread) AS unread FROM
2376 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2377 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2378 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2379 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2380 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2382 if (db_num_rows($result) != 0) {
2383 return db_fetch_result($result, 0, "unread");
2389 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2390 $owner_uid = false) {
2392 $n_feed = sprintf("%d", $feed);
2394 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2397 $unread_qpart = "unread = true";
2399 $unread_qpart = "true";
2402 $age_qpart = getMaxAgeSubquery();
2405 return getCategoryUnread($link, $n_feed, $owner_uid);
2406 } else if ($n_feed == -1) {
2407 $match_part = "marked = true";
2408 } else if ($n_feed == -2) {
2409 $match_part = "published = true";
2410 } else if ($n_feed == -3) {
2411 $match_part = "unread = true";
2413 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2415 if (DB_TYPE
== "pgsql") {
2416 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2418 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2420 } else if ($n_feed == -4) {
2421 $match_part = "true";
2422 } else if ($n_feed > 0) {
2424 $result = db_query($link, "SELECT id FROM ttrss_feeds
2425 WHERE parent_feed = '$n_feed'
2427 AND owner_uid = " . $owner_uid);
2429 if (db_num_rows($result) > 0) {
2431 $linked_feeds = array();
2432 while ($line = db_fetch_assoc($result)) {
2433 array_push($linked_feeds, "feed_id = " . $line["id"]);
2436 array_push($linked_feeds, "feed_id = $n_feed");
2438 $match_part = implode(" OR ", $linked_feeds);
2440 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2441 FROM ttrss_user_entries,ttrss_entries
2442 WHERE $unread_qpart AND
2443 ttrss_user_entries.ref_id = ttrss_entries.id AND
2446 owner_uid = " . $owner_uid);
2450 # this needs to be rewritten
2451 while ($line = db_fetch_assoc($result)) {
2452 $unread +
= $line["unread"];
2458 $match_part = "feed_id = '$n_feed'";
2460 } else if ($feed < -10) {
2462 $label_id = -$feed - 11;
2464 return getLabelUnread($link, $label_id, $owner_uid);
2470 $result = db_query($link, "SELECT count(int_id) AS unread
2471 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2472 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2473 ttrss_user_entries.ref_id = ttrss_entries.id AND
2474 ttrss_feeds.hidden = false AND
2476 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2480 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2481 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2482 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2483 AND $unread_qpart AND $age_qpart AND
2484 ttrss_tags.owner_uid = " . $owner_uid);
2487 $unread = db_fetch_result($result, 0, "unread");
2492 function getGlobalUnread($link, $user_id = false) {
2495 $user_id = $_SESSION["uid"];
2498 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2499 WHERE owner_uid = '$user_id' AND feed_id > 0");
2501 $c_id = db_fetch_result($result, 0, "c_id");
2506 function getGlobalCounters($link, $global_unread = -1) {
2507 if ($global_unread == -1) {
2508 $global_unread = getGlobalUnread($link);
2510 print "<counter type=\"global\" id='global-unread'
2511 counter='$global_unread'/>";
2513 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2514 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2516 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2518 print "<counter type=\"global\" id='subscribed-feeds'
2519 counter='$subscribed_feeds'/>";
2523 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2526 if (!$_SESSION["tctr_last_value"]) {
2527 $_SESSION["tctr_last_value"] = array();
2531 $old_counters = $_SESSION["tctr_last_value"];
2533 $tctrs_modified = false;
2535 $age_qpart = getMaxAgeSubquery();
2537 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2538 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2539 AND ref_id = id AND $age_qpart
2540 AND unread = true)) AS count FROM ttrss_tags
2541 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2542 ORDER BY count DESC LIMIT 55");
2546 while ($line = db_fetch_assoc($result)) {
2547 $tags[$line["tag_name"]] +
= $line["count"];
2550 foreach (array_keys($tags) as $tag) {
2551 $unread = $tags[$tag];
2553 $tag = htmlspecialchars($tag);
2555 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2556 $old_counters[$tag] = $unread;
2557 $tctrs_modified = true;
2558 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2563 if ($smart_mode && $tctrs_modified) {
2564 $_SESSION["tctr_last_value"] = $old_counters;
2569 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2571 $age_qpart = getMaxAgeSubquery();
2574 if (!$_SESSION["lctr_last_value"]) {
2575 $_SESSION["lctr_last_value"] = array();
2581 for ($i = -1; $i >= -4; $i--) {
2583 $count = getFeedUnread($link, $i);
2587 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2588 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2593 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2595 $ret_arr[$i]["counter"] = $count;
2596 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2601 $old_counters = $_SESSION["lctr_last_value"];
2602 $lctrs_modified = false;
2605 $owner_uid = $_SESSION["uid"];
2607 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2608 WHERE owner_uid = '$owner_uid'");
2610 while ($line = db_fetch_assoc($result)) {
2612 $id = -$line["id"] - 11;
2614 $label_name = $line["caption"];
2615 $count = getFeedUnread($link, $id);
2617 if (!$smart_mode ||
$old_counters[$id] != $count) {
2618 $old_counters[$id] = $count;
2619 $lctrs_modified = true;
2622 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2623 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2628 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2630 $ret_arr[$id]["counter"] = $count;
2631 $ret_arr[$id]["description"] = $label_name;
2635 error_reporting (DEFAULT_ERROR_LEVEL
);
2638 if ($smart_mode && $lctrs_modified) {
2639 $_SESSION["lctr_last_value"] = $old_counters;
2645 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2647 $age_qpart = getMaxAgeSubquery();
2650 if (!$_SESSION["fctr_last_value"]) {
2651 $_SESSION["fctr_last_value"] = array();
2655 $old_counters = $_SESSION["fctr_last_value"];
2657 $query = "SELECT ttrss_feeds.id,
2659 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2660 last_error, value AS count
2661 FROM ttrss_feeds, ttrss_counters_cache
2662 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2663 AND parent_feed IS NULL
2664 AND ttrss_counters_cache.feed_id = id";
2666 $result = db_query($link, $query);
2667 $fctrs_modified = false;
2669 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2671 while ($line = db_fetch_assoc($result)) {
2674 $count = $line["count"];
2675 $last_error = htmlspecialchars($line["last_error"]);
2677 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2678 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2680 $last_updated = date($short_date, strtotime($line["last_updated"]));
2683 $last_updated = htmlspecialchars($last_updated);
2685 $has_img = feed_has_icon($id);
2687 $tmp_result = db_query($link,
2688 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2689 WHERE parent_feed = '$id' AND feed_id = id");
2691 $count +
= db_fetch_result($tmp_result, 0, "unread");
2693 if (!$smart_mode ||
$old_counters[$id] != $count) {
2694 $old_counters[$id] = $count;
2695 $fctrs_modified = true;
2698 $error_part = "error=\"$last_error\"";
2704 $has_img_part = "hi=\"$has_img\"";
2709 if ($active_feed && $id == $active_feed) {
2710 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2712 $has_title_part = "";
2715 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2716 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2719 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2723 if ($smart_mode && $fctrs_modified) {
2724 $_SESSION["fctr_last_value"] = $old_counters;
2728 function get_script_dt_add() {
2729 if (strpos(VERSION
, ".99") === false) {
2736 function get_pgsql_version($link) {
2737 $result = db_query($link, "SELECT version() AS version");
2738 $version = split(" ", db_fetch_result($result, 0, "version"));
2742 function print_error_xml($code, $add_msg = "") {
2745 $error_msg = $ERRORS[$code];
2748 $error_msg = "$error_msg; $add_msg";
2751 print "<rpc-reply>";
2752 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2753 print "</rpc-reply>";
2756 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2757 $auth_login = '', $auth_pass = '') {
2759 # check for feed:http://url
2760 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2762 # check for feed://URL
2763 if (strpos($feed_link, "//") === 0) {
2764 $feed_link = "http:$feed_link";
2767 if ($feed_link == "") return;
2769 if ($cat_id == "0" ||
!$cat_id) {
2770 $cat_qpart = "NULL";
2772 $cat_qpart = "'$cat_id'";
2775 $result = db_query($link,
2776 "SELECT id FROM ttrss_feeds
2777 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2779 if (db_num_rows($result) == 0) {
2781 $result = db_query($link,
2782 "INSERT INTO ttrss_feeds
2783 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2784 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2785 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2787 $result = db_query($link,
2788 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2789 AND owner_uid = " . $_SESSION["uid"]);
2791 $feed_id = db_fetch_result($result, 0, "id");
2794 update_rss_feed($link, $feed_link, $feed_id, true);
2803 function print_feed_select($link, $id, $default_id = "",
2804 $attributes = "", $include_all_feeds = true) {
2806 print "<select id=\"$id\" name=\"$id\" $attributes>";
2807 if ($include_all_feeds) {
2808 print "<option value=\"0\">".__('All feeds')."</option>";
2811 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2812 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2814 if (db_num_rows($result) > 0 && $include_all_feeds) {
2815 print "<option disabled>--------</option>";
2818 while ($line = db_fetch_assoc($result)) {
2819 if ($line["id"] == $default_id) {
2820 $is_selected = "selected";
2824 printf("<option $is_selected value='%d'>%s</option>",
2825 $line["id"], htmlspecialchars($line["title"]));
2831 function print_feed_cat_select($link, $id, $default_id = "",
2832 $attributes = "", $include_all_cats = true) {
2834 print "<select id=\"$id\" name=\"$id\" $attributes>";
2836 if ($include_all_cats) {
2837 print "<option value=\"0\">".__('Uncategorized')."</option>";
2840 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2841 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2843 if (db_num_rows($result) > 0 && $include_all_cats) {
2844 print "<option disabled>--------</option>";
2847 while ($line = db_fetch_assoc($result)) {
2848 if ($line["id"] == $default_id) {
2849 $is_selected = "selected";
2853 printf("<option $is_selected value='%d'>%s</option>",
2854 $line["id"], htmlspecialchars($line["title"]));
2860 function checkbox_to_sql_bool($val) {
2861 return ($val == "on") ?
"true" : "false";
2864 function getFeedCatTitle($link, $id) {
2866 return __("Special");
2867 } else if ($id < -10) {
2868 return __("Labels");
2869 } else if ($id > 0) {
2870 $result = db_query($link, "SELECT ttrss_feed_categories.title
2871 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2872 cat_id = ttrss_feed_categories.id");
2873 if (db_num_rows($result) == 1) {
2874 return db_fetch_result($result, 0, "title");
2876 return __("Uncategorized");
2879 return "getFeedCatTitle($id) failed";
2884 function getFeedTitle($link, $id) {
2886 return __("Starred articles");
2887 } else if ($id == -2) {
2888 return __("Published articles");
2889 } else if ($id == -3) {
2890 return __("Fresh articles");
2891 } else if ($id == -4) {
2892 return __("All articles");
2893 } else if ($id < -10) {
2894 $label_id = -$id - 11;
2895 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2896 if (db_num_rows($result) == 1) {
2897 return db_fetch_result($result, 0, "caption");
2899 return "Unknown label ($label_id)";
2902 } else if ($id > 0) {
2903 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2904 if (db_num_rows($result) == 1) {
2905 return db_fetch_result($result, 0, "title");
2907 return "Unknown feed ($id)";
2910 return "getFeedTitle($id) failed";
2915 function get_session_cookie_name() {
2916 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2919 function print_init_params($link) {
2920 print "<init-params>";
2921 if ($_SESSION["stored-params"]) {
2922 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2924 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2925 print "<param key=\"$key\" value=\"$value\"/>";
2930 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2931 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2932 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2933 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2935 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2936 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2938 print "<param key=\"hide_read_feeds\" value=\"" .
2939 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2941 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2942 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2944 print "<param key=\"confirm_feed_catchup\" value=\"" .
2945 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2947 print "<param key=\"cdm_auto_catchup\" value=\"" .
2948 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2950 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2952 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2954 print "<param key=\"default_view_mode\" value=\"" .
2955 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2957 print "<param key=\"default_view_limit\" value=\"" .
2958 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2960 print "<param key=\"default_view_order_by\" value=\"" .
2961 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
2963 print "<param key=\"prefs_active_tab\" value=\"" .
2964 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2966 print "<param key=\"infobox_disable_overlay\" value=\"" .
2967 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2969 print "<param key=\"icons_location\" value=\"" .
2972 print "<param key=\"hide_read_shows_special\" value=\"" .
2973 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2975 print "<param key=\"hide_feedlist\" value=\"" .
2976 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
2978 print "<param key=\"bw_limit\" value=\"".
2979 (int) $_SESSION["bw_limit"]."\"/>";
2981 // print "<param key=\"sync_counters\" value=\"" .
2982 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
2984 print "<param key=\"sync_counters\" value=\"1\"/>";
2986 print "</init-params>";
2989 function print_runtime_info($link) {
2990 print "<runtime-info>";
2992 if (ENABLE_UPDATE_DAEMON
) {
2993 print "<param key=\"daemon_is_running\" value=\"".
2994 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2996 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2998 $stamp = (int)read_stampfile("update_daemon.stamp");
3000 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3003 $stamp_delta = time() - $stamp;
3005 if ($stamp_delta > 1800) {
3009 $_SESSION["daemon_stamp_check"] = time();
3012 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3014 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3016 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3021 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3023 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3024 $new_version_details = check_for_update($link);
3026 print "<param key=\"new_version_available\" value=\"".
3027 sprintf("%d", $new_version_details != ""). "\"/>";
3029 $_SESSION["last_version_check"] = time();
3033 // print "<param key=\"new_version_available\" value=\"1\"/>";
3035 print "</runtime-info>";
3038 function getSearchSql($search, $match_on) {
3040 $search_query_part = "";
3042 $keywords = split(" ", $search);
3043 $query_keywords = array();
3045 if ($match_on == "both") {
3047 foreach ($keywords as $k) {
3048 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3049 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3052 $search_query_part = implode("AND", $query_keywords) . " AND ";
3054 } else if ($match_on == "title") {
3056 foreach ($keywords as $k) {
3057 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3060 $search_query_part = implode("AND", $query_keywords) . " AND ";
3062 } else if ($match_on == "content") {
3064 foreach ($keywords as $k) {
3065 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3069 $search_query_part = implode("AND", $query_keywords);
3071 return $search_query_part;
3074 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3076 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3080 $search_query_part = getSearchSql($search, $match_on);
3081 $search_query_part .= " AND ";
3084 $search_query_part = "";
3087 $view_query_part = "";
3089 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3091 $view_query_part = " ";
3092 } else if ($feed != -1) {
3093 $unread = getFeedUnread($link, $feed, $cat_view);
3095 $view_query_part = " unread = true AND ";
3100 if ($view_mode == "marked") {
3101 $view_query_part = " marked = true AND ";
3104 if ($view_mode == "unread") {
3105 $view_query_part = " unread = true AND ";
3108 if ($view_mode == "updated") {
3109 $view_query_part = " (last_read is null and unread = false) AND ";
3113 $limit_query_part = "LIMIT " . $limit;
3116 $vfeed_query_part = "";
3118 // override query strategy and enable feed display when searching globally
3119 if ($search && $search_mode == "all_feeds") {
3120 $query_strategy_part = "ttrss_entries.id > 0";
3121 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3122 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3123 $query_strategy_part = "ttrss_entries.id > 0";
3124 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3125 id = feed_id) as feed_title,";
3126 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3128 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3130 $tmp_result = false;
3133 $tmp_result = db_query($link, "SELECT id
3134 FROM ttrss_feeds WHERE cat_id = '$feed'");
3136 $tmp_result = db_query($link, "SELECT id
3137 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3138 WHERE id = '$feed') AND id != '$feed'");
3141 $cat_siblings = array();
3143 if (db_num_rows($tmp_result) > 0) {
3144 while ($p = db_fetch_assoc($tmp_result)) {
3145 array_push($cat_siblings, "feed_id = " . $p["id"]);
3148 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3149 $feed, implode(" OR ", $cat_siblings));
3152 $query_strategy_part = "ttrss_entries.id > 0";
3155 } else if ($feed >= 0) {
3160 $query_strategy_part = "cat_id = '$feed'";
3162 $query_strategy_part = "cat_id IS NULL";
3165 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3168 $tmp_result = db_query($link, "SELECT id
3169 FROM ttrss_feeds WHERE parent_feed = '$feed'
3170 ORDER BY cat_id,title");
3172 $parent_ids = array();
3174 if (db_num_rows($tmp_result) > 0) {
3175 while ($p = db_fetch_assoc($tmp_result)) {
3176 array_push($parent_ids, "feed_id = " . $p["id"]);
3179 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3180 $feed, implode(" OR ", $parent_ids));
3182 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3184 $query_strategy_part = "feed_id = '$feed'";
3187 } else if ($feed == -1) { // starred virtual feed
3188 $query_strategy_part = "marked = true";
3189 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3190 } else if ($feed == -2) { // published virtual feed OR labels category
3193 $query_strategy_part = "published = true";
3194 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3196 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3198 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3200 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3201 ttrss_user_labels2.article_id = ref_id";
3205 } else if ($feed == -3) { // fresh virtual feed
3206 $query_strategy_part = "unread = true";
3208 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3210 if (DB_TYPE
== "pgsql") {
3211 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3213 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3216 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3217 } else if ($feed == -4) { // all articles virtual feed
3218 $query_strategy_part = "true";
3219 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3220 } else if ($feed <= -10) { // labels
3221 $label_id = -$feed - 11;
3223 $query_strategy_part = "label_id = '$label_id' AND
3224 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3225 ttrss_user_labels2.article_id = ref_id";
3227 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3228 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3231 $query_strategy_part = "id > 0"; // dumb
3234 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3235 $order_by = "updated";
3237 $order_by = "updated DESC";
3240 if ($view_mode != "noscores") {
3241 $order_by = "score DESC, $order_by";
3244 if ($override_order) {
3245 $order_by = $override_order;
3250 if ($search && $search_mode == "all_feeds") {
3251 $feed_title = __("Search results")." ($search)";
3252 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3253 $feed_title = __("Search results")." ($search, $feed)";
3254 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3255 $feed_title = $feed;
3256 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3261 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3262 WHERE id = '$feed' AND owner_uid = $owner_uid");
3263 $feed_title = db_fetch_result($result, 0, "title");
3265 $feed_title = __("Uncategorized");
3269 $feed_title = __("Searched for")." $search ($feed_title)";
3274 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3275 WHERE id = '$feed' AND owner_uid = $owner_uid");
3277 $feed_title = db_fetch_result($result, 0, "title");
3278 $feed_site_url = db_fetch_result($result, 0, "site_url");
3279 $last_error = db_fetch_result($result, 0, "last_error");
3282 $feed_title = __("Searched for") . " $search ($feed_title)";
3286 } else if ($feed == -1) {
3287 $feed_title = __("Starred articles");
3288 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3289 } else if ($feed == -2) {
3291 $feed_title = __("Published articles");
3292 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3294 $feed_title = __("Labels");
3296 } else if ($feed == -3) {
3297 $feed_title = __("Fresh articles");
3298 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3299 } else if ($feed == -4) {
3300 $feed_title = __("All articles");
3301 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3302 } else if ($feed < -10) {
3303 $label_id = -$feed - 11;
3304 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3305 WHERE id = '$label_id'");
3306 $feed_title = db_fetch_result($result, 0, "caption");
3309 $feed_title = __("Searched for") . " $search ($feed_title)";
3315 if ($feed < -10) error_reporting (0);
3317 $content_query_part = "content as content_preview,";
3319 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3322 $feed_kind = "Feeds";
3324 $feed_kind = "Labels";
3327 if ($limit_query_part) {
3328 $offset_query_part = "OFFSET $offset";
3331 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3332 if (!$override_order) {
3333 $order_by = "ttrss_feeds.title, $order_by";
3336 // Special output for Fresh feed
3338 /* if ($feed == -3) {
3339 $group_limit_part = "(select count(*) from
3340 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3341 t1.ref_id = t2.id and t1.owner_uid = 2 and
3342 t1.feed_id = ttrss_user_entries.feed_id and
3343 t2.updated > ttrss_entries.updated) <= 5 AND";
3347 $query = "SELECT DISTINCT
3349 ttrss_entries.id,ttrss_entries.title,
3351 unread,feed_id,marked,published,link,last_read,
3352 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3355 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3358 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3361 ttrss_feeds.hidden = false AND
3362 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3363 ttrss_user_entries.ref_id = ttrss_entries.id AND
3364 ttrss_user_entries.owner_uid = '$owner_uid' AND
3367 $query_strategy_part ORDER BY $order_by
3368 $limit_query_part $offset_query_part";
3370 if ($_GET["debug"]) print $query;
3372 $result = db_query($link, $query);
3377 $feed_kind = "Tags";
3379 $result = db_query($link, "SELECT
3381 ttrss_entries.id as id,title,
3384 marked,link,last_read,
3385 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3388 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3391 ttrss_entries,ttrss_user_entries,ttrss_tags
3393 ref_id = ttrss_entries.id AND
3394 ttrss_user_entries.owner_uid = '$owner_uid' AND
3395 post_int_id = int_id AND tag_name = '$feed' AND
3398 $query_strategy_part ORDER BY $order_by
3399 $limit_query_part");
3402 return array($result, $feed_title, $feed_site_url, $last_error);
3406 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3407 $limit, $search, $search_mode, $match_on) {
3409 if (!$limit) $limit = 30;
3411 $qfh_ret = queryFeedHeadlines($link, $feed,
3412 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3415 $result = $qfh_ret[0];
3416 $feed_title = htmlspecialchars($qfh_ret[1]);
3417 $feed_site_url = $qfh_ret[2];
3418 $last_error = $qfh_ret[3];
3420 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3422 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3423 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3424 <rss version=\"2.0\">
3426 <title>$feed_title</title>
3427 <link>$feed_site_url</link>
3428 <description>Feed generated by Tiny Tiny RSS</description>";
3430 while ($line = db_fetch_assoc($result)) {
3432 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3433 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3435 $tags = get_article_tags($link, $line["id"], $owner_uid);
3437 foreach ($tags as $tag) {
3438 print "<category>" . htmlspecialchars($tag) . "</category>";
3441 $rfc822_date = date('r', strtotime($line["updated"]));
3443 print "<pubDate>$rfc822_date</pubDate>";
3446 htmlspecialchars($line["title"]) . "</title>";
3448 print "<description><![CDATA[" .
3449 $line["content_preview"] . "]]></description>";
3454 print "</channel></rss>";
3458 function getCategoryTitle($link, $cat_id) {
3460 if ($cat_id == -1) {
3461 return __("Special");
3462 } else if ($cat_id == -2) {
3463 return __("Labels");
3466 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3469 if (db_num_rows($result) == 1) {
3470 return db_fetch_result($result, 0, "title");
3472 return "Uncategorized";
3477 // http://ru2.php.net/strip-tags
3479 function strip_tags_long($textstring, $allowed){
3480 while($textstring != strip_tags($textstring, $allowed))
3482 while (strlen($textstring) != 0)
3484 if (strlen($textstring) > 1024) {
3487 $otherlen = strlen($textstring);
3489 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3490 $safetext .= $temptext;
3491 $textstring = substr_replace($textstring,'',0,$otherlen);
3493 $textstring = $safetext;
3499 function sanitize_rss($link, $str, $force_strip_tags = false) {
3502 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3504 $res = strip_tags_long($res,
3505 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3507 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3508 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3511 if (get_pref($link, "STRIP_IMAGES")) {
3513 $res = preg_replace('/<img[^>]+>/is', '', $res);
3521 * Send by mail a digest of last articles.
3523 * @param mixed $link The database connection.
3524 * @param integer $limit The maximum number of articles by digest.
3525 * @return boolean Return false if digests are not enabled.
3527 function send_headlines_digests($link, $limit = 100) {
3529 if (!DIGEST_ENABLE
) return false;
3531 $user_limit = DIGEST_EMAIL_LIMIT
;
3534 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3536 if (DB_TYPE
== "pgsql") {
3537 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3538 } else if (DB_TYPE
== "mysql") {
3539 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3542 $result = db_query($link, "SELECT id,email FROM ttrss_users
3543 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3545 while ($line = db_fetch_assoc($result)) {
3547 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3548 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3550 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3552 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3553 $digest = $tuple[0];
3554 $headlines_count = $tuple[1];
3555 $affected_ids = $tuple[2];
3556 $digest_text = $tuple[3];
3558 if ($headlines_count > 0) {
3560 $mail = new PHPMailer();
3562 $mail->PluginDir
= "lib/phpmailer/";
3563 $mail->SetLanguage("en", "lib/phpmailer/language/");
3565 $mail->CharSet
= "UTF-8";
3567 $mail->From
= DIGEST_FROM_ADDRESS
;
3568 $mail->FromName
= DIGEST_FROM_NAME
;
3569 $mail->AddAddress($line["email"], $line["login"]);
3571 if (DIGEST_SMTP_HOST
) {
3572 $mail->Host
= DIGEST_SMTP_HOST
;
3573 $mail->Mailer
= "smtp";
3574 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3575 $mail->Username
= DIGEST_SMTP_LOGIN
;
3576 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3579 $mail->IsHTML(true);
3580 $mail->Subject
= DIGEST_SUBJECT
;
3581 $mail->Body
= $digest;
3582 $mail->AltBody
= $digest_text;
3584 $rc = $mail->Send();
3586 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3590 if ($rc && $do_catchup) {
3591 print "Marking affected articles as read...\n";
3592 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3595 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3596 WHERE id = " . $line["id"]);
3598 print "No headlines\n";
3603 print "All done.\n";
3607 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3609 require_once "lib/MiniTemplator.class.php";
3611 $tpl = new MiniTemplator
;
3612 $tpl_t = new MiniTemplator
;
3614 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3615 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3617 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3618 $tpl->setVariable('CUR_TIME', date('G:i'));
3620 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3621 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3623 $affected_ids = array();
3625 if (DB_TYPE
== "pgsql") {
3626 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3627 } else if (DB_TYPE
== "mysql") {
3628 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3631 $result = db_query($link, "SELECT ttrss_entries.title,
3632 ttrss_feeds.title AS feed_title,
3634 ttrss_user_entries.ref_id,
3636 SUBSTRING(content, 1, 120) AS excerpt,
3637 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3639 ttrss_user_entries,ttrss_entries,ttrss_feeds
3641 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3642 AND include_in_digest = true
3645 AND ttrss_user_entries.owner_uid = $user_id
3647 ORDER BY ttrss_feeds.title, date_entered DESC
3650 $cur_feed_title = "";
3652 $headlines_count = db_num_rows($result);
3654 $headlines = array();
3656 while ($line = db_fetch_assoc($result)) {
3657 array_push($headlines, $line);
3660 for ($i = 0; $i < sizeof($headlines); $i++
) {
3662 $line = $headlines[$i];
3664 array_push($affected_ids, $line["ref_id"]);
3666 $updated = smart_date_time(strtotime($line["last_updated"]));
3668 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3669 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3670 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3671 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3672 $tpl->setVariable('ARTICLE_EXCERPT',
3673 truncate_string(strip_tags($line["excerpt"]), 100));
3675 $tpl->addBlock('article');
3677 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3678 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3679 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3680 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3681 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3682 // truncate_string(strip_tags($line["excerpt"]), 100));
3684 $tpl_t->addBlock('article');
3686 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3687 $tpl->addBlock('feed');
3688 $tpl_t->addBlock('feed');
3693 $tpl->addBlock('digest');
3694 $tpl->generateOutputToString($tmp);
3696 $tpl_t->addBlock('digest');
3697 $tpl_t->generateOutputToString($tmp_t);
3699 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3702 function check_for_update($link) {
3703 $releases_feed = "http://tt-rss.org/releases.rss";
3705 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3710 if (ENABLE_SIMPLEPIE
) {
3711 $rss = new SimplePie();
3712 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3713 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3714 $rss->set_feed_url($fetch_url);
3715 $rss->set_output_encoding('UTF-8');
3718 $rss = fetch_rss($releases_feed);
3720 error_reporting (DEFAULT_ERROR_LEVEL
);
3724 if (ENABLE_SIMPLEPIE
) {
3725 $items = $rss->get_items();
3727 $items = $rss->items
;
3729 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3730 if (!$items ||
!is_array($items)) $items = $rss;
3733 if (!is_array($items) ||
count($items) == 0) {
3737 $latest_item = $items[0];
3739 if (ENABLE_SIMPLEPIE
) {
3740 $last_title = $latest_item->get_title();
3742 $last_title = $latest_item["title"];
3745 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3747 if (ENABLE_SIMPLEPIE
) {
3748 $release_url = sanitize_rss($link, $latest_item->get_link());
3749 $content = sanitize_rss($link, $latest_item->get_description());
3751 $release_url = sanitize_rss($link, $latest_item["link"]);
3752 $content = sanitize_rss($link, $latest_item["description"]);
3755 if (version_compare(VERSION
, $latest_version) == -1) {
3756 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3757 $latest_version)."<div class='milestoneDetails'>$content</div>";
3764 function markArticlesById($link, $ids, $cmode) {
3768 foreach ($ids as $id) {
3769 array_push($tmp_ids, "ref_id = '$id'");
3772 $ids_qpart = join(" OR ", $tmp_ids);
3775 db_query($link, "UPDATE ttrss_user_entries SET
3776 marked = false,last_read = NOW()
3777 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3778 } else if ($cmode == 1) {
3779 db_query($link, "UPDATE ttrss_user_entries SET
3781 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3783 db_query($link, "UPDATE ttrss_user_entries SET
3784 marked = NOT marked,last_read = NOW()
3785 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3789 function publishArticlesById($link, $ids, $cmode) {
3793 foreach ($ids as $id) {
3794 array_push($tmp_ids, "ref_id = '$id'");
3797 $ids_qpart = join(" OR ", $tmp_ids);
3800 db_query($link, "UPDATE ttrss_user_entries SET
3801 published = false,last_read = NOW()
3802 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3803 } else if ($cmode == 1) {
3804 db_query($link, "UPDATE ttrss_user_entries SET
3806 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3808 db_query($link, "UPDATE ttrss_user_entries SET
3809 published = NOT published,last_read = NOW()
3810 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3814 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3816 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3820 foreach ($ids as $id) {
3821 array_push($tmp_ids, "ref_id = '$id'");
3824 $ids_qpart = join(" OR ", $tmp_ids);
3827 db_query($link, "UPDATE ttrss_user_entries SET
3828 unread = false,last_read = NOW()
3829 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3830 } else if ($cmode == 1) {
3831 db_query($link, "UPDATE ttrss_user_entries SET
3833 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3835 db_query($link, "UPDATE ttrss_user_entries SET
3836 unread = NOT unread,last_read = NOW()
3837 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3842 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3843 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3845 while ($line = db_fetch_assoc($result)) {
3846 ccache_update($link, $line["feed_id"], $owner_uid);
3850 function catchupArticleById($link, $id, $cmode) {
3853 db_query($link, "UPDATE ttrss_user_entries SET
3854 unread = false,last_read = NOW()
3855 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3856 } else if ($cmode == 1) {
3857 db_query($link, "UPDATE ttrss_user_entries SET
3859 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3861 db_query($link, "UPDATE ttrss_user_entries SET
3862 unread = NOT unread,last_read = NOW()
3863 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3867 function make_guid_from_title($title) {
3868 return preg_replace("/[ \"\',.:;]/", "-",
3869 mb_strtolower(strip_tags($title), 'utf-8'));
3872 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3873 $bottom = false, $rtl_content = false, $feed_id = 0,
3874 $is_cat = false, $search = false, $match_on = false,
3875 $search_mode = false, $offset = 0, $limit = 0,
3876 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3878 $user_page_offset = $offset +
1;
3881 $class = "headlinesSubToolbar";
3882 $tid = "headlineActionsTop";
3884 $class = "headlinesSubToolbar";
3885 $tid = "headlineActionsBottom";
3888 print "<nobr><table class=\"$class\" id=\"$tid\"
3889 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3897 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3898 $page_next_link = "javascript:viewFeedGoPage(1)";
3899 $page_first_link = "javascript:viewFeedGoPage(0)";
3901 $catchup_page_link = "javascript:catchupPage()";
3902 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3903 $catchup_sel_link = "javascript:catchupSelection()";
3905 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3907 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3908 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3909 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3910 $sel_inv_link = "javascript:invertHeadlineSelection()";
3912 $tog_unread_link = "javascript:selectionToggleUnread()";
3913 $tog_marked_link = "javascript:selectionToggleMarked()";
3914 $tog_published_link = "javascript:selectionTogglePublished()";
3918 $sel_all_link = "javascript:cdmSelectArticles('all')";
3919 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3920 $sel_none_link = "javascript:cdmSelectArticles('none')";
3922 $sel_inv_link = "javascript:invertHeadlineSelection()";
3924 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3925 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3926 $tog_published_link = "javascript:selectionTogglePublished(true)";
3930 print "<td class=\"headlineActions$rtl_cpart\">";
3933 print __('Select:')."
3934 <a href=\"$sel_all_link\">".__('All')."</a>,
3935 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3936 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3937 <a href=\"$sel_none_link\">".__('None')."</a></li>";
3939 print " ";
3942 onmouseover=\"enable_selection(false)\"
3943 onmouseout=\"enable_selection(true)\"
3944 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
3945 __("Actions...") . " <img src=\"images/down_arrow.png\">
3948 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
3950 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
3951 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
3952 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
3953 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
3954 <!-- <li><span class=\"insensitive\">--------</span></li> -->
3955 <li class=\"insensitive\">".__('Mark as read:')."</li>
3956 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
3958 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
3961 //print "<li><span class=\"insensitive\">--------</span></li>";
3962 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
3964 print "<li onclick=\"javascript:addLabel()\">
3965 ".__("Create label...")."</li>";
3967 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
3968 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3970 while ($line = db_fetch_assoc($result)) {
3972 $label_id = $line["id"];
3973 $label_caption = $line["caption"];
3975 if ($feed_id < -10 && $feed_id == -11-$label_id) {
3976 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
3977 $label_caption ".__('(remove)')."</li>";
3979 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
3980 $label_caption</li>";
3987 print "<td class=\"headlineTitle$rtl_cpart\">";
3989 print "<span id=\"subtoolbar_ftitle\">";
3991 if ($feed_site_url) {
3993 $target = "target=\"_blank\"";
3995 print "<a $target href=\"$feed_site_url\">".
3996 truncate_string($feed_title,30)."</a>";
4002 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4005 if ($user_page_offset > 1) {
4006 print " [$user_page_offset] ";
4009 if (!$bottom && !$disable_feed) {
4011 <a target=\"_blank\"
4012 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4013 <img class=\"noborder\"
4014 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4016 } else if ($feed_small_icon) {
4017 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4023 print "</tr></table></nobr>";
4027 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4029 $tmp_category = getCategoryTitle($link, $cat_id);
4032 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4033 } else if ($cat_id == 0 ||
$cat_id == -2) {
4034 $cat_unread = getCategoryUnread($link, $cat_id);
4038 $holder_style = "display:none;";
4045 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4048 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4049 $inner_title_class = "catTitle";
4051 $browse_cat_link = "";
4052 $inner_title_class = "catTitleNL";
4055 $cat_class = "feedCat";
4057 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4058 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4059 title=\"".__('Click to collapse category')."\"
4060 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4061 id=\"FCATN-$cat_id\" $browse_cat_link
4062 \">$tmp_category</span>";
4064 print "<span id=\"FCAP-$cat_id\">";
4066 print " <span id=\"FCATCTR-$cat_id\"
4067 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4073 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4077 function outputFeedList($link, $tags = false) {
4079 print "<ul class=\"feedList\" id=\"feedList\">";
4081 $owner_uid = $_SESSION["uid"];
4085 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4087 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4090 $cat_hidden = false;
4093 printCategoryHeader($link, -1, $cat_hidden, false);
4096 $num_starred = getFeedUnread($link, -1);
4097 $num_published = getFeedUnread($link, -2);
4098 $num_fresh = getFeedUnread($link, -3);
4099 $num_total = getFeedUnread($link, -4);
4103 if ($num_total > 0) $class .= "Unread";
4105 printFeedEntry(-4, $class, __("All articles"), $num_total,
4106 "images/tag.png", $link);
4110 if ($num_fresh > 0) $class .= "Unread";
4112 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4113 "images/fresh.png", $link);
4117 if ($num_starred > 0) $class .= "Unread";
4119 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4122 $mark_img_ext = "gif";
4124 $mark_img_ext = "png";
4127 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4128 "images/mark_set.$mark_img_ext", $link);
4132 if ($num_published > 0) $class .= "Unread";
4134 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4135 "images/pub_set.gif", $link);
4137 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4144 $result = db_query($link, "SELECT id,caption FROM
4145 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4147 if (db_num_rows($result) > 0) {
4148 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4150 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4153 $cat_hidden = false;
4156 printCategoryHeader($link, -2, $cat_hidden, true);
4159 print "<li><hr></li>";
4163 while ($line = db_fetch_assoc($result)) {
4165 $label_id = -$line['id'] - 11;
4166 $count = getFeedUnread($link, $label_id);
4174 printFeedEntry($label_id,
4175 $class, $line["caption"],
4176 $count, "images/label.png", $link);
4180 if (db_num_rows($result) > 0) {
4181 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4187 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4188 print "<li><hr></li>";
4191 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4192 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4193 $order_by_qpart = "order_id,category,unread DESC,title";
4195 $order_by_qpart = "order_id,category,title";
4198 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4199 $order_by_qpart = "unread DESC,title";
4201 $order_by_qpart = "title";
4205 $age_qpart = getMaxAgeSubquery();
4207 $query = "SELECT ttrss_feeds.*,
4208 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4210 ttrss_feed_categories.title AS category,
4211 ttrss_feed_categories.collapsed,
4213 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4214 ON (ttrss_feed_categories.id = cat_id)
4215 LEFT JOIN ttrss_counters_cache
4217 (ttrss_feeds.id = feed_id)
4219 ttrss_feeds.hidden = false AND
4220 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4221 ORDER BY $order_by_qpart";
4223 $result = db_query($link, $query);
4225 $actid = $_GET["actid"];
4235 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4237 while ($line = db_fetch_assoc($result)) {
4239 $feed = trim($line["title"]);
4241 if (!$feed) $feed = "[Untitled]";
4243 $feed_id = $line["id"];
4244 $unread = $line["unread"];
4246 $subop = $_GET["subop"];
4248 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4249 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4251 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4254 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4257 $rtl_tag = "dir=\"RTL\"";
4262 $tmp_result = db_query($link,
4263 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4264 WHERE parent_feed = '$feed_id' AND feed_id = id");
4266 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4268 $cat_id = $line["cat_id"];
4270 $tmp_category = $line["category"];
4272 if (!$tmp_category) {
4273 $tmp_category = __("Uncategorized");
4276 // $class = ($lnum % 2) ? "even" : "odd";
4278 if ($line["last_error"]) {
4284 if ($unread > 0) $class .= "Unread";
4286 if ($actid == $feed_id) {
4287 $class .= "Selected";
4290 $total_unread +
= $unread;
4292 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4298 $category = $tmp_category;
4300 $collapsed = sql_bool_to_bool($line["collapsed"]);
4302 // workaround for NULL category
4303 if ($category == __("Uncategorized")) {
4304 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4309 $cat_id = sprintf("%d", $cat_id);
4311 printCategoryHeader($link, $cat_id, $collapsed, true);
4315 printFeedEntry($feed_id, $class, $feed, $unread,
4316 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4317 $last_updated, $line["last_error"]);
4322 if (db_num_rows($result) == 0) {
4323 print "<li>".__('No feeds to display.')."</li>";
4330 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4331 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4332 post_int_id = ttrss_user_entries.int_id AND
4333 unread = true AND ref_id = ttrss_entries.id
4334 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4336 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4337 ORDER BY tag_name"); */
4339 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4340 print "<li class=\"feedCat\">".__('Tags')."</li>";
4341 print "<ul class=\"feedCatList\">";
4344 $age_qpart = getMaxAgeSubquery();
4346 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4347 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4348 AND ref_id = id AND $age_qpart
4349 AND unread = true)) AS count FROM ttrss_tags
4350 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4351 ORDER BY count DESC LIMIT 50");
4355 while ($line = db_fetch_assoc($result)) {
4356 $tags[$line["tag_name"]] +
= $line["count"];
4359 foreach (array_keys($tags) as $tag) {
4361 $unread = $tags[$tag];
4369 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4373 if (db_num_rows($result) == 0) {
4374 print "<li>No tags to display.</li>";
4377 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4387 function get_article_tags($link, $id, $owner_uid = 0) {
4389 $a_id = db_escape_string($id);
4391 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4393 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4394 owner_uid as owner FROM
4395 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4396 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4400 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4401 array_push($tags, $tmp_line["tag_name"]);
4407 function trim_value(&$value) {
4408 $value = trim($value);
4411 function trim_array($array) {
4413 array_walk($tmp, 'trim_value');
4417 function tag_is_valid($tag) {
4418 if ($tag == '') return false;
4419 if (preg_match("/^[0-9]*$/", $tag)) return false;
4421 if (function_exists('iconv')) {
4422 $tag = iconv("utf-8", "utf-8", $tag);
4425 if (!$tag) return false;
4430 function render_login_form($link, $mobile = false) {
4432 require_once "login_form.php";
4434 require_once "mobile/login_form.php";
4438 // from http://developer.apple.com/internet/safari/faq.html
4439 function no_cache_incantation() {
4440 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4441 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4442 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4443 header("Cache-Control: post-check=0, pre-check=0", false);
4444 header("Pragma: no-cache"); // HTTP/1.0
4447 function format_warning($msg, $id = "") {
4448 return "<div class=\"warning\" id=\"$id\">
4449 <img src=\"images/sign_excl.gif\">$msg</div>";
4452 function format_notice($msg) {
4453 return "<div class=\"notice\">
4454 <img src=\"images/sign_info.gif\">$msg</div>";
4457 function format_error($msg) {
4458 return "<div class=\"error\">
4459 <img src=\"images/sign_excl.gif\">$msg</div>";
4462 function print_notice($msg) {
4463 return print format_notice($msg);
4466 function print_warning($msg) {
4467 return print format_warning($msg);
4470 function print_error($msg) {
4471 return print format_error($msg);
4475 function T_sprintf() {
4476 $args = func_get_args();
4477 return vsprintf(__(array_shift($args)), $args);
4480 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4481 $zoom_mode = false) {
4483 /* we can figure out feed_id from article id anyway, why do we
4484 * pass feed_id here? */
4486 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4487 WHERE ref_id = '$id'");
4489 $feed_id = db_fetch_result($result, 0, "feed_id");
4491 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4493 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4494 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4496 if (db_num_rows($result) == 1) {
4497 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4499 $rtl_content = false;
4503 $rtl_tag = "dir=\"RTL\"";
4510 if ($mark_as_read) {
4511 $result = db_query($link, "UPDATE ttrss_user_entries
4512 SET unread = false,last_read = NOW()
4513 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4515 ccache_update($link, $feed_id, $_SESSION["uid"]);
4518 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4519 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4520 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4523 FROM ttrss_entries,ttrss_user_entries
4524 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4530 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4531 $link_target = "target=\"_blank\"";
4534 $line = db_fetch_assoc($result);
4536 if ($line["icon_url"]) {
4537 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4539 $feed_icon = " ";
4542 $num_comments = $line["num_comments"];
4543 $entry_comments = "";
4545 if ($num_comments > 0) {
4546 if ($line["comments"]) {
4547 $comments_url = $line["comments"];
4549 $comments_url = $line["link"];
4551 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4553 if ($line["comments"] && $line["link"] != $line["comments"]) {
4554 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4559 header("Content-Type: text/html");
4561 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4562 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4563 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4568 print "<div class=\"postReply\">";
4570 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4571 onmouseout=\"enable_resize(false)\">";
4573 $entry_author = $line["author"];
4575 if ($entry_author) {
4576 $entry_author = __(" - ") . $entry_author;
4579 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4580 strtotime($line["updated"]));
4582 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4584 if ($line["link"]) {
4585 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4586 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4588 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4591 $tags = get_article_tags($link, $id);
4594 $tags_nolinks_str = "";
4599 if ($_SESSION["theme"] == "3pane") {
4605 foreach ($tags as $tag) {
4607 $tag_escaped = str_replace("'", "\\'", $tag);
4609 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4611 if ($num_tags == $tag_limit) {
4612 $tags_str .= "…";
4613 $tags_nolinks_str .= "…";
4615 } else if ($num_tags < $tag_limit) {
4616 $tags_str .= $tag_str;
4617 $tags_nolinks_str .= "$tag, ";
4619 $f_tags_str .= $tag_str;
4622 $tags_str = preg_replace("/, $/", "", $tags_str);
4623 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4624 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4626 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4627 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4629 if (!$entry_comments) $entry_comments = " "; # placeholder
4631 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4632 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4634 print "<div style='float : right'>
4635 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4639 <a title=\"".__('Edit tags for this article')."\"
4640 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4642 if (defined('_ENABLE_INLINE_VIEW')) {
4644 print "<img src=\"images/art-inline.png\" class='tagsPic'
4645 style=\"cursor : pointer\" style=\"cursor : pointer\"
4646 onclick=\"showOriginalArticleInline($id)\"
4647 alt='Inline' title='".__('Display original article content')."'>";
4651 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4652 style=\"cursor : pointer\" style=\"cursor : pointer\"
4653 onclick=\"zoomToArticle($id)\"
4654 alt='Zoom' title='".__('Show article summary in new window')."'>";
4656 print "$tags_nolinks_str";
4659 print "<div clear='both'>$entry_comments</div>";
4663 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4665 print "<div class=\"postContent\">";
4667 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4669 $article_content = sanitize_rss($link, $line["content"]);
4671 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4672 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4676 print $article_content;
4678 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4679 post_id = '$id' AND content_url != ''");
4681 if (db_num_rows($result) > 0) {
4683 $entries_html = array();
4686 while ($line = db_fetch_assoc($result)) {
4688 $url = $line["content_url"];
4689 $ctype = $line["content_type"];
4691 if (!$ctype) $ctype = __("unknown type");
4693 $filename = substr($url, strrpos($url, "/")+
1);
4697 if (($ctype == __("audio/mpeg")) &&
4698 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4700 $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> ";
4704 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4705 $filename . " (" . $ctype . ")" . "</a>";
4707 array_push($entries_html, $entry);
4711 $entry["type"] = $ctype;
4712 $entry["filename"] = $filename;
4713 $entry["url"] = $url;
4715 array_push($entries, $entry);
4718 print "<div class=\"postEnclosures\">";
4720 if (!preg_match("/img/i", $article_content)) {
4721 foreach ($entries as $entry) {
4722 if (preg_match("/image/", $entry["type"])) {
4724 alt=\"".htmlspecialchars($entry["filename"])."\"
4725 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4730 print "<div class=\"postEnclosures\">";
4732 if (db_num_rows($result) == 1) {
4733 print __("Attachment:") . " ";
4735 print __("Attachments:") . " ";
4738 print join(", ", $entries_html);
4750 print "]]></article>";
4753 <div style=\"text-align : center\">
4754 <input type=\"submit\" onclick=\"return window.close()\"
4755 value=\"".__("Close this window")."\"></div>";
4756 print "</body></html>";
4762 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4763 $next_unread_feed, $offset, $vgr_last_feed = false,
4764 $override_order = false) {
4766 $disable_cache = false;
4768 $timing_info = getmicrotime();
4770 $topmost_article_ids = array();
4776 if ($subop == "undefined") $subop = "";
4778 $subop_split = split(":", $subop);
4780 if ($subop == "CatchupSelected") {
4781 $ids = split(",", db_escape_string($_GET["ids"]));
4782 $cmode = sprintf("%d", $_GET["cmode"]);
4784 catchupArticlesById($link, $ids, $cmode);
4787 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4788 update_generic_feed($link, $feed, $cat_view, true);
4791 if ($subop == "MarkAllRead") {
4792 catchup_feed($link, $feed, $cat_view);
4794 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4795 if ($next_unread_feed) {
4796 $feed = $next_unread_feed;
4801 if ($subop_split[0] == "MarkAllReadGR") {
4802 catchup_feed($link, $subop_split[1], false);
4807 $result = db_query($link,
4808 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4810 if (db_num_rows($result) == 0) {
4811 print "<div align='center'>".__('Feed not found.')."</div>";
4816 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4818 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4819 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4821 if (db_num_rows($result) == 1) {
4822 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4824 $rtl_content = false;
4828 $rtl_tag = "dir=\"RTL\"";
4834 $rtl_content = false;
4837 $script_dt_add = get_script_dt_add();
4839 /// START /////////////////////////////////////////////////////////////////////////////////
4841 $search = db_escape_string($_GET["query"]);
4844 $disable_cache = true;
4847 $search_mode = db_escape_string($_GET["search_mode"]);
4848 $match_on = db_escape_string($_GET["match_on"]);
4854 $real_offset = $offset * $limit;
4856 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4858 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4859 $search, $search_mode, $match_on, $override_order, $real_offset);
4861 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4863 $result = $qfh_ret[0];
4864 $feed_title = $qfh_ret[1];
4865 $feed_site_url = $qfh_ret[2];
4866 $last_error = $qfh_ret[3];
4868 $vgroup_last_feed = $vgr_last_feed;
4871 $feed_site_url = article_publish_url($link);
4874 /// STOP //////////////////////////////////////////////////////////////////////////////////
4877 print "<div id=\"headlinesContainer\" $rtl_tag>";
4880 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4884 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4885 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4888 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4891 $headlines_count = db_num_rows($result);
4893 if (db_num_rows($result) > 0) {
4895 # print "\{$offset}";
4897 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4898 print "<table class=\"headlinesList\" id=\"headlinesList\"
4899 cellspacing=\"0\">";
4902 $lnum = $limit*$offset;
4904 error_reporting (DEFAULT_ERROR_LEVEL
);
4907 $cur_feed_title = '';
4909 while ($line = db_fetch_assoc($result)) {
4911 $class = ($lnum %
2) ?
"even" : "odd";
4914 $feed_id = $line["feed_id"];
4916 $labels = get_article_labels($link, $id);
4917 $labels_str = "<span id=\"HLLCTR-$id\">";
4919 foreach ($labels as $l) {
4920 $labels_str .= "<span
4921 class='hlLabelRef'>".
4925 $labels_str .= "</span>";
4927 if (count($topmost_article_ids) < 5) {
4928 array_push($topmost_article_ids, $id);
4931 if ($line["last_read"] == "" &&
4932 ($line["unread"] != "t" && $line["unread"] != "1")) {
4934 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4937 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4941 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4949 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4952 $mark_img_ext = "gif";
4954 $mark_img_ext = "png";
4957 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4958 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4960 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4962 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4964 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4967 if ($line["published"] == "t" ||
$line["published"] == "1") {
4968 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4970 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4972 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4974 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4977 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4978 # $line["title"] . "</a>";
4980 # $content_link = "<a
4981 # href=\"" . htmlspecialchars($line["link"]) . "\"
4982 # onclick=\"view($id,$feed_id);\">" .
4983 # $line["title"] . "</a>";
4985 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4986 # $line["title"] . "</a>";
4988 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4989 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4991 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4992 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4995 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4996 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5000 $score = $line["score"];
5002 $score_pic = get_score_pic($score);
5004 /* $score_title = __("(Click to change)");
5005 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5006 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5008 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5013 } else if ($score < -100) {
5019 $entry_author = $line["author"];
5021 if ($entry_author) {
5022 $entry_author = " - $entry_author";
5025 $has_feed_icon = feed_has_icon($feed_id);
5027 if ($has_feed_icon) {
5028 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5030 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5031 $feed_icon_img = "";
5034 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5036 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5037 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5039 $cur_feed_title = $line["feed_title"];
5040 $vgroup_last_feed = $feed_id;
5042 $cur_feed_title = htmlspecialchars($cur_feed_title);
5044 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5046 print "<tr class='feedTitle'><td colspan='7'>".
5047 "<div style=\"float : right\">$feed_icon_img</div>".
5048 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5049 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5053 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5054 onmouseout='postMouseOut($id)'";
5056 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5058 print "<td class='hlUpdPic'>$update_pic</td>";
5060 print "<td class='hlSelectRow'>
5061 <input type=\"checkbox\" onclick=\"tSR(this)\"
5065 print "<td class='hlMarkedPic'>$marked_pic</td>";
5066 print "<td class='hlMarkedPic'>$published_pic</td>";
5068 # if ($line["feed_title"]) {
5069 # print "<td class='hlContent'>$content_link</td>";
5070 # print "<td class='hlFeed'>
5071 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5072 # truncate_string($line["feed_title"],30)."</a> </td>";
5075 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5077 print "<a id=\"RTITLE-$id\"
5078 href=\"" . htmlspecialchars($line["link"]) . "\"
5079 onclick=\"return view($id,$feed_id);\">" .
5082 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5083 if ($content_preview) {
5084 print "<span class=\"contentPreview\"> - $content_preview</span>";
5092 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5093 # $line["feed_title"]."</a>
5095 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5096 if ($line["feed_title"]) {
5097 print "<span class=\"hlFeed\">
5098 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5099 $line["feed_title"]."</a>)
5107 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5109 print "<td class='hlMarkedPic'>$score_pic</td>";
5111 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5112 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5119 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5120 if ($feed_id != $vgroup_last_feed) {
5122 $cur_feed_title = $line["feed_title"];
5123 $vgroup_last_feed = $feed_id;
5125 $cur_feed_title = htmlspecialchars($cur_feed_title);
5127 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5129 $has_feed_icon = feed_has_icon($feed_id);
5131 if ($has_feed_icon) {
5132 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5134 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5137 print "<div class='cdmFeedTitle'>".
5138 "<div style=\"float : right\">$feed_icon_img</div>".
5139 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5140 $line["feed_title"]."</a> $vf_catchup_link</div>";
5145 $add_class = "Unread";
5150 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5151 $show_excerpt = false;
5153 if ($expand_cdm && $score >= -100) {
5155 $show_excerpt = false;
5157 $cdm_cstyle = "style=\"display : none\"";
5158 $show_excerpt = true;
5161 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5162 onmouseout='postMouseOut($id)'";
5164 print "<div class=\"cdmArticle$add_class\"
5166 $mouseover_attrs'>";
5168 print "<div class=\"cdmHeader\">";
5170 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5171 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5174 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5177 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5178 onclick=\"javascript:toggleUnread($id, 0)\"
5179 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5182 print $entry_author;
5184 /* if (!$expand_cdm || $score < -100) {
5185 print " <a id=\"CICH-$id\"
5186 href=\"javascript:cdmExpandArticle($id)\">
5187 (".__('Show article').")</a>";
5192 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5193 if ($line["feed_title"]) {
5194 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5198 print "</span></div>";
5200 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5201 $line["content_preview"] = preg_replace("/href=/i",
5202 "target=\"_blank\" href=", $line["content_preview"]);
5205 if ($show_excerpt) {
5206 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5207 onclick=\"cdmExpandArticle($id)\"
5208 title=\"".__('Click to expand article')."\">";
5209 print truncate_string(strip_tags($line["content_preview"]), 100);
5213 print "<div class=\"cdmContent\"
5214 onclick=\"cdmClicked($id)\"
5215 id=\"CICD-$id\" $cdm_cstyle>";
5217 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5219 print sanitize_rss($link, $line["content_preview"]);
5220 $article_content = $line["content_preview"];
5222 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5223 post_id = '$id' AND content_url != ''");
5225 if (db_num_rows($e_result) > 0) {
5227 $entries_html = array();
5230 while ($e_line = db_fetch_assoc($e_result)) {
5232 $url = $e_line["content_url"];
5233 $ctype = $e_line["content_type"];
5234 if (!$ctype) $ctype = __("unknown type");
5236 $filename = substr($url, strrpos($url, "/")+
1);
5240 if (($ctype == __("audio/mpeg")) &&
5241 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5243 $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> ";
5247 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5248 $filename . " (" . $ctype . ")" . "</a>";
5250 array_push($entries_html, $entry);
5254 $entry["type"] = $ctype;
5255 $entry["filename"] = $filename;
5256 $entry["url"] = $url;
5258 array_push($entries, $entry);
5261 if (!preg_match("/img/i", $article_content)) {
5262 foreach ($entries as $entry) {
5263 if (preg_match("/image/", $entry["type"])) {
5265 alt=\"".htmlspecialchars($entry["filename"])."\"
5266 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5271 print "<div class=\"cdmEnclosures\">";
5273 if (db_num_rows($e_result) == 1) {
5274 print __("Attachment:") . " ";
5276 print __("Attachments:") . " ";
5279 print join(", ", $entries_html);
5285 print "<br clear='both'>";
5288 /* if (!$expand_cdm) {
5289 print "<a id=\"CICH-$id\"
5290 href=\"javascript:cdmExpandArticle($id)\">
5296 print "<div class=\"cdmFooter\"><span class='s0'>";
5298 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5300 print __("Select:").
5301 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5302 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5304 print "</span><span class='s1'>$marked_pic</span> ";
5305 print "<span class='s1'>$published_pic</span> ";
5306 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5307 onclick=\"zoomToArticle($id)\"
5308 style=\"cursor : pointer\"
5310 title='".__('Show article summary in new window')."'></span>";
5312 $tags = get_article_tags($link, $id);
5315 $full_tags_str = "";
5318 foreach ($tags as $tag) {
5320 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5321 if ($num_tags < 5) {
5322 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5323 } else if ($num_tags == 5) {
5324 $tags_str .= "…";
5328 $tags_str = preg_replace("/, $/", "", $tags_str);
5329 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5331 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5333 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5336 if ($tags_str == "") $tags_str = "no tags";
5338 // print "<img src='images/tag.png' class='markedPic'>";
5340 print "<span class='s1'>
5341 <img class='tagsPic' src='images/tag.png' alt='Tags'
5342 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5343 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5347 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5348 href=\"javascript:toggleUnread($id)\">
5359 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5366 switch ($view_mode) {
5368 $message = __("No unread articles found to display.");
5371 $message = __("No updated articles found to display.");
5374 $message = __("No starred articles found to display.");
5378 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5380 $message = __("No articles found to display.");
5384 if (!$offset) print "<div class='whiteBox'>$message</div>";
5392 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5395 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5397 function printTagCloud($link) {
5399 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5400 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5401 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5403 $result = db_query($link, $query);
5407 while ($line = db_fetch_assoc($result)) {
5408 $tags[$line["tag_name"]] = $line["count"];
5413 $max_size = 32; // max font size in pixels
5414 $min_size = 11; // min font size in pixels
5416 // largest and smallest array values
5417 $max_qty = max(array_values($tags));
5418 $min_qty = min(array_values($tags));
5420 // find the range of values
5421 $spread = $max_qty - $min_qty;
5422 if ($spread == 0) { // we don't want to divide by zero
5426 // set the font-size increment
5427 $step = ($max_size - $min_size) / ($spread);
5429 // loop through the tag array
5430 foreach ($tags as $key => $value) {
5431 // calculate font-size
5432 // find the $value in excess of $min_qty
5433 // multiply by the font-size increment ($size)
5434 // and add the $min_size set above
5435 $size = round($min_size +
(($value - $min_qty) * $step));
5437 $key_escaped = str_replace("'", "\\'", $key);
5439 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5440 $size . "px\" title=\"$value articles tagged with " .
5441 $key . '">' . $key . '</a> ';
5445 function print_checkpoint($n, $s) {
5446 $ts = getmicrotime();
5447 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5451 function sanitize_tag($tag) {
5454 $tag = mb_strtolower($tag, 'utf-8');
5456 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5458 // $tag = str_replace('"', "", $tag);
5459 // $tag = str_replace("+", " ", $tag);
5460 $tag = str_replace("technorati tag: ", "", $tag);
5465 function generate_publish_key() {
5466 return sha1(uniqid(rand(), true));
5469 function article_publish_url($link) {
5474 if ($_SERVER['HTTPS'] != "on") {
5475 $url_path = "http://";
5477 $url_path = "https://";
5480 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5481 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5487 * Purge a feed contents, marked articles excepted.
5489 * @param mixed $link The database connection.
5490 * @param integer $id The id of the feed to purge.
5493 function clear_feed_articles($link, $id) {
5494 $result = db_query($link, "DELETE FROM ttrss_user_entries
5495 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5497 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5498 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5500 ccache_update($link, $id, $_SESSION['uid']);
5501 } // function clear_feed_articles
5504 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5506 * @return string The Mozilla Firefox feed adding URL.
5508 function add_feed_url() {
5509 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5510 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5512 } // function add_feed_url
5515 * Encrypt a password in SHA1.
5517 * @param string $pass The password to encrypt.
5518 * @param string $login A optionnal login.
5519 * @return string The encrypted password.
5521 function encrypt_password($pass, $login = '') {
5523 return "SHA1X:" . sha1("$login:$pass");
5525 return "SHA1:" . sha1($pass);
5527 } // function encrypt_password
5530 * Update a feed batch.
5531 * Used by daemons to update n feeds by run.
5532 * Only update feed needing a update, and not being processed
5533 * by another process.
5535 * @param mixed $link Database link
5536 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5537 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5538 * @param boolean $debug Set to false to disable debug output. Default to true.
5541 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5542 // Process all other feeds using last_updated and interval parameters
5544 // Test if the user has loggued in recently. If not, it does not update its feeds.
5545 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5546 if (DB_TYPE
== "pgsql") {
5547 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5549 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5552 $login_thresh_qpart = "";
5555 // Test if the feed need a update (update interval exceded).
5556 if (DB_TYPE
== "pgsql") {
5557 $update_limit_qpart = "AND ((
5558 ttrss_feeds.update_interval = 0
5559 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5561 ttrss_feeds.update_interval > 0
5562 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5563 ) OR ttrss_feeds.last_updated IS NULL)";
5565 $update_limit_qpart = "AND ((
5566 ttrss_feeds.update_interval = 0
5567 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5569 ttrss_feeds.update_interval > 0
5570 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5571 ) OR ttrss_feeds.last_updated IS NULL)";
5574 // Test if feed is currently being updated by another process.
5575 if (DB_TYPE
== "pgsql") {
5576 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5578 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5581 // Test if there is a limit to number of updated feeds
5583 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5585 $random_qpart = sql_random_function();
5587 // We search for feed needing update.
5588 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5589 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5590 ttrss_feeds.update_interval
5592 ttrss_feeds, ttrss_users, ttrss_user_prefs
5594 ttrss_feeds.owner_uid = ttrss_users.id
5595 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5596 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5597 $login_thresh_qpart $update_limit_qpart
5598 $updstart_thresh_qpart
5599 ORDER BY $random_qpart $query_limit");
5601 $user_prefs_cache = array();
5603 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5605 // Here is a little cache magic in order to minimize risk of double feed updates.
5606 $feeds_to_update = array();
5607 while ($line = db_fetch_assoc($result)) {
5608 $feeds_to_update[$line['id']] = $line;
5611 // We update the feed last update started date before anything else.
5612 // There is no lag due to feed contents downloads
5613 // It prevent an other process to update the same feed.
5614 $feed_ids = array_keys($feeds_to_update);
5616 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5617 WHERE id IN (%s)", implode(',', $feed_ids)));
5620 // For each feed, we call the feed update function.
5621 while ($line = array_pop($feeds_to_update)) {
5623 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5625 // We setup a alarm to alert if the feed take more than 300s to update.
5627 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5628 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5629 // Cancel the alarm (the update went well)
5630 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5632 sleep(1); // prevent flood (FIXME make this an option?)
5635 // Send feed digests by email if needed.
5636 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5638 purge_orphans($link);
5640 } // function update_daemon_common
5642 function sanitize_article_content($text) {
5643 # we don't support CDATA sections in articles, they break our own escaping
5644 $text = preg_replace("/\[\[CDATA/", "", $text);
5645 $text = preg_replace("/\]\]\>/", "", $text);
5649 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5652 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5654 $result = db_query($link, "SELECT reg_exp,
5655 ttrss_filter_types.name AS name,
5656 ttrss_filter_actions.name AS action,
5660 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5663 owner_uid = $owner_uid AND
5664 ttrss_filter_types.id = filter_type AND
5665 ttrss_filter_actions.id = action_id AND
5666 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5668 while ($line = db_fetch_assoc($result)) {
5669 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5670 $filter["reg_exp"] = $line["reg_exp"];
5671 $filter["action"] = $line["action"];
5672 $filter["action_param"] = $line["action_param"];
5673 $filter["filter_param"] = $line["filter_param"];
5674 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5676 array_push($filters[$line["name"]], $filter);
5682 function get_score_pic($score) {
5684 return "score_high.png";
5685 } else if ($score > 0) {
5686 return "score_half_high.png";
5687 } else if ($score < -100) {
5688 return "score_low.png";
5689 } else if ($score < 0) {
5690 return "score_half_low.png";
5692 return "score_neutral.png";
5696 function rounded_table_start($classname, $header = " ") {
5697 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5698 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5699 print "<tr><td class='left'> </td><td class='content'>";
5702 function rounded_table_end($footer = " ") {
5703 print "</td><td class='right'> </td></tr>";
5704 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5708 function feed_has_icon($id) {
5709 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5712 function init_connection($link) {
5713 if (DB_TYPE
== "pgsql") {
5714 pg_query($link, "set client_encoding = 'UTF-8'");
5715 pg_set_client_encoding("UNICODE");
5716 pg_query($link, "set datestyle = 'ISO, european'");
5718 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5719 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5720 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5725 function update_feedbrowser_cache($link) {
5727 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5728 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5729 WHERE tf.feed_url = ttrss_feeds.feed_url
5730 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5731 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5733 db_query($link, "BEGIN");
5735 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5739 while ($line = db_fetch_assoc($result)) {
5740 $subscribers = db_escape_string($line["subscribers"]);
5741 $feed_url = db_escape_string($line["feed_url"]);
5742 $title = db_escape_string($line["title"]);
5744 $tmp_result = db_query($link, "SELECT subscribers FROM
5745 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5747 if (db_num_rows($tmp_result) == 0) {
5749 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5750 (feed_url, title, subscribers) VALUES ('$feed_url',
5751 '$title', '$subscribers')");
5759 db_query($link, "COMMIT");
5765 function ccache_zero($link, $feed_id, $owner_uid) {
5766 db_query($link, "UPDATE ttrss_counters_cache SET
5767 value = 0, updated = NOW() WHERE
5768 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5771 function ccache_zero_all($link, $owner_uid) {
5772 db_query($link, "UPDATE ttrss_counters_cache SET
5773 value = 0 WHERE owner_uid = '$owner_uid'");
5775 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5776 value = 0 WHERE owner_uid = '$owner_uid'");
5779 function ccache_update_all($link, $owner_uid) {
5781 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5783 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5784 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5786 while ($line = db_fetch_assoc($result)) {
5787 ccache_update($link, $line["feed_id"], $owner_uid, true);
5790 /* We have to manually include category 0 */
5792 ccache_update($link, 0, $owner_uid, true);
5795 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5796 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5798 while ($line = db_fetch_assoc($result)) {
5799 print ccache_update($link, $line["feed_id"], $owner_uid);
5806 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5807 $no_update = false) {
5810 $table = "ttrss_counters_cache";
5812 $table = "ttrss_cat_counters_cache";
5815 if (DB_TYPE
== "pgsql") {
5816 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5817 } else if (DB_TYPE
== "mysql") {
5818 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5821 $result = db_query($link, "SELECT value FROM $table
5822 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5825 if (db_num_rows($result) == 1) {
5826 return db_fetch_result($result, 0, "value");
5831 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5837 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5838 $update_pcat = true) {
5840 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5842 /* When updating a label, all we need to do is recalculate feed counters
5843 * because labels are not cached */
5846 ccache_update_all($link, $owner_uid);
5851 $table = "ttrss_counters_cache";
5853 $table = "ttrss_cat_counters_cache";
5856 if ($is_cat && $feed_id >= 0) {
5857 if ($feed_id != 0) {
5858 $cat_qpart = "cat_id = '$feed_id'";
5860 $cat_qpart = "cat_id IS NULL";
5863 /* Recalculate counters for child feeds */
5865 $result = db_query($link, "SELECT id FROM ttrss_feeds
5866 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5868 while ($line = db_fetch_assoc($result)) {
5869 ccache_update($link, $line["id"], $owner_uid, false, false);
5872 $result = db_query($link, "SELECT SUM(value) AS sv
5873 FROM ttrss_counters_cache, ttrss_feeds
5874 WHERE id = feed_id AND $cat_qpart AND
5875 ttrss_feeds.owner_uid = '$owner_uid'");
5877 $unread = (int) db_fetch_result($result, 0, "sv");
5880 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5883 $result = db_query($link, "SELECT feed_id FROM $table
5884 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5886 if (db_num_rows($result) == 1) {
5887 db_query($link, "UPDATE $table SET
5888 value = '$unread', updated = NOW() WHERE
5889 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5892 db_query($link, "INSERT INTO $table
5893 (feed_id, value, owner_uid, updated)
5895 ($feed_id, $unread, $owner_uid, NOW())");
5898 if ($feed_id > 0 && $prev_unread != $unread) {
5902 /* Update parent category */
5906 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5907 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5909 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5911 ccache_update($link, $cat_id, $owner_uid, true);
5915 } else if ($feed_id < 0) {
5916 ccache_update_all($link, $owner_uid);
5922 function label_find_id($link, $label, $owner_uid) {
5923 $result = db_query($link,
5924 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5925 AND owner_uid = '$owner_uid' LIMIT 1");
5927 if (db_num_rows($result) == 1) {
5928 return db_fetch_result($result, 0, "id");
5934 function get_article_labels($link, $id) {
5935 $result = db_query($link,
5936 "SELECT DISTINCT label_id,caption
5937 FROM ttrss_labels2, ttrss_user_labels2
5939 AND article_id = '$id'
5940 AND owner_uid = ".$_SESSION["uid"] . "
5945 while ($line = db_fetch_assoc($result)) {
5946 $rk = array($line["label_id"], $line["caption"]);
5947 array_push($rv, $rk);
5954 function label_find_caption($link, $label, $owner_uid) {
5955 $result = db_query($link,
5956 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5957 AND owner_uid = '$owner_uid' LIMIT 1");
5959 if (db_num_rows($result) == 1) {
5960 return db_fetch_result($result, 0, "caption");
5966 function label_remove_article($link, $id, $label, $owner_uid) {
5968 $label_id = label_find_id($link, $label, $owner_uid);
5970 if (!$label_id) return;
5972 $result = db_query($link,
5973 "DELETE FROM ttrss_user_labels2
5975 label_id = '$label_id' AND
5976 article_id = '$id'");
5979 function label_add_article($link, $id, $label, $owner_uid) {
5981 $label_id = label_find_id($link, $label, $owner_uid);
5983 if (!$label_id) return;
5985 $result = db_query($link,
5987 article_id FROM ttrss_labels2, ttrss_user_labels2
5990 label_id = '$label_id' AND
5991 article_id = '$id' AND owner_uid = '$owner_uid'
5994 if (db_num_rows($result) == 0) {
5995 db_query($link, "INSERT INTO ttrss_user_labels2
5996 (label_id, article_id) VALUES ('$label_id', '$id')");
6000 function label_remove($link, $id, $owner_uid) {
6002 db_query($link, "BEGIN");
6004 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6007 $caption = db_fetch_result($result, 0, "caption");
6009 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6010 AND owner_uid = " . $_SESSION["uid"]);
6012 if (db_affected_rows($link, $result) != 0 && $caption) {
6014 /* Disable filters that reference label being removed */
6016 db_query($link, "UPDATE ttrss_filters SET
6017 enabled = false WHERE action_param = '$caption'
6019 AND owner_uid = " . $_SESSION["uid"]);
6022 db_query($link, "COMMIT");