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,
1576 $fg_content = false, $bg_content = false) {
1578 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1579 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1581 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1585 $rtl_tag = "dir=\"rtl\"";
1587 $rtl_tag = "dir=\"ltr\"";
1590 $error_notify_msg = "";
1593 $link_title = "Error: $last_error ($last_updated)";
1594 $error_notify_msg = "(Error)";
1595 } else if ($last_updated) {
1596 $link_title = "Updated: $last_updated";
1599 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1600 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1602 /* if ($feed_id < -10) {
1603 $bg_color = "#00ccff";
1604 $fg_color = "white";
1607 if ($fg_color || $bg_color) {
1608 $color_str = "<div class='labelColorIndicator'
1609 style='color : $fg_color; background-color : $bg_color'>l</div>";
1612 print $color_str; */
1614 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1615 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1619 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1622 $fctr_class = "class=\"feedCtrHasUnread\"";
1624 $fctr_class = "class=\"feedCtrNoUnread\"";
1627 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1628 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1630 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1631 $total = getFeedArticles($link, $feed_id);
1632 print "<div class=\"feedExtInfo\">
1633 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1640 function getmicrotime() {
1641 list($usec, $sec) = explode(" ",microtime());
1642 return ((float)$usec +
(float)$sec);
1645 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1646 foreach ($values as $v) {
1653 if ($v == $true_is) {
1654 $sel .= " value=\"1\"";
1656 $sel .= " value=\"0\"";
1659 print "<input class=\"noborder\"
1660 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1665 function initialize_user_prefs($link, $uid) {
1667 $uid = db_escape_string($uid);
1669 db_query($link, "BEGIN");
1671 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1673 $u_result = db_query($link, "SELECT pref_name
1674 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1676 $active_prefs = array();
1678 while ($line = db_fetch_assoc($u_result)) {
1679 array_push($active_prefs, $line["pref_name"]);
1682 while ($line = db_fetch_assoc($result)) {
1683 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1684 // print "adding " . $line["pref_name"] . "<br>";
1686 db_query($link, "INSERT INTO ttrss_user_prefs
1687 (owner_uid,pref_name,value) VALUES
1688 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1693 db_query($link, "COMMIT");
1697 function lookup_user_id($link, $user) {
1699 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1702 if (db_num_rows($result) == 1) {
1703 return db_fetch_result($result, 0, "id");
1709 function http_authenticate_user($link) {
1711 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1713 if (!$_SERVER["PHP_AUTH_USER"]) {
1715 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1716 header('HTTP/1.0 401 Unauthorized');
1720 $auth_result = authenticate_user($link,
1721 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1723 if (!$auth_result) {
1724 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1725 header('HTTP/1.0 401 Unauthorized');
1733 function authenticate_user($link, $login, $password, $force_auth = false) {
1735 if (!SINGLE_USER_MODE
) {
1737 $pwd_hash1 = encrypt_password($password);
1738 $pwd_hash2 = encrypt_password($password, $login);
1740 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1741 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1743 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1745 $query = "SELECT id,login,access_level,pwd_hash
1746 FROM ttrss_users WHERE
1750 $query = "SELECT id,login,access_level,pwd_hash
1751 FROM ttrss_users WHERE
1752 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1753 pwd_hash = '$pwd_hash2')";
1756 $result = db_query($link, $query);
1758 if (db_num_rows($result) == 1) {
1759 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1760 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1761 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1763 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1766 $user_theme = get_user_theme_path($link);
1768 $_SESSION["theme"] = $user_theme;
1769 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1770 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1772 initialize_user_prefs($link, $_SESSION["uid"]);
1781 $_SESSION["uid"] = 1;
1782 $_SESSION["name"] = "admin";
1784 $user_theme = get_user_theme_path($link);
1786 $_SESSION["theme"] = $user_theme;
1787 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1789 initialize_user_prefs($link, $_SESSION["uid"]);
1795 function make_password($length = 8) {
1798 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1802 while ($i < $length) {
1803 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1805 if (!strstr($password, $char)) {
1813 // this is called after user is created to initialize default feeds, labels
1816 // user preferences are checked on every login, not here
1818 function initialize_user($link, $uid) {
1820 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1821 VALUES ('$uid', 'All Articles')");
1823 db_query($link, "INSERT INTO ttrss_filters
1824 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1825 action_id, action_param, filter_param)
1826 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1828 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1829 values ('$uid', 'Tiny Tiny RSS: New Releases',
1830 'http://tt-rss.org/releases.rss')");
1832 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1833 values ('$uid', 'Tiny Tiny RSS: Forum',
1834 'http://tt-rss.org/forum/rss.php')");
1837 function logout_user() {
1839 if (isset($_COOKIE[session_name()])) {
1840 setcookie(session_name(), '', time()-42000, '/');
1844 function get_script_urlpath() {
1845 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1848 function validate_session($link) {
1849 if (SINGLE_USER_MODE
) {
1853 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1854 if ($_SESSION["ip_address"]) {
1855 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1856 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1862 if ($_SESSION["uid"]) {
1864 $result = db_query($link,
1865 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1867 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1869 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1874 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1876 //print_r($_SESSION);
1878 if (time() > $_SESSION["cookie_lifetime"]) {
1886 function login_sequence($link, $mobile = false) {
1887 if (!SINGLE_USER_MODE
) {
1889 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1890 $swu = db_escape_string($_REQUEST["swu"]);
1892 $_SESSION["prefs_cache"] = false;
1893 return authenticate_user($link, $swu, null, true);
1897 $login_action = $_POST["login_action"];
1899 # try to authenticate user if called from login form
1900 if ($login_action == "do_login") {
1901 $login = $_POST["login"];
1902 $password = $_POST["password"];
1903 $remember_me = $_POST["remember_me"];
1905 if (authenticate_user($link, $login, $password)) {
1906 $_POST["password"] = "";
1908 $_SESSION["language"] = $_POST["language"];
1909 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1911 header("Location: " . $_SERVER["REQUEST_URI"]);
1916 $_SESSION["login_error_msg"] = "Incorrect username or password";
1920 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1921 //render_login_form($link, $mobile);
1922 header("Location: login.php");
1925 /* bump login timestamp */
1926 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1929 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1930 setcookie("ttrss_lang", $_SESSION["language"],
1931 time() + SESSION_COOKIE_LIFETIME
);
1934 /* bump counters stamp since we're getting reloaded anyway */
1936 $_SESSION["get_all_counters_stamp"] = time();
1940 return authenticate_user($link, "admin", null);
1944 function truncate_string($str, $max_len) {
1945 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1946 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1952 function get_user_theme_path($link) {
1953 $result = db_query($link, "SELECT theme_path
1955 ttrss_themes,ttrss_users
1956 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1957 if (db_num_rows($result) != 0) {
1958 return db_fetch_result($result, 0, "theme_path");
1964 function smart_date_time($timestamp) {
1965 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1966 return date("G:i", $timestamp);
1967 } else if (date("Y", $timestamp) == date("Y")) {
1968 return date("M d, G:i", $timestamp);
1970 return date("Y/m/d, G:i", $timestamp);
1974 function smart_date($timestamp) {
1975 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1977 } else if (date("Y", $timestamp) == date("Y")) {
1978 return date("D m", $timestamp);
1980 return date("Y/m/d", $timestamp);
1984 function sql_bool_to_string($s) {
1985 if ($s == "t" ||
$s == "1") {
1992 function sql_bool_to_bool($s) {
1993 if ($s == "t" ||
$s == "1") {
2000 function bool_to_sql_bool($s) {
2008 function toggleEvenOdd($a) {
2015 function sanity_check($link) {
2020 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2021 $schema_version = db_fetch_result($result, 0, "schema_version");
2023 if ($schema_version != SCHEMA_VERSION
) {
2027 if (DB_TYPE
== "mysql") {
2028 $result = db_query($link, "SELECT true", false);
2029 if (db_num_rows($result) != 1) {
2034 if (db_escape_string("testTEST") != "testTEST") {
2038 error_reporting (DEFAULT_ERROR_LEVEL
);
2040 if ($error_code != 0) {
2041 print_error_xml($error_code);
2048 function file_is_locked($filename) {
2049 if (function_exists('flock')) {
2051 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2052 error_reporting(DEFAULT_ERROR_LEVEL
);
2054 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2055 flock($fp, LOCK_UN
);
2065 return true; // consider the file always locked and skip the test
2068 function make_lockfile($filename) {
2069 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2071 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2078 function make_stampfile($filename) {
2079 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2081 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2082 fwrite($fp, time() . "\n");
2083 flock($fp, LOCK_UN
);
2091 function read_stampfile($filename) {
2094 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2095 error_reporting (DEFAULT_ERROR_LEVEL
);
2098 if (flock($fp, LOCK_EX
)) {
2099 $stamp = fgets($fp);
2100 flock($fp, LOCK_UN
);
2111 function sql_random_function() {
2112 if (DB_TYPE
== "mysql") {
2119 function catchup_feed($link, $feed, $cat_view) {
2121 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2128 $cat_qpart = "cat_id = '$feed'";
2130 $cat_qpart = "cat_id IS NULL";
2133 $tmp_result = db_query($link, "SELECT id
2134 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2137 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2139 $tmp_feed = $tmp_line["id"];
2141 db_query($link, "UPDATE ttrss_user_entries
2142 SET unread = false,last_read = NOW()
2143 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2145 } else if ($feed == -2) {
2147 /* FIXME catchup for all labels vfeed */
2150 } else if ($feed > 0) {
2152 $tmp_result = db_query($link, "SELECT id
2153 FROM ttrss_feeds WHERE parent_feed = '$feed'
2154 ORDER BY cat_id,title");
2156 $parent_ids = array();
2158 if (db_num_rows($tmp_result) > 0) {
2159 while ($p = db_fetch_assoc($tmp_result)) {
2160 array_push($parent_ids, "feed_id = " . $p["id"]);
2163 $children_qpart = implode(" OR ", $parent_ids);
2165 db_query($link, "UPDATE ttrss_user_entries
2166 SET unread = false,last_read = NOW()
2167 WHERE (feed_id = '$feed' OR $children_qpart)
2168 AND owner_uid = " . $_SESSION["uid"]);
2171 db_query($link, "UPDATE ttrss_user_entries
2172 SET unread = false,last_read = NOW()
2173 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2176 } else if ($feed < 0 && $feed > -10) { // special, like starred
2179 db_query($link, "UPDATE ttrss_user_entries
2180 SET unread = false,last_read = NOW()
2181 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2185 db_query($link, "UPDATE ttrss_user_entries
2186 SET unread = false,last_read = NOW()
2187 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2192 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2194 if (DB_TYPE
== "pgsql") {
2195 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2197 $match_part = "updated > DATE_SUB(NOW(),
2198 INTERVAL $intl HOUR) ";
2201 $result = db_query($link, "SELECT id FROM ttrss_entries,
2202 ttrss_user_entries WHERE $match_part AND
2204 ttrss_user_entries.ref_id = ttrss_entries.id AND
2205 owner_uid = ".$_SESSION["uid"]);
2207 $affected_ids = array();
2209 while ($line = db_fetch_assoc($result)) {
2210 array_push($affected_ids, $line["id"]);
2213 catchupArticlesById($link, $affected_ids, 0);
2217 db_query($link, "UPDATE ttrss_user_entries
2218 SET unread = false,last_read = NOW()
2219 WHERE owner_uid = ".$_SESSION["uid"]);
2222 } else if ($feed < -10) { // label
2224 $label_id = -$feed - 11;
2226 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2227 SET unread = false WHERE label_id = '$label_id' AND unread = true
2228 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2232 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2235 db_query($link, "BEGIN");
2237 $tag_name = db_escape_string($feed);
2239 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2240 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2242 while ($line = db_fetch_assoc($result)) {
2243 db_query($link, "UPDATE ttrss_user_entries SET
2244 unread = false, last_read = NOW()
2245 WHERE int_id = " . $line["post_int_id"]);
2247 db_query($link, "COMMIT");
2251 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2255 $cat_qpart = "cat_id = '$feed'";
2257 $cat_qpart = "cat_id IS NULL";
2260 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2261 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2263 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2264 $feed_url = $tmp_line["feed_url"];
2265 $feed_id = $tmp_line["id"];
2266 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2270 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2271 WHERE id = '$feed'");
2272 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2273 update_rss_feed($link, $feed_url, $feed, $force_update);
2277 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2279 if (!$omode) $omode = "flc";
2281 getGlobalCounters($link);
2283 if (strchr($omode, "l")) getLabelCounters($link);
2284 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2285 if (strchr($omode, "t")) getTagCounters($link);
2286 if (strchr($omode, "c")) {
2287 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2288 getCategoryCounters($link);
2293 function getCategoryCounters($link) {
2294 # two special categories are -1 and -2 (all virtuals; all labels)
2296 /* $ctr = getCategoryUnread($link, -1);
2298 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2300 $ctr = getCategoryUnread($link, -2);
2302 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2304 $age_qpart = getMaxAgeSubquery();
2306 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2307 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2308 WHERE ttrss_cat_counters_cache.feed_id = id AND
2309 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2311 while ($line = db_fetch_assoc($result)) {
2312 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2314 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2315 $line["unread"]."\"/>";
2318 /* Special case: NULL category doesn't actually exist in the DB */
2320 print "<counter type=\"category\" id=\"0\" counter=\"".
2321 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2325 function getCategoryUnread($link, $cat, $owner_uid = false) {
2327 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2332 $cat_query = "cat_id = '$cat'";
2334 $cat_query = "cat_id IS NULL";
2337 $age_qpart = getMaxAgeSubquery();
2339 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2341 AND owner_uid = " . $owner_uid);
2343 $cat_feeds = array();
2344 while ($line = db_fetch_assoc($result)) {
2345 array_push($cat_feeds, "feed_id = " . $line["id"]);
2348 if (count($cat_feeds) == 0) return 0;
2350 $match_part = implode(" OR ", $cat_feeds);
2352 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2353 FROM ttrss_user_entries,ttrss_entries
2354 WHERE unread = true AND ($match_part) AND id = ref_id
2355 AND $age_qpart AND owner_uid = " . $owner_uid);
2359 # this needs to be rewritten
2360 while ($line = db_fetch_assoc($result)) {
2361 $unread +
= $line["unread"];
2365 } else if ($cat == -1) {
2366 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2367 } else if ($cat == -2) {
2369 $result = db_query($link, "
2370 SELECT COUNT(unread) AS unread FROM
2371 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2372 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2373 ttrss_labels2.owner_uid = '$owner_uid'
2374 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2375 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2377 $unread = db_fetch_result($result, 0, "unread");
2384 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2385 if (DB_TYPE
== "pgsql") {
2386 return "ttrss_entries.date_entered >
2387 NOW() - INTERVAL '$days days'";
2389 return "ttrss_entries.date_entered >
2390 DATE_SUB(NOW(), INTERVAL $days DAY)";
2394 function getFeedUnread($link, $feed, $is_cat = false) {
2395 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2398 function getLabelUnread($link, $label_id, $owner_uid = false) {
2399 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2401 $result = db_query($link, "
2402 SELECT COUNT(unread) AS unread FROM
2403 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2404 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2405 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2406 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2407 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2409 if (db_num_rows($result) != 0) {
2410 return db_fetch_result($result, 0, "unread");
2416 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2417 $owner_uid = false) {
2419 $n_feed = sprintf("%d", $feed);
2421 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2424 $unread_qpart = "unread = true";
2426 $unread_qpart = "true";
2429 $age_qpart = getMaxAgeSubquery();
2432 return getCategoryUnread($link, $n_feed, $owner_uid);
2433 } else if ($n_feed == -1) {
2434 $match_part = "marked = true";
2435 } else if ($n_feed == -2) {
2436 $match_part = "published = true";
2437 } else if ($n_feed == -3) {
2438 $match_part = "unread = true";
2440 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2442 if (DB_TYPE
== "pgsql") {
2443 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2445 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2447 } else if ($n_feed == -4) {
2448 $match_part = "true";
2449 } else if ($n_feed > 0) {
2451 $result = db_query($link, "SELECT id FROM ttrss_feeds
2452 WHERE parent_feed = '$n_feed'
2454 AND owner_uid = " . $owner_uid);
2456 if (db_num_rows($result) > 0) {
2458 $linked_feeds = array();
2459 while ($line = db_fetch_assoc($result)) {
2460 array_push($linked_feeds, "feed_id = " . $line["id"]);
2463 array_push($linked_feeds, "feed_id = $n_feed");
2465 $match_part = implode(" OR ", $linked_feeds);
2467 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2468 FROM ttrss_user_entries,ttrss_entries
2469 WHERE $unread_qpart AND
2470 ttrss_user_entries.ref_id = ttrss_entries.id AND
2473 owner_uid = " . $owner_uid);
2477 # this needs to be rewritten
2478 while ($line = db_fetch_assoc($result)) {
2479 $unread +
= $line["unread"];
2485 $match_part = "feed_id = '$n_feed'";
2487 } else if ($feed < -10) {
2489 $label_id = -$feed - 11;
2491 return getLabelUnread($link, $label_id, $owner_uid);
2497 $result = db_query($link, "SELECT count(int_id) AS unread
2498 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2499 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2500 ttrss_user_entries.ref_id = ttrss_entries.id AND
2501 ttrss_feeds.hidden = false AND
2503 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2507 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2508 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2509 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2510 AND $unread_qpart AND $age_qpart AND
2511 ttrss_tags.owner_uid = " . $owner_uid);
2514 $unread = db_fetch_result($result, 0, "unread");
2519 function getGlobalUnread($link, $user_id = false) {
2522 $user_id = $_SESSION["uid"];
2525 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2526 WHERE owner_uid = '$user_id' AND feed_id > 0");
2528 $c_id = db_fetch_result($result, 0, "c_id");
2533 function getGlobalCounters($link, $global_unread = -1) {
2534 if ($global_unread == -1) {
2535 $global_unread = getGlobalUnread($link);
2537 print "<counter type=\"global\" id='global-unread'
2538 counter='$global_unread'/>";
2540 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2541 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2543 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2545 print "<counter type=\"global\" id='subscribed-feeds'
2546 counter='$subscribed_feeds'/>";
2550 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2553 if (!$_SESSION["tctr_last_value"]) {
2554 $_SESSION["tctr_last_value"] = array();
2558 $old_counters = $_SESSION["tctr_last_value"];
2560 $tctrs_modified = false;
2562 $age_qpart = getMaxAgeSubquery();
2564 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2565 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2566 AND ref_id = id AND $age_qpart
2567 AND unread = true)) AS count FROM ttrss_tags
2568 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2569 ORDER BY count DESC LIMIT 55");
2573 while ($line = db_fetch_assoc($result)) {
2574 $tags[$line["tag_name"]] +
= $line["count"];
2577 foreach (array_keys($tags) as $tag) {
2578 $unread = $tags[$tag];
2580 $tag = htmlspecialchars($tag);
2582 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2583 $old_counters[$tag] = $unread;
2584 $tctrs_modified = true;
2585 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2590 if ($smart_mode && $tctrs_modified) {
2591 $_SESSION["tctr_last_value"] = $old_counters;
2596 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2598 $age_qpart = getMaxAgeSubquery();
2601 if (!$_SESSION["lctr_last_value"]) {
2602 $_SESSION["lctr_last_value"] = array();
2608 for ($i = -1; $i >= -4; $i--) {
2610 $count = getFeedUnread($link, $i);
2614 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2615 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2620 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2622 $ret_arr[$i]["counter"] = $count;
2623 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2628 $old_counters = $_SESSION["lctr_last_value"];
2629 $lctrs_modified = false;
2632 $owner_uid = $_SESSION["uid"];
2634 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2635 WHERE owner_uid = '$owner_uid'");
2637 while ($line = db_fetch_assoc($result)) {
2639 $id = -$line["id"] - 11;
2641 $label_name = $line["caption"];
2642 $count = getFeedUnread($link, $id);
2644 if (!$smart_mode ||
$old_counters[$id] != $count) {
2645 $old_counters[$id] = $count;
2646 $lctrs_modified = true;
2649 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2650 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2655 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2657 $ret_arr[$id]["counter"] = $count;
2658 $ret_arr[$id]["description"] = $label_name;
2662 error_reporting (DEFAULT_ERROR_LEVEL
);
2665 if ($smart_mode && $lctrs_modified) {
2666 $_SESSION["lctr_last_value"] = $old_counters;
2672 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2674 $age_qpart = getMaxAgeSubquery();
2677 if (!$_SESSION["fctr_last_value"]) {
2678 $_SESSION["fctr_last_value"] = array();
2682 $old_counters = $_SESSION["fctr_last_value"];
2684 $query = "SELECT ttrss_feeds.id,
2686 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2687 last_error, value AS count
2688 FROM ttrss_feeds, ttrss_counters_cache
2689 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2690 AND parent_feed IS NULL
2691 AND ttrss_counters_cache.feed_id = id";
2693 $result = db_query($link, $query);
2694 $fctrs_modified = false;
2696 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2698 while ($line = db_fetch_assoc($result)) {
2701 $count = $line["count"];
2702 $last_error = htmlspecialchars($line["last_error"]);
2704 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2705 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2707 $last_updated = date($short_date, strtotime($line["last_updated"]));
2710 $last_updated = htmlspecialchars($last_updated);
2712 $has_img = feed_has_icon($id);
2714 $tmp_result = db_query($link,
2715 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2716 WHERE parent_feed = '$id' AND feed_id = id");
2718 $count +
= db_fetch_result($tmp_result, 0, "unread");
2720 if (!$smart_mode ||
$old_counters[$id] != $count) {
2721 $old_counters[$id] = $count;
2722 $fctrs_modified = true;
2725 $error_part = "error=\"$last_error\"";
2731 $has_img_part = "hi=\"$has_img\"";
2736 if ($active_feed && $id == $active_feed) {
2737 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2739 $has_title_part = "";
2742 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2743 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2746 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2750 if ($smart_mode && $fctrs_modified) {
2751 $_SESSION["fctr_last_value"] = $old_counters;
2755 function get_script_dt_add() {
2756 /* if (strpos(VERSION, ".99") === false) {
2764 function get_pgsql_version($link) {
2765 $result = db_query($link, "SELECT version() AS version");
2766 $version = split(" ", db_fetch_result($result, 0, "version"));
2770 function print_error_xml($code, $add_msg = "") {
2773 $error_msg = $ERRORS[$code];
2776 $error_msg = "$error_msg; $add_msg";
2779 print "<rpc-reply>";
2780 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2781 print "</rpc-reply>";
2784 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2785 $auth_login = '', $auth_pass = '') {
2787 # check for feed:http://url
2788 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2790 # check for feed://URL
2791 if (strpos($feed_link, "//") === 0) {
2792 $feed_link = "http:$feed_link";
2795 if ($feed_link == "") return;
2797 if ($cat_id == "0" ||
!$cat_id) {
2798 $cat_qpart = "NULL";
2800 $cat_qpart = "'$cat_id'";
2803 $result = db_query($link,
2804 "SELECT id FROM ttrss_feeds
2805 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2807 if (db_num_rows($result) == 0) {
2809 $result = db_query($link,
2810 "INSERT INTO ttrss_feeds
2811 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2812 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2813 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2815 $result = db_query($link,
2816 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2817 AND owner_uid = " . $_SESSION["uid"]);
2819 $feed_id = db_fetch_result($result, 0, "id");
2822 update_rss_feed($link, $feed_link, $feed_id, true);
2831 function print_feed_select($link, $id, $default_id = "",
2832 $attributes = "", $include_all_feeds = true) {
2834 print "<select id=\"$id\" name=\"$id\" $attributes>";
2835 if ($include_all_feeds) {
2836 print "<option value=\"0\">".__('All feeds')."</option>";
2839 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2840 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2842 if (db_num_rows($result) > 0 && $include_all_feeds) {
2843 print "<option disabled>--------</option>";
2846 while ($line = db_fetch_assoc($result)) {
2847 if ($line["id"] == $default_id) {
2848 $is_selected = "selected";
2852 printf("<option $is_selected value='%d'>%s</option>",
2853 $line["id"], htmlspecialchars($line["title"]));
2859 function print_feed_cat_select($link, $id, $default_id = "",
2860 $attributes = "", $include_all_cats = true) {
2862 print "<select id=\"$id\" name=\"$id\" $attributes>";
2864 if ($include_all_cats) {
2865 print "<option value=\"0\">".__('Uncategorized')."</option>";
2868 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2869 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2871 if (db_num_rows($result) > 0 && $include_all_cats) {
2872 print "<option disabled>--------</option>";
2875 while ($line = db_fetch_assoc($result)) {
2876 if ($line["id"] == $default_id) {
2877 $is_selected = "selected";
2881 printf("<option $is_selected value='%d'>%s</option>",
2882 $line["id"], htmlspecialchars($line["title"]));
2888 function checkbox_to_sql_bool($val) {
2889 return ($val == "on") ?
"true" : "false";
2892 function getFeedCatTitle($link, $id) {
2894 return __("Special");
2895 } else if ($id < -10) {
2896 return __("Labels");
2897 } else if ($id > 0) {
2898 $result = db_query($link, "SELECT ttrss_feed_categories.title
2899 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2900 cat_id = ttrss_feed_categories.id");
2901 if (db_num_rows($result) == 1) {
2902 return db_fetch_result($result, 0, "title");
2904 return __("Uncategorized");
2907 return "getFeedCatTitle($id) failed";
2912 function getFeedTitle($link, $id) {
2914 return __("Starred articles");
2915 } else if ($id == -2) {
2916 return __("Published articles");
2917 } else if ($id == -3) {
2918 return __("Fresh articles");
2919 } else if ($id == -4) {
2920 return __("All articles");
2921 } else if ($id < -10) {
2922 $label_id = -$id - 11;
2923 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2924 if (db_num_rows($result) == 1) {
2925 return db_fetch_result($result, 0, "caption");
2927 return "Unknown label ($label_id)";
2930 } else if ($id > 0) {
2931 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2932 if (db_num_rows($result) == 1) {
2933 return db_fetch_result($result, 0, "title");
2935 return "Unknown feed ($id)";
2938 return "getFeedTitle($id) failed";
2943 function get_session_cookie_name() {
2944 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2947 function print_init_params($link) {
2948 print "<init-params>";
2949 if ($_SESSION["stored-params"]) {
2950 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2952 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2953 print "<param key=\"$key\" value=\"$value\"/>";
2958 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2959 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2960 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2961 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2963 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2964 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2966 print "<param key=\"hide_read_feeds\" value=\"" .
2967 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2969 print "<param key=\"enable_feed_cats\" value=\"" .
2970 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2972 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2973 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2975 print "<param key=\"confirm_feed_catchup\" value=\"" .
2976 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2978 print "<param key=\"cdm_auto_catchup\" value=\"" .
2979 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2981 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2983 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2985 print "<param key=\"default_view_mode\" value=\"" .
2986 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2988 print "<param key=\"default_view_limit\" value=\"" .
2989 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2991 print "<param key=\"default_view_order_by\" value=\"" .
2992 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
2994 print "<param key=\"prefs_active_tab\" value=\"" .
2995 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2997 print "<param key=\"infobox_disable_overlay\" value=\"" .
2998 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3000 print "<param key=\"icons_location\" value=\"" .
3003 print "<param key=\"hide_read_shows_special\" value=\"" .
3004 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3006 print "<param key=\"hide_feedlist\" value=\"" .
3007 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3009 print "<param key=\"bw_limit\" value=\"".
3010 (int) $_SESSION["bw_limit"]."\"/>";
3012 // print "<param key=\"sync_counters\" value=\"" .
3013 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3015 print "<param key=\"sync_counters\" value=\"1\"/>";
3017 print "<param key=\"offline_enabled\" value=\"".
3018 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3020 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3021 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3023 $num_feeds = db_fetch_result($result, 0, "cf");
3025 print "<param key=\"num_feeds\" value=\"".
3026 (int)$num_feeds. "\"/>";
3028 print "</init-params>";
3031 function print_runtime_info($link) {
3032 print "<runtime-info>";
3034 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3035 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3037 $num_feeds = db_fetch_result($result, 0, "cf");
3039 print "<param key=\"num_feeds\" value=\"".
3040 (int)$num_feeds. "\"/>";
3042 if (ENABLE_UPDATE_DAEMON
) {
3043 print "<param key=\"daemon_is_running\" value=\"".
3044 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3046 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3048 $stamp = (int)read_stampfile("update_daemon.stamp");
3050 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3053 $stamp_delta = time() - $stamp;
3055 if ($stamp_delta > 1800) {
3059 $_SESSION["daemon_stamp_check"] = time();
3062 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3064 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3066 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3071 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3073 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3074 $new_version_details = check_for_update($link);
3076 print "<param key=\"new_version_available\" value=\"".
3077 sprintf("%d", $new_version_details != ""). "\"/>";
3079 $_SESSION["last_version_check"] = time();
3083 // print "<param key=\"new_version_available\" value=\"1\"/>";
3085 print "</runtime-info>";
3088 function getSearchSql($search, $match_on) {
3090 $search_query_part = "";
3092 $keywords = split(" ", $search);
3093 $query_keywords = array();
3095 if ($match_on == "both") {
3097 foreach ($keywords as $k) {
3098 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3099 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3102 $search_query_part = implode("AND", $query_keywords) . " AND ";
3104 } else if ($match_on == "title") {
3106 foreach ($keywords as $k) {
3107 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3110 $search_query_part = implode("AND", $query_keywords) . " AND ";
3112 } else if ($match_on == "content") {
3114 foreach ($keywords as $k) {
3115 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3119 $search_query_part = implode("AND", $query_keywords);
3121 return $search_query_part;
3124 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3126 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3130 $search_query_part = getSearchSql($search, $match_on);
3131 $search_query_part .= " AND ";
3134 $search_query_part = "";
3137 $view_query_part = "";
3139 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3141 $view_query_part = " ";
3142 } else if ($feed != -1) {
3143 $unread = getFeedUnread($link, $feed, $cat_view);
3145 $view_query_part = " unread = true AND ";
3150 if ($view_mode == "marked") {
3151 $view_query_part = " marked = true AND ";
3154 if ($view_mode == "unread") {
3155 $view_query_part = " unread = true AND ";
3158 if ($view_mode == "updated") {
3159 $view_query_part = " (last_read is null and unread = false) AND ";
3163 $limit_query_part = "LIMIT " . $limit;
3166 $vfeed_query_part = "";
3168 // override query strategy and enable feed display when searching globally
3169 if ($search && $search_mode == "all_feeds") {
3170 $query_strategy_part = "ttrss_entries.id > 0";
3171 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3172 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3173 $query_strategy_part = "ttrss_entries.id > 0";
3174 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3175 id = feed_id) as feed_title,";
3176 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3178 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3180 $tmp_result = false;
3183 $tmp_result = db_query($link, "SELECT id
3184 FROM ttrss_feeds WHERE cat_id = '$feed'");
3186 $tmp_result = db_query($link, "SELECT id
3187 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3188 WHERE id = '$feed') AND id != '$feed'");
3191 $cat_siblings = array();
3193 if (db_num_rows($tmp_result) > 0) {
3194 while ($p = db_fetch_assoc($tmp_result)) {
3195 array_push($cat_siblings, "feed_id = " . $p["id"]);
3198 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3199 $feed, implode(" OR ", $cat_siblings));
3202 $query_strategy_part = "ttrss_entries.id > 0";
3205 } else if ($feed >= 0) {
3210 $query_strategy_part = "cat_id = '$feed'";
3212 $query_strategy_part = "cat_id IS NULL";
3215 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3218 $tmp_result = db_query($link, "SELECT id
3219 FROM ttrss_feeds WHERE parent_feed = '$feed'
3220 ORDER BY cat_id,title");
3222 $parent_ids = array();
3224 if (db_num_rows($tmp_result) > 0) {
3225 while ($p = db_fetch_assoc($tmp_result)) {
3226 array_push($parent_ids, "feed_id = " . $p["id"]);
3229 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3230 $feed, implode(" OR ", $parent_ids));
3232 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3234 $query_strategy_part = "feed_id = '$feed'";
3237 } else if ($feed == -1) { // starred virtual feed
3238 $query_strategy_part = "marked = true";
3239 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3240 } else if ($feed == -2) { // published virtual feed OR labels category
3243 $query_strategy_part = "published = true";
3244 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3246 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3248 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3250 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3251 ttrss_user_labels2.article_id = ref_id";
3255 } else if ($feed == -3) { // fresh virtual feed
3256 $query_strategy_part = "unread = true";
3258 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3260 if (DB_TYPE
== "pgsql") {
3261 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3263 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3266 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3267 } else if ($feed == -4) { // all articles virtual feed
3268 $query_strategy_part = "true";
3269 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3270 } else if ($feed <= -10) { // labels
3271 $label_id = -$feed - 11;
3273 $query_strategy_part = "label_id = '$label_id' AND
3274 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3275 ttrss_user_labels2.article_id = ref_id";
3277 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3278 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3281 $query_strategy_part = "id > 0"; // dumb
3284 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3285 $order_by = "updated";
3287 $order_by = "updated DESC";
3290 if ($view_mode != "noscores") {
3291 $order_by = "score DESC, $order_by";
3294 if ($override_order) {
3295 $order_by = $override_order;
3300 if ($search && $search_mode == "all_feeds") {
3301 $feed_title = __("Search results")." ($search)";
3302 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3303 $feed_title = __("Search results")." ($search, $feed)";
3304 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3305 $feed_title = $feed;
3306 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3311 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3312 WHERE id = '$feed' AND owner_uid = $owner_uid");
3313 $feed_title = db_fetch_result($result, 0, "title");
3315 $feed_title = __("Uncategorized");
3319 $feed_title = __("Searched for")." $search ($feed_title)";
3324 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3325 WHERE id = '$feed' AND owner_uid = $owner_uid");
3327 $feed_title = db_fetch_result($result, 0, "title");
3328 $feed_site_url = db_fetch_result($result, 0, "site_url");
3329 $last_error = db_fetch_result($result, 0, "last_error");
3332 $feed_title = __("Searched for") . " $search ($feed_title)";
3336 } else if ($feed == -1) {
3337 $feed_title = __("Starred articles");
3338 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3339 } else if ($feed == -2) {
3341 $feed_title = __("Published articles");
3342 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3344 $feed_title = __("Labels");
3346 } else if ($feed == -3) {
3347 $feed_title = __("Fresh articles");
3348 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3349 } else if ($feed == -4) {
3350 $feed_title = __("All articles");
3351 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3352 } else if ($feed < -10) {
3353 $label_id = -$feed - 11;
3354 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3355 WHERE id = '$label_id'");
3356 $feed_title = db_fetch_result($result, 0, "caption");
3359 $feed_title = __("Searched for") . " $search ($feed_title)";
3365 $content_query_part = "content as content_preview,";
3367 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3370 $feed_kind = "Feeds";
3372 $feed_kind = "Labels";
3375 if ($limit_query_part) {
3376 $offset_query_part = "OFFSET $offset";
3379 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3380 if (!$override_order) {
3381 $order_by = "ttrss_feeds.title, $order_by";
3384 // Special output for Fresh feed
3386 /* if ($feed == -3) {
3387 $group_limit_part = "(select count(*) from
3388 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3389 t1.ref_id = t2.id and t1.owner_uid = 2 and
3390 t1.feed_id = ttrss_user_entries.feed_id and
3391 t2.updated > ttrss_entries.updated) <= 5 AND";
3395 $query = "SELECT DISTINCT
3397 ttrss_entries.id,ttrss_entries.title,
3399 unread,feed_id,marked,published,link,last_read,
3400 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3403 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3406 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3409 ttrss_feeds.hidden = false AND
3410 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3411 ttrss_user_entries.ref_id = ttrss_entries.id AND
3412 ttrss_user_entries.owner_uid = '$owner_uid' AND
3415 $query_strategy_part ORDER BY $order_by
3416 $limit_query_part $offset_query_part";
3418 if ($_GET["debug"]) print $query;
3420 $result = db_query($link, $query);
3425 $feed_kind = "Tags";
3427 $result = db_query($link, "SELECT
3429 ttrss_entries.id as id,title,
3432 marked,link,last_read,
3433 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3436 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3439 ttrss_entries,ttrss_user_entries,ttrss_tags
3441 ref_id = ttrss_entries.id AND
3442 ttrss_user_entries.owner_uid = '$owner_uid' AND
3443 post_int_id = int_id AND tag_name = '$feed' AND
3446 $query_strategy_part ORDER BY $order_by
3447 $limit_query_part");
3450 return array($result, $feed_title, $feed_site_url, $last_error);
3454 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3455 $limit, $search, $search_mode, $match_on) {
3457 if (!$limit) $limit = 30;
3459 $qfh_ret = queryFeedHeadlines($link, $feed,
3460 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3463 $result = $qfh_ret[0];
3464 $feed_title = htmlspecialchars($qfh_ret[1]);
3465 $feed_site_url = $qfh_ret[2];
3466 $last_error = $qfh_ret[3];
3468 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3470 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3471 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3472 <rss version=\"2.0\">
3474 <title>$feed_title</title>
3475 <link>$feed_site_url</link>
3476 <description>Feed generated by Tiny Tiny RSS</description>";
3478 while ($line = db_fetch_assoc($result)) {
3480 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3481 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3483 $tags = get_article_tags($link, $line["id"], $owner_uid);
3485 foreach ($tags as $tag) {
3486 print "<category>" . htmlspecialchars($tag) . "</category>";
3489 $rfc822_date = date('r', strtotime($line["updated"]));
3491 print "<pubDate>$rfc822_date</pubDate>";
3494 htmlspecialchars($line["title"]) . "</title>";
3496 print "<description><![CDATA[" .
3497 $line["content_preview"] . "]]></description>";
3502 print "</channel></rss>";
3506 function getCategoryTitle($link, $cat_id) {
3508 if ($cat_id == -1) {
3509 return __("Special");
3510 } else if ($cat_id == -2) {
3511 return __("Labels");
3514 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3517 if (db_num_rows($result) == 1) {
3518 return db_fetch_result($result, 0, "title");
3520 return "Uncategorized";
3525 // http://ru2.php.net/strip-tags
3527 function strip_tags_long($textstring, $allowed){
3528 while($textstring != strip_tags($textstring, $allowed))
3530 while (strlen($textstring) != 0)
3532 if (strlen($textstring) > 1024) {
3535 $otherlen = strlen($textstring);
3537 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3538 $safetext .= $temptext;
3539 $textstring = substr_replace($textstring,'',0,$otherlen);
3541 $textstring = $safetext;
3547 function sanitize_rss($link, $str, $force_strip_tags = false) {
3550 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3552 $res = strip_tags_long($res,
3553 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3555 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3556 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3559 if (get_pref($link, "STRIP_IMAGES")) {
3561 $res = preg_replace('/<img[^>]+>/is', '', $res);
3569 * Send by mail a digest of last articles.
3571 * @param mixed $link The database connection.
3572 * @param integer $limit The maximum number of articles by digest.
3573 * @return boolean Return false if digests are not enabled.
3575 function send_headlines_digests($link, $limit = 100) {
3577 if (!DIGEST_ENABLE
) return false;
3579 $user_limit = DIGEST_EMAIL_LIMIT
;
3582 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3584 if (DB_TYPE
== "pgsql") {
3585 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3586 } else if (DB_TYPE
== "mysql") {
3587 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3590 $result = db_query($link, "SELECT id,email FROM ttrss_users
3591 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3593 while ($line = db_fetch_assoc($result)) {
3595 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3596 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3598 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3600 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3601 $digest = $tuple[0];
3602 $headlines_count = $tuple[1];
3603 $affected_ids = $tuple[2];
3604 $digest_text = $tuple[3];
3606 if ($headlines_count > 0) {
3608 $mail = new PHPMailer();
3610 $mail->PluginDir
= "lib/phpmailer/";
3611 $mail->SetLanguage("en", "lib/phpmailer/language/");
3613 $mail->CharSet
= "UTF-8";
3615 $mail->From
= DIGEST_FROM_ADDRESS
;
3616 $mail->FromName
= DIGEST_FROM_NAME
;
3617 $mail->AddAddress($line["email"], $line["login"]);
3619 if (DIGEST_SMTP_HOST
) {
3620 $mail->Host
= DIGEST_SMTP_HOST
;
3621 $mail->Mailer
= "smtp";
3622 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3623 $mail->Username
= DIGEST_SMTP_LOGIN
;
3624 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3627 $mail->IsHTML(true);
3628 $mail->Subject
= DIGEST_SUBJECT
;
3629 $mail->Body
= $digest;
3630 $mail->AltBody
= $digest_text;
3632 $rc = $mail->Send();
3634 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3638 if ($rc && $do_catchup) {
3639 print "Marking affected articles as read...\n";
3640 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3643 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3644 WHERE id = " . $line["id"]);
3646 print "No headlines\n";
3651 print "All done.\n";
3655 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3657 require_once "lib/MiniTemplator.class.php";
3659 $tpl = new MiniTemplator
;
3660 $tpl_t = new MiniTemplator
;
3662 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3663 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3665 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3666 $tpl->setVariable('CUR_TIME', date('G:i'));
3668 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3669 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3671 $affected_ids = array();
3673 if (DB_TYPE
== "pgsql") {
3674 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3675 } else if (DB_TYPE
== "mysql") {
3676 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3679 $result = db_query($link, "SELECT ttrss_entries.title,
3680 ttrss_feeds.title AS feed_title,
3682 ttrss_user_entries.ref_id,
3684 SUBSTRING(content, 1, 120) AS excerpt,
3685 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3687 ttrss_user_entries,ttrss_entries,ttrss_feeds
3689 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3690 AND include_in_digest = true
3693 AND ttrss_user_entries.owner_uid = $user_id
3695 ORDER BY ttrss_feeds.title, date_entered DESC
3698 $cur_feed_title = "";
3700 $headlines_count = db_num_rows($result);
3702 $headlines = array();
3704 while ($line = db_fetch_assoc($result)) {
3705 array_push($headlines, $line);
3708 for ($i = 0; $i < sizeof($headlines); $i++
) {
3710 $line = $headlines[$i];
3712 array_push($affected_ids, $line["ref_id"]);
3714 $updated = smart_date_time(strtotime($line["last_updated"]));
3716 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3717 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3718 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3719 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3720 $tpl->setVariable('ARTICLE_EXCERPT',
3721 truncate_string(strip_tags($line["excerpt"]), 100));
3723 $tpl->addBlock('article');
3725 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3726 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3727 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3728 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3729 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3730 // truncate_string(strip_tags($line["excerpt"]), 100));
3732 $tpl_t->addBlock('article');
3734 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3735 $tpl->addBlock('feed');
3736 $tpl_t->addBlock('feed');
3741 $tpl->addBlock('digest');
3742 $tpl->generateOutputToString($tmp);
3744 $tpl_t->addBlock('digest');
3745 $tpl_t->generateOutputToString($tmp_t);
3747 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3750 function check_for_update($link) {
3751 $releases_feed = "http://tt-rss.org/releases.rss";
3753 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3758 if (ENABLE_SIMPLEPIE
) {
3759 $rss = new SimplePie();
3760 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3761 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3762 $rss->set_feed_url($fetch_url);
3763 $rss->set_output_encoding('UTF-8');
3766 $rss = fetch_rss($releases_feed);
3768 error_reporting (DEFAULT_ERROR_LEVEL
);
3772 if (ENABLE_SIMPLEPIE
) {
3773 $items = $rss->get_items();
3775 $items = $rss->items
;
3777 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3778 if (!$items ||
!is_array($items)) $items = $rss;
3781 if (!is_array($items) ||
count($items) == 0) {
3785 $latest_item = $items[0];
3787 if (ENABLE_SIMPLEPIE
) {
3788 $last_title = $latest_item->get_title();
3790 $last_title = $latest_item["title"];
3793 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3795 if (ENABLE_SIMPLEPIE
) {
3796 $release_url = sanitize_rss($link, $latest_item->get_link());
3797 $content = sanitize_rss($link, $latest_item->get_description());
3799 $release_url = sanitize_rss($link, $latest_item["link"]);
3800 $content = sanitize_rss($link, $latest_item["description"]);
3803 if (version_compare(VERSION
, $latest_version) == -1) {
3804 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3805 $latest_version)."<div class='milestoneDetails'>$content</div>";
3812 function markArticlesById($link, $ids, $cmode) {
3816 foreach ($ids as $id) {
3817 array_push($tmp_ids, "ref_id = '$id'");
3820 $ids_qpart = join(" OR ", $tmp_ids);
3823 db_query($link, "UPDATE ttrss_user_entries SET
3824 marked = false,last_read = NOW()
3825 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3826 } else if ($cmode == 1) {
3827 db_query($link, "UPDATE ttrss_user_entries SET
3829 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3831 db_query($link, "UPDATE ttrss_user_entries SET
3832 marked = NOT marked,last_read = NOW()
3833 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3837 function publishArticlesById($link, $ids, $cmode) {
3841 foreach ($ids as $id) {
3842 array_push($tmp_ids, "ref_id = '$id'");
3845 $ids_qpart = join(" OR ", $tmp_ids);
3848 db_query($link, "UPDATE ttrss_user_entries SET
3849 published = false,last_read = NOW()
3850 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3851 } else if ($cmode == 1) {
3852 db_query($link, "UPDATE ttrss_user_entries SET
3854 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3856 db_query($link, "UPDATE ttrss_user_entries SET
3857 published = NOT published,last_read = NOW()
3858 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3862 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3864 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3868 foreach ($ids as $id) {
3869 array_push($tmp_ids, "ref_id = '$id'");
3872 $ids_qpart = join(" OR ", $tmp_ids);
3875 db_query($link, "UPDATE ttrss_user_entries SET
3876 unread = false,last_read = NOW()
3877 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3878 } else if ($cmode == 1) {
3879 db_query($link, "UPDATE ttrss_user_entries SET
3881 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3883 db_query($link, "UPDATE ttrss_user_entries SET
3884 unread = NOT unread,last_read = NOW()
3885 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3890 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3891 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3893 while ($line = db_fetch_assoc($result)) {
3894 ccache_update($link, $line["feed_id"], $owner_uid);
3898 function catchupArticleById($link, $id, $cmode) {
3901 db_query($link, "UPDATE ttrss_user_entries SET
3902 unread = false,last_read = NOW()
3903 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3904 } else if ($cmode == 1) {
3905 db_query($link, "UPDATE ttrss_user_entries SET
3907 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3909 db_query($link, "UPDATE ttrss_user_entries SET
3910 unread = NOT unread,last_read = NOW()
3911 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3915 function make_guid_from_title($title) {
3916 return preg_replace("/[ \"\',.:;]/", "-",
3917 mb_strtolower(strip_tags($title), 'utf-8'));
3920 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3921 $feed_id, $is_cat, $search, $match_on,
3924 print "<div class=\"headlinesSubToolbar\">";
3926 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3927 $page_next_link = "javascript:viewFeedGoPage(1)";
3928 $page_first_link = "javascript:viewFeedGoPage(0)";
3930 $catchup_page_link = "javascript:catchupPage()";
3931 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3932 $catchup_sel_link = "javascript:catchupSelection()";
3934 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3936 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3937 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3938 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3939 $sel_inv_link = "javascript:invertHeadlineSelection()";
3941 $tog_unread_link = "javascript:selectionToggleUnread()";
3942 $tog_marked_link = "javascript:selectionToggleMarked()";
3943 $tog_published_link = "javascript:selectionTogglePublished()";
3947 $sel_all_link = "javascript:cdmSelectArticles('all')";
3948 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3949 $sel_none_link = "javascript:cdmSelectArticles('none')";
3951 $sel_inv_link = "javascript:invertHeadlineSelection()";
3953 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3954 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3955 $tog_published_link = "javascript:selectionTogglePublished(true)";
3959 print "<div id=\"subtoolbar_ftitle\">";
3961 if ($feed_site_url) {
3963 $target = "target=\"_blank\"";
3965 print "<a $target href=\"$feed_site_url\">".
3966 truncate_string($feed_title,30)."</a>";
3972 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3976 <a target=\"_blank\"
3977 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3978 <img class=\"noborder\"
3979 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3984 print __('Select:')."
3985 <a href=\"$sel_all_link\">".__('All')."</a>,
3986 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3987 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3988 <a href=\"$sel_none_link\">".__('None')."</a></li>";
3990 print " ";
3993 onmouseover=\"enable_selection(false)\"
3994 onmouseout=\"enable_selection(true)\"
3995 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
3996 __("Actions...") . " <img src=\"images/down_arrow.png\">
3999 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4001 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4002 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4003 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4004 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4005 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4006 <li class=\"insensitive\">".__('Mark as read:')."</li>
4007 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4009 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4012 //print "<li><span class=\"insensitive\">--------</span></li>";
4013 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4015 print_labels_headlines_dropdown($link, $feed_id);
4022 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4024 $tmp_category = getCategoryTitle($link, $cat_id);
4027 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4028 } else if ($cat_id == 0 ||
$cat_id == -2) {
4029 $cat_unread = getCategoryUnread($link, $cat_id);
4033 $holder_style = "display:none;";
4040 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4043 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4044 $inner_title_class = "catTitle";
4046 $browse_cat_link = "";
4047 $inner_title_class = "catTitleNL";
4050 $cat_class = "feedCat";
4052 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4053 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4054 title=\"".__('Click to collapse category')."\"
4055 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4056 id=\"FCATN-$cat_id\" $browse_cat_link
4057 \">$tmp_category</span>";
4059 print "<span id=\"FCAP-$cat_id\">";
4061 print " <span id=\"FCATCTR-$cat_id\"
4062 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4068 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4072 function outputFeedList($link, $tags = false) {
4074 print "<ul class=\"feedList\" id=\"feedList\">";
4076 $owner_uid = $_SESSION["uid"];
4080 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4082 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4085 $cat_hidden = false;
4088 printCategoryHeader($link, -1, $cat_hidden, false);
4091 $num_starred = getFeedUnread($link, -1);
4092 $num_published = getFeedUnread($link, -2);
4093 $num_fresh = getFeedUnread($link, -3);
4094 $num_total = getFeedUnread($link, -4);
4098 if ($num_total > 0) $class .= "Unread";
4100 printFeedEntry(-4, $class, __("All articles"), $num_total,
4101 "images/tag.png", $link);
4105 if ($num_fresh > 0) $class .= "Unread";
4107 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4108 "images/fresh.png", $link);
4112 if ($num_starred > 0) $class .= "Unread";
4114 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4117 $mark_img_ext = "gif";
4119 $mark_img_ext = "png";
4122 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4123 "images/mark_set.$mark_img_ext", $link);
4127 if ($num_published > 0) $class .= "Unread";
4129 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4130 "images/pub_set.gif", $link);
4132 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4139 $result = db_query($link, "SELECT * FROM
4140 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4142 if (db_num_rows($result) > 0) {
4143 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4145 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4148 $cat_hidden = false;
4151 printCategoryHeader($link, -2, $cat_hidden, true);
4154 print "<li><hr></li>";
4158 while ($line = db_fetch_assoc($result)) {
4160 $label_id = -$line['id'] - 11;
4161 $count = getFeedUnread($link, $label_id);
4169 printFeedEntry($label_id,
4170 $class, $line["caption"],
4171 $count, "images/label.png", $link,
4172 false, false, false,
4173 $line['fg_color'], $line['bg_color']);
4177 if (db_num_rows($result) > 0) {
4178 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4184 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4185 print "<li><hr></li>";
4188 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4189 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4190 $order_by_qpart = "order_id,category,unread DESC,title";
4192 $order_by_qpart = "order_id,category,title";
4195 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4196 $order_by_qpart = "unread DESC,title";
4198 $order_by_qpart = "title";
4202 $age_qpart = getMaxAgeSubquery();
4204 $query = "SELECT ttrss_feeds.*,
4205 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4207 ttrss_feed_categories.title AS category,
4208 ttrss_feed_categories.collapsed,
4210 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4211 ON (ttrss_feed_categories.id = cat_id)
4212 LEFT JOIN ttrss_counters_cache
4214 (ttrss_feeds.id = feed_id)
4216 ttrss_feeds.hidden = false AND
4217 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4218 ORDER BY $order_by_qpart";
4220 $result = db_query($link, $query);
4222 $actid = $_GET["actid"];
4232 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4234 while ($line = db_fetch_assoc($result)) {
4236 $feed = trim($line["title"]);
4238 if (!$feed) $feed = "[Untitled]";
4240 $feed_id = $line["id"];
4241 $unread = $line["unread"];
4243 $subop = $_GET["subop"];
4245 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4246 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4248 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4251 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4254 $rtl_tag = "dir=\"RTL\"";
4259 $tmp_result = db_query($link,
4260 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4261 WHERE parent_feed = '$feed_id' AND feed_id = id");
4263 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4265 $cat_id = $line["cat_id"];
4267 $tmp_category = $line["category"];
4269 if (!$tmp_category) {
4270 $tmp_category = __("Uncategorized");
4273 // $class = ($lnum % 2) ? "even" : "odd";
4275 if ($line["last_error"]) {
4281 if ($unread > 0) $class .= "Unread";
4283 if ($actid == $feed_id) {
4284 $class .= "Selected";
4287 $total_unread +
= $unread;
4289 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4295 $category = $tmp_category;
4297 $collapsed = sql_bool_to_bool($line["collapsed"]);
4299 // workaround for NULL category
4300 if ($category == __("Uncategorized")) {
4301 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4306 $cat_id = sprintf("%d", $cat_id);
4308 printCategoryHeader($link, $cat_id, $collapsed, true);
4312 printFeedEntry($feed_id, $class, $feed, $unread,
4313 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4314 $last_updated, $line["last_error"]);
4319 if (db_num_rows($result) == 0) {
4320 print "<li>".__('No feeds to display.')."</li>";
4327 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4328 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4329 post_int_id = ttrss_user_entries.int_id AND
4330 unread = true AND ref_id = ttrss_entries.id
4331 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4333 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4334 ORDER BY tag_name"); */
4336 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4337 print "<li class=\"feedCat\">".__('Tags')."</li>";
4338 print "<ul class=\"feedCatList\">";
4341 $age_qpart = getMaxAgeSubquery();
4343 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4344 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4345 AND ref_id = id AND $age_qpart
4346 AND unread = true)) AS count FROM ttrss_tags
4347 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4348 ORDER BY count DESC LIMIT 50");
4352 while ($line = db_fetch_assoc($result)) {
4353 $tags[$line["tag_name"]] +
= $line["count"];
4356 foreach (array_keys($tags) as $tag) {
4358 $unread = $tags[$tag];
4366 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4370 if (db_num_rows($result) == 0) {
4371 print "<li>No tags to display.</li>";
4374 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4384 function get_article_tags($link, $id, $owner_uid = 0) {
4386 $a_id = db_escape_string($id);
4388 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4390 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4391 owner_uid as owner FROM
4392 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4393 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4397 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4398 array_push($tags, $tmp_line["tag_name"]);
4404 function trim_value(&$value) {
4405 $value = trim($value);
4408 function trim_array($array) {
4410 array_walk($tmp, 'trim_value');
4414 function tag_is_valid($tag) {
4415 if ($tag == '') return false;
4416 if (preg_match("/^[0-9]*$/", $tag)) return false;
4418 if (function_exists('iconv')) {
4419 $tag = iconv("utf-8", "utf-8", $tag);
4422 if (!$tag) return false;
4427 function render_login_form($link, $mobile = false) {
4429 require_once "login_form.php";
4431 require_once "mobile/login_form.php";
4435 // from http://developer.apple.com/internet/safari/faq.html
4436 function no_cache_incantation() {
4437 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4438 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4439 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4440 header("Cache-Control: post-check=0, pre-check=0", false);
4441 header("Pragma: no-cache"); // HTTP/1.0
4444 function format_warning($msg, $id = "") {
4445 return "<div class=\"warning\" id=\"$id\">
4446 <img src=\"images/sign_excl.gif\">$msg</div>";
4449 function format_notice($msg) {
4450 return "<div class=\"notice\">
4451 <img src=\"images/sign_info.gif\">$msg</div>";
4454 function format_error($msg) {
4455 return "<div class=\"error\">
4456 <img src=\"images/sign_excl.gif\">$msg</div>";
4459 function print_notice($msg) {
4460 return print format_notice($msg);
4463 function print_warning($msg) {
4464 return print format_warning($msg);
4467 function print_error($msg) {
4468 return print format_error($msg);
4472 function T_sprintf() {
4473 $args = func_get_args();
4474 return vsprintf(__(array_shift($args)), $args);
4477 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4478 $zoom_mode = false) {
4480 /* we can figure out feed_id from article id anyway, why do we
4481 * pass feed_id here? */
4483 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4484 WHERE ref_id = '$id'");
4486 $feed_id = db_fetch_result($result, 0, "feed_id");
4488 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4490 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4491 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4493 if (db_num_rows($result) == 1) {
4494 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4496 $rtl_content = false;
4500 $rtl_tag = "dir=\"RTL\"";
4507 if ($mark_as_read) {
4508 $result = db_query($link, "UPDATE ttrss_user_entries
4509 SET unread = false,last_read = NOW()
4510 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4512 ccache_update($link, $feed_id, $_SESSION["uid"]);
4515 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4516 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4517 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4520 FROM ttrss_entries,ttrss_user_entries
4521 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4527 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4528 $link_target = "target=\"_blank\"";
4531 $line = db_fetch_assoc($result);
4533 if ($line["icon_url"]) {
4534 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4536 $feed_icon = " ";
4539 $num_comments = $line["num_comments"];
4540 $entry_comments = "";
4542 if ($num_comments > 0) {
4543 if ($line["comments"]) {
4544 $comments_url = $line["comments"];
4546 $comments_url = $line["link"];
4548 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4550 if ($line["comments"] && $line["link"] != $line["comments"]) {
4551 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4556 header("Content-Type: text/html");
4558 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4559 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4560 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4565 print "<div class=\"postReply\">";
4567 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4568 onmouseout=\"enable_resize(false)\">";
4570 $entry_author = $line["author"];
4572 if ($entry_author) {
4573 $entry_author = __(" - ") . $entry_author;
4576 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4577 strtotime($line["updated"]));
4579 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4581 if ($line["link"]) {
4582 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4583 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4585 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4588 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4590 if (!$entry_comments) $entry_comments = " "; # placeholder
4592 print "<div style='float : right'>
4593 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4596 print "<span id=\"ATSTR-$id\">$tags_str</span>
4597 <a title=\"".__('Edit tags for this article')."\"
4598 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4600 if (defined('_ENABLE_INLINE_VIEW')) {
4602 print "<img src=\"images/art-inline.png\" class='tagsPic'
4603 style=\"cursor : pointer\" style=\"cursor : pointer\"
4604 onclick=\"showOriginalArticleInline($id)\"
4605 alt='Inline' title='".__('Display original article content')."'>";
4609 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4610 style=\"cursor : pointer\" style=\"cursor : pointer\"
4611 onclick=\"zoomToArticle($id)\"
4612 alt='Zoom' title='".__('Show article summary in new window')."'>";
4615 print "<div clear='both'>$entry_comments</div>";
4619 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4621 print "<div class=\"postContent\">";
4623 $article_content = sanitize_rss($link, $line["content"]);
4625 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4626 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4630 print $article_content;
4632 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4633 post_id = '$id' AND content_url != ''");
4635 if (db_num_rows($result) > 0) {
4637 $entries_html = array();
4640 while ($line = db_fetch_assoc($result)) {
4642 $url = $line["content_url"];
4643 $ctype = $line["content_type"];
4645 if (!$ctype) $ctype = __("unknown type");
4647 $filename = substr($url, strrpos($url, "/")+
1);
4651 if (($ctype == __("audio/mpeg")) &&
4652 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4654 $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> ";
4658 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4659 $filename . " (" . $ctype . ")" . "</a>";
4661 array_push($entries_html, $entry);
4665 $entry["type"] = $ctype;
4666 $entry["filename"] = $filename;
4667 $entry["url"] = $url;
4669 array_push($entries, $entry);
4672 print "<div class=\"postEnclosures\">";
4674 if (!preg_match("/img/i", $article_content)) {
4675 foreach ($entries as $entry) {
4676 if (preg_match("/image/", $entry["type"])) {
4678 alt=\"".htmlspecialchars($entry["filename"])."\"
4679 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4684 print "<div class=\"postEnclosures\">";
4686 if (db_num_rows($result) == 1) {
4687 print __("Attachment:") . " ";
4689 print __("Attachments:") . " ";
4692 print join(", ", $entries_html);
4704 print "]]></article>";
4707 <div style=\"text-align : center\">
4708 <input type=\"submit\" onclick=\"return window.close()\"
4709 value=\"".__("Close this window")."\"></div>";
4710 print "</body></html>";
4716 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4717 $next_unread_feed, $offset, $vgr_last_feed = false,
4718 $override_order = false) {
4720 $disable_cache = false;
4722 $timing_info = getmicrotime();
4724 $topmost_article_ids = array();
4730 if ($subop == "undefined") $subop = "";
4732 $subop_split = split(":", $subop);
4734 if ($subop == "CatchupSelected") {
4735 $ids = split(",", db_escape_string($_GET["ids"]));
4736 $cmode = sprintf("%d", $_GET["cmode"]);
4738 catchupArticlesById($link, $ids, $cmode);
4741 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4742 update_generic_feed($link, $feed, $cat_view, true);
4745 if ($subop == "MarkAllRead") {
4746 catchup_feed($link, $feed, $cat_view);
4748 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4749 if ($next_unread_feed) {
4750 $feed = $next_unread_feed;
4755 if ($subop_split[0] == "MarkAllReadGR") {
4756 catchup_feed($link, $subop_split[1], false);
4761 $result = db_query($link,
4762 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4764 if (db_num_rows($result) == 0) {
4765 print "<div align='center'>".__('Feed not found.')."</div>";
4770 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4772 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4773 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4775 if (db_num_rows($result) == 1) {
4776 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4778 $rtl_content = false;
4782 $rtl_tag = "dir=\"RTL\"";
4788 $rtl_content = false;
4791 $script_dt_add = get_script_dt_add();
4793 /// START /////////////////////////////////////////////////////////////////////////////////
4795 $search = db_escape_string($_GET["query"]);
4798 $disable_cache = true;
4801 $search_mode = db_escape_string($_GET["search_mode"]);
4802 $match_on = db_escape_string($_GET["match_on"]);
4808 $real_offset = $offset * $limit;
4810 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4812 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4813 $search, $search_mode, $match_on, $override_order, $real_offset);
4815 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4817 $result = $qfh_ret[0];
4818 $feed_title = $qfh_ret[1];
4819 $feed_site_url = $qfh_ret[2];
4820 $last_error = $qfh_ret[3];
4822 $vgroup_last_feed = $vgr_last_feed;
4825 $feed_site_url = article_publish_url($link);
4828 /// STOP //////////////////////////////////////////////////////////////////////////////////
4831 print "<div id=\"headlinesContainer\" $rtl_tag>";
4834 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4838 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4839 $feed, $cat_view, $search, $match_on, $search_mode);
4841 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4844 $headlines_count = db_num_rows($result);
4846 if (db_num_rows($result) > 0) {
4848 # print "\{$offset}";
4850 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4851 print "<table class=\"headlinesList\" id=\"headlinesList\"
4852 cellspacing=\"0\">";
4855 $lnum = $limit*$offset;
4857 error_reporting (DEFAULT_ERROR_LEVEL
);
4860 $cur_feed_title = '';
4862 while ($line = db_fetch_assoc($result)) {
4864 $class = ($lnum %
2) ?
"even" : "odd";
4867 $feed_id = $line["feed_id"];
4869 $labels = get_article_labels($link, $id);
4871 $labels_str = "<span id=\"HLLCTR-$id\">";
4872 $labels_str .= format_article_labels($labels, $id);
4873 $labels_str .= "</span>";
4875 if (count($topmost_article_ids) < 5) {
4876 array_push($topmost_article_ids, $id);
4879 if ($line["last_read"] == "" &&
4880 ($line["unread"] != "t" && $line["unread"] != "1")) {
4882 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4885 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4889 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4897 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4900 $mark_img_ext = "gif";
4902 $mark_img_ext = "png";
4905 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4906 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4908 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4910 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4912 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4915 if ($line["published"] == "t" ||
$line["published"] == "1") {
4916 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4918 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4920 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4922 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4925 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4926 # $line["title"] . "</a>";
4928 # $content_link = "<a
4929 # href=\"" . htmlspecialchars($line["link"]) . "\"
4930 # onclick=\"view($id,$feed_id);\">" .
4931 # $line["title"] . "</a>";
4933 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4934 # $line["title"] . "</a>";
4936 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4937 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4939 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4940 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4943 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4944 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4948 $score = $line["score"];
4950 $score_pic = get_score_pic($score);
4952 /* $score_title = __("(Click to change)");
4953 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4954 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4956 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4961 } else if ($score < -100) {
4967 $entry_author = $line["author"];
4969 if ($entry_author) {
4970 $entry_author = " - $entry_author";
4973 $has_feed_icon = feed_has_icon($feed_id);
4975 if ($has_feed_icon) {
4976 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
4978 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
4979 $feed_icon_img = "";
4982 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4984 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4985 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4987 $cur_feed_title = $line["feed_title"];
4988 $vgroup_last_feed = $feed_id;
4990 $cur_feed_title = htmlspecialchars($cur_feed_title);
4992 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
4994 print "<tr class='feedTitle'><td colspan='7'>".
4995 "<div style=\"float : right\">$feed_icon_img</div>".
4996 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4997 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5001 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5002 onmouseout='postMouseOut($id)'";
5004 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5006 print "<td class='hlUpdPic'>$update_pic</td>";
5008 print "<td class='hlSelectRow'>
5009 <input type=\"checkbox\" onclick=\"tSR(this)\"
5013 print "<td class='hlMarkedPic'>$marked_pic</td>";
5014 print "<td class='hlMarkedPic'>$published_pic</td>";
5016 # if ($line["feed_title"]) {
5017 # print "<td class='hlContent'>$content_link</td>";
5018 # print "<td class='hlFeed'>
5019 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5020 # truncate_string($line["feed_title"],30)."</a> </td>";
5023 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5025 print "<a id=\"RTITLE-$id\"
5026 href=\"" . htmlspecialchars($line["link"]) . "\"
5027 onclick=\"return view($id,$feed_id);\">" .
5030 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5031 if ($content_preview) {
5032 print "<span class=\"contentPreview\"> - $content_preview</span>";
5040 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5041 # $line["feed_title"]."</a>
5043 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5044 if ($line["feed_title"]) {
5045 print "<span class=\"hlFeed\">
5046 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5047 $line["feed_title"]."</a>)
5055 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5057 print "<td class='hlMarkedPic'>$score_pic</td>";
5059 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5060 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5067 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5068 if ($feed_id != $vgroup_last_feed) {
5070 $cur_feed_title = $line["feed_title"];
5071 $vgroup_last_feed = $feed_id;
5073 $cur_feed_title = htmlspecialchars($cur_feed_title);
5075 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5077 $has_feed_icon = feed_has_icon($feed_id);
5079 if ($has_feed_icon) {
5080 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5082 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5085 print "<div class='cdmFeedTitle'>".
5086 "<div style=\"float : right\">$feed_icon_img</div>".
5087 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5088 $line["feed_title"]."</a> $vf_catchup_link</div>";
5093 $add_class = "Unread";
5098 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5099 $show_excerpt = false;
5101 if ($expand_cdm && $score >= -100) {
5103 $show_excerpt = false;
5105 $cdm_cstyle = "style=\"display : none\"";
5106 $show_excerpt = true;
5109 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5110 onmouseout='postMouseOut($id)'";
5112 print "<div class=\"cdmArticle$add_class\"
5114 $mouseover_attrs'>";
5116 print "<div class=\"cdmHeader\">";
5118 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5119 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5122 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5125 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5126 onclick=\"javascript:toggleUnread($id, 0)\"
5127 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5130 print $entry_author;
5132 /* if (!$expand_cdm || $score < -100) {
5133 print " <a id=\"CICH-$id\"
5134 href=\"javascript:cdmExpandArticle($id)\">
5135 (".__('Show article').")</a>";
5140 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5141 if ($line["feed_title"]) {
5142 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5146 print "</span></div>";
5148 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5149 $line["content_preview"] = preg_replace("/href=/i",
5150 "target=\"_blank\" href=", $line["content_preview"]);
5153 if ($show_excerpt) {
5154 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5155 onclick=\"cdmExpandArticle($id)\"
5156 title=\"".__('Click to expand article')."\">";
5157 print truncate_string(strip_tags($line["content_preview"]), 100);
5161 print "<div class=\"cdmContent\"
5162 onclick=\"cdmClicked($id)\"
5163 id=\"CICD-$id\" $cdm_cstyle>";
5165 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5167 print sanitize_rss($link, $line["content_preview"]);
5168 $article_content = $line["content_preview"];
5170 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5171 post_id = '$id' AND content_url != ''");
5173 if (db_num_rows($e_result) > 0) {
5175 $entries_html = array();
5178 while ($e_line = db_fetch_assoc($e_result)) {
5180 $url = $e_line["content_url"];
5181 $ctype = $e_line["content_type"];
5182 if (!$ctype) $ctype = __("unknown type");
5184 $filename = substr($url, strrpos($url, "/")+
1);
5188 if (($ctype == __("audio/mpeg")) &&
5189 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5191 $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> ";
5195 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5196 $filename . " (" . $ctype . ")" . "</a>";
5198 array_push($entries_html, $entry);
5202 $entry["type"] = $ctype;
5203 $entry["filename"] = $filename;
5204 $entry["url"] = $url;
5206 array_push($entries, $entry);
5209 if (!preg_match("/img/i", $article_content)) {
5210 foreach ($entries as $entry) {
5211 if (preg_match("/image/", $entry["type"])) {
5213 alt=\"".htmlspecialchars($entry["filename"])."\"
5214 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5219 print "<div class=\"cdmEnclosures\">";
5221 if (db_num_rows($e_result) == 1) {
5222 print __("Attachment:") . " ";
5224 print __("Attachments:") . " ";
5227 print join(", ", $entries_html);
5233 print "<br clear='both'>";
5236 /* if (!$expand_cdm) {
5237 print "<a id=\"CICH-$id\"
5238 href=\"javascript:cdmExpandArticle($id)\">
5244 print "<div class=\"cdmFooter\"><span class='s0'>";
5246 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5248 print __("Select:").
5249 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5250 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5252 print "</span><span class='s1'>$marked_pic</span> ";
5253 print "<span class='s1'>$published_pic</span> ";
5254 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5255 onclick=\"zoomToArticle($id)\"
5256 style=\"cursor : pointer\"
5258 title='".__('Show article summary in new window')."'></span>";
5260 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5262 // print "<img src='images/tag.png' class='markedPic'>";
5264 print "<span class='s1'>
5265 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5266 <span id=\"ATSTR-$id\">$tags_str</span>
5267 <a title=\"".__('Edit tags for this article')."\"
5268 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5272 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5273 href=\"javascript:toggleUnread($id)\">
5284 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5291 switch ($view_mode) {
5293 $message = __("No unread articles found to display.");
5296 $message = __("No updated articles found to display.");
5299 $message = __("No starred articles found to display.");
5303 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5305 $message = __("No articles found to display.");
5309 if (!$offset) print "<div class='whiteBox'>$message</div>";
5317 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5320 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5322 function printTagCloud($link) {
5324 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5325 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5326 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5328 $result = db_query($link, $query);
5332 while ($line = db_fetch_assoc($result)) {
5333 $tags[$line["tag_name"]] = $line["count"];
5338 $max_size = 32; // max font size in pixels
5339 $min_size = 11; // min font size in pixels
5341 // largest and smallest array values
5342 $max_qty = max(array_values($tags));
5343 $min_qty = min(array_values($tags));
5345 // find the range of values
5346 $spread = $max_qty - $min_qty;
5347 if ($spread == 0) { // we don't want to divide by zero
5351 // set the font-size increment
5352 $step = ($max_size - $min_size) / ($spread);
5354 // loop through the tag array
5355 foreach ($tags as $key => $value) {
5356 // calculate font-size
5357 // find the $value in excess of $min_qty
5358 // multiply by the font-size increment ($size)
5359 // and add the $min_size set above
5360 $size = round($min_size +
(($value - $min_qty) * $step));
5362 $key_escaped = str_replace("'", "\\'", $key);
5364 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5365 $size . "px\" title=\"$value articles tagged with " .
5366 $key . '">' . $key . '</a> ';
5370 function print_checkpoint($n, $s) {
5371 $ts = getmicrotime();
5372 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5376 function sanitize_tag($tag) {
5379 $tag = mb_strtolower($tag, 'utf-8');
5381 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5383 // $tag = str_replace('"', "", $tag);
5384 // $tag = str_replace("+", " ", $tag);
5385 $tag = str_replace("technorati tag: ", "", $tag);
5390 function generate_publish_key() {
5391 return sha1(uniqid(rand(), true));
5394 function article_publish_url($link) {
5399 if ($_SERVER['HTTPS'] != "on") {
5400 $url_path = "http://";
5402 $url_path = "https://";
5405 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5406 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5412 * Purge a feed contents, marked articles excepted.
5414 * @param mixed $link The database connection.
5415 * @param integer $id The id of the feed to purge.
5418 function clear_feed_articles($link, $id) {
5419 $result = db_query($link, "DELETE FROM ttrss_user_entries
5420 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5422 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5423 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5425 ccache_update($link, $id, $_SESSION['uid']);
5426 } // function clear_feed_articles
5429 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5431 * @return string The Mozilla Firefox feed adding URL.
5433 function add_feed_url() {
5434 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5435 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5437 } // function add_feed_url
5440 * Encrypt a password in SHA1.
5442 * @param string $pass The password to encrypt.
5443 * @param string $login A optionnal login.
5444 * @return string The encrypted password.
5446 function encrypt_password($pass, $login = '') {
5448 return "SHA1X:" . sha1("$login:$pass");
5450 return "SHA1:" . sha1($pass);
5452 } // function encrypt_password
5455 * Update a feed batch.
5456 * Used by daemons to update n feeds by run.
5457 * Only update feed needing a update, and not being processed
5458 * by another process.
5460 * @param mixed $link Database link
5461 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5462 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5463 * @param boolean $debug Set to false to disable debug output. Default to true.
5466 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5467 // Process all other feeds using last_updated and interval parameters
5469 // Test if the user has loggued in recently. If not, it does not update its feeds.
5470 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5471 if (DB_TYPE
== "pgsql") {
5472 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5474 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5477 $login_thresh_qpart = "";
5480 // Test if the feed need a update (update interval exceded).
5481 if (DB_TYPE
== "pgsql") {
5482 $update_limit_qpart = "AND ((
5483 ttrss_feeds.update_interval = 0
5484 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5486 ttrss_feeds.update_interval > 0
5487 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5488 ) OR ttrss_feeds.last_updated IS NULL)";
5490 $update_limit_qpart = "AND ((
5491 ttrss_feeds.update_interval = 0
5492 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5494 ttrss_feeds.update_interval > 0
5495 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5496 ) OR ttrss_feeds.last_updated IS NULL)";
5499 // Test if feed is currently being updated by another process.
5500 if (DB_TYPE
== "pgsql") {
5501 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5503 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5506 // Test if there is a limit to number of updated feeds
5508 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5510 $random_qpart = sql_random_function();
5512 // We search for feed needing update.
5513 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5514 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5515 ttrss_feeds.update_interval
5517 ttrss_feeds, ttrss_users, ttrss_user_prefs
5519 ttrss_feeds.owner_uid = ttrss_users.id
5520 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5521 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5522 $login_thresh_qpart $update_limit_qpart
5523 $updstart_thresh_qpart
5524 ORDER BY $random_qpart $query_limit");
5526 $user_prefs_cache = array();
5528 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5530 // Here is a little cache magic in order to minimize risk of double feed updates.
5531 $feeds_to_update = array();
5532 while ($line = db_fetch_assoc($result)) {
5533 $feeds_to_update[$line['id']] = $line;
5536 // We update the feed last update started date before anything else.
5537 // There is no lag due to feed contents downloads
5538 // It prevent an other process to update the same feed.
5539 $feed_ids = array_keys($feeds_to_update);
5541 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5542 WHERE id IN (%s)", implode(',', $feed_ids)));
5545 // For each feed, we call the feed update function.
5546 while ($line = array_pop($feeds_to_update)) {
5548 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5550 // We setup a alarm to alert if the feed take more than 300s to update.
5552 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5553 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5554 // Cancel the alarm (the update went well)
5555 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5557 sleep(1); // prevent flood (FIXME make this an option?)
5560 // Send feed digests by email if needed.
5561 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5563 purge_orphans($link);
5565 } // function update_daemon_common
5567 function sanitize_article_content($text) {
5568 # we don't support CDATA sections in articles, they break our own escaping
5569 $text = preg_replace("/\[\[CDATA/", "", $text);
5570 $text = preg_replace("/\]\]\>/", "", $text);
5574 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5577 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5579 $result = db_query($link, "SELECT reg_exp,
5580 ttrss_filter_types.name AS name,
5581 ttrss_filter_actions.name AS action,
5585 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5588 owner_uid = $owner_uid AND
5589 ttrss_filter_types.id = filter_type AND
5590 ttrss_filter_actions.id = action_id AND
5591 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5593 while ($line = db_fetch_assoc($result)) {
5594 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5595 $filter["reg_exp"] = $line["reg_exp"];
5596 $filter["action"] = $line["action"];
5597 $filter["action_param"] = $line["action_param"];
5598 $filter["filter_param"] = $line["filter_param"];
5599 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5601 array_push($filters[$line["name"]], $filter);
5607 function get_score_pic($score) {
5609 return "score_high.png";
5610 } else if ($score > 0) {
5611 return "score_half_high.png";
5612 } else if ($score < -100) {
5613 return "score_low.png";
5614 } else if ($score < 0) {
5615 return "score_half_low.png";
5617 return "score_neutral.png";
5621 function rounded_table_start($classname, $header = " ") {
5622 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5623 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5624 print "<tr><td class='left'> </td><td class='content'>";
5627 function rounded_table_end($footer = " ") {
5628 print "</td><td class='right'> </td></tr>";
5629 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5633 function feed_has_icon($id) {
5634 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5637 function init_connection($link) {
5638 if (DB_TYPE
== "pgsql") {
5639 pg_query($link, "set client_encoding = 'UTF-8'");
5640 pg_set_client_encoding("UNICODE");
5641 pg_query($link, "set datestyle = 'ISO, european'");
5643 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5644 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5645 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5650 function update_feedbrowser_cache($link) {
5652 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5653 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5654 WHERE tf.feed_url = ttrss_feeds.feed_url
5655 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5656 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5658 db_query($link, "BEGIN");
5660 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5664 while ($line = db_fetch_assoc($result)) {
5665 $subscribers = db_escape_string($line["subscribers"]);
5666 $feed_url = db_escape_string($line["feed_url"]);
5667 $title = db_escape_string($line["title"]);
5669 $tmp_result = db_query($link, "SELECT subscribers FROM
5670 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5672 if (db_num_rows($tmp_result) == 0) {
5674 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5675 (feed_url, title, subscribers) VALUES ('$feed_url',
5676 '$title', '$subscribers')");
5684 db_query($link, "COMMIT");
5690 function ccache_zero($link, $feed_id, $owner_uid) {
5691 db_query($link, "UPDATE ttrss_counters_cache SET
5692 value = 0, updated = NOW() WHERE
5693 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5696 function ccache_zero_all($link, $owner_uid) {
5697 db_query($link, "UPDATE ttrss_counters_cache SET
5698 value = 0 WHERE owner_uid = '$owner_uid'");
5700 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5701 value = 0 WHERE owner_uid = '$owner_uid'");
5704 function ccache_update_all($link, $owner_uid) {
5706 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5708 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5709 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5711 while ($line = db_fetch_assoc($result)) {
5712 ccache_update($link, $line["feed_id"], $owner_uid, true);
5715 /* We have to manually include category 0 */
5717 ccache_update($link, 0, $owner_uid, true);
5720 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5721 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5723 while ($line = db_fetch_assoc($result)) {
5724 print ccache_update($link, $line["feed_id"], $owner_uid);
5731 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5732 $no_update = false) {
5734 if (!is_numeric($feed_id)) return;
5737 $table = "ttrss_counters_cache";
5739 $table = "ttrss_cat_counters_cache";
5742 if (DB_TYPE
== "pgsql") {
5743 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5744 } else if (DB_TYPE
== "mysql") {
5745 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5748 $result = db_query($link, "SELECT value FROM $table
5749 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5752 if (db_num_rows($result) == 1) {
5753 return db_fetch_result($result, 0, "value");
5758 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5764 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5765 $update_pcat = true) {
5767 if (!is_numeric($feed_id)) return;
5769 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5771 /* When updating a label, all we need to do is recalculate feed counters
5772 * because labels are not cached */
5775 ccache_update_all($link, $owner_uid);
5780 $table = "ttrss_counters_cache";
5782 $table = "ttrss_cat_counters_cache";
5785 if ($is_cat && $feed_id >= 0) {
5786 if ($feed_id != 0) {
5787 $cat_qpart = "cat_id = '$feed_id'";
5789 $cat_qpart = "cat_id IS NULL";
5792 /* Recalculate counters for child feeds */
5794 $result = db_query($link, "SELECT id FROM ttrss_feeds
5795 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5797 while ($line = db_fetch_assoc($result)) {
5798 ccache_update($link, $line["id"], $owner_uid, false, false);
5801 $result = db_query($link, "SELECT SUM(value) AS sv
5802 FROM ttrss_counters_cache, ttrss_feeds
5803 WHERE id = feed_id AND $cat_qpart AND
5804 ttrss_feeds.owner_uid = '$owner_uid'");
5806 $unread = (int) db_fetch_result($result, 0, "sv");
5809 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5812 $result = db_query($link, "SELECT feed_id FROM $table
5813 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5815 if (db_num_rows($result) == 1) {
5816 db_query($link, "UPDATE $table SET
5817 value = '$unread', updated = NOW() WHERE
5818 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5821 db_query($link, "INSERT INTO $table
5822 (feed_id, value, owner_uid, updated)
5824 ($feed_id, $unread, $owner_uid, NOW())");
5827 if ($feed_id > 0 && $prev_unread != $unread) {
5831 /* Update parent category */
5835 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5836 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5838 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5840 ccache_update($link, $cat_id, $owner_uid, true);
5844 } else if ($feed_id < 0) {
5845 ccache_update_all($link, $owner_uid);
5851 function label_find_id($link, $label, $owner_uid) {
5852 $result = db_query($link,
5853 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5854 AND owner_uid = '$owner_uid' LIMIT 1");
5856 if (db_num_rows($result) == 1) {
5857 return db_fetch_result($result, 0, "id");
5863 function get_article_labels($link, $id) {
5864 $result = db_query($link,
5865 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5866 FROM ttrss_labels2, ttrss_user_labels2
5868 AND article_id = '$id'
5869 AND owner_uid = ".$_SESSION["uid"] . "
5874 while ($line = db_fetch_assoc($result)) {
5875 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5877 array_push($rv, $rk);
5884 function label_find_caption($link, $label, $owner_uid) {
5885 $result = db_query($link,
5886 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5887 AND owner_uid = '$owner_uid' LIMIT 1");
5889 if (db_num_rows($result) == 1) {
5890 return db_fetch_result($result, 0, "caption");
5896 function label_remove_article($link, $id, $label, $owner_uid) {
5898 $label_id = label_find_id($link, $label, $owner_uid);
5900 if (!$label_id) return;
5902 $result = db_query($link,
5903 "DELETE FROM ttrss_user_labels2
5905 label_id = '$label_id' AND
5906 article_id = '$id'");
5909 function label_add_article($link, $id, $label, $owner_uid) {
5911 $label_id = label_find_id($link, $label, $owner_uid);
5913 if (!$label_id) return;
5915 $result = db_query($link,
5917 article_id FROM ttrss_labels2, ttrss_user_labels2
5920 label_id = '$label_id' AND
5921 article_id = '$id' AND owner_uid = '$owner_uid'
5924 if (db_num_rows($result) == 0) {
5925 db_query($link, "INSERT INTO ttrss_user_labels2
5926 (label_id, article_id) VALUES ('$label_id', '$id')");
5930 function label_remove($link, $id, $owner_uid) {
5932 db_query($link, "BEGIN");
5934 $result = db_query($link, "SELECT caption FROM ttrss_labels2
5937 $caption = db_fetch_result($result, 0, "caption");
5939 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
5940 AND owner_uid = " . $_SESSION["uid"]);
5942 if (db_affected_rows($link, $result) != 0 && $caption) {
5944 /* Disable filters that reference label being removed */
5946 db_query($link, "UPDATE ttrss_filters SET
5947 enabled = false WHERE action_param = '$caption'
5949 AND owner_uid = " . $_SESSION["uid"]);
5952 db_query($link, "COMMIT");
5955 function label_create($link, $caption) {
5957 db_query($link, "BEGIN");
5961 $result = db_query($link, "SELECT id FROM ttrss_labels2
5962 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
5964 if (db_num_rows($result) == 0) {
5965 $result = db_query($link,
5966 "INSERT INTO ttrss_labels2 (caption,owner_uid)
5967 VALUES ('$caption', '".$_SESSION["uid"]."')");
5969 $result = db_affected_rows($link, $result) != 0;
5972 db_query($link, "COMMIT");
5977 function print_labels_headlines_dropdown($link, $feed_id) {
5978 print "<li onclick=\"javascript:addLabel()\">
5979 ".__("Create label...")."</li>";
5981 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
5982 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
5984 while ($line = db_fetch_assoc($result)) {
5986 $label_id = $line["id"];
5987 $label_caption = $line["caption"];
5989 if ($feed_id < -10 && $feed_id == -11-$label_id) {
5990 print "<li id=\"LHDL-$id\"
5991 onclick=\"javascript:selectionRemoveLabel($label_id)\">
5992 $label_caption ".__('(remove)')."</li>";
5994 print "<li id=\"LHDL-$id\"
5995 onclick=\"javascript:selectionAssignLabel($label_id)\">
5996 $label_caption</li>";
6001 function format_tags_string($tags, $id) {
6004 $tags_nolinks_str = "";
6008 if ($_SESSION["theme"] == "3pane") {
6014 $formatted_tags = array();
6016 foreach ($tags as $tag) {
6018 $tag_escaped = str_replace("'", "\\'", $tag);
6020 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6022 array_push($formatted_tags, $tag_str);
6024 if ($num_tags == $tag_limit) {
6029 $tags_str = implode(", ", $formatted_tags);
6031 if ($num_tags < count($tags)) {
6032 $tags_str .= ", …";
6035 if ($num_tags == 0) {
6036 $tags_str = __("no tags");
6043 function format_article_labels($labels, $id) {
6047 foreach ($labels as $l) {
6048 $labels_str .= sprintf("<span class='hlLabelRef'
6049 style='color : %s; background-color : %s'>%s</span>",
6050 $l[2], $l[3], $l[1]);