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);
1744 $login = db_escape_string($login);
1746 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1747 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1749 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1751 $query = "SELECT id,login,access_level,pwd_hash
1752 FROM ttrss_users WHERE
1756 $query = "SELECT id,login,access_level,pwd_hash
1757 FROM ttrss_users WHERE
1758 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1759 pwd_hash = '$pwd_hash2')";
1762 $result = db_query($link, $query);
1764 if (db_num_rows($result) == 1) {
1765 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1766 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1767 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1769 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1772 $user_theme = get_user_theme_path($link);
1774 $_SESSION["theme"] = $user_theme;
1775 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1776 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1778 initialize_user_prefs($link, $_SESSION["uid"]);
1787 $_SESSION["uid"] = 1;
1788 $_SESSION["name"] = "admin";
1790 $user_theme = get_user_theme_path($link);
1792 $_SESSION["theme"] = $user_theme;
1793 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1795 initialize_user_prefs($link, $_SESSION["uid"]);
1801 function make_password($length = 8) {
1804 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1808 while ($i < $length) {
1809 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1811 if (!strstr($password, $char)) {
1819 // this is called after user is created to initialize default feeds, labels
1822 // user preferences are checked on every login, not here
1824 function initialize_user($link, $uid) {
1826 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1827 VALUES ('$uid', 'All Articles')");
1829 db_query($link, "INSERT INTO ttrss_filters
1830 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1831 action_id, action_param, filter_param)
1832 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1834 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1835 values ('$uid', 'Tiny Tiny RSS: New Releases',
1836 'http://tt-rss.org/releases.rss')");
1838 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1839 values ('$uid', 'Tiny Tiny RSS: Forum',
1840 'http://tt-rss.org/forum/rss.php')");
1843 function logout_user() {
1845 if (isset($_COOKIE[session_name()])) {
1846 setcookie(session_name(), '', time()-42000, '/');
1850 function get_script_urlpath() {
1851 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1854 function validate_session($link) {
1855 if (SINGLE_USER_MODE
) {
1859 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1860 if ($_SESSION["ip_address"]) {
1861 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1862 $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1868 if ($_SESSION["uid"]) {
1870 $result = db_query($link,
1871 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1873 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1875 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1880 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1882 //print_r($_SESSION);
1884 if (time() > $_SESSION["cookie_lifetime"]) {
1892 function login_sequence($link, $mobile = false) {
1893 if (!SINGLE_USER_MODE
) {
1895 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1896 $swu = db_escape_string($_REQUEST["swu"]);
1898 $_SESSION["prefs_cache"] = false;
1899 return authenticate_user($link, $swu, null, true);
1903 $login_action = $_POST["login_action"];
1905 # try to authenticate user if called from login form
1906 if ($login_action == "do_login") {
1907 $login = $_POST["login"];
1908 $password = $_POST["password"];
1909 $remember_me = $_POST["remember_me"];
1911 if (authenticate_user($link, $login, $password)) {
1912 $_POST["password"] = "";
1914 $_SESSION["language"] = $_POST["language"];
1915 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1917 header("Location: " . $_SERVER["REQUEST_URI"]);
1922 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1926 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1927 render_login_form($link, $mobile);
1928 //header("Location: login.php");
1931 /* bump login timestamp */
1932 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1935 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1936 setcookie("ttrss_lang", $_SESSION["language"],
1937 time() + SESSION_COOKIE_LIFETIME
);
1940 /* bump counters stamp since we're getting reloaded anyway */
1942 $_SESSION["get_all_counters_stamp"] = time();
1946 return authenticate_user($link, "admin", null);
1950 function truncate_string($str, $max_len) {
1951 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1952 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1958 function get_user_theme_path($link) {
1959 $result = db_query($link, "SELECT theme_path
1961 ttrss_themes,ttrss_users
1962 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1963 if (db_num_rows($result) != 0) {
1964 return db_fetch_result($result, 0, "theme_path");
1970 function smart_date_time($timestamp) {
1971 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1972 return date("G:i", $timestamp);
1973 } else if (date("Y", $timestamp) == date("Y")) {
1974 return date("M d, G:i", $timestamp);
1976 return date("Y/m/d, G:i", $timestamp);
1980 function smart_date($timestamp) {
1981 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1983 } else if (date("Y", $timestamp) == date("Y")) {
1984 return date("D m", $timestamp);
1986 return date("Y/m/d", $timestamp);
1990 function sql_bool_to_string($s) {
1991 if ($s == "t" ||
$s == "1") {
1998 function sql_bool_to_bool($s) {
1999 if ($s == "t" ||
$s == "1") {
2006 function bool_to_sql_bool($s) {
2014 function toggleEvenOdd($a) {
2021 function sanity_check($link) {
2026 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2027 $schema_version = db_fetch_result($result, 0, "schema_version");
2029 if ($schema_version != SCHEMA_VERSION
) {
2033 if (DB_TYPE
== "mysql") {
2034 $result = db_query($link, "SELECT true", false);
2035 if (db_num_rows($result) != 1) {
2040 if (db_escape_string("testTEST") != "testTEST") {
2044 error_reporting (DEFAULT_ERROR_LEVEL
);
2046 if ($error_code != 0) {
2047 print_error_xml($error_code);
2054 function file_is_locked($filename) {
2055 if (function_exists('flock')) {
2057 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2058 error_reporting(DEFAULT_ERROR_LEVEL
);
2060 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2061 flock($fp, LOCK_UN
);
2071 return true; // consider the file always locked and skip the test
2074 function make_lockfile($filename) {
2075 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2077 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2084 function make_stampfile($filename) {
2085 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2087 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2088 fwrite($fp, time() . "\n");
2089 flock($fp, LOCK_UN
);
2097 function read_stampfile($filename) {
2100 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2101 error_reporting (DEFAULT_ERROR_LEVEL
);
2104 if (flock($fp, LOCK_EX
)) {
2105 $stamp = fgets($fp);
2106 flock($fp, LOCK_UN
);
2117 function sql_random_function() {
2118 if (DB_TYPE
== "mysql") {
2125 function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2127 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2129 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2136 $cat_qpart = "cat_id = '$feed'";
2138 $cat_qpart = "cat_id IS NULL";
2141 $tmp_result = db_query($link, "SELECT id
2142 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2144 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2146 $tmp_feed = $tmp_line["id"];
2148 db_query($link, "UPDATE ttrss_user_entries
2149 SET unread = false,last_read = NOW()
2150 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2152 } else if ($feed == -2) {
2155 db_query($link, "UPDATE ttrss_user_entries
2156 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2157 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2158 AND unread = true AND owner_uid = $owner_uid");
2161 } else if ($feed > 0) {
2163 $tmp_result = db_query($link, "SELECT id
2164 FROM ttrss_feeds WHERE parent_feed = '$feed'
2165 ORDER BY cat_id,title");
2167 $parent_ids = array();
2169 if (db_num_rows($tmp_result) > 0) {
2170 while ($p = db_fetch_assoc($tmp_result)) {
2171 array_push($parent_ids, "feed_id = " . $p["id"]);
2174 $children_qpart = implode(" OR ", $parent_ids);
2176 db_query($link, "UPDATE ttrss_user_entries
2177 SET unread = false,last_read = NOW()
2178 WHERE (feed_id = '$feed' OR $children_qpart)
2179 AND owner_uid = $owner_uid");
2182 db_query($link, "UPDATE ttrss_user_entries
2183 SET unread = false,last_read = NOW()
2184 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2187 } else if ($feed < 0 && $feed > -10) { // special, like starred
2190 db_query($link, "UPDATE ttrss_user_entries
2191 SET unread = false,last_read = NOW()
2192 WHERE marked = true AND owner_uid = $owner_uid");
2196 db_query($link, "UPDATE ttrss_user_entries
2197 SET unread = false,last_read = NOW()
2198 WHERE published = true AND owner_uid = $owner_uid");
2203 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2205 if (DB_TYPE
== "pgsql") {
2206 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2208 $match_part = "updated > DATE_SUB(NOW(),
2209 INTERVAL $intl HOUR) ";
2212 $result = db_query($link, "SELECT id FROM ttrss_entries,
2213 ttrss_user_entries WHERE $match_part AND
2215 ttrss_user_entries.ref_id = ttrss_entries.id AND
2216 owner_uid = $owner_uid");
2218 $affected_ids = array();
2220 while ($line = db_fetch_assoc($result)) {
2221 array_push($affected_ids, $line["id"]);
2224 catchupArticlesById($link, $affected_ids, 0);
2228 db_query($link, "UPDATE ttrss_user_entries
2229 SET unread = false,last_read = NOW()
2230 WHERE owner_uid = $owner_uid");
2233 } else if ($feed < -10) { // label
2235 $label_id = -$feed - 11;
2237 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2238 SET unread = false, last_read = NOW()
2239 WHERE label_id = '$label_id' AND unread = true
2240 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2244 ccache_update($link, $feed, $owner_uid, $cat_view);
2247 db_query($link, "BEGIN");
2249 $tag_name = db_escape_string($feed);
2251 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2252 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2254 while ($line = db_fetch_assoc($result)) {
2255 db_query($link, "UPDATE ttrss_user_entries SET
2256 unread = false, last_read = NOW()
2257 WHERE int_id = " . $line["post_int_id"]);
2259 db_query($link, "COMMIT");
2263 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2267 $cat_qpart = "cat_id = '$feed'";
2269 $cat_qpart = "cat_id IS NULL";
2272 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2273 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2275 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2276 $feed_url = $tmp_line["feed_url"];
2277 $feed_id = $tmp_line["id"];
2278 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2282 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2283 WHERE id = '$feed'");
2284 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2285 update_rss_feed($link, $feed_url, $feed, $force_update);
2289 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2291 if (!$omode) $omode = "flc";
2293 getGlobalCounters($link);
2295 if (strchr($omode, "l")) getLabelCounters($link);
2296 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2297 if (strchr($omode, "t")) getTagCounters($link);
2298 if (strchr($omode, "c")) {
2299 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2300 getCategoryCounters($link);
2305 function getCategoryCounters($link) {
2306 # two special categories are -1 and -2 (all virtuals; all labels)
2308 /* $ctr = getCategoryUnread($link, -1);
2310 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2312 $ctr = getCategoryUnread($link, -2);
2314 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2316 $age_qpart = getMaxAgeSubquery();
2318 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2319 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2320 WHERE ttrss_cat_counters_cache.feed_id = id AND
2321 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2323 while ($line = db_fetch_assoc($result)) {
2324 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2326 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2327 $line["unread"]."\"/>";
2330 /* Special case: NULL category doesn't actually exist in the DB */
2332 print "<counter type=\"category\" id=\"0\" counter=\"".
2333 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2337 function getCategoryUnread($link, $cat, $owner_uid = false) {
2339 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2344 $cat_query = "cat_id = '$cat'";
2346 $cat_query = "cat_id IS NULL";
2349 $age_qpart = getMaxAgeSubquery();
2351 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2353 AND owner_uid = " . $owner_uid);
2355 $cat_feeds = array();
2356 while ($line = db_fetch_assoc($result)) {
2357 array_push($cat_feeds, "feed_id = " . $line["id"]);
2360 if (count($cat_feeds) == 0) return 0;
2362 $match_part = implode(" OR ", $cat_feeds);
2364 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2365 FROM ttrss_user_entries,ttrss_entries
2366 WHERE unread = true AND ($match_part) AND id = ref_id
2367 AND $age_qpart AND owner_uid = " . $owner_uid);
2371 # this needs to be rewritten
2372 while ($line = db_fetch_assoc($result)) {
2373 $unread +
= $line["unread"];
2377 } else if ($cat == -1) {
2378 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2379 } else if ($cat == -2) {
2381 $result = db_query($link, "
2382 SELECT COUNT(unread) AS unread FROM
2383 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2384 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2385 ttrss_labels2.owner_uid = '$owner_uid'
2386 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2387 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2389 $unread = db_fetch_result($result, 0, "unread");
2396 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2397 if (DB_TYPE
== "pgsql") {
2398 return "ttrss_entries.date_entered >
2399 NOW() - INTERVAL '$days days'";
2401 return "ttrss_entries.date_entered >
2402 DATE_SUB(NOW(), INTERVAL $days DAY)";
2406 function getFeedUnread($link, $feed, $is_cat = false) {
2407 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2410 function getLabelUnread($link, $label_id, $owner_uid = false) {
2411 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2413 $result = db_query($link, "
2414 SELECT COUNT(unread) AS unread FROM
2415 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2416 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2417 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2418 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2419 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2421 if (db_num_rows($result) != 0) {
2422 return db_fetch_result($result, 0, "unread");
2428 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2429 $owner_uid = false) {
2431 $n_feed = sprintf("%d", $feed);
2433 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2436 $unread_qpart = "unread = true";
2438 $unread_qpart = "true";
2441 $age_qpart = getMaxAgeSubquery();
2444 return getCategoryUnread($link, $n_feed, $owner_uid);
2445 } else if ($n_feed == -1) {
2446 $match_part = "marked = true";
2447 } else if ($n_feed == -2) {
2448 $match_part = "published = true";
2449 } else if ($n_feed == -3) {
2450 $match_part = "unread = true";
2452 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2454 if (DB_TYPE
== "pgsql") {
2455 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2457 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2459 } else if ($n_feed == -4) {
2460 $match_part = "true";
2461 } else if ($n_feed > 0) {
2463 $result = db_query($link, "SELECT id FROM ttrss_feeds
2464 WHERE parent_feed = '$n_feed'
2466 AND owner_uid = " . $owner_uid);
2468 if (db_num_rows($result) > 0) {
2470 $linked_feeds = array();
2471 while ($line = db_fetch_assoc($result)) {
2472 array_push($linked_feeds, "feed_id = " . $line["id"]);
2475 array_push($linked_feeds, "feed_id = $n_feed");
2477 $match_part = implode(" OR ", $linked_feeds);
2479 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2480 FROM ttrss_user_entries,ttrss_entries
2481 WHERE $unread_qpart AND
2482 ttrss_user_entries.ref_id = ttrss_entries.id AND
2485 owner_uid = " . $owner_uid);
2489 # this needs to be rewritten
2490 while ($line = db_fetch_assoc($result)) {
2491 $unread +
= $line["unread"];
2497 $match_part = "feed_id = '$n_feed'";
2499 } else if ($feed < -10) {
2501 $label_id = -$feed - 11;
2503 return getLabelUnread($link, $label_id, $owner_uid);
2509 $result = db_query($link, "SELECT count(int_id) AS unread
2510 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2511 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2512 ttrss_user_entries.ref_id = ttrss_entries.id AND
2513 ttrss_feeds.hidden = false AND
2515 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2519 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2520 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2521 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2522 AND $unread_qpart AND $age_qpart AND
2523 ttrss_tags.owner_uid = " . $owner_uid);
2526 $unread = db_fetch_result($result, 0, "unread");
2531 function getGlobalUnread($link, $user_id = false) {
2534 $user_id = $_SESSION["uid"];
2537 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2538 WHERE owner_uid = '$user_id' AND feed_id > 0");
2540 $c_id = db_fetch_result($result, 0, "c_id");
2545 function getGlobalCounters($link, $global_unread = -1) {
2546 if ($global_unread == -1) {
2547 $global_unread = getGlobalUnread($link);
2549 print "<counter type=\"global\" id='global-unread'
2550 counter='$global_unread'/>";
2552 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2553 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2555 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2557 print "<counter type=\"global\" id='subscribed-feeds'
2558 counter='$subscribed_feeds'/>";
2562 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2565 if (!$_SESSION["tctr_last_value"]) {
2566 $_SESSION["tctr_last_value"] = array();
2570 $old_counters = $_SESSION["tctr_last_value"];
2572 $tctrs_modified = false;
2574 $age_qpart = getMaxAgeSubquery();
2576 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2577 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2578 AND ref_id = id AND $age_qpart
2579 AND unread = true)) AS count FROM ttrss_tags
2580 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2581 ORDER BY count DESC LIMIT 55");
2585 while ($line = db_fetch_assoc($result)) {
2586 $tags[$line["tag_name"]] +
= $line["count"];
2589 foreach (array_keys($tags) as $tag) {
2590 $unread = $tags[$tag];
2592 $tag = htmlspecialchars($tag);
2594 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2595 $old_counters[$tag] = $unread;
2596 $tctrs_modified = true;
2597 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2602 if ($smart_mode && $tctrs_modified) {
2603 $_SESSION["tctr_last_value"] = $old_counters;
2608 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2610 $age_qpart = getMaxAgeSubquery();
2613 if (!$_SESSION["lctr_last_value"]) {
2614 $_SESSION["lctr_last_value"] = array();
2620 for ($i = -1; $i >= -4; $i--) {
2622 $count = getFeedUnread($link, $i);
2626 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2627 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2632 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2634 $ret_arr[$i]["counter"] = $count;
2635 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2640 $old_counters = $_SESSION["lctr_last_value"];
2641 $lctrs_modified = false;
2644 $owner_uid = $_SESSION["uid"];
2646 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2647 WHERE owner_uid = '$owner_uid'");
2649 while ($line = db_fetch_assoc($result)) {
2651 $id = -$line["id"] - 11;
2653 $label_name = $line["caption"];
2654 $count = getFeedUnread($link, $id);
2656 if (!$smart_mode ||
$old_counters[$id] != $count) {
2657 $old_counters[$id] = $count;
2658 $lctrs_modified = true;
2661 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2662 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2667 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2669 $ret_arr[$id]["counter"] = $count;
2670 $ret_arr[$id]["description"] = $label_name;
2674 error_reporting (DEFAULT_ERROR_LEVEL
);
2677 if ($smart_mode && $lctrs_modified) {
2678 $_SESSION["lctr_last_value"] = $old_counters;
2684 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2686 $age_qpart = getMaxAgeSubquery();
2689 if (!$_SESSION["fctr_last_value"]) {
2690 $_SESSION["fctr_last_value"] = array();
2694 $old_counters = $_SESSION["fctr_last_value"];
2696 $query = "SELECT ttrss_feeds.id,
2698 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2699 last_error, value AS count
2700 FROM ttrss_feeds, ttrss_counters_cache
2701 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2702 AND parent_feed IS NULL
2703 AND ttrss_counters_cache.feed_id = id";
2705 $result = db_query($link, $query);
2706 $fctrs_modified = false;
2708 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2710 while ($line = db_fetch_assoc($result)) {
2713 $count = $line["count"];
2714 $last_error = htmlspecialchars($line["last_error"]);
2716 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2717 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2719 $last_updated = date($short_date, strtotime($line["last_updated"]));
2722 $last_updated = htmlspecialchars($last_updated);
2724 $has_img = feed_has_icon($id);
2726 $tmp_result = db_query($link,
2727 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2728 WHERE parent_feed = '$id' AND feed_id = id");
2730 $count +
= db_fetch_result($tmp_result, 0, "unread");
2732 if (!$smart_mode ||
$old_counters[$id] != $count) {
2733 $old_counters[$id] = $count;
2734 $fctrs_modified = true;
2737 $error_part = "error=\"$last_error\"";
2743 $has_img_part = "hi=\"$has_img\"";
2748 if ($active_feed && $id == $active_feed) {
2749 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2751 $has_title_part = "";
2754 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2755 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2758 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2762 if ($smart_mode && $fctrs_modified) {
2763 $_SESSION["fctr_last_value"] = $old_counters;
2767 function get_script_dt_add() {
2768 /* if (strpos(VERSION, ".99") === false) {
2776 function get_pgsql_version($link) {
2777 $result = db_query($link, "SELECT version() AS version");
2778 $version = split(" ", db_fetch_result($result, 0, "version"));
2782 function print_error_xml($code, $add_msg = "") {
2785 $error_msg = $ERRORS[$code];
2788 $error_msg = "$error_msg; $add_msg";
2791 print "<rpc-reply>";
2792 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2793 print "</rpc-reply>";
2796 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2797 $auth_login = '', $auth_pass = '') {
2799 # check for feed:http://url
2800 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2802 # check for feed://URL
2803 if (strpos($feed_link, "//") === 0) {
2804 $feed_link = "http:$feed_link";
2807 if ($feed_link == "") return;
2809 if ($cat_id == "0" ||
!$cat_id) {
2810 $cat_qpart = "NULL";
2812 $cat_qpart = "'$cat_id'";
2815 $result = db_query($link,
2816 "SELECT id FROM ttrss_feeds
2817 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2819 if (db_num_rows($result) == 0) {
2821 $result = db_query($link,
2822 "INSERT INTO ttrss_feeds
2823 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2824 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2825 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2827 $result = db_query($link,
2828 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2829 AND owner_uid = " . $_SESSION["uid"]);
2831 $feed_id = db_fetch_result($result, 0, "id");
2834 update_rss_feed($link, $feed_link, $feed_id, true);
2843 function print_feed_select($link, $id, $default_id = "",
2844 $attributes = "", $include_all_feeds = true) {
2846 print "<select id=\"$id\" name=\"$id\" $attributes>";
2847 if ($include_all_feeds) {
2848 print "<option value=\"0\">".__('All feeds')."</option>";
2851 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2852 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2854 if (db_num_rows($result) > 0 && $include_all_feeds) {
2855 print "<option disabled>--------</option>";
2858 while ($line = db_fetch_assoc($result)) {
2859 if ($line["id"] == $default_id) {
2860 $is_selected = "selected";
2864 printf("<option $is_selected value='%d'>%s</option>",
2865 $line["id"], htmlspecialchars($line["title"]));
2871 function print_feed_cat_select($link, $id, $default_id = "",
2872 $attributes = "", $include_all_cats = true) {
2874 print "<select id=\"$id\" name=\"$id\" $attributes>";
2876 if ($include_all_cats) {
2877 print "<option value=\"0\">".__('Uncategorized')."</option>";
2880 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2881 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2883 if (db_num_rows($result) > 0 && $include_all_cats) {
2884 print "<option disabled>--------</option>";
2887 while ($line = db_fetch_assoc($result)) {
2888 if ($line["id"] == $default_id) {
2889 $is_selected = "selected";
2893 printf("<option $is_selected value='%d'>%s</option>",
2894 $line["id"], htmlspecialchars($line["title"]));
2900 function checkbox_to_sql_bool($val) {
2901 return ($val == "on") ?
"true" : "false";
2904 function getFeedCatTitle($link, $id) {
2906 return __("Special");
2907 } else if ($id < -10) {
2908 return __("Labels");
2909 } else if ($id > 0) {
2910 $result = db_query($link, "SELECT ttrss_feed_categories.title
2911 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2912 cat_id = ttrss_feed_categories.id");
2913 if (db_num_rows($result) == 1) {
2914 return db_fetch_result($result, 0, "title");
2916 return __("Uncategorized");
2919 return "getFeedCatTitle($id) failed";
2924 function getFeedTitle($link, $id) {
2926 return __("Starred articles");
2927 } else if ($id == -2) {
2928 return __("Published articles");
2929 } else if ($id == -3) {
2930 return __("Fresh articles");
2931 } else if ($id == -4) {
2932 return __("All articles");
2933 } else if ($id < -10) {
2934 $label_id = -$id - 11;
2935 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2936 if (db_num_rows($result) == 1) {
2937 return db_fetch_result($result, 0, "caption");
2939 return "Unknown label ($label_id)";
2942 } else if ($id > 0) {
2943 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2944 if (db_num_rows($result) == 1) {
2945 return db_fetch_result($result, 0, "title");
2947 return "Unknown feed ($id)";
2950 if (preg_match("/^-?[0-9][0-9]*$/", $id)) {
2951 return "getFeedTitle($id) failed";
2959 function get_session_cookie_name() {
2960 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2963 function print_init_params($link) {
2964 print "<init-params>";
2965 if ($_SESSION["stored-params"]) {
2966 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2968 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2969 print "<param key=\"$key\" value=\"$value\"/>";
2974 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2975 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2976 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2977 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2979 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2980 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2982 print "<param key=\"hide_read_feeds\" value=\"" .
2983 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2985 print "<param key=\"enable_feed_cats\" value=\"" .
2986 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2988 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2989 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2991 print "<param key=\"confirm_feed_catchup\" value=\"" .
2992 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2994 print "<param key=\"cdm_auto_catchup\" value=\"" .
2995 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2997 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2999 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3001 print "<param key=\"default_view_mode\" value=\"" .
3002 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3004 print "<param key=\"default_view_limit\" value=\"" .
3005 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3007 print "<param key=\"default_view_order_by\" value=\"" .
3008 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3010 print "<param key=\"prefs_active_tab\" value=\"" .
3011 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3013 print "<param key=\"infobox_disable_overlay\" value=\"" .
3014 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3016 print "<param key=\"icons_location\" value=\"" .
3019 print "<param key=\"hide_read_shows_special\" value=\"" .
3020 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3022 print "<param key=\"hide_feedlist\" value=\"" .
3023 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3025 print "<param key=\"bw_limit\" value=\"".
3026 (int) $_SESSION["bw_limit"]."\"/>";
3028 // print "<param key=\"sync_counters\" value=\"" .
3029 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3031 print "<param key=\"sync_counters\" value=\"1\"/>";
3033 print "<param key=\"offline_enabled\" value=\"".
3034 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3036 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3037 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3039 $num_feeds = db_fetch_result($result, 0, "cf");
3041 print "<param key=\"num_feeds\" value=\"".
3042 (int)$num_feeds. "\"/>";
3044 print "</init-params>";
3047 function print_runtime_info($link) {
3048 print "<runtime-info>";
3050 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3051 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3053 $num_feeds = db_fetch_result($result, 0, "cf");
3055 print "<param key=\"num_feeds\" value=\"".
3056 (int)$num_feeds. "\"/>";
3058 if (ENABLE_UPDATE_DAEMON
) {
3059 print "<param key=\"daemon_is_running\" value=\"".
3060 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3062 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3064 $stamp = (int)read_stampfile("update_daemon.stamp");
3066 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3069 $stamp_delta = time() - $stamp;
3071 if ($stamp_delta > 1800) {
3075 $_SESSION["daemon_stamp_check"] = time();
3078 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3080 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3082 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3087 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3089 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3090 $new_version_details = check_for_update($link);
3092 print "<param key=\"new_version_available\" value=\"".
3093 sprintf("%d", $new_version_details != ""). "\"/>";
3095 $_SESSION["last_version_check"] = time();
3099 // print "<param key=\"new_version_available\" value=\"1\"/>";
3101 print "</runtime-info>";
3104 function getSearchSql($search, $match_on) {
3106 $search_query_part = "";
3108 $keywords = split(" ", $search);
3109 $query_keywords = array();
3111 if ($match_on == "both") {
3113 foreach ($keywords as $k) {
3114 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3115 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3118 $search_query_part = implode("AND", $query_keywords) . " AND ";
3120 } else if ($match_on == "title") {
3122 foreach ($keywords as $k) {
3123 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3126 $search_query_part = implode("AND", $query_keywords) . " AND ";
3128 } else if ($match_on == "content") {
3130 foreach ($keywords as $k) {
3131 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3135 $search_query_part = implode("AND", $query_keywords);
3137 return $search_query_part;
3140 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3142 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3146 $search_query_part = getSearchSql($search, $match_on);
3147 $search_query_part .= " AND ";
3150 $search_query_part = "";
3153 $view_query_part = "";
3155 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3157 $view_query_part = " ";
3158 } else if ($feed != -1) {
3159 $unread = getFeedUnread($link, $feed, $cat_view);
3161 $view_query_part = " unread = true AND ";
3166 if ($view_mode == "marked") {
3167 $view_query_part = " marked = true AND ";
3170 if ($view_mode == "unread") {
3171 $view_query_part = " unread = true AND ";
3174 if ($view_mode == "updated") {
3175 $view_query_part = " (last_read is null and unread = false) AND ";
3179 $limit_query_part = "LIMIT " . $limit;
3182 $vfeed_query_part = "";
3184 // override query strategy and enable feed display when searching globally
3185 if ($search && $search_mode == "all_feeds") {
3186 $query_strategy_part = "ttrss_entries.id > 0";
3187 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3188 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3189 $query_strategy_part = "ttrss_entries.id > 0";
3190 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3191 id = feed_id) as feed_title,";
3192 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3194 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3196 $tmp_result = false;
3199 $tmp_result = db_query($link, "SELECT id
3200 FROM ttrss_feeds WHERE cat_id = '$feed'");
3202 $tmp_result = db_query($link, "SELECT id
3203 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3204 WHERE id = '$feed') AND id != '$feed'");
3207 $cat_siblings = array();
3209 if (db_num_rows($tmp_result) > 0) {
3210 while ($p = db_fetch_assoc($tmp_result)) {
3211 array_push($cat_siblings, "feed_id = " . $p["id"]);
3214 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3215 $feed, implode(" OR ", $cat_siblings));
3218 $query_strategy_part = "ttrss_entries.id > 0";
3221 } else if ($feed >= 0) {
3226 $query_strategy_part = "cat_id = '$feed'";
3228 $query_strategy_part = "cat_id IS NULL";
3231 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3234 $tmp_result = db_query($link, "SELECT id
3235 FROM ttrss_feeds WHERE parent_feed = '$feed'
3236 ORDER BY cat_id,title");
3238 $parent_ids = array();
3240 if (db_num_rows($tmp_result) > 0) {
3241 while ($p = db_fetch_assoc($tmp_result)) {
3242 array_push($parent_ids, "feed_id = " . $p["id"]);
3245 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3246 $feed, implode(" OR ", $parent_ids));
3248 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3250 $query_strategy_part = "feed_id = '$feed'";
3253 } else if ($feed == -1) { // starred virtual feed
3254 $query_strategy_part = "marked = true";
3255 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3256 } else if ($feed == -2) { // published virtual feed OR labels category
3259 $query_strategy_part = "published = true";
3260 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3262 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3264 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3266 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3267 ttrss_user_labels2.article_id = ref_id";
3271 } else if ($feed == -3) { // fresh virtual feed
3272 $query_strategy_part = "unread = true";
3274 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3276 if (DB_TYPE
== "pgsql") {
3277 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3279 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3282 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3283 } else if ($feed == -4) { // all articles virtual feed
3284 $query_strategy_part = "true";
3285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3286 } else if ($feed <= -10) { // labels
3287 $label_id = -$feed - 11;
3289 $query_strategy_part = "label_id = '$label_id' AND
3290 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3291 ttrss_user_labels2.article_id = ref_id";
3293 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3294 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3297 $query_strategy_part = "id > 0"; // dumb
3300 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3301 $order_by = "updated";
3303 $order_by = "updated DESC";
3306 if ($view_mode != "noscores") {
3307 $order_by = "score DESC, $order_by";
3310 if ($override_order) {
3311 $order_by = $override_order;
3316 if ($search && $search_mode == "all_feeds") {
3317 $feed_title = __("Search results")." ($search)";
3318 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3319 $feed_title = __("Search results")." ($search, $feed)";
3320 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3321 $feed_title = $feed;
3322 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3327 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3328 WHERE id = '$feed' AND owner_uid = $owner_uid");
3329 $feed_title = db_fetch_result($result, 0, "title");
3331 $feed_title = __("Uncategorized");
3335 $feed_title = __("Searched for")." $search ($feed_title)";
3340 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3341 WHERE id = '$feed' AND owner_uid = $owner_uid");
3343 $feed_title = db_fetch_result($result, 0, "title");
3344 $feed_site_url = db_fetch_result($result, 0, "site_url");
3345 $last_error = db_fetch_result($result, 0, "last_error");
3348 $feed_title = __("Searched for") . " $search ($feed_title)";
3352 } else if ($feed == -1) {
3353 $feed_title = __("Starred articles");
3354 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3355 } else if ($feed == -2) {
3357 $feed_title = __("Published articles");
3358 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3360 $feed_title = __("Labels");
3362 } else if ($feed == -3) {
3363 $feed_title = __("Fresh articles");
3364 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3365 } else if ($feed == -4) {
3366 $feed_title = __("All articles");
3367 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3368 } else if ($feed < -10) {
3369 $label_id = -$feed - 11;
3370 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3371 WHERE id = '$label_id'");
3372 $feed_title = db_fetch_result($result, 0, "caption");
3375 $feed_title = __("Searched for") . " $search ($feed_title)";
3381 $content_query_part = "content as content_preview,";
3383 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3386 $feed_kind = "Feeds";
3388 $feed_kind = "Labels";
3391 if ($limit_query_part) {
3392 $offset_query_part = "OFFSET $offset";
3395 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3396 if (!$override_order) {
3397 $order_by = "ttrss_feeds.title, $order_by";
3400 // Special output for Fresh feed
3402 /* if ($feed == -3) {
3403 $group_limit_part = "(select count(*) from
3404 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3405 t1.ref_id = t2.id and t1.owner_uid = 2 and
3406 t1.feed_id = ttrss_user_entries.feed_id and
3407 t2.updated > ttrss_entries.updated) <= 5 AND";
3411 $query = "SELECT DISTINCT
3413 ttrss_entries.id,ttrss_entries.title,
3416 unread,feed_id,marked,published,link,last_read,
3417 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3420 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3423 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3426 ttrss_feeds.hidden = false AND
3427 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3428 ttrss_user_entries.ref_id = ttrss_entries.id AND
3429 ttrss_user_entries.owner_uid = '$owner_uid' AND
3432 $query_strategy_part ORDER BY $order_by
3433 $limit_query_part $offset_query_part";
3435 if ($_GET["debug"]) print $query;
3437 $result = db_query($link, $query);
3442 $feed_kind = "Tags";
3444 $result = db_query($link, "SELECT
3447 ttrss_entries.id as id,title,
3450 marked,link,last_read,
3451 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3454 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3457 ttrss_entries,ttrss_user_entries,ttrss_tags
3459 ref_id = ttrss_entries.id AND
3460 ttrss_user_entries.owner_uid = '$owner_uid' AND
3461 post_int_id = int_id AND tag_name = '$feed' AND
3464 $query_strategy_part ORDER BY $order_by
3465 $limit_query_part");
3468 return array($result, $feed_title, $feed_site_url, $last_error);
3472 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3473 $limit, $search, $search_mode, $match_on) {
3475 $note_style = "background-color : #fff7d5; border-width : 1px; ".
3476 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3477 "margin-top : 5px; color : #9a8c59;";
3479 if (!$limit) $limit = 30;
3481 $qfh_ret = queryFeedHeadlines($link, $feed,
3482 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3485 $result = $qfh_ret[0];
3486 $feed_title = htmlspecialchars($qfh_ret[1]);
3487 $feed_site_url = $qfh_ret[2];
3488 $last_error = $qfh_ret[3];
3490 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3492 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3493 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3494 <rss version=\"2.0\">
3496 <title>$feed_title</title>
3497 <link>$feed_site_url</link>
3498 <description>Feed generated by Tiny Tiny RSS</description>";
3500 while ($line = db_fetch_assoc($result)) {
3502 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3503 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3505 $tags = get_article_tags($link, $line["id"], $owner_uid);
3507 foreach ($tags as $tag) {
3508 print "<category>" . htmlspecialchars($tag) . "</category>";
3511 $rfc822_date = date('r', strtotime($line["updated"]));
3513 print "<pubDate>$rfc822_date</pubDate>";
3516 htmlspecialchars($line["title"]) . "</title>";
3518 print "<description><![CDATA[";
3519 print $line["content_preview"];
3520 if ($line["note"]) {
3521 print "<div style='$note_style'>";
3522 print $line["note"];
3525 print "]]></description>";
3530 print "</channel></rss>";
3534 function getCategoryTitle($link, $cat_id) {
3536 if ($cat_id == -1) {
3537 return __("Special");
3538 } else if ($cat_id == -2) {
3539 return __("Labels");
3542 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3545 if (db_num_rows($result) == 1) {
3546 return db_fetch_result($result, 0, "title");
3548 return "Uncategorized";
3553 // http://ru2.php.net/strip-tags
3555 function strip_tags_long($textstring, $allowed){
3556 while($textstring != strip_tags($textstring, $allowed))
3558 while (strlen($textstring) != 0)
3560 if (strlen($textstring) > 1024) {
3563 $otherlen = strlen($textstring);
3565 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3566 $safetext .= $temptext;
3567 $textstring = substr_replace($textstring,'',0,$otherlen);
3569 $textstring = $safetext;
3575 function sanitize_rss($link, $str, $force_strip_tags = false) {
3578 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3580 $res = strip_tags_long($res,
3581 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3583 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3584 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3587 if (get_pref($link, "STRIP_IMAGES")) {
3589 $res = preg_replace('/<img[^>]+>/is', '', $res);
3597 * Send by mail a digest of last articles.
3599 * @param mixed $link The database connection.
3600 * @param integer $limit The maximum number of articles by digest.
3601 * @return boolean Return false if digests are not enabled.
3603 function send_headlines_digests($link, $limit = 100) {
3605 if (!DIGEST_ENABLE
) return false;
3607 $user_limit = DIGEST_EMAIL_LIMIT
;
3610 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3612 if (DB_TYPE
== "pgsql") {
3613 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3614 } else if (DB_TYPE
== "mysql") {
3615 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3618 $result = db_query($link, "SELECT id,email FROM ttrss_users
3619 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3621 while ($line = db_fetch_assoc($result)) {
3623 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3624 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3626 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3628 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3629 $digest = $tuple[0];
3630 $headlines_count = $tuple[1];
3631 $affected_ids = $tuple[2];
3632 $digest_text = $tuple[3];
3634 if ($headlines_count > 0) {
3636 $mail = new PHPMailer();
3638 $mail->PluginDir
= "lib/phpmailer/";
3639 $mail->SetLanguage("en", "lib/phpmailer/language/");
3641 $mail->CharSet
= "UTF-8";
3643 $mail->From
= DIGEST_FROM_ADDRESS
;
3644 $mail->FromName
= DIGEST_FROM_NAME
;
3645 $mail->AddAddress($line["email"], $line["login"]);
3647 if (DIGEST_SMTP_HOST
) {
3648 $mail->Host
= DIGEST_SMTP_HOST
;
3649 $mail->Mailer
= "smtp";
3650 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3651 $mail->Username
= DIGEST_SMTP_LOGIN
;
3652 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3655 $mail->IsHTML(true);
3656 $mail->Subject
= DIGEST_SUBJECT
;
3657 $mail->Body
= $digest;
3658 $mail->AltBody
= $digest_text;
3660 $rc = $mail->Send();
3662 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3666 if ($rc && $do_catchup) {
3667 print "Marking affected articles as read...\n";
3668 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3671 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3672 WHERE id = " . $line["id"]);
3674 print "No headlines\n";
3679 print "All done.\n";
3683 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3685 require_once "lib/MiniTemplator.class.php";
3687 $tpl = new MiniTemplator
;
3688 $tpl_t = new MiniTemplator
;
3690 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3691 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3693 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3694 $tpl->setVariable('CUR_TIME', date('G:i'));
3696 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3697 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3699 $affected_ids = array();
3701 if (DB_TYPE
== "pgsql") {
3702 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3703 } else if (DB_TYPE
== "mysql") {
3704 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3707 $result = db_query($link, "SELECT ttrss_entries.title,
3708 ttrss_feeds.title AS feed_title,
3710 ttrss_user_entries.ref_id,
3712 SUBSTRING(content, 1, 120) AS excerpt,
3713 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3715 ttrss_user_entries,ttrss_entries,ttrss_feeds
3717 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3718 AND include_in_digest = true
3721 AND ttrss_user_entries.owner_uid = $user_id
3723 ORDER BY ttrss_feeds.title, date_entered DESC
3726 $cur_feed_title = "";
3728 $headlines_count = db_num_rows($result);
3730 $headlines = array();
3732 while ($line = db_fetch_assoc($result)) {
3733 array_push($headlines, $line);
3736 for ($i = 0; $i < sizeof($headlines); $i++
) {
3738 $line = $headlines[$i];
3740 array_push($affected_ids, $line["ref_id"]);
3742 $updated = smart_date_time(strtotime($line["last_updated"]));
3744 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3745 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3746 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3747 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3748 $tpl->setVariable('ARTICLE_EXCERPT',
3749 truncate_string(strip_tags($line["excerpt"]), 100));
3751 $tpl->addBlock('article');
3753 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3754 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3755 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3756 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3757 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3758 // truncate_string(strip_tags($line["excerpt"]), 100));
3760 $tpl_t->addBlock('article');
3762 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3763 $tpl->addBlock('feed');
3764 $tpl_t->addBlock('feed');
3769 $tpl->addBlock('digest');
3770 $tpl->generateOutputToString($tmp);
3772 $tpl_t->addBlock('digest');
3773 $tpl_t->generateOutputToString($tmp_t);
3775 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3778 function check_for_update($link) {
3779 $releases_feed = "http://tt-rss.org/releases.rss";
3781 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3786 if (ENABLE_SIMPLEPIE
) {
3787 $rss = new SimplePie();
3788 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3789 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3790 $rss->set_feed_url($fetch_url);
3791 $rss->set_output_encoding('UTF-8');
3794 $rss = fetch_rss($releases_feed);
3796 error_reporting (DEFAULT_ERROR_LEVEL
);
3800 if (ENABLE_SIMPLEPIE
) {
3801 $items = $rss->get_items();
3803 $items = $rss->items
;
3805 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3806 if (!$items ||
!is_array($items)) $items = $rss;
3809 if (!is_array($items) ||
count($items) == 0) {
3813 $latest_item = $items[0];
3815 if (ENABLE_SIMPLEPIE
) {
3816 $last_title = $latest_item->get_title();
3818 $last_title = $latest_item["title"];
3821 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3823 if (ENABLE_SIMPLEPIE
) {
3824 $release_url = sanitize_rss($link, $latest_item->get_link());
3825 $content = sanitize_rss($link, $latest_item->get_description());
3827 $release_url = sanitize_rss($link, $latest_item["link"]);
3828 $content = sanitize_rss($link, $latest_item["description"]);
3831 if (version_compare(VERSION
, $latest_version) == -1) {
3832 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3833 $latest_version)."<div class='milestoneDetails'>$content</div>";
3840 function markArticlesById($link, $ids, $cmode) {
3844 foreach ($ids as $id) {
3845 array_push($tmp_ids, "ref_id = '$id'");
3848 $ids_qpart = join(" OR ", $tmp_ids);
3851 db_query($link, "UPDATE ttrss_user_entries SET
3852 marked = false,last_read = NOW()
3853 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3854 } else if ($cmode == 1) {
3855 db_query($link, "UPDATE ttrss_user_entries SET
3857 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3859 db_query($link, "UPDATE ttrss_user_entries SET
3860 marked = NOT marked,last_read = NOW()
3861 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3865 function publishArticlesById($link, $ids, $cmode) {
3869 foreach ($ids as $id) {
3870 array_push($tmp_ids, "ref_id = '$id'");
3873 $ids_qpart = join(" OR ", $tmp_ids);
3876 db_query($link, "UPDATE ttrss_user_entries SET
3877 published = false,last_read = NOW()
3878 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3879 } else if ($cmode == 1) {
3880 db_query($link, "UPDATE ttrss_user_entries SET
3882 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3884 db_query($link, "UPDATE ttrss_user_entries SET
3885 published = NOT published,last_read = NOW()
3886 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3890 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3892 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3896 foreach ($ids as $id) {
3897 array_push($tmp_ids, "ref_id = '$id'");
3900 $ids_qpart = join(" OR ", $tmp_ids);
3903 db_query($link, "UPDATE ttrss_user_entries SET
3904 unread = false,last_read = NOW()
3905 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3906 } else if ($cmode == 1) {
3907 db_query($link, "UPDATE ttrss_user_entries SET
3909 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3911 db_query($link, "UPDATE ttrss_user_entries SET
3912 unread = NOT unread,last_read = NOW()
3913 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3918 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3919 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3921 while ($line = db_fetch_assoc($result)) {
3922 ccache_update($link, $line["feed_id"], $owner_uid);
3926 function catchupArticleById($link, $id, $cmode) {
3929 db_query($link, "UPDATE ttrss_user_entries SET
3930 unread = false,last_read = NOW()
3931 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3932 } else if ($cmode == 1) {
3933 db_query($link, "UPDATE ttrss_user_entries SET
3935 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3937 db_query($link, "UPDATE ttrss_user_entries SET
3938 unread = NOT unread,last_read = NOW()
3939 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3943 function make_guid_from_title($title) {
3944 return preg_replace("/[ \"\',.:;]/", "-",
3945 mb_strtolower(strip_tags($title), 'utf-8'));
3948 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3949 $feed_id, $is_cat, $search, $match_on,
3952 print "<div class=\"headlinesSubToolbar\">";
3954 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3955 $page_next_link = "javascript:viewFeedGoPage(1)";
3956 $page_first_link = "javascript:viewFeedGoPage(0)";
3958 $catchup_page_link = "javascript:catchupPage()";
3959 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3960 $catchup_sel_link = "javascript:catchupSelection()";
3962 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3964 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3965 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3966 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3967 $sel_inv_link = "javascript:invertHeadlineSelection()";
3969 $tog_unread_link = "javascript:selectionToggleUnread()";
3970 $tog_marked_link = "javascript:selectionToggleMarked()";
3971 $tog_published_link = "javascript:selectionTogglePublished()";
3975 $sel_all_link = "javascript:cdmSelectArticles('all')";
3976 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3977 $sel_none_link = "javascript:cdmSelectArticles('none')";
3979 $sel_inv_link = "javascript:invertHeadlineSelection()";
3981 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3982 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3983 $tog_published_link = "javascript:selectionTogglePublished(true)";
3987 print "<div id=\"subtoolbar_ftitle\">";
3989 if ($feed_site_url) {
3991 $target = "target=\"_blank\"";
3993 print "<a $target href=\"$feed_site_url\">".
3994 truncate_string($feed_title,30)."</a>";
4000 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4004 <a target=\"_blank\"
4005 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4006 <img class=\"noborder\"
4007 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4012 print __('Select:')."
4013 <a href=\"$sel_all_link\">".__('All')."</a>,
4014 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4015 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4016 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4018 print " ";
4021 onmouseover=\"enable_selection(false)\"
4022 onmouseout=\"enable_selection(true)\"
4023 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4024 __("Actions...") . " <img src=\"images/down_arrow.png\">
4027 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4029 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4030 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4031 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4032 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4033 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4034 <li class=\"insensitive\">".__('Mark as read:')."</li>
4035 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4037 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4040 //print "<li><span class=\"insensitive\">--------</span></li>";
4041 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4043 print_labels_headlines_dropdown($link, $feed_id);
4050 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4052 $tmp_category = getCategoryTitle($link, $cat_id);
4055 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4056 } else if ($cat_id == 0 ||
$cat_id == -2) {
4057 $cat_unread = getCategoryUnread($link, $cat_id);
4061 $holder_style = "display:none;";
4068 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4071 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4072 $inner_title_class = "catTitle";
4074 $browse_cat_link = "";
4075 $inner_title_class = "catTitleNL";
4078 $cat_class = "feedCat";
4080 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4081 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4082 title=\"".__('Click to collapse category')."\"
4083 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4084 id=\"FCATN-$cat_id\" $browse_cat_link
4085 \">$tmp_category</span>";
4087 print "<span id=\"FCAP-$cat_id\">";
4089 print " <span id=\"FCATCTR-$cat_id\"
4090 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4096 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4100 function outputFeedList($link, $tags = false) {
4102 print "<ul class=\"feedList\" id=\"feedList\">";
4104 $owner_uid = $_SESSION["uid"];
4108 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4110 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4113 $cat_hidden = false;
4116 printCategoryHeader($link, -1, $cat_hidden, false);
4119 $num_starred = getFeedUnread($link, -1);
4120 $num_published = getFeedUnread($link, -2);
4121 $num_fresh = getFeedUnread($link, -3);
4122 $num_total = getFeedUnread($link, -4);
4126 if ($num_total > 0) $class .= "Unread";
4128 printFeedEntry(-4, $class, __("All articles"), $num_total,
4129 "images/tag.png", $link);
4133 if ($num_fresh > 0) $class .= "Unread";
4135 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4136 "images/fresh.png", $link);
4140 if ($num_starred > 0) $class .= "Unread";
4142 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4145 $mark_img_ext = "gif";
4147 $mark_img_ext = "png";
4150 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4151 "images/mark_set.$mark_img_ext", $link);
4155 if ($num_published > 0) $class .= "Unread";
4157 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4158 "images/pub_set.gif", $link);
4160 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4167 $result = db_query($link, "SELECT * FROM
4168 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4170 if (db_num_rows($result) > 0) {
4171 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4173 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4176 $cat_hidden = false;
4179 printCategoryHeader($link, -2, $cat_hidden, true);
4182 print "<li><hr></li>";
4186 while ($line = db_fetch_assoc($result)) {
4188 $label_id = -$line['id'] - 11;
4189 $count = getFeedUnread($link, $label_id);
4197 printFeedEntry($label_id,
4198 $class, $line["caption"],
4199 $count, "images/label.png", $link,
4200 false, false, false,
4201 $line['fg_color'], $line['bg_color']);
4205 if (db_num_rows($result) > 0) {
4206 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4212 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4213 print "<li><hr></li>";
4216 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4217 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4218 $order_by_qpart = "order_id,category,unread DESC,title";
4220 $order_by_qpart = "order_id,category,title";
4223 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4224 $order_by_qpart = "unread DESC,title";
4226 $order_by_qpart = "title";
4230 $age_qpart = getMaxAgeSubquery();
4232 $query = "SELECT ttrss_feeds.*,
4233 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4235 ttrss_feed_categories.title AS category,
4236 ttrss_feed_categories.collapsed,
4238 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4239 ON (ttrss_feed_categories.id = cat_id)
4240 LEFT JOIN ttrss_counters_cache
4242 (ttrss_feeds.id = feed_id)
4244 ttrss_feeds.hidden = false AND
4245 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4246 ORDER BY $order_by_qpart";
4248 $result = db_query($link, $query);
4250 $actid = $_GET["actid"];
4260 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4262 while ($line = db_fetch_assoc($result)) {
4264 $feed = htmlspecialchars(trim($line["title"]));
4266 if (!$feed) $feed = "[Untitled]";
4268 $feed_id = $line["id"];
4269 $unread = $line["unread"];
4271 $subop = $_GET["subop"];
4273 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4274 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4276 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4279 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4282 $rtl_tag = "dir=\"RTL\"";
4287 $tmp_result = db_query($link,
4288 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4289 WHERE parent_feed = '$feed_id' AND feed_id = id");
4291 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4293 $cat_id = $line["cat_id"];
4295 $tmp_category = $line["category"];
4297 if (!$tmp_category) {
4298 $tmp_category = __("Uncategorized");
4301 // $class = ($lnum % 2) ? "even" : "odd";
4303 if ($line["last_error"]) {
4309 if ($unread > 0) $class .= "Unread";
4311 if ($actid == $feed_id) {
4312 $class .= "Selected";
4315 $total_unread +
= $unread;
4317 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4323 $category = $tmp_category;
4325 $collapsed = sql_bool_to_bool($line["collapsed"]);
4327 // workaround for NULL category
4328 if ($category == __("Uncategorized")) {
4329 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4334 $cat_id = sprintf("%d", $cat_id);
4336 printCategoryHeader($link, $cat_id, $collapsed, true);
4340 printFeedEntry($feed_id, $class, $feed, $unread,
4341 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4342 $last_updated, $line["last_error"]);
4347 if (db_num_rows($result) == 0) {
4348 print "<li>".__('No feeds to display.')."</li>";
4355 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4356 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4357 post_int_id = ttrss_user_entries.int_id AND
4358 unread = true AND ref_id = ttrss_entries.id
4359 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4361 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4362 ORDER BY tag_name"); */
4364 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4365 print "<li class=\"feedCat\">".__('Tags')."</li>";
4366 print "<ul class=\"feedCatList\">";
4369 $age_qpart = getMaxAgeSubquery();
4371 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4372 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4373 AND ref_id = id AND $age_qpart
4374 AND unread = true)) AS count FROM ttrss_tags
4375 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4376 ORDER BY count DESC LIMIT 50");
4380 while ($line = db_fetch_assoc($result)) {
4381 $tags[$line["tag_name"]] +
= $line["count"];
4384 foreach (array_keys($tags) as $tag) {
4386 $unread = $tags[$tag];
4394 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4398 if (db_num_rows($result) == 0) {
4399 print "<li>No tags to display.</li>";
4402 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4412 function get_article_tags($link, $id, $owner_uid = 0) {
4414 $a_id = db_escape_string($id);
4416 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4418 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4419 owner_uid as owner FROM
4420 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4421 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4425 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4426 array_push($tags, $tmp_line["tag_name"]);
4432 function trim_value(&$value) {
4433 $value = trim($value);
4436 function trim_array($array) {
4438 array_walk($tmp, 'trim_value');
4442 function tag_is_valid($tag) {
4443 if ($tag == '') return false;
4444 if (preg_match("/^[0-9]*$/", $tag)) return false;
4445 if (mb_strlen($tag) > 250) return false;
4447 if (function_exists('iconv')) {
4448 $tag = iconv("utf-8", "utf-8", $tag);
4451 if (!$tag) return false;
4456 function render_login_form($link, $mobile = false) {
4458 require_once "login_form.php";
4460 require_once "mobile/login_form.php";
4464 // from http://developer.apple.com/internet/safari/faq.html
4465 function no_cache_incantation() {
4466 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4467 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4468 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4469 header("Cache-Control: post-check=0, pre-check=0", false);
4470 header("Pragma: no-cache"); // HTTP/1.0
4473 function format_warning($msg, $id = "") {
4474 return "<div class=\"warning\" id=\"$id\">
4475 <img src=\"images/sign_excl.gif\">$msg</div>";
4478 function format_notice($msg) {
4479 return "<div class=\"notice\">
4480 <img src=\"images/sign_info.gif\">$msg</div>";
4483 function format_error($msg) {
4484 return "<div class=\"error\">
4485 <img src=\"images/sign_excl.gif\">$msg</div>";
4488 function print_notice($msg) {
4489 return print format_notice($msg);
4492 function print_warning($msg) {
4493 return print format_warning($msg);
4496 function print_error($msg) {
4497 return print format_error($msg);
4501 function T_sprintf() {
4502 $args = func_get_args();
4503 return vsprintf(__(array_shift($args)), $args);
4506 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4507 $zoom_mode = false) {
4509 /* we can figure out feed_id from article id anyway, why do we
4510 * pass feed_id here? */
4512 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4513 WHERE ref_id = '$id'");
4515 $feed_id = db_fetch_result($result, 0, "feed_id");
4517 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4519 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4520 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4522 if (db_num_rows($result) == 1) {
4523 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4525 $rtl_content = false;
4529 $rtl_tag = "dir=\"RTL\"";
4536 if ($mark_as_read) {
4537 $result = db_query($link, "UPDATE ttrss_user_entries
4538 SET unread = false,last_read = NOW()
4539 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4541 ccache_update($link, $feed_id, $_SESSION["uid"]);
4544 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4545 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4546 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4550 FROM ttrss_entries,ttrss_user_entries
4551 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4557 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4558 $link_target = "target=\"_blank\"";
4561 $line = db_fetch_assoc($result);
4563 if ($line["icon_url"]) {
4564 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4566 $feed_icon = " ";
4569 $num_comments = $line["num_comments"];
4570 $entry_comments = "";
4572 if ($num_comments > 0) {
4573 if ($line["comments"]) {
4574 $comments_url = $line["comments"];
4576 $comments_url = $line["link"];
4578 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4580 if ($line["comments"] && $line["link"] != $line["comments"]) {
4581 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4586 header("Content-Type: text/html");
4588 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4589 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4590 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4595 print "<div class=\"postReply\">";
4597 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4598 onmouseout=\"enable_resize(false)\">";
4600 $entry_author = $line["author"];
4602 if ($entry_author) {
4603 $entry_author = __(" - ") . $entry_author;
4606 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4607 strtotime($line["updated"]));
4609 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4611 if ($line["link"]) {
4612 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4613 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4615 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4618 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4620 if (!$entry_comments) $entry_comments = " "; # placeholder
4622 print "<div style='float : right'>
4623 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'> ";
4626 print "<span id=\"ATSTR-$id\">$tags_str</span>
4627 <a title=\"".__('Edit tags for this article')."\"
4628 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4630 if (defined('_ENABLE_INLINE_VIEW')) {
4632 print "<img src=\"images/art-inline.png\" class='tagsPic'
4633 style=\"cursor : pointer\" style=\"cursor : pointer\"
4634 onclick=\"showOriginalArticleInline($id)\"
4635 alt='Inline' title='".__('Display original article content')."'>";
4639 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4640 style=\"cursor : pointer\" style=\"cursor : pointer\"
4641 onclick=\"zoomToArticle($id)\"
4642 alt='Zoom' title='".__('Show article summary in new window')."'>";
4644 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4646 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
4647 style=\"cursor : pointer\" style=\"cursor : pointer\"
4648 onclick=\"publishWithNote($id, '$note_escaped')\"
4649 alt='PubNote' title='".__('Publish article with a note')."'>";
4653 print "<div clear='both'>$entry_comments</div>";
4657 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4659 print "<div class=\"postContent\">";
4661 $article_content = sanitize_rss($link, $line["content"]);
4663 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4664 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4668 print $article_content;
4670 print "<div id=\"POSTNOTE-$id\">";
4671 if ($line['note']) {
4672 print format_article_note($id, $line['note']);
4676 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4677 post_id = '$id' AND content_url != ''");
4679 if (db_num_rows($result) > 0) {
4681 $entries_html = array();
4684 while ($line = db_fetch_assoc($result)) {
4686 $url = $line["content_url"];
4687 $ctype = $line["content_type"];
4689 if (!$ctype) $ctype = __("unknown type");
4691 $filename = substr($url, strrpos($url, "/")+
1);
4695 if (substr($ctype,0,6)=="audio/" ||
$ctype=="application/ogg" ||
$ctype=="application/x-ogg") {
4696 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4697 if (($ctype == __("audio/mpeg")) &&
4698 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4699 $entry .= "<div><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></div>";
4701 $entry .= "</audio>";
4702 if (($ctype == __("audio/mpeg")) &&
4703 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4704 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a><br />";
4705 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
4707 } elseif (substr($ctype,0,6)=="video/") {
4708 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4709 $entry .= "</video>";
4712 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4713 $filename . " (" . $ctype . ")" . "</a>";
4715 array_push($entries_html, $entry);
4719 $entry["type"] = $ctype;
4720 $entry["filename"] = $filename;
4721 $entry["url"] = $url;
4723 array_push($entries, $entry);
4726 print "<div class=\"postEnclosures\">";
4728 if (!preg_match("/<img/i", $article_content)) {
4729 foreach ($entries as $entry) {
4730 if (preg_match("/image/", $entry["type"])) {
4732 alt=\"".htmlspecialchars($entry["filename"])."\"
4733 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4738 print "<div class=\"postEnclosures\">";
4740 if (db_num_rows($result) == 1) {
4741 print __("Attachment:") . " ";
4743 print __("Attachments:") . " ";
4746 print join(", ", $entries_html);
4758 print "]]></article>";
4761 <div style=\"text-align : center\">
4762 <input type=\"submit\" onclick=\"return window.close()\"
4763 value=\"".__("Close this window")."\"></div>";
4764 print "</body></html>";
4770 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4771 $next_unread_feed, $offset, $vgr_last_feed = false,
4772 $override_order = false) {
4774 $disable_cache = false;
4776 $timing_info = getmicrotime();
4778 $topmost_article_ids = array();
4784 if ($subop == "undefined") $subop = "";
4786 $subop_split = split(":", $subop);
4788 if ($subop == "CatchupSelected") {
4789 $ids = split(",", db_escape_string($_GET["ids"]));
4790 $cmode = sprintf("%d", $_GET["cmode"]);
4792 catchupArticlesById($link, $ids, $cmode);
4795 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4796 update_generic_feed($link, $feed, $cat_view, true);
4799 if ($subop == "MarkAllRead") {
4800 catchup_feed($link, $feed, $cat_view);
4802 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4803 if ($next_unread_feed) {
4804 $feed = $next_unread_feed;
4809 if ($subop_split[0] == "MarkAllReadGR") {
4810 catchup_feed($link, $subop_split[1], false);
4815 $result = db_query($link,
4816 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4818 if (db_num_rows($result) == 0) {
4819 print "<div align='center'>".__('Feed not found.')."</div>";
4824 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4826 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4827 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4829 if (db_num_rows($result) == 1) {
4830 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4832 $rtl_content = false;
4836 $rtl_tag = "dir=\"RTL\"";
4842 $rtl_content = false;
4845 $script_dt_add = get_script_dt_add();
4847 /// START /////////////////////////////////////////////////////////////////////////////////
4849 $search = db_escape_string($_GET["query"]);
4852 $disable_cache = true;
4855 $search_mode = db_escape_string($_GET["search_mode"]);
4856 $match_on = db_escape_string($_GET["match_on"]);
4862 $real_offset = $offset * $limit;
4864 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4866 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4867 $search, $search_mode, $match_on, $override_order, $real_offset);
4869 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4871 $result = $qfh_ret[0];
4872 $feed_title = $qfh_ret[1];
4873 $feed_site_url = $qfh_ret[2];
4874 $last_error = $qfh_ret[3];
4876 $vgroup_last_feed = $vgr_last_feed;
4879 $feed_site_url = article_publish_url($link);
4882 /// STOP //////////////////////////////////////////////////////////////////////////////////
4885 print "<div id=\"headlinesContainer\" $rtl_tag>";
4888 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4892 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4893 $feed, $cat_view, $search, $match_on, $search_mode);
4895 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4898 $headlines_count = db_num_rows($result);
4900 if (db_num_rows($result) > 0) {
4902 # print "\{$offset}";
4904 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4905 print "<table class=\"headlinesList\" id=\"headlinesList\"
4906 cellspacing=\"0\">";
4909 $lnum = $limit*$offset;
4911 error_reporting (DEFAULT_ERROR_LEVEL
);
4914 $cur_feed_title = '';
4916 while ($line = db_fetch_assoc($result)) {
4918 $class = ($lnum %
2) ?
"even" : "odd";
4921 $feed_id = $line["feed_id"];
4923 $labels = get_article_labels($link, $id);
4925 $labels_str = "<span id=\"HLLCTR-$id\">";
4926 $labels_str .= format_article_labels($labels, $id);
4927 $labels_str .= "</span>";
4929 if (count($topmost_article_ids) < 5) {
4930 array_push($topmost_article_ids, $id);
4933 if ($line["last_read"] == "" &&
4934 ($line["unread"] != "t" && $line["unread"] != "1")) {
4936 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4939 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4943 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4951 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4954 $mark_img_ext = "gif";
4956 $mark_img_ext = "png";
4959 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4960 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4962 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4964 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4966 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4969 if ($line["published"] == "t" ||
$line["published"] == "1") {
4970 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4972 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4974 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4976 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4979 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4980 # $line["title"] . "</a>";
4982 # $content_link = "<a
4983 # href=\"" . htmlspecialchars($line["link"]) . "\"
4984 # onclick=\"view($id,$feed_id);\">" .
4985 # $line["title"] . "</a>";
4987 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4988 # $line["title"] . "</a>";
4990 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4991 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4993 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4994 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4997 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4998 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5002 $score = $line["score"];
5004 $score_pic = get_score_pic($score);
5006 /* $score_title = __("(Click to change)");
5007 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5008 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5010 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5015 } else if ($score < -100) {
5021 $entry_author = $line["author"];
5023 if ($entry_author) {
5024 $entry_author = " - $entry_author";
5027 $has_feed_icon = feed_has_icon($feed_id);
5029 if ($has_feed_icon) {
5030 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5032 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5033 $feed_icon_img = "";
5036 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5038 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5039 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5041 $cur_feed_title = $line["feed_title"];
5042 $vgroup_last_feed = $feed_id;
5044 $cur_feed_title = htmlspecialchars($cur_feed_title);
5046 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5048 print "<tr class='feedTitle'><td colspan='7'>".
5049 "<div style=\"float : right\">$feed_icon_img</div>".
5050 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5051 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5055 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5056 onmouseout='postMouseOut($id)'";
5058 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5060 print "<td class='hlUpdPic'>$update_pic</td>";
5062 print "<td class='hlSelectRow'>
5063 <input type=\"checkbox\" onclick=\"tSR(this)\"
5067 print "<td class='hlMarkedPic'>$marked_pic</td>";
5068 print "<td class='hlMarkedPic'>$published_pic</td>";
5070 # if ($line["feed_title"]) {
5071 # print "<td class='hlContent'>$content_link</td>";
5072 # print "<td class='hlFeed'>
5073 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5074 # truncate_string($line["feed_title"],30)."</a> </td>";
5077 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5079 print "<a id=\"RTITLE-$id\"
5080 href=\"" . htmlspecialchars($line["link"]) . "\"
5081 onclick=\"return view($id,$feed_id);\">" .
5084 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5085 if ($content_preview) {
5086 print "<span class=\"contentPreview\"> - $content_preview</span>";
5094 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5095 # $line["feed_title"]."</a>
5097 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5098 if ($line["feed_title"]) {
5099 print "<span class=\"hlFeed\">
5100 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5101 $line["feed_title"]."</a>)
5109 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5111 print "<td class='hlMarkedPic'>$score_pic</td>";
5113 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5114 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5121 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5122 if ($feed_id != $vgroup_last_feed) {
5124 $cur_feed_title = $line["feed_title"];
5125 $vgroup_last_feed = $feed_id;
5127 $cur_feed_title = htmlspecialchars($cur_feed_title);
5129 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5131 $has_feed_icon = feed_has_icon($feed_id);
5133 if ($has_feed_icon) {
5134 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5136 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5139 print "<div class='cdmFeedTitle'>".
5140 "<div style=\"float : right\">$feed_icon_img</div>".
5141 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5142 $line["feed_title"]."</a> $vf_catchup_link</div>";
5147 $add_class = "Unread";
5152 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5153 $show_excerpt = false;
5155 if ($expand_cdm && $score >= -100) {
5157 $show_excerpt = false;
5159 $cdm_cstyle = "style=\"display : none\"";
5160 $show_excerpt = true;
5163 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5164 onmouseout='postMouseOut($id)'";
5166 print "<div class=\"cdmArticle$add_class\"
5168 $mouseover_attrs'>";
5170 print "<div class=\"cdmHeader\">";
5172 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5173 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5176 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5179 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5180 onclick=\"javascript:toggleUnread($id, 0)\"
5181 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5184 print $entry_author;
5186 /* if (!$expand_cdm || $score < -100) {
5187 print " <a id=\"CICH-$id\"
5188 href=\"javascript:cdmExpandArticle($id)\">
5189 (".__('Show article').")</a>";
5194 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5195 if ($line["feed_title"]) {
5196 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5200 print "</span></div>";
5202 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5203 $line["content_preview"] = preg_replace("/href=/i",
5204 "target=\"_blank\" href=", $line["content_preview"]);
5207 if ($show_excerpt) {
5208 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5209 onclick=\"cdmExpandArticle($id)\"
5210 title=\"".__('Click to expand article')."\">";
5211 print truncate_string(strip_tags($line["content_preview"]), 100);
5215 print "<div class=\"cdmContent\"
5216 onclick=\"cdmClicked($id)\"
5217 id=\"CICD-$id\" $cdm_cstyle>";
5219 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5221 print sanitize_rss($link, $line["content_preview"]);
5223 print "<div id=\"POSTNOTE-$id\">";
5224 if ($line['note']) {
5225 print format_article_note($id, $line['note']);
5229 $article_content = $line["content_preview"];
5231 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5232 post_id = '$id' AND content_url != ''");
5234 if (db_num_rows($e_result) > 0) {
5236 $entries_html = array();
5239 while ($e_line = db_fetch_assoc($e_result)) {
5241 $url = $e_line["content_url"];
5242 $ctype = $e_line["content_type"];
5243 if (!$ctype) $ctype = __("unknown type");
5245 $filename = substr($url, strrpos($url, "/")+
1);
5249 if (substr($ctype,0,6)=="audio/" ||
$ctype=="application/ogg" ||
$ctype=="application/x-ogg") {
5250 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
5251 if (($ctype == __("audio/mpeg")) &&
5252 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5253 $entry .= "<div><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></div>";
5255 $entry .= "</audio>";
5256 if (($ctype == __("audio/mpeg")) &&
5257 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5258 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a><br />";
5259 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
5261 } elseif (substr($ctype,0,6)=="video/") {
5262 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
5263 $entry .= "</video>";
5266 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5267 $filename . " (" . $ctype . ")" . "</a>";
5269 array_push($entries_html, $entry);
5273 $entry["type"] = $ctype;
5274 $entry["filename"] = $filename;
5275 $entry["url"] = $url;
5277 array_push($entries, $entry);
5280 if (!preg_match("/img/i", $article_content)) {
5281 foreach ($entries as $entry) {
5282 if (preg_match("/image/", $entry["type"])) {
5284 alt=\"".htmlspecialchars($entry["filename"])."\"
5285 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5290 print "<div class=\"cdmEnclosures\">";
5292 if (db_num_rows($e_result) == 1) {
5293 print __("Attachment:") . " ";
5295 print __("Attachments:") . " ";
5298 print join(", ", $entries_html);
5304 print "<br clear='both'>";
5307 /* if (!$expand_cdm) {
5308 print "<a id=\"CICH-$id\"
5309 href=\"javascript:cdmExpandArticle($id)\">
5315 print "<div class=\"cdmFooter\"><span class='s0'>";
5317 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5319 print __("Select:").
5320 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5321 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5323 print "</span><span class='s1'>$marked_pic ";
5324 print "$published_pic ";
5325 print "<img src=\"images/art-zoom.png\" class='tagsPic'
5326 onclick=\"zoomToArticle($id)\"
5327 style=\"cursor : pointer\"
5329 title='".__('Show article summary in new window')."'> ";
5331 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5333 print "<img src=\"images/art-pub-note.png\" class='tagsPic'
5334 style=\"cursor : pointer\" style=\"cursor : pointer\"
5335 onclick=\"publishWithNote($id, '$note_escaped')\"
5336 alt='PubNote' title='".__('Publish article with a note')."'>";
5340 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5342 // print "<img src='images/tag.png' class='markedPic'>";
5344 print "<span class='s1'>
5345 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5346 <span id=\"ATSTR-$id\">$tags_str</span>
5347 <a title=\"".__('Edit tags for this article')."\"
5348 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5352 print "<span class='s2'><a class=\"cdmToggleLink\"
5353 href=\"javascript:toggleUnread($id)\">
5354 ".__('toggle unread')."</a></span>";
5364 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5371 switch ($view_mode) {
5373 $message = __("No unread articles found to display.");
5376 $message = __("No updated articles found to display.");
5379 $message = __("No starred articles found to display.");
5383 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5385 $message = __("No articles found to display.");
5389 if (!$offset) print "<div class='whiteBox'>$message</div>";
5397 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5400 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5402 function printTagCloud($link) {
5404 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5405 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5406 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5408 $result = db_query($link, $query);
5412 while ($line = db_fetch_assoc($result)) {
5413 $tags[$line["tag_name"]] = $line["count"];
5418 $max_size = 32; // max font size in pixels
5419 $min_size = 11; // min font size in pixels
5421 // largest and smallest array values
5422 $max_qty = max(array_values($tags));
5423 $min_qty = min(array_values($tags));
5425 // find the range of values
5426 $spread = $max_qty - $min_qty;
5427 if ($spread == 0) { // we don't want to divide by zero
5431 // set the font-size increment
5432 $step = ($max_size - $min_size) / ($spread);
5434 // loop through the tag array
5435 foreach ($tags as $key => $value) {
5436 // calculate font-size
5437 // find the $value in excess of $min_qty
5438 // multiply by the font-size increment ($size)
5439 // and add the $min_size set above
5440 $size = round($min_size +
(($value - $min_qty) * $step));
5442 $key_escaped = str_replace("'", "\\'", $key);
5444 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5445 $size . "px\" title=\"$value articles tagged with " .
5446 $key . '">' . $key . '</a> ';
5450 function print_checkpoint($n, $s) {
5451 $ts = getmicrotime();
5452 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5456 function sanitize_tag($tag) {
5459 $tag = mb_strtolower($tag, 'utf-8');
5461 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5463 // $tag = str_replace('"', "", $tag);
5464 // $tag = str_replace("+", " ", $tag);
5465 $tag = str_replace("technorati tag: ", "", $tag);
5470 function generate_publish_key() {
5471 return sha1(uniqid(rand(), true));
5474 function article_publish_url($link) {
5479 if ($_SERVER['HTTPS'] != "on") {
5480 $url_path = "http://";
5482 $url_path = "https://";
5485 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5486 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5492 * Purge a feed contents, marked articles excepted.
5494 * @param mixed $link The database connection.
5495 * @param integer $id The id of the feed to purge.
5498 function clear_feed_articles($link, $id) {
5499 $result = db_query($link, "DELETE FROM ttrss_user_entries
5500 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5502 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5503 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5505 ccache_update($link, $id, $_SESSION['uid']);
5506 } // function clear_feed_articles
5509 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5511 * @return string The Mozilla Firefox feed adding URL.
5513 function add_feed_url() {
5514 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5515 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5517 } // function add_feed_url
5520 * Encrypt a password in SHA1.
5522 * @param string $pass The password to encrypt.
5523 * @param string $login A optionnal login.
5524 * @return string The encrypted password.
5526 function encrypt_password($pass, $login = '') {
5528 return "SHA1X:" . sha1("$login:$pass");
5530 return "SHA1:" . sha1($pass);
5532 } // function encrypt_password
5535 * Update a feed batch.
5536 * Used by daemons to update n feeds by run.
5537 * Only update feed needing a update, and not being processed
5538 * by another process.
5540 * @param mixed $link Database link
5541 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5542 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5543 * @param boolean $debug Set to false to disable debug output. Default to true.
5546 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5547 // Process all other feeds using last_updated and interval parameters
5549 // Test if the user has loggued in recently. If not, it does not update its feeds.
5550 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5551 if (DB_TYPE
== "pgsql") {
5552 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5554 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5557 $login_thresh_qpart = "";
5560 // Test if the feed need a update (update interval exceded).
5561 if (DB_TYPE
== "pgsql") {
5562 $update_limit_qpart = "AND ((
5563 ttrss_feeds.update_interval = 0
5564 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5566 ttrss_feeds.update_interval > 0
5567 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5568 ) OR ttrss_feeds.last_updated IS NULL)";
5570 $update_limit_qpart = "AND ((
5571 ttrss_feeds.update_interval = 0
5572 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5574 ttrss_feeds.update_interval > 0
5575 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5576 ) OR ttrss_feeds.last_updated IS NULL)";
5579 // Test if feed is currently being updated by another process.
5580 if (DB_TYPE
== "pgsql") {
5581 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5583 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5586 // Test if there is a limit to number of updated feeds
5588 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5590 $random_qpart = sql_random_function();
5592 // We search for feed needing update.
5593 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5594 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5595 ttrss_feeds.update_interval
5597 ttrss_feeds, ttrss_users, ttrss_user_prefs
5599 ttrss_feeds.owner_uid = ttrss_users.id
5600 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5601 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5602 $login_thresh_qpart $update_limit_qpart
5603 $updstart_thresh_qpart
5604 ORDER BY $random_qpart $query_limit");
5606 $user_prefs_cache = array();
5608 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5610 // Here is a little cache magic in order to minimize risk of double feed updates.
5611 $feeds_to_update = array();
5612 while ($line = db_fetch_assoc($result)) {
5613 $feeds_to_update[$line['id']] = $line;
5616 // We update the feed last update started date before anything else.
5617 // There is no lag due to feed contents downloads
5618 // It prevent an other process to update the same feed.
5619 $feed_ids = array_keys($feeds_to_update);
5621 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5622 WHERE id IN (%s)", implode(',', $feed_ids)));
5625 // For each feed, we call the feed update function.
5626 while ($line = array_pop($feeds_to_update)) {
5628 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5630 // We setup a alarm to alert if the feed take more than 300s to update.
5632 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5633 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5634 // Cancel the alarm (the update went well)
5635 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5637 sleep(1); // prevent flood (FIXME make this an option?)
5640 // Send feed digests by email if needed.
5641 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5643 purge_orphans($link);
5645 } // function update_daemon_common
5647 function sanitize_article_content($text) {
5648 # we don't support CDATA sections in articles, they break our own escaping
5649 $text = preg_replace("/\[\[CDATA/", "", $text);
5650 $text = preg_replace("/\]\]\>/", "", $text);
5654 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5657 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5659 $result = db_query($link, "SELECT reg_exp,
5660 ttrss_filter_types.name AS name,
5661 ttrss_filter_actions.name AS action,
5665 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5668 owner_uid = $owner_uid AND
5669 ttrss_filter_types.id = filter_type AND
5670 ttrss_filter_actions.id = action_id AND
5671 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5673 while ($line = db_fetch_assoc($result)) {
5674 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5675 $filter["reg_exp"] = $line["reg_exp"];
5676 $filter["action"] = $line["action"];
5677 $filter["action_param"] = $line["action_param"];
5678 $filter["filter_param"] = $line["filter_param"];
5679 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5681 array_push($filters[$line["name"]], $filter);
5687 function get_score_pic($score) {
5689 return "score_high.png";
5690 } else if ($score > 0) {
5691 return "score_half_high.png";
5692 } else if ($score < -100) {
5693 return "score_low.png";
5694 } else if ($score < 0) {
5695 return "score_half_low.png";
5697 return "score_neutral.png";
5701 function rounded_table_start($classname, $header = " ") {
5702 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5703 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5704 print "<tr><td class='left'> </td><td class='content'>";
5707 function rounded_table_end($footer = " ") {
5708 print "</td><td class='right'> </td></tr>";
5709 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5713 function feed_has_icon($id) {
5714 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5717 function init_connection($link) {
5718 if (DB_TYPE
== "pgsql") {
5719 pg_query($link, "set client_encoding = 'UTF-8'");
5720 pg_set_client_encoding("UNICODE");
5721 pg_query($link, "set datestyle = 'ISO, european'");
5723 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5724 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5725 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5730 function update_feedbrowser_cache($link) {
5732 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5733 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5734 WHERE tf.feed_url = ttrss_feeds.feed_url
5735 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5736 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5738 db_query($link, "BEGIN");
5740 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5744 while ($line = db_fetch_assoc($result)) {
5745 $subscribers = db_escape_string($line["subscribers"]);
5746 $feed_url = db_escape_string($line["feed_url"]);
5747 $title = db_escape_string($line["title"]);
5749 $tmp_result = db_query($link, "SELECT subscribers FROM
5750 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5752 if (db_num_rows($tmp_result) == 0) {
5754 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5755 (feed_url, title, subscribers) VALUES ('$feed_url',
5756 '$title', '$subscribers')");
5764 db_query($link, "COMMIT");
5770 function ccache_zero($link, $feed_id, $owner_uid) {
5771 db_query($link, "UPDATE ttrss_counters_cache SET
5772 value = 0, updated = NOW() WHERE
5773 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5776 function ccache_zero_all($link, $owner_uid) {
5777 db_query($link, "UPDATE ttrss_counters_cache SET
5778 value = 0 WHERE owner_uid = '$owner_uid'");
5780 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5781 value = 0 WHERE owner_uid = '$owner_uid'");
5784 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5787 $table = "ttrss_counters_cache";
5789 $table = "ttrss_cat_counters_cache";
5792 db_query($link, "DELETE FROM $table WHERE
5793 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5797 function ccache_update_all($link, $owner_uid) {
5799 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5801 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5802 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5804 while ($line = db_fetch_assoc($result)) {
5805 ccache_update($link, $line["feed_id"], $owner_uid, true);
5808 /* We have to manually include category 0 */
5810 ccache_update($link, 0, $owner_uid, true);
5813 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5814 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5816 while ($line = db_fetch_assoc($result)) {
5817 print ccache_update($link, $line["feed_id"], $owner_uid);
5824 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5825 $no_update = false) {
5827 if (!is_numeric($feed_id)) return;
5830 $table = "ttrss_counters_cache";
5832 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5833 WHERE id = '$feed_id'");
5834 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5837 $table = "ttrss_cat_counters_cache";
5840 if (DB_TYPE
== "pgsql") {
5841 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5842 } else if (DB_TYPE
== "mysql") {
5843 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5846 $result = db_query($link, "SELECT value FROM $table
5847 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5850 if (db_num_rows($result) == 1) {
5851 return db_fetch_result($result, 0, "value");
5856 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5862 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5863 $update_pcat = true) {
5865 if (!is_numeric($feed_id)) return;
5867 if (!$is_cat && $feed_id > 0) {
5868 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5869 WHERE id = '$feed_id'");
5870 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5873 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5875 /* When updating a label, all we need to do is recalculate feed counters
5876 * because labels are not cached */
5879 ccache_update_all($link, $owner_uid);
5884 $table = "ttrss_counters_cache";
5886 $table = "ttrss_cat_counters_cache";
5889 if ($is_cat && $feed_id >= 0) {
5890 if ($feed_id != 0) {
5891 $cat_qpart = "cat_id = '$feed_id'";
5893 $cat_qpart = "cat_id IS NULL";
5896 /* Recalculate counters for child feeds */
5898 $result = db_query($link, "SELECT id FROM ttrss_feeds
5899 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5901 while ($line = db_fetch_assoc($result)) {
5902 ccache_update($link, $line["id"], $owner_uid, false, false);
5905 $result = db_query($link, "SELECT SUM(value) AS sv
5906 FROM ttrss_counters_cache, ttrss_feeds
5907 WHERE id = feed_id AND $cat_qpart AND
5908 ttrss_feeds.owner_uid = '$owner_uid'");
5910 $unread = (int) db_fetch_result($result, 0, "sv");
5913 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5916 db_query($link, "BEGIN");
5918 $result = db_query($link, "SELECT feed_id FROM $table
5919 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5921 if (db_num_rows($result) == 1) {
5922 db_query($link, "UPDATE $table SET
5923 value = '$unread', updated = NOW() WHERE
5924 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5927 db_query($link, "INSERT INTO $table
5928 (feed_id, value, owner_uid, updated)
5930 ($feed_id, $unread, $owner_uid, NOW())");
5933 db_query($link, "COMMIT");
5935 if ($feed_id > 0 && $prev_unread != $unread) {
5939 /* Update parent category */
5943 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5944 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5946 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5948 ccache_update($link, $cat_id, $owner_uid, true);
5952 } else if ($feed_id < 0) {
5953 ccache_update_all($link, $owner_uid);
5959 function label_find_id($link, $label, $owner_uid) {
5960 $result = db_query($link,
5961 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5962 AND owner_uid = '$owner_uid' LIMIT 1");
5964 if (db_num_rows($result) == 1) {
5965 return db_fetch_result($result, 0, "id");
5971 function get_article_labels($link, $id) {
5972 $result = db_query($link,
5973 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5974 FROM ttrss_labels2, ttrss_user_labels2
5976 AND article_id = '$id'
5977 AND owner_uid = ".$_SESSION["uid"] . "
5982 while ($line = db_fetch_assoc($result)) {
5983 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5985 array_push($rv, $rk);
5992 function label_find_caption($link, $label, $owner_uid) {
5993 $result = db_query($link,
5994 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5995 AND owner_uid = '$owner_uid' LIMIT 1");
5997 if (db_num_rows($result) == 1) {
5998 return db_fetch_result($result, 0, "caption");
6004 function label_remove_article($link, $id, $label, $owner_uid) {
6006 $label_id = label_find_id($link, $label, $owner_uid);
6008 if (!$label_id) return;
6010 $result = db_query($link,
6011 "DELETE FROM ttrss_user_labels2
6013 label_id = '$label_id' AND
6014 article_id = '$id'");
6017 function label_add_article($link, $id, $label, $owner_uid) {
6019 $label_id = label_find_id($link, $label, $owner_uid);
6021 if (!$label_id) return;
6023 $result = db_query($link,
6025 article_id FROM ttrss_labels2, ttrss_user_labels2
6028 label_id = '$label_id' AND
6029 article_id = '$id' AND owner_uid = '$owner_uid'
6032 if (db_num_rows($result) == 0) {
6033 db_query($link, "INSERT INTO ttrss_user_labels2
6034 (label_id, article_id) VALUES ('$label_id', '$id')");
6038 function label_remove($link, $id, $owner_uid) {
6040 db_query($link, "BEGIN");
6042 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6045 $caption = db_fetch_result($result, 0, "caption");
6047 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6048 AND owner_uid = " . $_SESSION["uid"]);
6050 if (db_affected_rows($link, $result) != 0 && $caption) {
6052 /* Disable filters that reference label being removed */
6054 db_query($link, "UPDATE ttrss_filters SET
6055 enabled = false WHERE action_param = '$caption'
6057 AND owner_uid = " . $_SESSION["uid"]);
6060 db_query($link, "COMMIT");
6063 function label_create($link, $caption) {
6065 db_query($link, "BEGIN");
6069 $result = db_query($link, "SELECT id FROM ttrss_labels2
6070 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6072 if (db_num_rows($result) == 0) {
6073 $result = db_query($link,
6074 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6075 VALUES ('$caption', '".$_SESSION["uid"]."')");
6077 $result = db_affected_rows($link, $result) != 0;
6080 db_query($link, "COMMIT");
6085 function print_labels_headlines_dropdown($link, $feed_id) {
6086 print "<li onclick=\"javascript:addLabel()\">
6087 ".__("Create label...")."</li>";
6089 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6090 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6092 while ($line = db_fetch_assoc($result)) {
6094 $label_id = $line["id"];
6095 $label_caption = $line["caption"];
6097 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6098 print "<li id=\"LHDL-$id\"
6099 onclick=\"javascript:selectionRemoveLabel($label_id)\">
6100 $label_caption ".__('(remove)')."</li>";
6102 print "<li id=\"LHDL-$id\"
6103 onclick=\"javascript:selectionAssignLabel($label_id)\">
6104 $label_caption</li>";
6109 function format_tags_string($tags, $id) {
6112 $tags_nolinks_str = "";
6116 if ($_SESSION["theme"] == "3pane") {
6122 $formatted_tags = array();
6124 foreach ($tags as $tag) {
6126 $tag_escaped = str_replace("'", "\\'", $tag);
6128 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6130 array_push($formatted_tags, $tag_str);
6132 if ($num_tags == $tag_limit) {
6137 $tags_str = implode(", ", $formatted_tags);
6139 if ($num_tags < count($tags)) {
6140 $tags_str .= ", …";
6143 if ($num_tags == 0) {
6144 $tags_str = __("no tags");
6151 function format_article_labels($labels, $id) {
6155 foreach ($labels as $l) {
6156 $labels_str .= sprintf("<span class='hlLabelRef'
6157 style='color : %s; background-color : %s'>%s</span>",
6158 $l[2], $l[3], $l[1]);
6165 function format_article_note($id, $note) {
6167 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6169 $str = "<div class='articleNote'>";
6170 $str .= "<div class='articleNoteOps'>";
6171 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6172 __('edit note')."</a>";