3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
28 "fr_FR" => "Français",
29 "hu_HU" => "Magyar (Hungarian)",
30 "it_IT" => "Italiano",
31 "ja_JP" => "日本語 (Japanese)",
32 "nb_NO" => "Norwegian bokmål",
34 "pt_BR" => "Portuguese/Brazil",
35 "zh_CN" => "Simplified Chinese");
40 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
41 require_once "accept-to-gettext.php";
42 require_once "lib/gettext/gettext.inc";
44 function startup_gettext() {
46 # Get locale from Accept-Language header
47 $lang = al2gt(array_keys(get_translations()), "text/html");
49 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
50 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
53 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
54 $lang = $_COOKIE["ttrss_lang"];
57 /* In login action of mobile version */
58 if ($_POST["language"] && defined('MOBILE_VERSION')) {
59 $lang = $_POST["language"];
60 $_COOKIE["ttrss_lang"] = $lang;
64 if (defined('LC_MESSAGES')) {
65 _setlocale(LC_MESSAGES
, $lang);
66 } else if (defined('LC_ALL')) {
67 _setlocale(LC_ALL
, $lang);
69 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
72 if (defined('MOBILE_VERSION')) {
73 _bindtextdomain("messages", "../locale");
75 _bindtextdomain("messages", "locale");
78 _textdomain("messages");
79 _bind_textdomain_codeset("messages", "UTF-8");
85 } else { // If translations are enabled.
89 function startup_gettext() {
93 } // If translations are enabled.
95 require_once 'db-prefs.php';
96 require_once 'compat.php';
97 require_once 'errors.php';
98 require_once 'version.php';
100 require_once 'lib/phpmailer/class.phpmailer.php';
102 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
103 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
104 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
106 require_once "lib/simplepie/simplepie.inc";
107 require_once "lib/magpierss/rss_fetch.inc";
108 require_once 'lib/magpierss/rss_utils.inc';
111 * Print a timestamped debug message.
113 * @param string $msg The debug message.
116 function _debug($msg) {
117 $ts = strftime("%H:%M:%S", time());
118 if (function_exists('posix_getpid')) {
119 $ts = "$ts/" . posix_getpid();
121 print "[$ts] $msg\n";
125 * Purge a feed old posts.
127 * @param mixed $link A database connection.
128 * @param mixed $feed_id The id of the purged feed.
129 * @param mixed $purge_interval Olderness of purged posts.
130 * @param boolean $debug Set to True to enable the debug. False by default.
134 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
136 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
140 $result = db_query($link,
141 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
145 if (db_num_rows($result) == 1) {
146 $owner_uid = db_fetch_result($result, 0, "owner_uid");
149 if ($purge_interval == -1 ||
!$purge_interval) {
151 ccache_update($link, $feed_id, $owner_uid);
156 if (!$owner_uid) return;
158 if (FORCE_ARTICLE_PURGE
== 0) {
159 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
162 $purge_unread = true;
163 $purge_interval = FORCE_ARTICLE_PURGE
;
166 if (!$purge_unread) $query_limit = " unread = false AND ";
168 if (DB_TYPE
== "pgsql") {
169 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
170 marked = false AND feed_id = '$feed_id' AND
171 (SELECT date_entered FROM ttrss_entries WHERE
172 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
174 $pg_version = get_pgsql_version($link);
176 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
178 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
179 ttrss_entries.id = ref_id AND
181 feed_id = '$feed_id' AND
183 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
187 $result = db_query($link, "DELETE FROM ttrss_user_entries
189 WHERE ttrss_entries.id = ref_id AND
191 feed_id = '$feed_id' AND
193 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
196 $rows = pg_affected_rows($result);
200 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
201 marked = false AND feed_id = '$feed_id' AND
202 (SELECT date_entered FROM ttrss_entries WHERE
203 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
205 $result = db_query($link, "DELETE FROM ttrss_user_entries
206 USING ttrss_user_entries, ttrss_entries
207 WHERE ttrss_entries.id = ref_id AND
209 feed_id = '$feed_id' AND
211 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
213 $rows = mysql_affected_rows($link);
217 ccache_update($link, $feed_id, $owner_uid);
220 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
222 } // function purge_feed
225 * Purge old posts from old feeds.
227 * @param mixed $link A database connection
228 * @param boolean $do_output Set to true to enable printed output, false by default.
229 * @param integer $limit The maximal number of removed posts.
233 function global_purge_old_posts($link, $do_output = false, $limit = false) {
235 $random_qpart = sql_random_function();
238 $limit_qpart = "LIMIT $limit";
243 $result = db_query($link,
244 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
245 ORDER BY $random_qpart $limit_qpart");
247 while ($line = db_fetch_assoc($result)) {
249 $feed_id = $line["id"];
250 $purge_interval = $line["purge_interval"];
251 $owner_uid = $line["owner_uid"];
253 if ($purge_interval == 0) {
255 $tmp_result = db_query($link,
256 "SELECT value FROM ttrss_user_prefs WHERE
257 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
259 if (db_num_rows($tmp_result) != 0) {
260 $purge_interval = db_fetch_result($tmp_result, 0, "value");
265 // print "Feed $feed_id: purge interval = $purge_interval\n";
268 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
269 purge_feed($link, $feed_id, $purge_interval, $do_output);
273 // purge orphaned posts in main content table
274 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
275 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
278 $rows = db_affected_rows($link, $result);
279 _debug("Purged $rows orphaned posts.");
282 } // function global_purge_old_posts
284 function feed_purge_interval($link, $feed_id) {
286 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
287 WHERE id = '$feed_id'");
289 if (db_num_rows($result) == 1) {
290 $purge_interval = db_fetch_result($result, 0, "purge_interval");
291 $owner_uid = db_fetch_result($result, 0, "owner_uid");
293 if ($purge_interval == 0) $purge_interval = get_pref($link,
294 'PURGE_OLD_DAYS', $owner_uid);
296 return $purge_interval;
303 function purge_old_posts($link) {
305 $user_id = $_SESSION["uid"];
307 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
308 WHERE owner_uid = '$user_id'");
310 while ($line = db_fetch_assoc($result)) {
312 $feed_id = $line["id"];
313 $purge_interval = $line["purge_interval"];
315 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
317 if ($purge_interval > 0) {
318 purge_feed($link, $feed_id, $purge_interval);
322 purge_orphans($link);
325 function purge_orphans($link) {
326 // purge orphaned posts in main content table
327 db_query($link, "DELETE FROM ttrss_entries WHERE
328 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
331 function get_feed_update_interval($link, $feed_id) {
332 $result = db_query($link, "SELECT owner_uid, update_interval FROM
333 ttrss_feeds WHERE id = '$feed_id'");
335 if (db_num_rows($result) == 1) {
336 $update_interval = db_fetch_result($result, 0, "update_interval");
337 $owner_uid = db_fetch_result($result, 0, "owner_uid");
339 if ($update_interval != 0) {
340 return $update_interval;
342 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
350 function fetch_file_contents($url) {
351 if (USE_CURL_FOR_ICONS
) {
352 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
354 $ch = curl_init($url);
355 $fp = fopen($tmpfile, "w");
358 curl_setopt($ch, CURLOPT_FILE
, $fp);
359 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
360 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
366 $contents = file_get_contents($tmpfile);
372 return file_get_contents($url);
378 * Try to determine the favicon URL for a feed.
379 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
380 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
382 * @param string $url A feed or page URL
384 * @return mixed The favicon URL, or false if none was found.
386 function get_favicon_url($url) {
388 if ($html = @fetch_file_contents
($url)) {
390 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
391 // Attempt to grab a favicon link from their webpage url
392 $linkUrl = html_entity_decode($matches[1]);
394 if (substr($linkUrl, 0, 1) == '/') {
395 $urlParts = parse_url($url);
396 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
397 } else if (substr($linkUrl, 0, 7) == 'http://') {
398 $faviconURL = $linkUrl;
400 $pos = strrpos($url, "/");
401 // no "/" in url or "/" is part of "://"
402 if ($pos === false ||
$pos == (strpos($url, "://")+
2)) {
403 $faviconURL = $url.'/'.$linkUrl;
405 $faviconURL = substr($url, 0, $pos+
1).$linkUrl;
410 // If unsuccessful, attempt to "guess" the favicon location
411 $urlParts = parse_url($url);
412 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
416 // Run a test to see if what we have attempted to get actually exists.
417 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
422 } // function get_favicon_url
425 * Check if a link is a valid and working URL.
427 * @param mixed $link A URL to check
429 * @return boolean True if the URL is valid, false otherwise.
431 function url_validate($link) {
433 $url_parts = @parse_url
($link);
435 if ( empty( $url_parts["host"] ) )
438 if ( !empty( $url_parts["path"] ) ) {
439 $documentpath = $url_parts["path"];
444 if ( !empty( $url_parts["query"] ) )
445 $documentpath .= "?" . $url_parts["query"];
447 $host = $url_parts["host"];
448 $port = $url_parts["port"];
453 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
458 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
460 $http_response = fgets( $socket, 22 );
462 $responses = "/(200 OK)|(30[123])/";
463 if ( preg_match($responses, $http_response) ) {
470 } // function url_validate
472 function check_feed_favicon($site_url, $feed, $link) {
473 $favicon_url = get_favicon_url($site_url);
475 # print "FAVICON [$site_url]: $favicon_url\n";
479 $icon_file = ICONS_DIR
. "/$feed.ico";
481 if ($favicon_url && !file_exists($icon_file)) {
482 $contents = fetch_file_contents($favicon_url);
484 $fp = fopen($icon_file, "w");
487 fwrite($fp, $contents);
489 chmod($icon_file, 0644);
493 error_reporting(DEFAULT_ERROR_LEVEL
);
497 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
499 if (!$_GET["daemon"] && !$ignore_daemon) {
503 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
504 _debug("update_rss_feed: start");
507 if (!$ignore_daemon) {
509 if (DB_TYPE
== "pgsql") {
510 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
512 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
515 $result = db_query($link, "SELECT id,update_interval,auth_login,
516 auth_pass,cache_images,update_method
517 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
521 $result = db_query($link, "SELECT id,update_interval,auth_login,
522 auth_pass,cache_images,update_method,hidden,last_updated
523 FROM ttrss_feeds WHERE id = '$feed'");
527 if (db_num_rows($result) == 0) {
528 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
529 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
534 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
535 $update_method = db_fetch_result($result, 0, "update_method");
536 $last_updated = db_fetch_result($result, 0, "last_updated");
538 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
539 WHERE id = '$feed'");
541 $auth_login = db_fetch_result($result, 0, "auth_login");
542 $auth_pass = db_fetch_result($result, 0, "auth_pass");
544 if (ALLOW_SELECT_UPDATE_METHOD
) {
545 if (ENABLE_SIMPLEPIE
) {
546 $use_simplepie = $update_method != 1;
548 $use_simplepie = $update_method == 2;
551 $use_simplepie = ENABLE_SIMPLEPIE
;
554 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
555 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
558 if (!$use_simplepie) {
559 $auth_login = urlencode($auth_login);
560 $auth_pass = urlencode($auth_pass);
563 $update_interval = db_fetch_result($result, 0, "update_interval");
564 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
566 if ($update_interval < 0) { return; }
568 $feed = db_escape_string($feed);
570 $fetch_url = $feed_url;
572 if ($auth_login && $auth_pass) {
573 $url_parts = array();
574 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
576 if ($url_parts[1] && $url_parts[2]) {
577 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
582 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
583 _debug("update_rss_feed: fetching [$fetch_url]...");
586 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
590 if (!$use_simplepie) {
591 $rss = fetch_rss($fetch_url);
593 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
594 mkdir(SIMPLEPIE_CACHE_DIR
);
597 $rss = new SimplePie();
598 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
599 # $rss->set_timeout(10);
600 $rss->set_feed_url($fetch_url);
601 $rss->set_output_encoding('UTF-8');
603 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
604 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
605 _debug("enabling image cache");
608 $rss->set_image_handler('./image.php', 'i');
611 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
612 _debug("feed update interval (sec): " .
613 get_feed_update_interval($link, $feed)*60);
616 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
617 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
618 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
626 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
627 _debug("update_rss_feed: fetch done, parsing...");
629 error_reporting (DEFAULT_ERROR_LEVEL
);
632 $feed = db_escape_string($feed);
634 if ($use_simplepie) {
635 $fetch_ok = !$rss->error();
642 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
643 _debug("update_rss_feed: processing feed data...");
646 // db_query($link, "BEGIN");
648 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
649 FROM ttrss_feeds WHERE id = '$feed'");
651 $registered_title = db_fetch_result($result, 0, "title");
652 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
653 $orig_site_url = db_fetch_result($result, 0, "site_url");
655 $owner_uid = db_fetch_result($result, 0, "owner_uid");
657 if ($use_simplepie) {
658 $site_url = $rss->get_link();
660 $site_url = $rss->channel
["link"];
663 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
664 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
665 _debug("update_rss_feed: checking favicon...");
668 check_feed_favicon($site_url, $feed, $link);
671 if (!$registered_title ||
$registered_title == "[Unknown]") {
673 if ($use_simplepie) {
674 $feed_title = db_escape_string($rss->get_title());
676 $feed_title = db_escape_string($rss->channel
["title"]);
679 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
680 _debug("update_rss_feed: registering title: $feed_title");
683 db_query($link, "UPDATE ttrss_feeds SET
684 title = '$feed_title' WHERE id = '$feed'");
687 // weird, weird Magpie
688 if (!$use_simplepie) {
689 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
692 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
693 db_query($link, "UPDATE ttrss_feeds SET
694 site_url = '$site_url' WHERE id = '$feed'");
697 // print "I: " . $rss->channel["image"]["url"];
699 if (!$use_simplepie) {
700 $icon_url = $rss->image
["url"];
702 $icon_url = $rss->get_image_url();
705 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
706 $icon_url = db_escape_string($icon_url);
707 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
710 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
711 _debug("update_rss_feed: loading filters...");
714 $filters = load_filters($link, $feed, $owner_uid);
716 if ($use_simplepie) {
717 $iterator = $rss->get_items();
719 $iterator = $rss->items
;
720 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
721 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
724 if (!is_array($iterator)) {
725 /* db_query($link, "UPDATE ttrss_feeds
726 SET last_error = 'Parse error: can\'t find any articles.'
727 WHERE id = '$feed'"); */
729 // clear any errors and mark feed as updated if fetched okay
730 // even if it's blank
732 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
733 _debug("update_rss_feed: entry iterator is not an array, no articles?");
736 db_query($link, "UPDATE ttrss_feeds
737 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
739 return; // no articles
742 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
743 _debug("update_rss_feed: processing articles...");
746 foreach ($iterator as $item) {
748 if ($_GET['xdebug']) {
753 if ($use_simplepie) {
754 $entry_guid = $item->get_id();
755 if (!$entry_guid) $entry_guid = $item->get_link();
756 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
760 $entry_guid = $item["id"];
762 if (!$entry_guid) $entry_guid = $item["guid"];
763 if (!$entry_guid) $entry_guid = $item["link"];
764 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
767 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
768 _debug("update_rss_feed: guid $entry_guid");
771 if (!$entry_guid) continue;
773 $entry_timestamp = "";
775 if ($use_simplepie) {
776 $entry_timestamp = strtotime($item->get_date());
778 $rss_2_date = $item['pubdate'];
779 $rss_1_date = $item['dc']['date'];
780 $atom_date = $item['issued'];
781 if (!$atom_date) $atom_date = $item['updated'];
783 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
784 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
785 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
788 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
789 $entry_timestamp = time();
790 $no_orig_date = 'true';
792 $no_orig_date = 'false';
795 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
797 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
798 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
801 if ($use_simplepie) {
802 $entry_title = $item->get_title();
804 $entry_title = trim(strip_tags($item["title"]));
807 if ($use_simplepie) {
808 $entry_link = $item->get_link();
810 // strange Magpie workaround
811 $entry_link = $item["link_"];
812 if (!$entry_link) $entry_link = $item["link"];
815 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
816 _debug("update_rss_feed: title $entry_title");
819 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
821 $entry_link = strip_tags($entry_link);
823 if ($use_simplepie) {
824 $entry_content = $item->get_content();
825 if (!$entry_content) $entry_content = $item->get_description();
827 $entry_content = $item["content:escaped"];
829 if (!$entry_content) $entry_content = $item["content:encoded"];
830 if (!$entry_content) $entry_content = $item["content"]["encoded"];
831 if (!$entry_content) $entry_content = $item["content"];
833 // Magpie bugs are getting ridiculous
834 if (trim($entry_content) == "Array") $entry_content = false;
836 if (!$entry_content) $entry_content = $item["atom_content"];
837 if (!$entry_content) $entry_content = $item["summary"];
839 if (!$entry_content ||
840 strlen($entry_content) < strlen($item["description"])) {
841 $entry_content = $item["description"];
845 if (is_array($entry_content)) {
846 $entry_content = $entry_content["encoded"];
847 if (!$entry_content) $entry_content = $entry_content["escaped"];
851 if ($_GET["xdebug"]) {
852 print "update_rss_feed: content: ";
853 print_r(htmlspecialchars($entry_content));
856 $entry_content_unescaped = $entry_content;
858 if ($use_simplepie) {
859 $entry_comments = strip_tags($item->data
["comments"]);
860 if ($item->get_author()) {
861 $entry_author_item = $item->get_author();
862 $entry_author = $entry_author_item->get_name();
863 if (!$entry_author) $entry_author = $entry_author_item->get_email();
865 $entry_author = db_escape_string($entry_author);
868 $entry_comments = strip_tags($item["comments"]);
870 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
872 if ($item['author']) {
874 if (is_array($item['author'])) {
876 if (!$entry_author) {
877 $entry_author = db_escape_string(strip_tags($item['author']['name']));
880 if (!$entry_author) {
881 $entry_author = db_escape_string(strip_tags($item['author']['email']));
885 if (!$entry_author) {
886 $entry_author = db_escape_string(strip_tags($item['author']));
891 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
893 $entry_guid = db_escape_string(strip_tags($entry_guid));
894 $entry_guid = mb_substr($entry_guid, 0, 250);
896 $result = db_query($link, "SELECT id FROM ttrss_entries
897 WHERE guid = '$entry_guid'");
899 $entry_content = db_escape_string($entry_content);
901 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
903 $entry_title = db_escape_string($entry_title);
904 $entry_link = db_escape_string($entry_link);
905 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
906 $entry_author = mb_substr($entry_author, 0, 250);
908 if ($use_simplepie) {
909 $num_comments = 0; #FIXME#
911 $num_comments = db_escape_string($item["slash"]["comments"]);
914 if (!$num_comments) $num_comments = 0;
916 // parse <category> entries into tags
918 if ($use_simplepie) {
920 $additional_tags = array();
921 $additional_tags_src = $item->get_categories();
923 if (is_array($additional_tags_src)) {
924 foreach ($additional_tags_src as $tobj) {
925 array_push($additional_tags, $tobj->get_term());
929 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
930 _debug("update_rss_feed: category tags:");
931 print_r($additional_tags);
936 $t_ctr = $item['category#'];
938 $additional_tags = false;
941 $additional_tags = false;
942 } else if ($t_ctr > 0) {
943 $additional_tags = array($item['category']);
945 if ($item['category@term']) {
946 array_push($additional_tags, $item['category@term']);
949 for ($i = 0; $i <= $t_ctr; $i++
) {
950 if ($item["category#$i"]) {
951 array_push($additional_tags, $item["category#$i"]);
954 if ($item["category#$i@term"]) {
955 array_push($additional_tags, $item["category#$i@term"]);
960 // parse <dc:subject> elements
962 $t_ctr = $item['dc']['subject#'];
965 $additional_tags = array($item['dc']['subject']);
967 for ($i = 0; $i <= $t_ctr; $i++
) {
968 if ($item['dc']["subject#$i"]) {
969 array_push($additional_tags, $item['dc']["subject#$i"]);
977 $enclosures = array();
979 if ($use_simplepie) {
980 $encs = $item->get_enclosures();
982 if (is_array($encs)) {
983 foreach ($encs as $e) {
985 $e->link
, $e->type
, $e->length
);
987 array_push($enclosures, $e_item);
994 $e_ctr = $item['enclosure#'];
997 $e_item = array($item['enclosure@url'],
998 $item['enclosure@type'],
999 $item['enclosure@length']);
1001 array_push($enclosures, $e_item);
1003 for ($i = 0; $i <= $e_ctr; $i++
) {
1005 if ($item["enclosure#$i@url"]) {
1006 $e_item = array($item["enclosure#$i@url"],
1007 $item["enclosure#$i@type"],
1008 $item["enclosure#$i@length"]);
1009 array_push($enclosures, $e_item);
1015 // can there be many of those? yes -fox
1017 $m_ctr = $item['media']['content#'];
1020 $e_item = array($item['media']['content@url'],
1021 $item['media']['content@medium'],
1022 $item['media']['content@length']);
1024 array_push($enclosures, $e_item);
1026 for ($i = 0; $i <= $m_ctr; $i++
) {
1028 if ($item["media"]["content#$i@url"]) {
1029 $e_item = array($item["media"]["content#$i@url"],
1030 $item["media"]["content#$i@medium"],
1031 $item["media"]["content#$i@length"]);
1032 array_push($enclosures, $e_item);
1041 $entry_content = sanitize_article_content($entry_content);
1042 $entry_title = sanitize_article_content($entry_title);
1044 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1045 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1048 db_query($link, "BEGIN");
1050 if (db_num_rows($result) == 0) {
1052 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1053 _debug("update_rss_feed: base guid not found");
1056 // base post entry does not exist, create it
1058 $result = db_query($link,
1059 "INSERT INTO ttrss_entries
1075 '$entry_timestamp_fmt',
1084 // we keep encountering the entry in feeds, so we need to
1085 // update date_entered column so that we don't get horrible
1086 // dupes when the entry gets purged and reinserted again e.g.
1087 // in the case of SLOW SLOW OMG SLOW updating feeds
1089 $base_entry_id = db_fetch_result($result, 0, "id");
1091 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1092 WHERE id = '$base_entry_id'");
1095 // now it should exist, if not - bad luck then
1097 $result = db_query($link, "SELECT
1098 id,content_hash,no_orig_date,title,
1099 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1100 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1104 WHERE guid = '$entry_guid'");
1109 if (db_num_rows($result) == 1) {
1111 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1112 _debug("update_rss_feed: base guid found, checking for user record");
1115 // this will be used below in update handler
1116 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1117 $orig_title = db_fetch_result($result, 0, "title");
1118 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1119 $orig_date_entered = strtotime(db_fetch_result($result,
1120 0, "date_entered"));
1122 $ref_id = db_fetch_result($result, 0, "id");
1123 $entry_ref_id = $ref_id;
1125 // check for user post link to main table
1127 // do we allow duplicate posts with same GUID in different feeds?
1128 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1129 $dupcheck_qpart = "AND feed_id = '$feed'";
1131 $dupcheck_qpart = "";
1134 // error_reporting(0);
1136 $article_filters = get_article_filters($filters, $entry_title,
1137 $entry_content, $entry_link, $entry_timestamp);
1139 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1140 _debug("update_rss_feed: article filters: ");
1141 if (count($article_filters) != 0) {
1142 print_r($article_filters);
1146 if (find_article_filter($article_filters, "filter")) {
1147 db_query($link, "COMMIT"); // close transaction in progress
1151 // error_reporting (DEFAULT_ERROR_LEVEL);
1153 $score = calculate_article_score($article_filters);
1155 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1156 _debug("update_rss_feed: initial score: $score");
1159 $result = db_query($link,
1160 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1161 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1164 // okay it doesn't exist - create user entry
1165 if (db_num_rows($result) == 0) {
1167 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1168 _debug("update_rss_feed: user record not found, creating...");
1171 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1173 $last_read_qpart = 'NULL';
1176 $last_read_qpart = 'NOW()';
1179 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1185 if (find_article_filter($article_filters, 'publish')) {
1186 $published = 'true';
1188 $published = 'false';
1191 $result = db_query($link,
1192 "INSERT INTO ttrss_user_entries
1193 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1195 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1196 $last_read_qpart, $marked, $published, '$score')");
1198 $result = db_query($link,
1199 "SELECT int_id FROM ttrss_user_entries WHERE
1200 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1201 feed_id = '$feed' LIMIT 1");
1203 if (db_num_rows($result) == 1) {
1204 $entry_int_id = db_fetch_result($result, 0, "int_id");
1207 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1208 $entry_int_id = db_fetch_result($result, 0, "int_id");
1211 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1212 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1215 $post_needs_update = false;
1217 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1218 ($content_hash != $orig_content_hash)) {
1219 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1220 $post_needs_update = true;
1223 if (db_escape_string($orig_title) != $entry_title) {
1224 $post_needs_update = true;
1227 if ($orig_num_comments != $num_comments) {
1228 $post_needs_update = true;
1231 // this doesn't seem to be very reliable
1233 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1234 // $post_needs_update = true;
1237 // if post needs update, update it and mark all user entries
1238 // linking to this post as updated
1239 if ($post_needs_update) {
1241 if (defined('DAEMON_EXTENDED_DEBUG')) {
1242 _debug("update_rss_feed: post $entry_guid needs update...");
1245 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1247 db_query($link, "UPDATE ttrss_entries
1248 SET title = '$entry_title', content = '$entry_content',
1249 content_hash = '$content_hash',
1250 num_comments = '$num_comments'
1251 WHERE id = '$ref_id'");
1253 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1254 db_query($link, "UPDATE ttrss_user_entries
1255 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1257 db_query($link, "UPDATE ttrss_user_entries
1258 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1264 db_query($link, "COMMIT");
1266 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1267 _debug("update_rss_feed: assigning labels...");
1270 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1273 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1274 _debug("update_rss_feed: looking for enclosures...");
1277 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1278 print_r($enclosures);
1281 db_query($link, "BEGIN");
1283 foreach ($enclosures as $enc) {
1284 $enc_url = db_escape_string($enc[0]);
1285 $enc_type = db_escape_string($enc[1]);
1286 $enc_dur = db_escape_string($enc[2]);
1288 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1289 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1291 if (db_num_rows($result) == 0) {
1292 db_query($link, "INSERT INTO ttrss_enclosures
1293 (content_url, content_type, title, duration, post_id) VALUES
1294 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1298 db_query($link, "COMMIT");
1300 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1301 _debug("update_rss_feed: looking for tags...");
1305 // <a href="..." rel="tag">Xorg</a>, //
1309 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1310 $entry_content_unescaped, $entry_tags);
1312 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1313 print_r($entry_tags);
1314 print "<br/></p>"; */
1316 $entry_tags = $entry_tags[1];
1318 # check for manual tags
1320 $tag_filter = find_article_filter($article_filters, "tag");
1324 $manual_tags = trim_array(split(",", $tag_filter[1]));
1326 foreach ($manual_tags as $tag) {
1327 if (tag_is_valid($tag)) {
1328 array_push($entry_tags, $tag);
1333 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1334 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1336 if ($additional_tags && is_array($additional_tags)) {
1337 foreach ($additional_tags as $tag) {
1338 if (tag_is_valid($tag) &&
1339 array_search($tag, $boring_tags) === FALSE) {
1340 array_push($entry_tags, $tag);
1345 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1347 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1348 print_r($entry_tags);
1351 if (count($entry_tags) > 0) {
1353 db_query($link, "BEGIN");
1355 foreach ($entry_tags as $tag) {
1357 $tag = sanitize_tag($tag);
1358 $tag = db_escape_string($tag);
1360 if (!tag_is_valid($tag)) continue;
1362 $result = db_query($link, "SELECT id FROM ttrss_tags
1363 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1364 owner_uid = '$owner_uid' LIMIT 1");
1366 // print db_fetch_result($result, 0, "id");
1368 if ($result && db_num_rows($result) == 0) {
1370 db_query($link, "INSERT INTO ttrss_tags
1371 (owner_uid,tag_name,post_int_id)
1372 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1376 db_query($link, "COMMIT");
1379 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1380 _debug("update_rss_feed: article processed");
1384 if (!$last_updated) {
1385 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1386 _debug("update_rss_feed: new feed, catching it up...");
1388 catchup_feed($link, $feed, false, $owner_uid);
1392 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1393 _debug("update_rss_feed: updating counters cache...");
1396 // disabled, purge_feed() does that...
1397 //ccache_update($link, $feed, $owner_uid);
1400 purge_feed($link, $feed, 0);
1402 db_query($link, "UPDATE ttrss_feeds
1403 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1405 // db_query($link, "COMMIT");
1409 if ($use_simplepie) {
1410 $error_msg = mb_substr($rss->error(), 0, 250);
1412 $error_msg = mb_substr(magpie_error(), 0, 250);
1415 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1416 _debug("update_rss_feed: error fetching feed: $error_msg");
1419 $error_msg = db_escape_string($error_msg);
1422 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1423 last_updated = NOW() WHERE id = '$feed'");
1426 if ($use_simplepie) {
1430 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1431 _debug("update_rss_feed: done");
1436 function print_select($id, $default, $values, $attributes = "") {
1437 print "<select name=\"$id\" id=\"$id\" $attributes>";
1438 foreach ($values as $v) {
1444 print "<option$sel>$v</option>";
1449 function print_select_hash($id, $default, $values, $attributes = "") {
1450 print "<select name=\"$id\" id='$id' $attributes>";
1451 foreach (array_keys($values) as $v) {
1453 $sel = 'selected="selected"';
1457 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1463 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1466 if ($filters["title"]) {
1467 foreach ($filters["title"] as $filter) {
1468 $reg_exp = $filter["reg_exp"];
1469 $inverse = $filter["inverse"];
1470 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1471 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1473 array_push($matches, array($filter["action"], $filter["action_param"]));
1478 if ($filters["content"]) {
1479 foreach ($filters["content"] as $filter) {
1480 $reg_exp = $filter["reg_exp"];
1481 $inverse = $filter["inverse"];
1483 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1484 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1486 array_push($matches, array($filter["action"], $filter["action_param"]));
1491 if ($filters["both"]) {
1492 foreach ($filters["both"] as $filter) {
1493 $reg_exp = $filter["reg_exp"];
1494 $inverse = $filter["inverse"];
1497 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1498 array_push($matches, array($filter["action"], $filter["action_param"]));
1501 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1502 array_push($matches, array($filter["action"], $filter["action_param"]));
1508 if ($filters["link"]) {
1509 $reg_exp = $filter["reg_exp"];
1510 foreach ($filters["link"] as $filter) {
1511 $reg_exp = $filter["reg_exp"];
1512 $inverse = $filter["inverse"];
1514 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1515 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1517 array_push($matches, array($filter["action"], $filter["action_param"]));
1522 if ($filters["date"]) {
1523 $reg_exp = $filter["reg_exp"];
1524 foreach ($filters["date"] as $filter) {
1525 $date_modifier = $filter["filter_param"];
1526 $inverse = $filter["inverse"];
1527 $check_timestamp = strtotime($filter["reg_exp"]);
1529 # no-op when timestamp doesn't parse to prevent misfires
1531 if ($check_timestamp) {
1534 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1535 $date_modifier == "after" && $timestamp > $check_timestamp) {
1539 if ($inverse) $match_ok = !$match_ok;
1542 array_push($matches, array($filter["action"], $filter["action_param"]));
1551 function find_article_filter($filters, $filter_name) {
1552 foreach ($filters as $f) {
1553 if ($f[0] == $filter_name) {
1560 function calculate_article_score($filters) {
1563 foreach ($filters as $f) {
1564 if ($f[0] == "score") {
1571 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1572 foreach ($filters as $f) {
1573 if ($f[0] == "label") {
1574 label_add_article($link, $id, $f[1], $owner_uid);
1579 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1580 $rtl_content = false, $last_updated = false, $last_error = false,
1581 $fg_content = false, $bg_content = false) {
1583 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1584 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1586 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1590 $rtl_tag = "dir=\"rtl\"";
1592 $rtl_tag = "dir=\"ltr\"";
1595 $error_notify_msg = "";
1598 $link_title = "Error: $last_error ($last_updated)";
1599 $error_notify_msg = "(Error)";
1600 } else if ($last_updated) {
1601 $link_title = "Updated: $last_updated";
1604 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1605 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1607 /* if ($feed_id < -10) {
1608 $bg_color = "#00ccff";
1609 $fg_color = "white";
1612 if ($fg_color || $bg_color) {
1613 $color_str = "<div class='labelColorIndicator'
1614 style='color : $fg_color; background-color : $bg_color'>l</div>";
1617 print $color_str; */
1619 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1620 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1624 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1627 $fctr_class = "class=\"feedCtrHasUnread\"";
1629 $fctr_class = "class=\"feedCtrNoUnread\"";
1632 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1633 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1635 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1636 $total = getFeedArticles($link, $feed_id);
1637 print "<div class=\"feedExtInfo\">
1638 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1645 function getmicrotime() {
1646 list($usec, $sec) = explode(" ",microtime());
1647 return ((float)$usec +
(float)$sec);
1650 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1651 foreach ($values as $v) {
1658 if ($v == $true_is) {
1659 $sel .= " value=\"1\"";
1661 $sel .= " value=\"0\"";
1664 print "<input class=\"noborder\"
1665 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1670 function initialize_user_prefs($link, $uid) {
1672 $uid = db_escape_string($uid);
1674 db_query($link, "BEGIN");
1676 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1678 $u_result = db_query($link, "SELECT pref_name
1679 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1681 $active_prefs = array();
1683 while ($line = db_fetch_assoc($u_result)) {
1684 array_push($active_prefs, $line["pref_name"]);
1687 while ($line = db_fetch_assoc($result)) {
1688 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1689 // print "adding " . $line["pref_name"] . "<br>";
1691 db_query($link, "INSERT INTO ttrss_user_prefs
1692 (owner_uid,pref_name,value) VALUES
1693 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1698 db_query($link, "COMMIT");
1702 function lookup_user_id($link, $user) {
1704 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1707 if (db_num_rows($result) == 1) {
1708 return db_fetch_result($result, 0, "id");
1714 function http_authenticate_user($link) {
1716 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1718 if (!$_SERVER["PHP_AUTH_USER"]) {
1720 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1721 header('HTTP/1.0 401 Unauthorized');
1725 $auth_result = authenticate_user($link,
1726 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1728 if (!$auth_result) {
1729 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1730 header('HTTP/1.0 401 Unauthorized');
1738 function authenticate_user($link, $login, $password, $force_auth = false) {
1740 if (!SINGLE_USER_MODE
) {
1742 $pwd_hash1 = encrypt_password($password);
1743 $pwd_hash2 = encrypt_password($password, $login);
1745 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1746 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1748 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1750 $query = "SELECT id,login,access_level,pwd_hash
1751 FROM ttrss_users WHERE
1755 $query = "SELECT id,login,access_level,pwd_hash
1756 FROM ttrss_users WHERE
1757 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1758 pwd_hash = '$pwd_hash2')";
1761 $result = db_query($link, $query);
1763 if (db_num_rows($result) == 1) {
1764 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1765 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1766 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1768 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1771 $user_theme = get_user_theme_path($link);
1773 $_SESSION["theme"] = $user_theme;
1774 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1775 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1777 initialize_user_prefs($link, $_SESSION["uid"]);
1786 $_SESSION["uid"] = 1;
1787 $_SESSION["name"] = "admin";
1789 $user_theme = get_user_theme_path($link);
1791 $_SESSION["theme"] = $user_theme;
1792 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1794 initialize_user_prefs($link, $_SESSION["uid"]);
1800 function make_password($length = 8) {
1803 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1807 while ($i < $length) {
1808 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1810 if (!strstr($password, $char)) {
1818 // this is called after user is created to initialize default feeds, labels
1821 // user preferences are checked on every login, not here
1823 function initialize_user($link, $uid) {
1825 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1826 VALUES ('$uid', 'All Articles')");
1828 db_query($link, "INSERT INTO ttrss_filters
1829 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1830 action_id, action_param, filter_param)
1831 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1833 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1834 values ('$uid', 'Tiny Tiny RSS: New Releases',
1835 'http://tt-rss.org/releases.rss')");
1837 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1838 values ('$uid', 'Tiny Tiny RSS: Forum',
1839 'http://tt-rss.org/forum/rss.php')");
1842 function logout_user() {
1844 if (isset($_COOKIE[session_name()])) {
1845 setcookie(session_name(), '', time()-42000, '/');
1849 function get_script_urlpath() {
1850 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1853 function validate_session($link) {
1854 if (SINGLE_USER_MODE
) {
1858 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1859 if ($_SESSION["ip_address"]) {
1860 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1861 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1867 if ($_SESSION["uid"]) {
1869 $result = db_query($link,
1870 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1872 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1874 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1879 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1881 //print_r($_SESSION);
1883 if (time() > $_SESSION["cookie_lifetime"]) {
1891 function login_sequence($link, $mobile = false) {
1892 if (!SINGLE_USER_MODE
) {
1894 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1895 $swu = db_escape_string($_REQUEST["swu"]);
1897 $_SESSION["prefs_cache"] = false;
1898 return authenticate_user($link, $swu, null, true);
1902 $login_action = $_POST["login_action"];
1904 # try to authenticate user if called from login form
1905 if ($login_action == "do_login") {
1906 $login = $_POST["login"];
1907 $password = $_POST["password"];
1908 $remember_me = $_POST["remember_me"];
1910 if (authenticate_user($link, $login, $password)) {
1911 $_POST["password"] = "";
1913 $_SESSION["language"] = $_POST["language"];
1914 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1916 header("Location: " . $_SERVER["REQUEST_URI"]);
1921 $_SESSION["login_error_msg"] = "Incorrect username or password";
1925 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1926 render_login_form($link, $mobile);
1927 //header("Location: login.php");
1930 /* bump login timestamp */
1931 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1934 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1935 setcookie("ttrss_lang", $_SESSION["language"],
1936 time() + SESSION_COOKIE_LIFETIME
);
1939 /* bump counters stamp since we're getting reloaded anyway */
1941 $_SESSION["get_all_counters_stamp"] = time();
1945 return authenticate_user($link, "admin", null);
1949 function truncate_string($str, $max_len) {
1950 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1951 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1957 function get_user_theme_path($link) {
1958 $result = db_query($link, "SELECT theme_path
1960 ttrss_themes,ttrss_users
1961 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1962 if (db_num_rows($result) != 0) {
1963 return db_fetch_result($result, 0, "theme_path");
1969 function smart_date_time($timestamp) {
1970 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1971 return date("G:i", $timestamp);
1972 } else if (date("Y", $timestamp) == date("Y")) {
1973 return date("M d, G:i", $timestamp);
1975 return date("Y/m/d, G:i", $timestamp);
1979 function smart_date($timestamp) {
1980 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1982 } else if (date("Y", $timestamp) == date("Y")) {
1983 return date("D m", $timestamp);
1985 return date("Y/m/d", $timestamp);
1989 function sql_bool_to_string($s) {
1990 if ($s == "t" ||
$s == "1") {
1997 function sql_bool_to_bool($s) {
1998 if ($s == "t" ||
$s == "1") {
2005 function bool_to_sql_bool($s) {
2013 function toggleEvenOdd($a) {
2020 function sanity_check($link) {
2025 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2026 $schema_version = db_fetch_result($result, 0, "schema_version");
2028 if ($schema_version != SCHEMA_VERSION
) {
2032 if (DB_TYPE
== "mysql") {
2033 $result = db_query($link, "SELECT true", false);
2034 if (db_num_rows($result) != 1) {
2039 if (db_escape_string("testTEST") != "testTEST") {
2043 error_reporting (DEFAULT_ERROR_LEVEL
);
2045 if ($error_code != 0) {
2046 print_error_xml($error_code);
2053 function file_is_locked($filename) {
2054 if (function_exists('flock')) {
2056 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2057 error_reporting(DEFAULT_ERROR_LEVEL
);
2059 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2060 flock($fp, LOCK_UN
);
2070 return true; // consider the file always locked and skip the test
2073 function make_lockfile($filename) {
2074 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2076 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2083 function make_stampfile($filename) {
2084 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2086 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2087 fwrite($fp, time() . "\n");
2088 flock($fp, LOCK_UN
);
2096 function read_stampfile($filename) {
2099 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2100 error_reporting (DEFAULT_ERROR_LEVEL
);
2103 if (flock($fp, LOCK_EX
)) {
2104 $stamp = fgets($fp);
2105 flock($fp, LOCK_UN
);
2116 function sql_random_function() {
2117 if (DB_TYPE
== "mysql") {
2124 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2126 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2128 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2135 $cat_qpart = "cat_id = '$feed'";
2137 $cat_qpart = "cat_id IS NULL";
2140 $tmp_result = db_query($link, "SELECT id
2141 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2143 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2145 $tmp_feed = $tmp_line["id"];
2147 db_query($link, "UPDATE ttrss_user_entries
2148 SET unread = false,last_read = NOW()
2149 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2151 } else if ($feed == -2) {
2154 db_query($link, "UPDATE ttrss_user_entries
2155 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2156 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2157 AND unread = true AND owner_uid = $owner_uid");
2160 } else if ($feed > 0) {
2162 $tmp_result = db_query($link, "SELECT id
2163 FROM ttrss_feeds WHERE parent_feed = '$feed'
2164 ORDER BY cat_id,title");
2166 $parent_ids = array();
2168 if (db_num_rows($tmp_result) > 0) {
2169 while ($p = db_fetch_assoc($tmp_result)) {
2170 array_push($parent_ids, "feed_id = " . $p["id"]);
2173 $children_qpart = implode(" OR ", $parent_ids);
2175 db_query($link, "UPDATE ttrss_user_entries
2176 SET unread = false,last_read = NOW()
2177 WHERE (feed_id = '$feed' OR $children_qpart)
2178 AND owner_uid = $owner_uid");
2181 db_query($link, "UPDATE ttrss_user_entries
2182 SET unread = false,last_read = NOW()
2183 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2186 } else if ($feed < 0 && $feed > -10) { // special, like starred
2189 db_query($link, "UPDATE ttrss_user_entries
2190 SET unread = false,last_read = NOW()
2191 WHERE marked = true AND owner_uid = $owner_uid");
2195 db_query($link, "UPDATE ttrss_user_entries
2196 SET unread = false,last_read = NOW()
2197 WHERE published = true AND owner_uid = $owner_uid");
2202 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2204 if (DB_TYPE
== "pgsql") {
2205 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2207 $match_part = "updated > DATE_SUB(NOW(),
2208 INTERVAL $intl HOUR) ";
2211 $result = db_query($link, "SELECT id FROM ttrss_entries,
2212 ttrss_user_entries WHERE $match_part AND
2214 ttrss_user_entries.ref_id = ttrss_entries.id AND
2215 owner_uid = $owner_uid");
2217 $affected_ids = array();
2219 while ($line = db_fetch_assoc($result)) {
2220 array_push($affected_ids, $line["id"]);
2223 catchupArticlesById($link, $affected_ids, 0);
2227 db_query($link, "UPDATE ttrss_user_entries
2228 SET unread = false,last_read = NOW()
2229 WHERE owner_uid = $owner_uid");
2232 } else if ($feed < -10) { // label
2234 $label_id = -$feed - 11;
2236 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2237 SET unread = false, last_read = NOW()
2238 WHERE label_id = '$label_id' AND unread = true
2239 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2243 ccache_update($link, $feed, $owner_uid, $cat_view);
2246 db_query($link, "BEGIN");
2248 $tag_name = db_escape_string($feed);
2250 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2251 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2253 while ($line = db_fetch_assoc($result)) {
2254 db_query($link, "UPDATE ttrss_user_entries SET
2255 unread = false, last_read = NOW()
2256 WHERE int_id = " . $line["post_int_id"]);
2258 db_query($link, "COMMIT");
2262 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2266 $cat_qpart = "cat_id = '$feed'";
2268 $cat_qpart = "cat_id IS NULL";
2271 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2272 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2274 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2275 $feed_url = $tmp_line["feed_url"];
2276 $feed_id = $tmp_line["id"];
2277 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2281 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2282 WHERE id = '$feed'");
2283 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2284 update_rss_feed($link, $feed_url, $feed, $force_update);
2288 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2290 if (!$omode) $omode = "flc";
2292 getGlobalCounters($link);
2294 if (strchr($omode, "l")) getLabelCounters($link);
2295 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2296 if (strchr($omode, "t")) getTagCounters($link);
2297 if (strchr($omode, "c")) {
2298 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2299 getCategoryCounters($link);
2304 function getCategoryCounters($link) {
2305 # two special categories are -1 and -2 (all virtuals; all labels)
2307 /* $ctr = getCategoryUnread($link, -1);
2309 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2311 $ctr = getCategoryUnread($link, -2);
2313 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2315 $age_qpart = getMaxAgeSubquery();
2317 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2318 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2319 WHERE ttrss_cat_counters_cache.feed_id = id AND
2320 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2322 while ($line = db_fetch_assoc($result)) {
2323 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2325 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2326 $line["unread"]."\"/>";
2329 /* Special case: NULL category doesn't actually exist in the DB */
2331 print "<counter type=\"category\" id=\"0\" counter=\"".
2332 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2336 function getCategoryUnread($link, $cat, $owner_uid = false) {
2338 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2343 $cat_query = "cat_id = '$cat'";
2345 $cat_query = "cat_id IS NULL";
2348 $age_qpart = getMaxAgeSubquery();
2350 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2352 AND owner_uid = " . $owner_uid);
2354 $cat_feeds = array();
2355 while ($line = db_fetch_assoc($result)) {
2356 array_push($cat_feeds, "feed_id = " . $line["id"]);
2359 if (count($cat_feeds) == 0) return 0;
2361 $match_part = implode(" OR ", $cat_feeds);
2363 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2364 FROM ttrss_user_entries,ttrss_entries
2365 WHERE unread = true AND ($match_part) AND id = ref_id
2366 AND $age_qpart AND owner_uid = " . $owner_uid);
2370 # this needs to be rewritten
2371 while ($line = db_fetch_assoc($result)) {
2372 $unread +
= $line["unread"];
2376 } else if ($cat == -1) {
2377 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2378 } else if ($cat == -2) {
2380 $result = db_query($link, "
2381 SELECT COUNT(unread) AS unread FROM
2382 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2383 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2384 ttrss_labels2.owner_uid = '$owner_uid'
2385 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2386 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2388 $unread = db_fetch_result($result, 0, "unread");
2395 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2396 if (DB_TYPE
== "pgsql") {
2397 return "ttrss_entries.date_entered >
2398 NOW() - INTERVAL '$days days'";
2400 return "ttrss_entries.date_entered >
2401 DATE_SUB(NOW(), INTERVAL $days DAY)";
2405 function getFeedUnread($link, $feed, $is_cat = false) {
2406 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2409 function getLabelUnread($link, $label_id, $owner_uid = false) {
2410 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2412 $result = db_query($link, "
2413 SELECT COUNT(unread) AS unread FROM
2414 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2415 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2416 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2417 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2418 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2420 if (db_num_rows($result) != 0) {
2421 return db_fetch_result($result, 0, "unread");
2427 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2428 $owner_uid = false) {
2430 $n_feed = sprintf("%d", $feed);
2432 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2435 $unread_qpart = "unread = true";
2437 $unread_qpart = "true";
2440 $age_qpart = getMaxAgeSubquery();
2443 return getCategoryUnread($link, $n_feed, $owner_uid);
2444 } else if ($n_feed == -1) {
2445 $match_part = "marked = true";
2446 } else if ($n_feed == -2) {
2447 $match_part = "published = true";
2448 } else if ($n_feed == -3) {
2449 $match_part = "unread = true";
2451 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2453 if (DB_TYPE
== "pgsql") {
2454 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2456 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2458 } else if ($n_feed == -4) {
2459 $match_part = "true";
2460 } else if ($n_feed > 0) {
2462 $result = db_query($link, "SELECT id FROM ttrss_feeds
2463 WHERE parent_feed = '$n_feed'
2465 AND owner_uid = " . $owner_uid);
2467 if (db_num_rows($result) > 0) {
2469 $linked_feeds = array();
2470 while ($line = db_fetch_assoc($result)) {
2471 array_push($linked_feeds, "feed_id = " . $line["id"]);
2474 array_push($linked_feeds, "feed_id = $n_feed");
2476 $match_part = implode(" OR ", $linked_feeds);
2478 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2479 FROM ttrss_user_entries,ttrss_entries
2480 WHERE $unread_qpart AND
2481 ttrss_user_entries.ref_id = ttrss_entries.id AND
2484 owner_uid = " . $owner_uid);
2488 # this needs to be rewritten
2489 while ($line = db_fetch_assoc($result)) {
2490 $unread +
= $line["unread"];
2496 $match_part = "feed_id = '$n_feed'";
2498 } else if ($feed < -10) {
2500 $label_id = -$feed - 11;
2502 return getLabelUnread($link, $label_id, $owner_uid);
2508 $result = db_query($link, "SELECT count(int_id) AS unread
2509 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2510 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2511 ttrss_user_entries.ref_id = ttrss_entries.id AND
2512 ttrss_feeds.hidden = false AND
2514 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2518 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2519 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2520 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2521 AND $unread_qpart AND $age_qpart AND
2522 ttrss_tags.owner_uid = " . $owner_uid);
2525 $unread = db_fetch_result($result, 0, "unread");
2530 function getGlobalUnread($link, $user_id = false) {
2533 $user_id = $_SESSION["uid"];
2536 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2537 WHERE owner_uid = '$user_id' AND feed_id > 0");
2539 $c_id = db_fetch_result($result, 0, "c_id");
2544 function getGlobalCounters($link, $global_unread = -1) {
2545 if ($global_unread == -1) {
2546 $global_unread = getGlobalUnread($link);
2548 print "<counter type=\"global\" id='global-unread'
2549 counter='$global_unread'/>";
2551 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2552 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2554 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2556 print "<counter type=\"global\" id='subscribed-feeds'
2557 counter='$subscribed_feeds'/>";
2561 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2564 if (!$_SESSION["tctr_last_value"]) {
2565 $_SESSION["tctr_last_value"] = array();
2569 $old_counters = $_SESSION["tctr_last_value"];
2571 $tctrs_modified = false;
2573 $age_qpart = getMaxAgeSubquery();
2575 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2576 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2577 AND ref_id = id AND $age_qpart
2578 AND unread = true)) AS count FROM ttrss_tags
2579 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2580 ORDER BY count DESC LIMIT 55");
2584 while ($line = db_fetch_assoc($result)) {
2585 $tags[$line["tag_name"]] +
= $line["count"];
2588 foreach (array_keys($tags) as $tag) {
2589 $unread = $tags[$tag];
2591 $tag = htmlspecialchars($tag);
2593 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2594 $old_counters[$tag] = $unread;
2595 $tctrs_modified = true;
2596 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2601 if ($smart_mode && $tctrs_modified) {
2602 $_SESSION["tctr_last_value"] = $old_counters;
2607 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2609 $age_qpart = getMaxAgeSubquery();
2612 if (!$_SESSION["lctr_last_value"]) {
2613 $_SESSION["lctr_last_value"] = array();
2619 for ($i = -1; $i >= -4; $i--) {
2621 $count = getFeedUnread($link, $i);
2625 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2626 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2631 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2633 $ret_arr[$i]["counter"] = $count;
2634 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2639 $old_counters = $_SESSION["lctr_last_value"];
2640 $lctrs_modified = false;
2643 $owner_uid = $_SESSION["uid"];
2645 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2646 WHERE owner_uid = '$owner_uid'");
2648 while ($line = db_fetch_assoc($result)) {
2650 $id = -$line["id"] - 11;
2652 $label_name = $line["caption"];
2653 $count = getFeedUnread($link, $id);
2655 if (!$smart_mode ||
$old_counters[$id] != $count) {
2656 $old_counters[$id] = $count;
2657 $lctrs_modified = true;
2660 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2661 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2666 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2668 $ret_arr[$id]["counter"] = $count;
2669 $ret_arr[$id]["description"] = $label_name;
2673 error_reporting (DEFAULT_ERROR_LEVEL
);
2676 if ($smart_mode && $lctrs_modified) {
2677 $_SESSION["lctr_last_value"] = $old_counters;
2683 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2685 $age_qpart = getMaxAgeSubquery();
2688 if (!$_SESSION["fctr_last_value"]) {
2689 $_SESSION["fctr_last_value"] = array();
2693 $old_counters = $_SESSION["fctr_last_value"];
2695 $query = "SELECT ttrss_feeds.id,
2697 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2698 last_error, value AS count
2699 FROM ttrss_feeds, ttrss_counters_cache
2700 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2701 AND parent_feed IS NULL
2702 AND ttrss_counters_cache.feed_id = id";
2704 $result = db_query($link, $query);
2705 $fctrs_modified = false;
2707 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2709 while ($line = db_fetch_assoc($result)) {
2712 $count = $line["count"];
2713 $last_error = htmlspecialchars($line["last_error"]);
2715 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2716 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2718 $last_updated = date($short_date, strtotime($line["last_updated"]));
2721 $last_updated = htmlspecialchars($last_updated);
2723 $has_img = feed_has_icon($id);
2725 $tmp_result = db_query($link,
2726 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2727 WHERE parent_feed = '$id' AND feed_id = id");
2729 $count +
= db_fetch_result($tmp_result, 0, "unread");
2731 if (!$smart_mode ||
$old_counters[$id] != $count) {
2732 $old_counters[$id] = $count;
2733 $fctrs_modified = true;
2736 $error_part = "error=\"$last_error\"";
2742 $has_img_part = "hi=\"$has_img\"";
2747 if ($active_feed && $id == $active_feed) {
2748 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2750 $has_title_part = "";
2753 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2754 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2757 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2761 if ($smart_mode && $fctrs_modified) {
2762 $_SESSION["fctr_last_value"] = $old_counters;
2766 function get_script_dt_add() {
2767 /* if (strpos(VERSION, ".99") === false) {
2775 function get_pgsql_version($link) {
2776 $result = db_query($link, "SELECT version() AS version");
2777 $version = split(" ", db_fetch_result($result, 0, "version"));
2781 function print_error_xml($code, $add_msg = "") {
2784 $error_msg = $ERRORS[$code];
2787 $error_msg = "$error_msg; $add_msg";
2790 print "<rpc-reply>";
2791 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2792 print "</rpc-reply>";
2795 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2796 $auth_login = '', $auth_pass = '') {
2798 # check for feed:http://url
2799 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2801 # check for feed://URL
2802 if (strpos($feed_link, "//") === 0) {
2803 $feed_link = "http:$feed_link";
2806 if ($feed_link == "") return;
2808 if ($cat_id == "0" ||
!$cat_id) {
2809 $cat_qpart = "NULL";
2811 $cat_qpart = "'$cat_id'";
2814 $result = db_query($link,
2815 "SELECT id FROM ttrss_feeds
2816 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2818 if (db_num_rows($result) == 0) {
2820 $result = db_query($link,
2821 "INSERT INTO ttrss_feeds
2822 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2823 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2824 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2826 $result = db_query($link,
2827 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2828 AND owner_uid = " . $_SESSION["uid"]);
2830 $feed_id = db_fetch_result($result, 0, "id");
2833 update_rss_feed($link, $feed_link, $feed_id, true);
2842 function print_feed_select($link, $id, $default_id = "",
2843 $attributes = "", $include_all_feeds = true) {
2845 print "<select id=\"$id\" name=\"$id\" $attributes>";
2846 if ($include_all_feeds) {
2847 print "<option value=\"0\">".__('All feeds')."</option>";
2850 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2851 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2853 if (db_num_rows($result) > 0 && $include_all_feeds) {
2854 print "<option disabled>--------</option>";
2857 while ($line = db_fetch_assoc($result)) {
2858 if ($line["id"] == $default_id) {
2859 $is_selected = "selected";
2863 printf("<option $is_selected value='%d'>%s</option>",
2864 $line["id"], htmlspecialchars($line["title"]));
2870 function print_feed_cat_select($link, $id, $default_id = "",
2871 $attributes = "", $include_all_cats = true) {
2873 print "<select id=\"$id\" name=\"$id\" $attributes>";
2875 if ($include_all_cats) {
2876 print "<option value=\"0\">".__('Uncategorized')."</option>";
2879 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2880 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2882 if (db_num_rows($result) > 0 && $include_all_cats) {
2883 print "<option disabled>--------</option>";
2886 while ($line = db_fetch_assoc($result)) {
2887 if ($line["id"] == $default_id) {
2888 $is_selected = "selected";
2892 printf("<option $is_selected value='%d'>%s</option>",
2893 $line["id"], htmlspecialchars($line["title"]));
2899 function checkbox_to_sql_bool($val) {
2900 return ($val == "on") ?
"true" : "false";
2903 function getFeedCatTitle($link, $id) {
2905 return __("Special");
2906 } else if ($id < -10) {
2907 return __("Labels");
2908 } else if ($id > 0) {
2909 $result = db_query($link, "SELECT ttrss_feed_categories.title
2910 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2911 cat_id = ttrss_feed_categories.id");
2912 if (db_num_rows($result) == 1) {
2913 return db_fetch_result($result, 0, "title");
2915 return __("Uncategorized");
2918 return "getFeedCatTitle($id) failed";
2923 function getFeedTitle($link, $id) {
2925 return __("Starred articles");
2926 } else if ($id == -2) {
2927 return __("Published articles");
2928 } else if ($id == -3) {
2929 return __("Fresh articles");
2930 } else if ($id == -4) {
2931 return __("All articles");
2932 } else if ($id < -10) {
2933 $label_id = -$id - 11;
2934 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2935 if (db_num_rows($result) == 1) {
2936 return db_fetch_result($result, 0, "caption");
2938 return "Unknown label ($label_id)";
2941 } else if ($id > 0) {
2942 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2943 if (db_num_rows($result) == 1) {
2944 return db_fetch_result($result, 0, "title");
2946 return "Unknown feed ($id)";
2949 return "getFeedTitle($id) failed";
2954 function get_session_cookie_name() {
2955 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2958 function print_init_params($link) {
2959 print "<init-params>";
2960 if ($_SESSION["stored-params"]) {
2961 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2963 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2964 print "<param key=\"$key\" value=\"$value\"/>";
2969 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2970 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2971 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2972 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2974 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2975 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2977 print "<param key=\"hide_read_feeds\" value=\"" .
2978 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2980 print "<param key=\"enable_feed_cats\" value=\"" .
2981 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2983 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2984 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2986 print "<param key=\"confirm_feed_catchup\" value=\"" .
2987 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2989 print "<param key=\"cdm_auto_catchup\" value=\"" .
2990 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2992 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2994 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2996 print "<param key=\"default_view_mode\" value=\"" .
2997 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2999 print "<param key=\"default_view_limit\" value=\"" .
3000 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3002 print "<param key=\"default_view_order_by\" value=\"" .
3003 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3005 print "<param key=\"prefs_active_tab\" value=\"" .
3006 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3008 print "<param key=\"infobox_disable_overlay\" value=\"" .
3009 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3011 print "<param key=\"icons_location\" value=\"" .
3014 print "<param key=\"hide_read_shows_special\" value=\"" .
3015 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3017 print "<param key=\"hide_feedlist\" value=\"" .
3018 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3020 print "<param key=\"bw_limit\" value=\"".
3021 (int) $_SESSION["bw_limit"]."\"/>";
3023 // print "<param key=\"sync_counters\" value=\"" .
3024 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3026 print "<param key=\"sync_counters\" value=\"1\"/>";
3028 print "<param key=\"offline_enabled\" value=\"".
3029 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3031 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3032 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3034 $num_feeds = db_fetch_result($result, 0, "cf");
3036 print "<param key=\"num_feeds\" value=\"".
3037 (int)$num_feeds. "\"/>";
3039 print "</init-params>";
3042 function print_runtime_info($link) {
3043 print "<runtime-info>";
3045 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3046 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3048 $num_feeds = db_fetch_result($result, 0, "cf");
3050 print "<param key=\"num_feeds\" value=\"".
3051 (int)$num_feeds. "\"/>";
3053 if (ENABLE_UPDATE_DAEMON
) {
3054 print "<param key=\"daemon_is_running\" value=\"".
3055 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3057 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3059 $stamp = (int)read_stampfile("update_daemon.stamp");
3061 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3064 $stamp_delta = time() - $stamp;
3066 if ($stamp_delta > 1800) {
3070 $_SESSION["daemon_stamp_check"] = time();
3073 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3075 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3077 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3082 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3084 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3085 $new_version_details = check_for_update($link);
3087 print "<param key=\"new_version_available\" value=\"".
3088 sprintf("%d", $new_version_details != ""). "\"/>";
3090 $_SESSION["last_version_check"] = time();
3094 // print "<param key=\"new_version_available\" value=\"1\"/>";
3096 print "</runtime-info>";
3099 function getSearchSql($search, $match_on) {
3101 $search_query_part = "";
3103 $keywords = split(" ", $search);
3104 $query_keywords = array();
3106 if ($match_on == "both") {
3108 foreach ($keywords as $k) {
3109 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3110 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3113 $search_query_part = implode("AND", $query_keywords) . " AND ";
3115 } else if ($match_on == "title") {
3117 foreach ($keywords as $k) {
3118 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3121 $search_query_part = implode("AND", $query_keywords) . " AND ";
3123 } else if ($match_on == "content") {
3125 foreach ($keywords as $k) {
3126 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3130 $search_query_part = implode("AND", $query_keywords);
3132 return $search_query_part;
3135 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3137 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3141 $search_query_part = getSearchSql($search, $match_on);
3142 $search_query_part .= " AND ";
3145 $search_query_part = "";
3148 $view_query_part = "";
3150 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3152 $view_query_part = " ";
3153 } else if ($feed != -1) {
3154 $unread = getFeedUnread($link, $feed, $cat_view);
3156 $view_query_part = " unread = true AND ";
3161 if ($view_mode == "marked") {
3162 $view_query_part = " marked = true AND ";
3165 if ($view_mode == "unread") {
3166 $view_query_part = " unread = true AND ";
3169 if ($view_mode == "updated") {
3170 $view_query_part = " (last_read is null and unread = false) AND ";
3174 $limit_query_part = "LIMIT " . $limit;
3177 $vfeed_query_part = "";
3179 // override query strategy and enable feed display when searching globally
3180 if ($search && $search_mode == "all_feeds") {
3181 $query_strategy_part = "ttrss_entries.id > 0";
3182 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3183 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3184 $query_strategy_part = "ttrss_entries.id > 0";
3185 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3186 id = feed_id) as feed_title,";
3187 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3189 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3191 $tmp_result = false;
3194 $tmp_result = db_query($link, "SELECT id
3195 FROM ttrss_feeds WHERE cat_id = '$feed'");
3197 $tmp_result = db_query($link, "SELECT id
3198 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3199 WHERE id = '$feed') AND id != '$feed'");
3202 $cat_siblings = array();
3204 if (db_num_rows($tmp_result) > 0) {
3205 while ($p = db_fetch_assoc($tmp_result)) {
3206 array_push($cat_siblings, "feed_id = " . $p["id"]);
3209 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3210 $feed, implode(" OR ", $cat_siblings));
3213 $query_strategy_part = "ttrss_entries.id > 0";
3216 } else if ($feed >= 0) {
3221 $query_strategy_part = "cat_id = '$feed'";
3223 $query_strategy_part = "cat_id IS NULL";
3226 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3229 $tmp_result = db_query($link, "SELECT id
3230 FROM ttrss_feeds WHERE parent_feed = '$feed'
3231 ORDER BY cat_id,title");
3233 $parent_ids = array();
3235 if (db_num_rows($tmp_result) > 0) {
3236 while ($p = db_fetch_assoc($tmp_result)) {
3237 array_push($parent_ids, "feed_id = " . $p["id"]);
3240 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3241 $feed, implode(" OR ", $parent_ids));
3243 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3245 $query_strategy_part = "feed_id = '$feed'";
3248 } else if ($feed == -1) { // starred virtual feed
3249 $query_strategy_part = "marked = true";
3250 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3251 } else if ($feed == -2) { // published virtual feed OR labels category
3254 $query_strategy_part = "published = true";
3255 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3257 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3259 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3261 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3262 ttrss_user_labels2.article_id = ref_id";
3266 } else if ($feed == -3) { // fresh virtual feed
3267 $query_strategy_part = "unread = true";
3269 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3271 if (DB_TYPE
== "pgsql") {
3272 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3274 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3277 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3278 } else if ($feed == -4) { // all articles virtual feed
3279 $query_strategy_part = "true";
3280 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3281 } else if ($feed <= -10) { // labels
3282 $label_id = -$feed - 11;
3284 $query_strategy_part = "label_id = '$label_id' AND
3285 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3286 ttrss_user_labels2.article_id = ref_id";
3288 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3289 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3292 $query_strategy_part = "id > 0"; // dumb
3295 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3296 $order_by = "updated";
3298 $order_by = "updated DESC";
3301 if ($view_mode != "noscores") {
3302 $order_by = "score DESC, $order_by";
3305 if ($override_order) {
3306 $order_by = $override_order;
3311 if ($search && $search_mode == "all_feeds") {
3312 $feed_title = __("Search results")." ($search)";
3313 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3314 $feed_title = __("Search results")." ($search, $feed)";
3315 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3316 $feed_title = $feed;
3317 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3322 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3323 WHERE id = '$feed' AND owner_uid = $owner_uid");
3324 $feed_title = db_fetch_result($result, 0, "title");
3326 $feed_title = __("Uncategorized");
3330 $feed_title = __("Searched for")." $search ($feed_title)";
3335 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3336 WHERE id = '$feed' AND owner_uid = $owner_uid");
3338 $feed_title = db_fetch_result($result, 0, "title");
3339 $feed_site_url = db_fetch_result($result, 0, "site_url");
3340 $last_error = db_fetch_result($result, 0, "last_error");
3343 $feed_title = __("Searched for") . " $search ($feed_title)";
3347 } else if ($feed == -1) {
3348 $feed_title = __("Starred articles");
3349 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3350 } else if ($feed == -2) {
3352 $feed_title = __("Published articles");
3353 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3355 $feed_title = __("Labels");
3357 } else if ($feed == -3) {
3358 $feed_title = __("Fresh articles");
3359 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3360 } else if ($feed == -4) {
3361 $feed_title = __("All articles");
3362 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3363 } else if ($feed < -10) {
3364 $label_id = -$feed - 11;
3365 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3366 WHERE id = '$label_id'");
3367 $feed_title = db_fetch_result($result, 0, "caption");
3370 $feed_title = __("Searched for") . " $search ($feed_title)";
3376 $content_query_part = "content as content_preview,";
3378 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3381 $feed_kind = "Feeds";
3383 $feed_kind = "Labels";
3386 if ($limit_query_part) {
3387 $offset_query_part = "OFFSET $offset";
3390 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3391 if (!$override_order) {
3392 $order_by = "ttrss_feeds.title, $order_by";
3395 // Special output for Fresh feed
3397 /* if ($feed == -3) {
3398 $group_limit_part = "(select count(*) from
3399 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3400 t1.ref_id = t2.id and t1.owner_uid = 2 and
3401 t1.feed_id = ttrss_user_entries.feed_id and
3402 t2.updated > ttrss_entries.updated) <= 5 AND";
3406 $query = "SELECT DISTINCT
3408 ttrss_entries.id,ttrss_entries.title,
3411 unread,feed_id,marked,published,link,last_read,
3412 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3415 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3418 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3421 ttrss_feeds.hidden = false AND
3422 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3423 ttrss_user_entries.ref_id = ttrss_entries.id AND
3424 ttrss_user_entries.owner_uid = '$owner_uid' AND
3427 $query_strategy_part ORDER BY $order_by
3428 $limit_query_part $offset_query_part";
3430 if ($_GET["debug"]) print $query;
3432 $result = db_query($link, $query);
3437 $feed_kind = "Tags";
3439 $result = db_query($link, "SELECT
3442 ttrss_entries.id as id,title,
3445 marked,link,last_read,
3446 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3449 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3452 ttrss_entries,ttrss_user_entries,ttrss_tags
3454 ref_id = ttrss_entries.id AND
3455 ttrss_user_entries.owner_uid = '$owner_uid' AND
3456 post_int_id = int_id AND tag_name = '$feed' AND
3459 $query_strategy_part ORDER BY $order_by
3460 $limit_query_part");
3463 return array($result, $feed_title, $feed_site_url, $last_error);
3467 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3468 $limit, $search, $search_mode, $match_on) {
3470 $note_style = "background-color : #fff7d5; border-width : 1px; ".
3471 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3472 "margin-top : 5px; color : #9a8c59;";
3474 if (!$limit) $limit = 30;
3476 $qfh_ret = queryFeedHeadlines($link, $feed,
3477 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3480 $result = $qfh_ret[0];
3481 $feed_title = htmlspecialchars($qfh_ret[1]);
3482 $feed_site_url = $qfh_ret[2];
3483 $last_error = $qfh_ret[3];
3485 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3487 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3488 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3489 <rss version=\"2.0\">
3491 <title>$feed_title</title>
3492 <link>$feed_site_url</link>
3493 <description>Feed generated by Tiny Tiny RSS</description>";
3495 while ($line = db_fetch_assoc($result)) {
3497 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3498 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3500 $tags = get_article_tags($link, $line["id"], $owner_uid);
3502 foreach ($tags as $tag) {
3503 print "<category>" . htmlspecialchars($tag) . "</category>";
3506 $rfc822_date = date('r', strtotime($line["updated"]));
3508 print "<pubDate>$rfc822_date</pubDate>";
3511 htmlspecialchars($line["title"]) . "</title>";
3513 print "<description><![CDATA[";
3514 print $line["content_preview"];
3515 if ($line["note"]) {
3516 print "<div style='$note_style'>";
3517 print $line["note"];
3520 print "]]></description>";
3525 print "</channel></rss>";
3529 function getCategoryTitle($link, $cat_id) {
3531 if ($cat_id == -1) {
3532 return __("Special");
3533 } else if ($cat_id == -2) {
3534 return __("Labels");
3537 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3540 if (db_num_rows($result) == 1) {
3541 return db_fetch_result($result, 0, "title");
3543 return "Uncategorized";
3548 // http://ru2.php.net/strip-tags
3550 function strip_tags_long($textstring, $allowed){
3551 while($textstring != strip_tags($textstring, $allowed))
3553 while (strlen($textstring) != 0)
3555 if (strlen($textstring) > 1024) {
3558 $otherlen = strlen($textstring);
3560 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3561 $safetext .= $temptext;
3562 $textstring = substr_replace($textstring,'',0,$otherlen);
3564 $textstring = $safetext;
3570 function sanitize_rss($link, $str, $force_strip_tags = false) {
3573 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3575 $res = strip_tags_long($res,
3576 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3578 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3579 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3582 if (get_pref($link, "STRIP_IMAGES")) {
3584 $res = preg_replace('/<img[^>]+>/is', '', $res);
3592 * Send by mail a digest of last articles.
3594 * @param mixed $link The database connection.
3595 * @param integer $limit The maximum number of articles by digest.
3596 * @return boolean Return false if digests are not enabled.
3598 function send_headlines_digests($link, $limit = 100) {
3600 if (!DIGEST_ENABLE
) return false;
3602 $user_limit = DIGEST_EMAIL_LIMIT
;
3605 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3607 if (DB_TYPE
== "pgsql") {
3608 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3609 } else if (DB_TYPE
== "mysql") {
3610 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3613 $result = db_query($link, "SELECT id,email FROM ttrss_users
3614 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3616 while ($line = db_fetch_assoc($result)) {
3618 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3619 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3621 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3623 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3624 $digest = $tuple[0];
3625 $headlines_count = $tuple[1];
3626 $affected_ids = $tuple[2];
3627 $digest_text = $tuple[3];
3629 if ($headlines_count > 0) {
3631 $mail = new PHPMailer();
3633 $mail->PluginDir
= "lib/phpmailer/";
3634 $mail->SetLanguage("en", "lib/phpmailer/language/");
3636 $mail->CharSet
= "UTF-8";
3638 $mail->From
= DIGEST_FROM_ADDRESS
;
3639 $mail->FromName
= DIGEST_FROM_NAME
;
3640 $mail->AddAddress($line["email"], $line["login"]);
3642 if (DIGEST_SMTP_HOST
) {
3643 $mail->Host
= DIGEST_SMTP_HOST
;
3644 $mail->Mailer
= "smtp";
3645 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3646 $mail->Username
= DIGEST_SMTP_LOGIN
;
3647 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3650 $mail->IsHTML(true);
3651 $mail->Subject
= DIGEST_SUBJECT
;
3652 $mail->Body
= $digest;
3653 $mail->AltBody
= $digest_text;
3655 $rc = $mail->Send();
3657 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3661 if ($rc && $do_catchup) {
3662 print "Marking affected articles as read...\n";
3663 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3666 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3667 WHERE id = " . $line["id"]);
3669 print "No headlines\n";
3674 print "All done.\n";
3678 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3680 require_once "lib/MiniTemplator.class.php";
3682 $tpl = new MiniTemplator
;
3683 $tpl_t = new MiniTemplator
;
3685 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3686 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3688 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3689 $tpl->setVariable('CUR_TIME', date('G:i'));
3691 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3692 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3694 $affected_ids = array();
3696 if (DB_TYPE
== "pgsql") {
3697 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3698 } else if (DB_TYPE
== "mysql") {
3699 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3702 $result = db_query($link, "SELECT ttrss_entries.title,
3703 ttrss_feeds.title AS feed_title,
3705 ttrss_user_entries.ref_id,
3707 SUBSTRING(content, 1, 120) AS excerpt,
3708 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3710 ttrss_user_entries,ttrss_entries,ttrss_feeds
3712 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3713 AND include_in_digest = true
3716 AND ttrss_user_entries.owner_uid = $user_id
3718 ORDER BY ttrss_feeds.title, date_entered DESC
3721 $cur_feed_title = "";
3723 $headlines_count = db_num_rows($result);
3725 $headlines = array();
3727 while ($line = db_fetch_assoc($result)) {
3728 array_push($headlines, $line);
3731 for ($i = 0; $i < sizeof($headlines); $i++
) {
3733 $line = $headlines[$i];
3735 array_push($affected_ids, $line["ref_id"]);
3737 $updated = smart_date_time(strtotime($line["last_updated"]));
3739 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3740 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3741 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3742 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3743 $tpl->setVariable('ARTICLE_EXCERPT',
3744 truncate_string(strip_tags($line["excerpt"]), 100));
3746 $tpl->addBlock('article');
3748 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3749 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3750 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3751 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3752 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3753 // truncate_string(strip_tags($line["excerpt"]), 100));
3755 $tpl_t->addBlock('article');
3757 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3758 $tpl->addBlock('feed');
3759 $tpl_t->addBlock('feed');
3764 $tpl->addBlock('digest');
3765 $tpl->generateOutputToString($tmp);
3767 $tpl_t->addBlock('digest');
3768 $tpl_t->generateOutputToString($tmp_t);
3770 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3773 function check_for_update($link) {
3774 $releases_feed = "http://tt-rss.org/releases.rss";
3776 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3781 if (ENABLE_SIMPLEPIE
) {
3782 $rss = new SimplePie();
3783 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3784 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3785 $rss->set_feed_url($fetch_url);
3786 $rss->set_output_encoding('UTF-8');
3789 $rss = fetch_rss($releases_feed);
3791 error_reporting (DEFAULT_ERROR_LEVEL
);
3795 if (ENABLE_SIMPLEPIE
) {
3796 $items = $rss->get_items();
3798 $items = $rss->items
;
3800 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3801 if (!$items ||
!is_array($items)) $items = $rss;
3804 if (!is_array($items) ||
count($items) == 0) {
3808 $latest_item = $items[0];
3810 if (ENABLE_SIMPLEPIE
) {
3811 $last_title = $latest_item->get_title();
3813 $last_title = $latest_item["title"];
3816 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3818 if (ENABLE_SIMPLEPIE
) {
3819 $release_url = sanitize_rss($link, $latest_item->get_link());
3820 $content = sanitize_rss($link, $latest_item->get_description());
3822 $release_url = sanitize_rss($link, $latest_item["link"]);
3823 $content = sanitize_rss($link, $latest_item["description"]);
3826 if (version_compare(VERSION
, $latest_version) == -1) {
3827 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3828 $latest_version)."<div class='milestoneDetails'>$content</div>";
3835 function markArticlesById($link, $ids, $cmode) {
3839 foreach ($ids as $id) {
3840 array_push($tmp_ids, "ref_id = '$id'");
3843 $ids_qpart = join(" OR ", $tmp_ids);
3846 db_query($link, "UPDATE ttrss_user_entries SET
3847 marked = false,last_read = NOW()
3848 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3849 } else if ($cmode == 1) {
3850 db_query($link, "UPDATE ttrss_user_entries SET
3852 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3854 db_query($link, "UPDATE ttrss_user_entries SET
3855 marked = NOT marked,last_read = NOW()
3856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3860 function publishArticlesById($link, $ids, $cmode) {
3864 foreach ($ids as $id) {
3865 array_push($tmp_ids, "ref_id = '$id'");
3868 $ids_qpart = join(" OR ", $tmp_ids);
3871 db_query($link, "UPDATE ttrss_user_entries SET
3872 published = false,last_read = NOW()
3873 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3874 } else if ($cmode == 1) {
3875 db_query($link, "UPDATE ttrss_user_entries SET
3877 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3879 db_query($link, "UPDATE ttrss_user_entries SET
3880 published = NOT published,last_read = NOW()
3881 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3885 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3887 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3891 foreach ($ids as $id) {
3892 array_push($tmp_ids, "ref_id = '$id'");
3895 $ids_qpart = join(" OR ", $tmp_ids);
3898 db_query($link, "UPDATE ttrss_user_entries SET
3899 unread = false,last_read = NOW()
3900 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3901 } else if ($cmode == 1) {
3902 db_query($link, "UPDATE ttrss_user_entries SET
3904 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3906 db_query($link, "UPDATE ttrss_user_entries SET
3907 unread = NOT unread,last_read = NOW()
3908 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3913 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3914 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3916 while ($line = db_fetch_assoc($result)) {
3917 ccache_update($link, $line["feed_id"], $owner_uid);
3921 function catchupArticleById($link, $id, $cmode) {
3924 db_query($link, "UPDATE ttrss_user_entries SET
3925 unread = false,last_read = NOW()
3926 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3927 } else if ($cmode == 1) {
3928 db_query($link, "UPDATE ttrss_user_entries SET
3930 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3932 db_query($link, "UPDATE ttrss_user_entries SET
3933 unread = NOT unread,last_read = NOW()
3934 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3938 function make_guid_from_title($title) {
3939 return preg_replace("/[ \"\',.:;]/", "-",
3940 mb_strtolower(strip_tags($title), 'utf-8'));
3943 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3944 $feed_id, $is_cat, $search, $match_on,
3947 print "<div class=\"headlinesSubToolbar\">";
3949 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3950 $page_next_link = "javascript:viewFeedGoPage(1)";
3951 $page_first_link = "javascript:viewFeedGoPage(0)";
3953 $catchup_page_link = "javascript:catchupPage()";
3954 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3955 $catchup_sel_link = "javascript:catchupSelection()";
3957 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3959 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3960 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3961 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3962 $sel_inv_link = "javascript:invertHeadlineSelection()";
3964 $tog_unread_link = "javascript:selectionToggleUnread()";
3965 $tog_marked_link = "javascript:selectionToggleMarked()";
3966 $tog_published_link = "javascript:selectionTogglePublished()";
3970 $sel_all_link = "javascript:cdmSelectArticles('all')";
3971 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3972 $sel_none_link = "javascript:cdmSelectArticles('none')";
3974 $sel_inv_link = "javascript:invertHeadlineSelection()";
3976 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3977 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3978 $tog_published_link = "javascript:selectionTogglePublished(true)";
3982 print "<div id=\"subtoolbar_ftitle\">";
3984 if ($feed_site_url) {
3986 $target = "target=\"_blank\"";
3988 print "<a $target href=\"$feed_site_url\">".
3989 truncate_string($feed_title,30)."</a>";
3995 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3999 <a target=\"_blank\"
4000 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4001 <img class=\"noborder\"
4002 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4007 print __('Select:')."
4008 <a href=\"$sel_all_link\">".__('All')."</a>,
4009 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4010 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4011 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4013 print " ";
4016 onmouseover=\"enable_selection(false)\"
4017 onmouseout=\"enable_selection(true)\"
4018 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4019 __("Actions...") . " <img src=\"images/down_arrow.png\">
4022 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4024 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4025 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4026 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4027 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4028 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4029 <li class=\"insensitive\">".__('Mark as read:')."</li>
4030 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4032 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4035 //print "<li><span class=\"insensitive\">--------</span></li>";
4036 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4038 print_labels_headlines_dropdown($link, $feed_id);
4045 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4047 $tmp_category = getCategoryTitle($link, $cat_id);
4050 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4051 } else if ($cat_id == 0 ||
$cat_id == -2) {
4052 $cat_unread = getCategoryUnread($link, $cat_id);
4056 $holder_style = "display:none;";
4063 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4066 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4067 $inner_title_class = "catTitle";
4069 $browse_cat_link = "";
4070 $inner_title_class = "catTitleNL";
4073 $cat_class = "feedCat";
4075 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4076 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4077 title=\"".__('Click to collapse category')."\"
4078 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4079 id=\"FCATN-$cat_id\" $browse_cat_link
4080 \">$tmp_category</span>";
4082 print "<span id=\"FCAP-$cat_id\">";
4084 print " <span id=\"FCATCTR-$cat_id\"
4085 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4091 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4095 function outputFeedList($link, $tags = false) {
4097 print "<ul class=\"feedList\" id=\"feedList\">";
4099 $owner_uid = $_SESSION["uid"];
4103 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4105 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4108 $cat_hidden = false;
4111 printCategoryHeader($link, -1, $cat_hidden, false);
4114 $num_starred = getFeedUnread($link, -1);
4115 $num_published = getFeedUnread($link, -2);
4116 $num_fresh = getFeedUnread($link, -3);
4117 $num_total = getFeedUnread($link, -4);
4121 if ($num_total > 0) $class .= "Unread";
4123 printFeedEntry(-4, $class, __("All articles"), $num_total,
4124 "images/tag.png", $link);
4128 if ($num_fresh > 0) $class .= "Unread";
4130 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4131 "images/fresh.png", $link);
4135 if ($num_starred > 0) $class .= "Unread";
4137 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4140 $mark_img_ext = "gif";
4142 $mark_img_ext = "png";
4145 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4146 "images/mark_set.$mark_img_ext", $link);
4150 if ($num_published > 0) $class .= "Unread";
4152 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4153 "images/pub_set.gif", $link);
4155 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4162 $result = db_query($link, "SELECT * FROM
4163 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4165 if (db_num_rows($result) > 0) {
4166 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4168 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4171 $cat_hidden = false;
4174 printCategoryHeader($link, -2, $cat_hidden, true);
4177 print "<li><hr></li>";
4181 while ($line = db_fetch_assoc($result)) {
4183 $label_id = -$line['id'] - 11;
4184 $count = getFeedUnread($link, $label_id);
4192 printFeedEntry($label_id,
4193 $class, $line["caption"],
4194 $count, "images/label.png", $link,
4195 false, false, false,
4196 $line['fg_color'], $line['bg_color']);
4200 if (db_num_rows($result) > 0) {
4201 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4207 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4208 print "<li><hr></li>";
4211 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4212 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4213 $order_by_qpart = "order_id,category,unread DESC,title";
4215 $order_by_qpart = "order_id,category,title";
4218 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4219 $order_by_qpart = "unread DESC,title";
4221 $order_by_qpart = "title";
4225 $age_qpart = getMaxAgeSubquery();
4227 $query = "SELECT ttrss_feeds.*,
4228 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4230 ttrss_feed_categories.title AS category,
4231 ttrss_feed_categories.collapsed,
4233 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4234 ON (ttrss_feed_categories.id = cat_id)
4235 LEFT JOIN ttrss_counters_cache
4237 (ttrss_feeds.id = feed_id)
4239 ttrss_feeds.hidden = false AND
4240 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4241 ORDER BY $order_by_qpart";
4243 $result = db_query($link, $query);
4245 $actid = $_GET["actid"];
4255 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4257 while ($line = db_fetch_assoc($result)) {
4259 $feed = trim($line["title"]);
4261 if (!$feed) $feed = "[Untitled]";
4263 $feed_id = $line["id"];
4264 $unread = $line["unread"];
4266 $subop = $_GET["subop"];
4268 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4269 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4271 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4274 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4277 $rtl_tag = "dir=\"RTL\"";
4282 $tmp_result = db_query($link,
4283 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4284 WHERE parent_feed = '$feed_id' AND feed_id = id");
4286 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4288 $cat_id = $line["cat_id"];
4290 $tmp_category = $line["category"];
4292 if (!$tmp_category) {
4293 $tmp_category = __("Uncategorized");
4296 // $class = ($lnum % 2) ? "even" : "odd";
4298 if ($line["last_error"]) {
4304 if ($unread > 0) $class .= "Unread";
4306 if ($actid == $feed_id) {
4307 $class .= "Selected";
4310 $total_unread +
= $unread;
4312 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4318 $category = $tmp_category;
4320 $collapsed = sql_bool_to_bool($line["collapsed"]);
4322 // workaround for NULL category
4323 if ($category == __("Uncategorized")) {
4324 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4329 $cat_id = sprintf("%d", $cat_id);
4331 printCategoryHeader($link, $cat_id, $collapsed, true);
4335 printFeedEntry($feed_id, $class, $feed, $unread,
4336 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4337 $last_updated, $line["last_error"]);
4342 if (db_num_rows($result) == 0) {
4343 print "<li>".__('No feeds to display.')."</li>";
4350 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4351 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4352 post_int_id = ttrss_user_entries.int_id AND
4353 unread = true AND ref_id = ttrss_entries.id
4354 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4356 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4357 ORDER BY tag_name"); */
4359 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4360 print "<li class=\"feedCat\">".__('Tags')."</li>";
4361 print "<ul class=\"feedCatList\">";
4364 $age_qpart = getMaxAgeSubquery();
4366 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4367 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4368 AND ref_id = id AND $age_qpart
4369 AND unread = true)) AS count FROM ttrss_tags
4370 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4371 ORDER BY count DESC LIMIT 50");
4375 while ($line = db_fetch_assoc($result)) {
4376 $tags[$line["tag_name"]] +
= $line["count"];
4379 foreach (array_keys($tags) as $tag) {
4381 $unread = $tags[$tag];
4389 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4393 if (db_num_rows($result) == 0) {
4394 print "<li>No tags to display.</li>";
4397 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4407 function get_article_tags($link, $id, $owner_uid = 0) {
4409 $a_id = db_escape_string($id);
4411 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4413 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4414 owner_uid as owner FROM
4415 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4416 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4420 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4421 array_push($tags, $tmp_line["tag_name"]);
4427 function trim_value(&$value) {
4428 $value = trim($value);
4431 function trim_array($array) {
4433 array_walk($tmp, 'trim_value');
4437 function tag_is_valid($tag) {
4438 if ($tag == '') return false;
4439 if (preg_match("/^[0-9]*$/", $tag)) return false;
4441 if (function_exists('iconv')) {
4442 $tag = iconv("utf-8", "utf-8", $tag);
4445 if (!$tag) return false;
4450 function render_login_form($link, $mobile = false) {
4452 require_once "login_form.php";
4454 require_once "mobile/login_form.php";
4458 // from http://developer.apple.com/internet/safari/faq.html
4459 function no_cache_incantation() {
4460 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4461 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4462 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4463 header("Cache-Control: post-check=0, pre-check=0", false);
4464 header("Pragma: no-cache"); // HTTP/1.0
4467 function format_warning($msg, $id = "") {
4468 return "<div class=\"warning\" id=\"$id\">
4469 <img src=\"images/sign_excl.gif\">$msg</div>";
4472 function format_notice($msg) {
4473 return "<div class=\"notice\">
4474 <img src=\"images/sign_info.gif\">$msg</div>";
4477 function format_error($msg) {
4478 return "<div class=\"error\">
4479 <img src=\"images/sign_excl.gif\">$msg</div>";
4482 function print_notice($msg) {
4483 return print format_notice($msg);
4486 function print_warning($msg) {
4487 return print format_warning($msg);
4490 function print_error($msg) {
4491 return print format_error($msg);
4495 function T_sprintf() {
4496 $args = func_get_args();
4497 return vsprintf(__(array_shift($args)), $args);
4500 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4501 $zoom_mode = false) {
4503 /* we can figure out feed_id from article id anyway, why do we
4504 * pass feed_id here? */
4506 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4507 WHERE ref_id = '$id'");
4509 $feed_id = db_fetch_result($result, 0, "feed_id");
4511 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4513 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4514 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4516 if (db_num_rows($result) == 1) {
4517 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4519 $rtl_content = false;
4523 $rtl_tag = "dir=\"RTL\"";
4530 if ($mark_as_read) {
4531 $result = db_query($link, "UPDATE ttrss_user_entries
4532 SET unread = false,last_read = NOW()
4533 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4535 ccache_update($link, $feed_id, $_SESSION["uid"]);
4538 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4539 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4540 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4544 FROM ttrss_entries,ttrss_user_entries
4545 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4551 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4552 $link_target = "target=\"_blank\"";
4555 $line = db_fetch_assoc($result);
4557 if ($line["icon_url"]) {
4558 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4560 $feed_icon = " ";
4563 $num_comments = $line["num_comments"];
4564 $entry_comments = "";
4566 if ($num_comments > 0) {
4567 if ($line["comments"]) {
4568 $comments_url = $line["comments"];
4570 $comments_url = $line["link"];
4572 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4574 if ($line["comments"] && $line["link"] != $line["comments"]) {
4575 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4580 header("Content-Type: text/html");
4582 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4583 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4584 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4589 print "<div class=\"postReply\">";
4591 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4592 onmouseout=\"enable_resize(false)\">";
4594 $entry_author = $line["author"];
4596 if ($entry_author) {
4597 $entry_author = __(" - ") . $entry_author;
4600 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4601 strtotime($line["updated"]));
4603 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4605 if ($line["link"]) {
4606 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4607 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4609 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4612 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4614 if (!$entry_comments) $entry_comments = " "; # placeholder
4616 print "<div style='float : right'>
4617 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'> ";
4620 print "<span id=\"ATSTR-$id\">$tags_str</span>
4621 <a title=\"".__('Edit tags for this article')."\"
4622 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4624 if (defined('_ENABLE_INLINE_VIEW')) {
4626 print "<img src=\"images/art-inline.png\" class='tagsPic'
4627 style=\"cursor : pointer\" style=\"cursor : pointer\"
4628 onclick=\"showOriginalArticleInline($id)\"
4629 alt='Inline' title='".__('Display original article content')."'>";
4633 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4634 style=\"cursor : pointer\" style=\"cursor : pointer\"
4635 onclick=\"zoomToArticle($id)\"
4636 alt='Zoom' title='".__('Show article summary in new window')."'>";
4638 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4640 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4641 style=\"cursor : pointer\" style=\"cursor : pointer\"
4642 onclick=\"publishWithNote($id, '$note_escaped')\"
4643 alt='PubNote' title='".__('Publish article with a note')."'>";
4647 print "<div clear='both'>$entry_comments</div>";
4651 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4653 print "<div class=\"postContent\">";
4655 $article_content = sanitize_rss($link, $line["content"]);
4657 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4658 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4662 print $article_content;
4664 print "<div id=\"POSTNOTE-$id\">";
4665 if ($line['note']) {
4666 print format_article_note($id, $line['note']);
4670 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4671 post_id = '$id' AND content_url != ''");
4673 if (db_num_rows($result) > 0) {
4675 $entries_html = array();
4678 while ($line = db_fetch_assoc($result)) {
4680 $url = $line["content_url"];
4681 $ctype = $line["content_type"];
4683 if (!$ctype) $ctype = __("unknown type");
4685 $filename = substr($url, strrpos($url, "/")+
1);
4689 if (($ctype == __("audio/mpeg")) &&
4690 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4692 $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> ";
4696 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4697 $filename . " (" . $ctype . ")" . "</a>";
4699 array_push($entries_html, $entry);
4703 $entry["type"] = $ctype;
4704 $entry["filename"] = $filename;
4705 $entry["url"] = $url;
4707 array_push($entries, $entry);
4710 print "<div class=\"postEnclosures\">";
4712 if (!preg_match("/<img/i", $article_content)) {
4713 foreach ($entries as $entry) {
4714 if (preg_match("/image/", $entry["type"])) {
4716 alt=\"".htmlspecialchars($entry["filename"])."\"
4717 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4722 print "<div class=\"postEnclosures\">";
4724 if (db_num_rows($result) == 1) {
4725 print __("Attachment:") . " ";
4727 print __("Attachments:") . " ";
4730 print join(", ", $entries_html);
4742 print "]]></article>";
4745 <div style=\"text-align : center\">
4746 <input type=\"submit\" onclick=\"return window.close()\"
4747 value=\"".__("Close this window")."\"></div>";
4748 print "</body></html>";
4754 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4755 $next_unread_feed, $offset, $vgr_last_feed = false,
4756 $override_order = false) {
4758 $disable_cache = false;
4760 $timing_info = getmicrotime();
4762 $topmost_article_ids = array();
4768 if ($subop == "undefined") $subop = "";
4770 $subop_split = split(":", $subop);
4772 if ($subop == "CatchupSelected") {
4773 $ids = split(",", db_escape_string($_GET["ids"]));
4774 $cmode = sprintf("%d", $_GET["cmode"]);
4776 catchupArticlesById($link, $ids, $cmode);
4779 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4780 update_generic_feed($link, $feed, $cat_view, true);
4783 if ($subop == "MarkAllRead") {
4784 catchup_feed($link, $feed, $cat_view);
4786 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4787 if ($next_unread_feed) {
4788 $feed = $next_unread_feed;
4793 if ($subop_split[0] == "MarkAllReadGR") {
4794 catchup_feed($link, $subop_split[1], false);
4799 $result = db_query($link,
4800 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4802 if (db_num_rows($result) == 0) {
4803 print "<div align='center'>".__('Feed not found.')."</div>";
4808 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4810 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4811 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4813 if (db_num_rows($result) == 1) {
4814 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4816 $rtl_content = false;
4820 $rtl_tag = "dir=\"RTL\"";
4826 $rtl_content = false;
4829 $script_dt_add = get_script_dt_add();
4831 /// START /////////////////////////////////////////////////////////////////////////////////
4833 $search = db_escape_string($_GET["query"]);
4836 $disable_cache = true;
4839 $search_mode = db_escape_string($_GET["search_mode"]);
4840 $match_on = db_escape_string($_GET["match_on"]);
4846 $real_offset = $offset * $limit;
4848 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4850 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4851 $search, $search_mode, $match_on, $override_order, $real_offset);
4853 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4855 $result = $qfh_ret[0];
4856 $feed_title = $qfh_ret[1];
4857 $feed_site_url = $qfh_ret[2];
4858 $last_error = $qfh_ret[3];
4860 $vgroup_last_feed = $vgr_last_feed;
4863 $feed_site_url = article_publish_url($link);
4866 /// STOP //////////////////////////////////////////////////////////////////////////////////
4869 print "<div id=\"headlinesContainer\" $rtl_tag>";
4872 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4876 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4877 $feed, $cat_view, $search, $match_on, $search_mode);
4879 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4882 $headlines_count = db_num_rows($result);
4884 if (db_num_rows($result) > 0) {
4886 # print "\{$offset}";
4888 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4889 print "<table class=\"headlinesList\" id=\"headlinesList\"
4890 cellspacing=\"0\">";
4893 $lnum = $limit*$offset;
4895 error_reporting (DEFAULT_ERROR_LEVEL
);
4898 $cur_feed_title = '';
4900 while ($line = db_fetch_assoc($result)) {
4902 $class = ($lnum %
2) ?
"even" : "odd";
4905 $feed_id = $line["feed_id"];
4907 $labels = get_article_labels($link, $id);
4909 $labels_str = "<span id=\"HLLCTR-$id\">";
4910 $labels_str .= format_article_labels($labels, $id);
4911 $labels_str .= "</span>";
4913 if (count($topmost_article_ids) < 5) {
4914 array_push($topmost_article_ids, $id);
4917 if ($line["last_read"] == "" &&
4918 ($line["unread"] != "t" && $line["unread"] != "1")) {
4920 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4923 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4927 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4935 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4938 $mark_img_ext = "gif";
4940 $mark_img_ext = "png";
4943 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4944 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4946 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4948 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4950 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4953 if ($line["published"] == "t" ||
$line["published"] == "1") {
4954 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4956 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4958 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4960 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4963 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4964 # $line["title"] . "</a>";
4966 # $content_link = "<a
4967 # href=\"" . htmlspecialchars($line["link"]) . "\"
4968 # onclick=\"view($id,$feed_id);\">" .
4969 # $line["title"] . "</a>";
4971 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4972 # $line["title"] . "</a>";
4974 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4975 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4977 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4978 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4981 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4982 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4986 $score = $line["score"];
4988 $score_pic = get_score_pic($score);
4990 /* $score_title = __("(Click to change)");
4991 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4992 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4994 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4999 } else if ($score < -100) {
5005 $entry_author = $line["author"];
5007 if ($entry_author) {
5008 $entry_author = " - $entry_author";
5011 $has_feed_icon = feed_has_icon($feed_id);
5013 if ($has_feed_icon) {
5014 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5016 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5017 $feed_icon_img = "";
5020 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5022 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5023 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5025 $cur_feed_title = $line["feed_title"];
5026 $vgroup_last_feed = $feed_id;
5028 $cur_feed_title = htmlspecialchars($cur_feed_title);
5030 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5032 print "<tr class='feedTitle'><td colspan='7'>".
5033 "<div style=\"float : right\">$feed_icon_img</div>".
5034 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5035 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5039 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5040 onmouseout='postMouseOut($id)'";
5042 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5044 print "<td class='hlUpdPic'>$update_pic</td>";
5046 print "<td class='hlSelectRow'>
5047 <input type=\"checkbox\" onclick=\"tSR(this)\"
5051 print "<td class='hlMarkedPic'>$marked_pic</td>";
5052 print "<td class='hlMarkedPic'>$published_pic</td>";
5054 # if ($line["feed_title"]) {
5055 # print "<td class='hlContent'>$content_link</td>";
5056 # print "<td class='hlFeed'>
5057 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5058 # truncate_string($line["feed_title"],30)."</a> </td>";
5061 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5063 print "<a id=\"RTITLE-$id\"
5064 href=\"" . htmlspecialchars($line["link"]) . "\"
5065 onclick=\"return view($id,$feed_id);\">" .
5068 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5069 if ($content_preview) {
5070 print "<span class=\"contentPreview\"> - $content_preview</span>";
5078 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5079 # $line["feed_title"]."</a>
5081 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5082 if ($line["feed_title"]) {
5083 print "<span class=\"hlFeed\">
5084 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5085 $line["feed_title"]."</a>)
5093 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5095 print "<td class='hlMarkedPic'>$score_pic</td>";
5097 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5098 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5105 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5106 if ($feed_id != $vgroup_last_feed) {
5108 $cur_feed_title = $line["feed_title"];
5109 $vgroup_last_feed = $feed_id;
5111 $cur_feed_title = htmlspecialchars($cur_feed_title);
5113 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5115 $has_feed_icon = feed_has_icon($feed_id);
5117 if ($has_feed_icon) {
5118 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5120 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5123 print "<div class='cdmFeedTitle'>".
5124 "<div style=\"float : right\">$feed_icon_img</div>".
5125 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5126 $line["feed_title"]."</a> $vf_catchup_link</div>";
5131 $add_class = "Unread";
5136 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5137 $show_excerpt = false;
5139 if ($expand_cdm && $score >= -100) {
5141 $show_excerpt = false;
5143 $cdm_cstyle = "style=\"display : none\"";
5144 $show_excerpt = true;
5147 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5148 onmouseout='postMouseOut($id)'";
5150 print "<div class=\"cdmArticle$add_class\"
5152 $mouseover_attrs'>";
5154 print "<div class=\"cdmHeader\">";
5156 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5157 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5160 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5163 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5164 onclick=\"javascript:toggleUnread($id, 0)\"
5165 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5168 print $entry_author;
5170 /* if (!$expand_cdm || $score < -100) {
5171 print " <a id=\"CICH-$id\"
5172 href=\"javascript:cdmExpandArticle($id)\">
5173 (".__('Show article').")</a>";
5178 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5179 if ($line["feed_title"]) {
5180 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5184 print "</span></div>";
5186 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5187 $line["content_preview"] = preg_replace("/href=/i",
5188 "target=\"_blank\" href=", $line["content_preview"]);
5191 if ($show_excerpt) {
5192 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5193 onclick=\"cdmExpandArticle($id)\"
5194 title=\"".__('Click to expand article')."\">";
5195 print truncate_string(strip_tags($line["content_preview"]), 100);
5199 print "<div class=\"cdmContent\"
5200 onclick=\"cdmClicked($id)\"
5201 id=\"CICD-$id\" $cdm_cstyle>";
5203 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5205 print sanitize_rss($link, $line["content_preview"]);
5207 print "<div id=\"POSTNOTE-$id\">";
5208 if ($line['note']) {
5209 print format_article_note($id, $line['note']);
5213 $article_content = $line["content_preview"];
5215 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5216 post_id = '$id' AND content_url != ''");
5218 if (db_num_rows($e_result) > 0) {
5220 $entries_html = array();
5223 while ($e_line = db_fetch_assoc($e_result)) {
5225 $url = $e_line["content_url"];
5226 $ctype = $e_line["content_type"];
5227 if (!$ctype) $ctype = __("unknown type");
5229 $filename = substr($url, strrpos($url, "/")+
1);
5233 if (($ctype == __("audio/mpeg")) &&
5234 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5236 $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> ";
5240 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5241 $filename . " (" . $ctype . ")" . "</a>";
5243 array_push($entries_html, $entry);
5247 $entry["type"] = $ctype;
5248 $entry["filename"] = $filename;
5249 $entry["url"] = $url;
5251 array_push($entries, $entry);
5254 if (!preg_match("/img/i", $article_content)) {
5255 foreach ($entries as $entry) {
5256 if (preg_match("/image/", $entry["type"])) {
5258 alt=\"".htmlspecialchars($entry["filename"])."\"
5259 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5264 print "<div class=\"cdmEnclosures\">";
5266 if (db_num_rows($e_result) == 1) {
5267 print __("Attachment:") . " ";
5269 print __("Attachments:") . " ";
5272 print join(", ", $entries_html);
5278 print "<br clear='both'>";
5281 /* if (!$expand_cdm) {
5282 print "<a id=\"CICH-$id\"
5283 href=\"javascript:cdmExpandArticle($id)\">
5289 print "<div class=\"cdmFooter\"><span class='s0'>";
5291 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5293 print __("Select:").
5294 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5295 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5297 print "</span><span class='s1'>$marked_pic ";
5298 print "$published_pic ";
5299 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5300 onclick=\"zoomToArticle($id)\"
5301 style=\"cursor : pointer\"
5303 title='".__('Show article summary in new window')."'> ";
5305 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5307 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5308 style=\"cursor : pointer\" style=\"cursor : pointer\"
5309 onclick=\"publishWithNote($id, '$note_escaped')\"
5310 alt='PubNote' title='".__('Publish article with a note')."'>";
5314 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5316 // print "<img src='images/tag.png' class='markedPic'>";
5318 print "<span class='s1'>
5319 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5320 <span id=\"ATSTR-$id\">$tags_str</span>
5321 <a title=\"".__('Edit tags for this article')."\"
5322 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5326 print "<span class='s2'><a class=\"cdmToggleLink\"
5327 href=\"javascript:toggleUnread($id)\">
5328 ".__('toggle unread')."</a></span>";
5338 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5345 switch ($view_mode) {
5347 $message = __("No unread articles found to display.");
5350 $message = __("No updated articles found to display.");
5353 $message = __("No starred articles found to display.");
5357 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5359 $message = __("No articles found to display.");
5363 if (!$offset) print "<div class='whiteBox'>$message</div>";
5371 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5374 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5376 function printTagCloud($link) {
5378 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5379 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5380 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5382 $result = db_query($link, $query);
5386 while ($line = db_fetch_assoc($result)) {
5387 $tags[$line["tag_name"]] = $line["count"];
5392 $max_size = 32; // max font size in pixels
5393 $min_size = 11; // min font size in pixels
5395 // largest and smallest array values
5396 $max_qty = max(array_values($tags));
5397 $min_qty = min(array_values($tags));
5399 // find the range of values
5400 $spread = $max_qty - $min_qty;
5401 if ($spread == 0) { // we don't want to divide by zero
5405 // set the font-size increment
5406 $step = ($max_size - $min_size) / ($spread);
5408 // loop through the tag array
5409 foreach ($tags as $key => $value) {
5410 // calculate font-size
5411 // find the $value in excess of $min_qty
5412 // multiply by the font-size increment ($size)
5413 // and add the $min_size set above
5414 $size = round($min_size +
(($value - $min_qty) * $step));
5416 $key_escaped = str_replace("'", "\\'", $key);
5418 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5419 $size . "px\" title=\"$value articles tagged with " .
5420 $key . '">' . $key . '</a> ';
5424 function print_checkpoint($n, $s) {
5425 $ts = getmicrotime();
5426 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5430 function sanitize_tag($tag) {
5433 $tag = mb_strtolower($tag, 'utf-8');
5435 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5437 // $tag = str_replace('"', "", $tag);
5438 // $tag = str_replace("+", " ", $tag);
5439 $tag = str_replace("technorati tag: ", "", $tag);
5444 function generate_publish_key() {
5445 return sha1(uniqid(rand(), true));
5448 function article_publish_url($link) {
5453 if ($_SERVER['HTTPS'] != "on") {
5454 $url_path = "http://";
5456 $url_path = "https://";
5459 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5460 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5466 * Purge a feed contents, marked articles excepted.
5468 * @param mixed $link The database connection.
5469 * @param integer $id The id of the feed to purge.
5472 function clear_feed_articles($link, $id) {
5473 $result = db_query($link, "DELETE FROM ttrss_user_entries
5474 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5476 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5477 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5479 ccache_update($link, $id, $_SESSION['uid']);
5480 } // function clear_feed_articles
5483 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5485 * @return string The Mozilla Firefox feed adding URL.
5487 function add_feed_url() {
5488 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5489 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5491 } // function add_feed_url
5494 * Encrypt a password in SHA1.
5496 * @param string $pass The password to encrypt.
5497 * @param string $login A optionnal login.
5498 * @return string The encrypted password.
5500 function encrypt_password($pass, $login = '') {
5502 return "SHA1X:" . sha1("$login:$pass");
5504 return "SHA1:" . sha1($pass);
5506 } // function encrypt_password
5509 * Update a feed batch.
5510 * Used by daemons to update n feeds by run.
5511 * Only update feed needing a update, and not being processed
5512 * by another process.
5514 * @param mixed $link Database link
5515 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5516 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5517 * @param boolean $debug Set to false to disable debug output. Default to true.
5520 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5521 // Process all other feeds using last_updated and interval parameters
5523 // Test if the user has loggued in recently. If not, it does not update its feeds.
5524 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5525 if (DB_TYPE
== "pgsql") {
5526 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5528 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5531 $login_thresh_qpart = "";
5534 // Test if the feed need a update (update interval exceded).
5535 if (DB_TYPE
== "pgsql") {
5536 $update_limit_qpart = "AND ((
5537 ttrss_feeds.update_interval = 0
5538 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5540 ttrss_feeds.update_interval > 0
5541 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5542 ) OR ttrss_feeds.last_updated IS NULL)";
5544 $update_limit_qpart = "AND ((
5545 ttrss_feeds.update_interval = 0
5546 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5548 ttrss_feeds.update_interval > 0
5549 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5550 ) OR ttrss_feeds.last_updated IS NULL)";
5553 // Test if feed is currently being updated by another process.
5554 if (DB_TYPE
== "pgsql") {
5555 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5557 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5560 // Test if there is a limit to number of updated feeds
5562 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5564 $random_qpart = sql_random_function();
5566 // We search for feed needing update.
5567 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5568 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5569 ttrss_feeds.update_interval
5571 ttrss_feeds, ttrss_users, ttrss_user_prefs
5573 ttrss_feeds.owner_uid = ttrss_users.id
5574 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5575 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5576 $login_thresh_qpart $update_limit_qpart
5577 $updstart_thresh_qpart
5578 ORDER BY $random_qpart $query_limit");
5580 $user_prefs_cache = array();
5582 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5584 // Here is a little cache magic in order to minimize risk of double feed updates.
5585 $feeds_to_update = array();
5586 while ($line = db_fetch_assoc($result)) {
5587 $feeds_to_update[$line['id']] = $line;
5590 // We update the feed last update started date before anything else.
5591 // There is no lag due to feed contents downloads
5592 // It prevent an other process to update the same feed.
5593 $feed_ids = array_keys($feeds_to_update);
5595 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5596 WHERE id IN (%s)", implode(',', $feed_ids)));
5599 // For each feed, we call the feed update function.
5600 while ($line = array_pop($feeds_to_update)) {
5602 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5604 // We setup a alarm to alert if the feed take more than 300s to update.
5606 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5607 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5608 // Cancel the alarm (the update went well)
5609 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5611 sleep(1); // prevent flood (FIXME make this an option?)
5614 // Send feed digests by email if needed.
5615 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5617 purge_orphans($link);
5619 } // function update_daemon_common
5621 function sanitize_article_content($text) {
5622 # we don't support CDATA sections in articles, they break our own escaping
5623 $text = preg_replace("/\[\[CDATA/", "", $text);
5624 $text = preg_replace("/\]\]\>/", "", $text);
5628 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5631 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5633 $result = db_query($link, "SELECT reg_exp,
5634 ttrss_filter_types.name AS name,
5635 ttrss_filter_actions.name AS action,
5639 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5642 owner_uid = $owner_uid AND
5643 ttrss_filter_types.id = filter_type AND
5644 ttrss_filter_actions.id = action_id AND
5645 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5647 while ($line = db_fetch_assoc($result)) {
5648 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5649 $filter["reg_exp"] = $line["reg_exp"];
5650 $filter["action"] = $line["action"];
5651 $filter["action_param"] = $line["action_param"];
5652 $filter["filter_param"] = $line["filter_param"];
5653 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5655 array_push($filters[$line["name"]], $filter);
5661 function get_score_pic($score) {
5663 return "score_high.png";
5664 } else if ($score > 0) {
5665 return "score_half_high.png";
5666 } else if ($score < -100) {
5667 return "score_low.png";
5668 } else if ($score < 0) {
5669 return "score_half_low.png";
5671 return "score_neutral.png";
5675 function rounded_table_start($classname, $header = " ") {
5676 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5677 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5678 print "<tr><td class='left'> </td><td class='content'>";
5681 function rounded_table_end($footer = " ") {
5682 print "</td><td class='right'> </td></tr>";
5683 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5687 function feed_has_icon($id) {
5688 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5691 function init_connection($link) {
5692 if (DB_TYPE
== "pgsql") {
5693 pg_query($link, "set client_encoding = 'UTF-8'");
5694 pg_set_client_encoding("UNICODE");
5695 pg_query($link, "set datestyle = 'ISO, european'");
5697 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5698 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5699 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5704 function update_feedbrowser_cache($link) {
5706 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5707 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5708 WHERE tf.feed_url = ttrss_feeds.feed_url
5709 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5710 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5712 db_query($link, "BEGIN");
5714 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5718 while ($line = db_fetch_assoc($result)) {
5719 $subscribers = db_escape_string($line["subscribers"]);
5720 $feed_url = db_escape_string($line["feed_url"]);
5721 $title = db_escape_string($line["title"]);
5723 $tmp_result = db_query($link, "SELECT subscribers FROM
5724 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5726 if (db_num_rows($tmp_result) == 0) {
5728 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5729 (feed_url, title, subscribers) VALUES ('$feed_url',
5730 '$title', '$subscribers')");
5738 db_query($link, "COMMIT");
5744 function ccache_zero($link, $feed_id, $owner_uid) {
5745 db_query($link, "UPDATE ttrss_counters_cache SET
5746 value = 0, updated = NOW() WHERE
5747 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5750 function ccache_zero_all($link, $owner_uid) {
5751 db_query($link, "UPDATE ttrss_counters_cache SET
5752 value = 0 WHERE owner_uid = '$owner_uid'");
5754 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5755 value = 0 WHERE owner_uid = '$owner_uid'");
5758 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5761 $table = "ttrss_counters_cache";
5763 $table = "ttrss_cat_counters_cache";
5766 db_query($link, "DELETE FROM $table WHERE
5767 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5771 function ccache_update_all($link, $owner_uid) {
5773 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5775 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5776 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5778 while ($line = db_fetch_assoc($result)) {
5779 ccache_update($link, $line["feed_id"], $owner_uid, true);
5782 /* We have to manually include category 0 */
5784 ccache_update($link, 0, $owner_uid, true);
5787 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5788 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5790 while ($line = db_fetch_assoc($result)) {
5791 print ccache_update($link, $line["feed_id"], $owner_uid);
5798 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5799 $no_update = false) {
5801 if (!is_numeric($feed_id)) return;
5804 $table = "ttrss_counters_cache";
5806 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5807 WHERE id = '$feed_id'");
5808 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5811 $table = "ttrss_cat_counters_cache";
5814 if (DB_TYPE
== "pgsql") {
5815 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5816 } else if (DB_TYPE
== "mysql") {
5817 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5820 $result = db_query($link, "SELECT value FROM $table
5821 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5824 if (db_num_rows($result) == 1) {
5825 return db_fetch_result($result, 0, "value");
5830 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5836 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5837 $update_pcat = true) {
5839 if (!is_numeric($feed_id)) return;
5841 if (!$is_cat && $feed_id > 0) {
5842 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5843 WHERE id = '$feed_id'");
5844 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5847 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5849 /* When updating a label, all we need to do is recalculate feed counters
5850 * because labels are not cached */
5853 ccache_update_all($link, $owner_uid);
5858 $table = "ttrss_counters_cache";
5860 $table = "ttrss_cat_counters_cache";
5863 if ($is_cat && $feed_id >= 0) {
5864 if ($feed_id != 0) {
5865 $cat_qpart = "cat_id = '$feed_id'";
5867 $cat_qpart = "cat_id IS NULL";
5870 /* Recalculate counters for child feeds */
5872 $result = db_query($link, "SELECT id FROM ttrss_feeds
5873 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5875 while ($line = db_fetch_assoc($result)) {
5876 ccache_update($link, $line["id"], $owner_uid, false, false);
5879 $result = db_query($link, "SELECT SUM(value) AS sv
5880 FROM ttrss_counters_cache, ttrss_feeds
5881 WHERE id = feed_id AND $cat_qpart AND
5882 ttrss_feeds.owner_uid = '$owner_uid'");
5884 $unread = (int) db_fetch_result($result, 0, "sv");
5887 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5890 db_query($link, "BEGIN");
5892 $result = db_query($link, "SELECT feed_id FROM $table
5893 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5895 if (db_num_rows($result) == 1) {
5896 db_query($link, "UPDATE $table SET
5897 value = '$unread', updated = NOW() WHERE
5898 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5901 db_query($link, "INSERT INTO $table
5902 (feed_id, value, owner_uid, updated)
5904 ($feed_id, $unread, $owner_uid, NOW())");
5907 db_query($link, "COMMIT");
5909 if ($feed_id > 0 && $prev_unread != $unread) {
5913 /* Update parent category */
5917 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5918 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5920 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5922 ccache_update($link, $cat_id, $owner_uid, true);
5926 } else if ($feed_id < 0) {
5927 ccache_update_all($link, $owner_uid);
5933 function label_find_id($link, $label, $owner_uid) {
5934 $result = db_query($link,
5935 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5936 AND owner_uid = '$owner_uid' LIMIT 1");
5938 if (db_num_rows($result) == 1) {
5939 return db_fetch_result($result, 0, "id");
5945 function get_article_labels($link, $id) {
5946 $result = db_query($link,
5947 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5948 FROM ttrss_labels2, ttrss_user_labels2
5950 AND article_id = '$id'
5951 AND owner_uid = ".$_SESSION["uid"] . "
5956 while ($line = db_fetch_assoc($result)) {
5957 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5959 array_push($rv, $rk);
5966 function label_find_caption($link, $label, $owner_uid) {
5967 $result = db_query($link,
5968 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5969 AND owner_uid = '$owner_uid' LIMIT 1");
5971 if (db_num_rows($result) == 1) {
5972 return db_fetch_result($result, 0, "caption");
5978 function label_remove_article($link, $id, $label, $owner_uid) {
5980 $label_id = label_find_id($link, $label, $owner_uid);
5982 if (!$label_id) return;
5984 $result = db_query($link,
5985 "DELETE FROM ttrss_user_labels2
5987 label_id = '$label_id' AND
5988 article_id = '$id'");
5991 function label_add_article($link, $id, $label, $owner_uid) {
5993 $label_id = label_find_id($link, $label, $owner_uid);
5995 if (!$label_id) return;
5997 $result = db_query($link,
5999 article_id FROM ttrss_labels2, ttrss_user_labels2
6002 label_id = '$label_id' AND
6003 article_id = '$id' AND owner_uid = '$owner_uid'
6006 if (db_num_rows($result) == 0) {
6007 db_query($link, "INSERT INTO ttrss_user_labels2
6008 (label_id, article_id) VALUES ('$label_id', '$id')");
6012 function label_remove($link, $id, $owner_uid) {
6014 db_query($link, "BEGIN");
6016 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6019 $caption = db_fetch_result($result, 0, "caption");
6021 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6022 AND owner_uid = " . $_SESSION["uid"]);
6024 if (db_affected_rows($link, $result) != 0 && $caption) {
6026 /* Disable filters that reference label being removed */
6028 db_query($link, "UPDATE ttrss_filters SET
6029 enabled = false WHERE action_param = '$caption'
6031 AND owner_uid = " . $_SESSION["uid"]);
6034 db_query($link, "COMMIT");
6037 function label_create($link, $caption) {
6039 db_query($link, "BEGIN");
6043 $result = db_query($link, "SELECT id FROM ttrss_labels2
6044 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6046 if (db_num_rows($result) == 0) {
6047 $result = db_query($link,
6048 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6049 VALUES ('$caption', '".$_SESSION["uid"]."')");
6051 $result = db_affected_rows($link, $result) != 0;
6054 db_query($link, "COMMIT");
6059 function print_labels_headlines_dropdown($link, $feed_id) {
6060 print "<li onclick=\"javascript:addLabel()\">
6061 ".__("Create label...")."</li>";
6063 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6064 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6066 while ($line = db_fetch_assoc($result)) {
6068 $label_id = $line["id"];
6069 $label_caption = $line["caption"];
6071 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6072 print "<li id=\"LHDL-$id\"
6073 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6074 $label_caption ".__('(remove)')."</li>";
6076 print "<li id=\"LHDL-$id\"
6077 onclick=\"javascript:selectionAssignLabel($label_id)\">
6078 $label_caption</li>";
6083 function format_tags_string($tags, $id) {
6086 $tags_nolinks_str = "";
6090 if ($_SESSION["theme"] == "3pane") {
6096 $formatted_tags = array();
6098 foreach ($tags as $tag) {
6100 $tag_escaped = str_replace("'", "\\'", $tag);
6102 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6104 array_push($formatted_tags, $tag_str);
6106 if ($num_tags == $tag_limit) {
6111 $tags_str = implode(", ", $formatted_tags);
6113 if ($num_tags < count($tags)) {
6114 $tags_str .= ", …";
6117 if ($num_tags == 0) {
6118 $tags_str = __("no tags");
6125 function format_article_labels($labels, $id) {
6129 foreach ($labels as $l) {
6130 $labels_str .= sprintf("<span class='hlLabelRef'
6131 style='color : %s; background-color : %s'>%s</span>",
6132 $l[2], $l[3], $l[1]);
6139 function format_article_note($id, $note) {
6141 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6143 $str = "<div class='articleNote'>";
6144 $str .= "<div class='articleNoteOps'>";
6145 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6146 __('edit note')."</a>";