3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 * Return available translations names.
21 * @return array A array of available translations.
23 function get_translations() {
25 "auto" => "Detect automatically",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
39 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
43 function startup_gettext() {
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES
, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL
, $lang);
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
74 _bindtextdomain("messages", "locale");
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
84 } else { // If translations are enabled.
88 function startup_gettext() {
92 } // If translations are enabled.
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
99 require_once 'phpmailer/class.phpmailer.php';
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
137 if ($purge_interval == -1 ||
!$purge_interval) {
138 ccache_update($link, $feed_id, $owner_uid);
144 $result = db_query($link,
145 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
149 if (db_num_rows($result) == 1) {
150 $owner_uid = db_fetch_result($result, 0, "owner_uid");
153 if (!$owner_uid) return;
155 if (FORCE_ARTICLE_PURGE
== 0) {
156 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
159 $purge_unread = true;
160 $purge_interval = FORCE_ARTICLE_PURGE
;
163 if (!$purge_unread) $query_limit = " unread = false AND ";
165 if (DB_TYPE
== "pgsql") {
166 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
167 marked = false AND feed_id = '$feed_id' AND
168 (SELECT date_entered FROM ttrss_entries WHERE
169 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
171 $pg_version = get_pgsql_version($link);
173 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
175 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
176 ttrss_entries.id = ref_id AND
178 feed_id = '$feed_id' AND
180 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
184 $result = db_query($link, "DELETE FROM ttrss_user_entries
186 WHERE ttrss_entries.id = ref_id AND
188 feed_id = '$feed_id' AND
190 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
193 $rows = pg_affected_rows($result);
197 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
198 marked = false AND feed_id = '$feed_id' AND
199 (SELECT date_entered FROM ttrss_entries WHERE
200 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
202 $result = db_query($link, "DELETE FROM ttrss_user_entries
203 USING ttrss_user_entries, ttrss_entries
204 WHERE ttrss_entries.id = ref_id AND
206 feed_id = '$feed_id' AND
208 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
210 $rows = mysql_affected_rows($link);
214 ccache_update($link, $feed_id, $owner_uid);
217 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
219 } // function purge_feed
222 * Purge old posts from old feeds.
224 * @param mixed $link A database connection
225 * @param boolean $do_output Set to true to enable printed output, false by default.
226 * @param integer $limit The maximal number of removed posts.
230 function global_purge_old_posts($link, $do_output = false, $limit = false) {
232 $random_qpart = sql_random_function();
235 $limit_qpart = "LIMIT $limit";
240 $result = db_query($link,
241 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
242 ORDER BY $random_qpart $limit_qpart");
244 while ($line = db_fetch_assoc($result)) {
246 $feed_id = $line["id"];
247 $purge_interval = $line["purge_interval"];
248 $owner_uid = $line["owner_uid"];
250 if ($purge_interval == 0) {
252 $tmp_result = db_query($link,
253 "SELECT value FROM ttrss_user_prefs WHERE
254 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
256 if (db_num_rows($tmp_result) != 0) {
257 $purge_interval = db_fetch_result($tmp_result, 0, "value");
262 // print "Feed $feed_id: purge interval = $purge_interval\n";
265 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
266 purge_feed($link, $feed_id, $purge_interval, $do_output);
270 // purge orphaned posts in main content table
271 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
272 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
275 $rows = db_affected_rows($link, $result);
276 _debug("Purged $rows orphaned posts.");
279 } // function global_purge_old_posts
281 function feed_purge_interval($link, $feed_id) {
283 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
284 WHERE id = '$feed_id'");
286 if (db_num_rows($result) == 1) {
287 $purge_interval = db_fetch_result($result, 0, "purge_interval");
288 $owner_uid = db_fetch_result($result, 0, "owner_uid");
290 if ($purge_interval == 0) $purge_interval = get_pref($link,
291 'PURGE_OLD_DAYS', $owner_uid);
293 return $purge_interval;
300 function purge_old_posts($link) {
302 $user_id = $_SESSION["uid"];
304 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
305 WHERE owner_uid = '$user_id'");
307 while ($line = db_fetch_assoc($result)) {
309 $feed_id = $line["id"];
310 $purge_interval = $line["purge_interval"];
312 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
314 if ($purge_interval > 0) {
315 purge_feed($link, $feed_id, $purge_interval);
319 purge_orphans($link);
322 function purge_orphans($link) {
323 // purge orphaned posts in main content table
324 db_query($link, "DELETE FROM ttrss_entries WHERE
325 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
328 function get_feed_update_interval($link, $feed_id) {
329 $result = db_query($link, "SELECT owner_uid, update_interval FROM
330 ttrss_feeds WHERE id = '$feed_id'");
332 if (db_num_rows($result) == 1) {
333 $update_interval = db_fetch_result($result, 0, "update_interval");
334 $owner_uid = db_fetch_result($result, 0, "owner_uid");
336 if ($update_interval != 0) {
337 return $update_interval;
339 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
347 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
349 if (WEB_DEMO_MODE
) return;
352 $user_id = $_SESSION["uid"];
353 purge_old_posts($link);
356 // db_query($link, "BEGIN");
358 if (MAX_UPDATE_TIME
> 0) {
359 if (DB_TYPE
== "mysql") {
362 $q_order = "RANDOM()";
365 $q_order = "last_updated DESC";
368 $result = db_query($link, "SELECT feed_url,id,
369 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
370 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
375 while ($line = db_fetch_assoc($result)) {
376 $upd_intl = $line["update_interval"];
378 if (!$upd_intl ||
$upd_intl == 0) {
379 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
383 // Updates for this feed are disabled
387 if ($fetch ||
(!$line["last_updated"] ||
388 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
390 // print "<!-- feed: ".$line["feed_url"]." -->";
392 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
394 $upd_elapsed = time() - $upd_start;
396 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
402 // db_query($link, "COMMIT");
406 function fetch_file_contents($url) {
407 if (USE_CURL_FOR_ICONS
) {
408 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
410 $ch = curl_init($url);
411 $fp = fopen($tmpfile, "w");
414 curl_setopt($ch, CURLOPT_FILE
, $fp);
415 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
416 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
422 $contents = file_get_contents($tmpfile);
428 return file_get_contents($url);
434 * Try to determine the favicon URL for a feed.
435 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
436 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
438 * @param string $url A feed or page URL
440 * @return mixed The favicon URL, or false if none was found.
442 function get_favicon_url($url) {
444 if ($html = @fetch_file_contents
($url)) {
446 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
447 // Attempt to grab a favicon link from their webpage url
448 $linkUrl = html_entity_decode($matches[1]);
450 if (substr($linkUrl, 0, 1) == '/') {
451 $urlParts = parse_url($url);
452 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
453 } else if (substr($linkUrl, 0, 7) == 'http://') {
454 $faviconURL = $linkUrl;
455 } else if (substr($url, -1, 1) == '/') {
456 $faviconURL = $url.$linkUrl;
458 $faviconURL = $url.'/'.$linkUrl;
462 // If unsuccessful, attempt to "guess" the favicon location
463 $urlParts = parse_url($url);
464 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
468 // Run a test to see if what we have attempted to get actually exists.
469 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
474 } // function get_favicon_url
477 * Check if a link is a valid and working URL.
479 * @param mixed $link A URL to check
481 * @return boolean True if the URL is valid, false otherwise.
483 function url_validate($link) {
485 $url_parts = @parse_url
($link);
487 if ( empty( $url_parts["host"] ) )
490 if ( !empty( $url_parts["path"] ) ) {
491 $documentpath = $url_parts["path"];
496 if ( !empty( $url_parts["query"] ) )
497 $documentpath .= "?" . $url_parts["query"];
499 $host = $url_parts["host"];
500 $port = $url_parts["port"];
505 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
510 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
512 $http_response = fgets( $socket, 22 );
514 $responses = "/(200 OK)|(30[0-9] Moved)/";
515 if ( preg_match($responses, $http_response) ) {
522 } // function url_validate
524 function check_feed_favicon($site_url, $feed, $link) {
525 $favicon_url = get_favicon_url($site_url);
527 # print "FAVICON [$site_url]: $favicon_url\n";
531 $icon_file = ICONS_DIR
. "/$feed.ico";
533 if ($favicon_url && !file_exists($icon_file)) {
534 $contents = fetch_file_contents($favicon_url);
536 $fp = fopen($icon_file, "w");
539 fwrite($fp, $contents);
541 chmod($icon_file, 0644);
545 error_reporting(DEFAULT_ERROR_LEVEL
);
549 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
551 if (!$_GET["daemon"] && !$ignore_daemon) {
555 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
556 _debug("update_rss_feed: start");
559 if (!$ignore_daemon) {
561 if (DB_TYPE
== "pgsql") {
562 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
564 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
567 $result = db_query($link, "SELECT id,update_interval,auth_login,
568 auth_pass,cache_images,update_method
569 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
573 $result = db_query($link, "SELECT id,update_interval,auth_login,
574 auth_pass,cache_images,update_method,hidden
575 FROM ttrss_feeds WHERE id = '$feed'");
579 if (db_num_rows($result) == 0) {
580 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
581 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
586 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
587 $update_method = db_fetch_result($result, 0, "update_method");
589 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
590 WHERE id = '$feed'");
592 $auth_login = db_fetch_result($result, 0, "auth_login");
593 $auth_pass = db_fetch_result($result, 0, "auth_pass");
595 if (ALLOW_SELECT_UPDATE_METHOD
) {
596 if (ENABLE_SIMPLEPIE
) {
597 $use_simplepie = $update_method != 1;
599 $use_simplepie = $update_method == 2;
602 $use_simplepie = ENABLE_SIMPLEPIE
;
605 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
606 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
609 if (!$use_simplepie) {
610 $auth_login = urlencode($auth_login);
611 $auth_pass = urlencode($auth_pass);
614 $update_interval = db_fetch_result($result, 0, "update_interval");
615 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
617 if ($update_interval < 0) { return; }
619 $feed = db_escape_string($feed);
621 $fetch_url = $feed_url;
623 if ($auth_login && $auth_pass) {
624 $url_parts = array();
625 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
627 if ($url_parts[1] && $url_parts[2]) {
628 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
633 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
634 _debug("update_rss_feed: fetching [$fetch_url]...");
637 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
641 if (!$use_simplepie) {
642 $rss = fetch_rss($fetch_url);
644 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
645 mkdir(SIMPLEPIE_CACHE_DIR
);
648 $rss = new SimplePie();
649 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
650 # $rss->set_timeout(10);
651 $rss->set_feed_url($fetch_url);
652 $rss->set_output_encoding('UTF-8');
654 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
655 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
656 _debug("enabling image cache");
659 $rss->set_image_handler('./image.php', 'i');
662 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
663 _debug("feed update interval (sec): " .
664 get_feed_update_interval($link, $feed)*60);
667 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
668 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
669 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
677 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
678 _debug("update_rss_feed: fetch done, parsing...");
680 error_reporting (DEFAULT_ERROR_LEVEL
);
683 $feed = db_escape_string($feed);
685 if ($use_simplepie) {
686 $fetch_ok = !$rss->error();
693 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
694 _debug("update_rss_feed: processing feed data...");
697 // db_query($link, "BEGIN");
699 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
700 FROM ttrss_feeds WHERE id = '$feed'");
702 $registered_title = db_fetch_result($result, 0, "title");
703 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
704 $orig_site_url = db_fetch_result($result, 0, "site_url");
706 $owner_uid = db_fetch_result($result, 0, "owner_uid");
708 if ($use_simplepie) {
709 $site_url = $rss->get_link();
711 $site_url = $rss->channel
["link"];
714 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
715 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
716 _debug("update_rss_feed: checking favicon...");
719 check_feed_favicon($site_url, $feed, $link);
722 if (!$registered_title ||
$registered_title == "[Unknown]") {
724 if ($use_simplepie) {
725 $feed_title = db_escape_string($rss->get_title());
727 $feed_title = db_escape_string($rss->channel
["title"]);
730 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
731 _debug("update_rss_feed: registering title: $feed_title");
734 db_query($link, "UPDATE ttrss_feeds SET
735 title = '$feed_title' WHERE id = '$feed'");
738 // weird, weird Magpie
739 if (!$use_simplepie) {
740 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
743 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
744 db_query($link, "UPDATE ttrss_feeds SET
745 site_url = '$site_url' WHERE id = '$feed'");
748 // print "I: " . $rss->channel["image"]["url"];
750 if (!$use_simplepie) {
751 $icon_url = $rss->image
["url"];
753 $icon_url = $rss->get_image_url();
756 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
757 $icon_url = db_escape_string($icon_url);
758 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
761 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
762 _debug("update_rss_feed: loading filters...");
765 $filters = load_filters($link, $feed, $owner_uid);
767 if ($use_simplepie) {
768 $iterator = $rss->get_items();
770 $iterator = $rss->items
;
771 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
772 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
775 if (!is_array($iterator)) {
776 /* db_query($link, "UPDATE ttrss_feeds
777 SET last_error = 'Parse error: can\'t find any articles.'
778 WHERE id = '$feed'"); */
780 // clear any errors and mark feed as updated if fetched okay
781 // even if it's blank
783 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
784 _debug("update_rss_feed: entry iterator is not an array, no articles?");
787 db_query($link, "UPDATE ttrss_feeds
788 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
790 return; // no articles
793 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
794 _debug("update_rss_feed: processing articles...");
797 foreach ($iterator as $item) {
799 if ($_GET['xdebug']) {
804 if ($use_simplepie) {
805 $entry_guid = $item->get_id();
806 if (!$entry_guid) $entry_guid = $item->get_link();
807 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
811 $entry_guid = $item["id"];
813 if (!$entry_guid) $entry_guid = $item["guid"];
814 if (!$entry_guid) $entry_guid = $item["link"];
815 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
818 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
819 _debug("update_rss_feed: guid $entry_guid");
822 if (!$entry_guid) continue;
824 $entry_timestamp = "";
826 if ($use_simplepie) {
827 $entry_timestamp = strtotime($item->get_date());
829 $rss_2_date = $item['pubdate'];
830 $rss_1_date = $item['dc']['date'];
831 $atom_date = $item['issued'];
832 if (!$atom_date) $atom_date = $item['updated'];
834 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
835 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
836 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
839 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
840 $entry_timestamp = time();
841 $no_orig_date = 'true';
843 $no_orig_date = 'false';
846 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
848 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
849 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
852 if ($use_simplepie) {
853 $entry_title = $item->get_title();
855 $entry_title = trim(strip_tags($item["title"]));
858 if ($use_simplepie) {
859 $entry_link = $item->get_link();
861 // strange Magpie workaround
862 $entry_link = $item["link_"];
863 if (!$entry_link) $entry_link = $item["link"];
866 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
867 _debug("update_rss_feed: title $entry_title");
870 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
872 $entry_link = strip_tags($entry_link);
874 if ($use_simplepie) {
875 $entry_content = $item->get_content();
876 if (!$entry_content) $entry_content = $item->get_description();
878 $entry_content = $item["content:escaped"];
880 if (!$entry_content) $entry_content = $item["content:encoded"];
881 if (!$entry_content) $entry_content = $item["content"]["encoded"];
882 if (!$entry_content) $entry_content = $item["content"];
884 // Magpie bugs are getting ridiculous
885 if (trim($entry_content) == "Array") $entry_content = false;
887 if (!$entry_content) $entry_content = $item["atom_content"];
888 if (!$entry_content) $entry_content = $item["summary"];
890 if (!$entry_content ||
891 strlen($entry_content) < strlen($item["description"])) {
892 $entry_content = $item["description"];
896 if (is_array($entry_content)) {
897 $entry_content = $entry_content["encoded"];
898 if (!$entry_content) $entry_content = $entry_content["escaped"];
902 if ($_GET["xdebug"]) {
903 print "update_rss_feed: content: ";
904 print_r(htmlspecialchars($entry_content));
907 $entry_content_unescaped = $entry_content;
909 if ($use_simplepie) {
910 $entry_comments = strip_tags($item->data
["comments"]);
911 if ($item->get_author()) {
912 $entry_author_item = $item->get_author();
913 $entry_author = $entry_author_item->get_name();
914 if (!$entry_author) $entry_author = $entry_author_item->get_email();
916 $entry_author = db_escape_string($entry_author);
919 $entry_comments = strip_tags($item["comments"]);
921 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
923 if ($item['author']) {
925 if (is_array($item['author'])) {
927 if (!$entry_author) {
928 $entry_author = db_escape_string(strip_tags($item['author']['name']));
931 if (!$entry_author) {
932 $entry_author = db_escape_string(strip_tags($item['author']['email']));
936 if (!$entry_author) {
937 $entry_author = db_escape_string(strip_tags($item['author']));
942 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
944 $entry_guid = db_escape_string(strip_tags($entry_guid));
945 $entry_guid = mb_substr($entry_guid, 0, 250);
947 $result = db_query($link, "SELECT id FROM ttrss_entries
948 WHERE guid = '$entry_guid'");
950 $entry_content = db_escape_string($entry_content);
952 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
954 $entry_title = db_escape_string($entry_title);
955 $entry_link = db_escape_string($entry_link);
956 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
957 $entry_author = mb_substr($entry_author, 0, 250);
959 if ($use_simplepie) {
960 $num_comments = 0; #FIXME#
962 $num_comments = db_escape_string($item["slash"]["comments"]);
965 if (!$num_comments) $num_comments = 0;
967 // parse <category> entries into tags
969 if ($use_simplepie) {
971 $additional_tags = array();
972 $additional_tags_src = $item->get_categories();
974 if (is_array($additional_tags_src)) {
975 foreach ($additional_tags_src as $tobj) {
976 array_push($additional_tags, $tobj->get_term());
980 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
981 _debug("update_rss_feed: category tags:");
982 print_r($additional_tags);
987 $t_ctr = $item['category#'];
989 $additional_tags = false;
992 $additional_tags = false;
993 } else if ($t_ctr > 0) {
994 $additional_tags = array($item['category']);
996 if ($item['category@term']) {
997 array_push($additional_tags, $item['category@term']);
1000 for ($i = 0; $i <= $t_ctr; $i++
) {
1001 if ($item["category#$i"]) {
1002 array_push($additional_tags, $item["category#$i"]);
1005 if ($item["category#$i@term"]) {
1006 array_push($additional_tags, $item["category#$i@term"]);
1011 // parse <dc:subject> elements
1013 $t_ctr = $item['dc']['subject#'];
1016 $additional_tags = array($item['dc']['subject']);
1018 for ($i = 0; $i <= $t_ctr; $i++
) {
1019 if ($item['dc']["subject#$i"]) {
1020 array_push($additional_tags, $item['dc']["subject#$i"]);
1028 $enclosures = array();
1030 if ($use_simplepie) {
1031 $encs = $item->get_enclosures();
1033 if (is_array($encs)) {
1034 foreach ($encs as $e) {
1036 $e->link
, $e->type
, $e->length
);
1038 array_push($enclosures, $e_item);
1045 $e_ctr = $item['enclosure#'];
1048 $e_item = array($item['enclosure@url'],
1049 $item['enclosure@type'],
1050 $item['enclosure@length']);
1052 array_push($enclosures, $e_item);
1054 for ($i = 0; $i <= $e_ctr; $i++
) {
1056 if ($item["enclosure#$i@url"]) {
1057 $e_item = array($item["enclosure#$i@url"],
1058 $item["enclosure#$i@type"],
1059 $item["enclosure#$i@length"]);
1060 array_push($enclosures, $e_item);
1066 // can there be many of those? yes -fox
1068 $m_ctr = $item['media']['content#'];
1071 $e_item = array($item['media']['content@url'],
1072 $item['media']['content@medium'],
1073 $item['media']['content@length']);
1075 array_push($enclosures, $e_item);
1077 for ($i = 0; $i <= $m_ctr; $i++
) {
1079 if ($item["media"]["content#$i@url"]) {
1080 $e_item = array($item["media"]["content#$i@url"],
1081 $item["media"]["content#$i@medium"],
1082 $item["media"]["content#$i@length"]);
1083 array_push($enclosures, $e_item);
1092 $entry_content = sanitize_article_content($entry_content);
1093 $entry_title = sanitize_article_content($entry_title);
1095 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1096 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1099 db_query($link, "BEGIN");
1101 if (db_num_rows($result) == 0) {
1103 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1104 _debug("update_rss_feed: base guid not found");
1107 // base post entry does not exist, create it
1109 $result = db_query($link,
1110 "INSERT INTO ttrss_entries
1126 '$entry_timestamp_fmt',
1135 // we keep encountering the entry in feeds, so we need to
1136 // update date_entered column so that we don't get horrible
1137 // dupes when the entry gets purged and reinserted again e.g.
1138 // in the case of SLOW SLOW OMG SLOW updating feeds
1140 $base_entry_id = db_fetch_result($result, 0, "id");
1142 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1143 WHERE id = '$base_entry_id'");
1146 // now it should exist, if not - bad luck then
1148 $result = db_query($link, "SELECT
1149 id,content_hash,no_orig_date,title,
1150 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1151 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1155 WHERE guid = '$entry_guid'");
1160 if (db_num_rows($result) == 1) {
1162 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1163 _debug("update_rss_feed: base guid found, checking for user record");
1166 // this will be used below in update handler
1167 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1168 $orig_title = db_fetch_result($result, 0, "title");
1169 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1170 $orig_date_entered = strtotime(db_fetch_result($result,
1171 0, "date_entered"));
1173 $ref_id = db_fetch_result($result, 0, "id");
1174 $entry_ref_id = $ref_id;
1176 // check for user post link to main table
1178 // do we allow duplicate posts with same GUID in different feeds?
1179 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1180 $dupcheck_qpart = "AND feed_id = '$feed'";
1182 $dupcheck_qpart = "";
1185 // error_reporting(0);
1187 $article_filters = get_article_filters($filters, $entry_title,
1188 $entry_content, $entry_link, $entry_timestamp);
1190 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1191 _debug("update_rss_feed: article filters: ");
1192 if (count($article_filters) != 0) {
1193 print_r($article_filters);
1197 if (find_article_filter($article_filters, "filter")) {
1198 db_query($link, "COMMIT"); // close transaction in progress
1202 // error_reporting (DEFAULT_ERROR_LEVEL);
1204 $score = calculate_article_score($article_filters);
1206 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1207 _debug("update_rss_feed: initial score: $score");
1210 $result = db_query($link,
1211 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1212 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1215 // okay it doesn't exist - create user entry
1216 if (db_num_rows($result) == 0) {
1218 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1219 _debug("update_rss_feed: user record not found, creating...");
1222 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1224 $last_read_qpart = 'NULL';
1227 $last_read_qpart = 'NOW()';
1230 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1236 if (find_article_filter($article_filters, 'publish')) {
1237 $published = 'true';
1239 $published = 'false';
1242 $result = db_query($link,
1243 "INSERT INTO ttrss_user_entries
1244 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1246 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1247 $last_read_qpart, $marked, $published, '$score')");
1249 $result = db_query($link,
1250 "SELECT int_id FROM ttrss_user_entries WHERE
1251 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1252 feed_id = '$feed' LIMIT 1");
1254 if (db_num_rows($result) == 1) {
1255 $entry_int_id = db_fetch_result($result, 0, "int_id");
1258 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1259 $entry_int_id = db_fetch_result($result, 0, "int_id");
1262 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1263 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1266 $post_needs_update = false;
1268 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1269 ($content_hash != $orig_content_hash)) {
1270 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1271 $post_needs_update = true;
1274 if (db_escape_string($orig_title) != $entry_title) {
1275 $post_needs_update = true;
1278 if ($orig_num_comments != $num_comments) {
1279 $post_needs_update = true;
1282 // this doesn't seem to be very reliable
1284 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1285 // $post_needs_update = true;
1288 // if post needs update, update it and mark all user entries
1289 // linking to this post as updated
1290 if ($post_needs_update) {
1292 if (defined('DAEMON_EXTENDED_DEBUG')) {
1293 _debug("update_rss_feed: post $entry_guid needs update...");
1296 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1298 db_query($link, "UPDATE ttrss_entries
1299 SET title = '$entry_title', content = '$entry_content',
1300 content_hash = '$content_hash',
1301 num_comments = '$num_comments'
1302 WHERE id = '$ref_id'");
1304 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1305 db_query($link, "UPDATE ttrss_user_entries
1306 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1308 db_query($link, "UPDATE ttrss_user_entries
1309 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1315 db_query($link, "COMMIT");
1317 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1318 _debug("update_rss_feed: assigning labels...");
1321 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1324 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1325 _debug("update_rss_feed: looking for enclosures...");
1328 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1329 print_r($enclosures);
1332 db_query($link, "BEGIN");
1334 foreach ($enclosures as $enc) {
1335 $enc_url = db_escape_string($enc[0]);
1336 $enc_type = db_escape_string($enc[1]);
1337 $enc_dur = db_escape_string($enc[2]);
1339 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1340 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1342 if (db_num_rows($result) == 0) {
1343 db_query($link, "INSERT INTO ttrss_enclosures
1344 (content_url, content_type, title, duration, post_id) VALUES
1345 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1349 db_query($link, "COMMIT");
1351 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1352 _debug("update_rss_feed: looking for tags...");
1356 // <a href="..." rel="tag">Xorg</a>, //
1360 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1361 $entry_content_unescaped, $entry_tags);
1363 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1364 print_r($entry_tags);
1365 print "<br/></p>"; */
1367 $entry_tags = $entry_tags[1];
1369 # check for manual tags
1371 $tag_filter = find_article_filter($article_filters, "tag");
1375 $manual_tags = trim_array(split(",", $tag_filter[1]));
1377 foreach ($manual_tags as $tag) {
1378 if (tag_is_valid($tag)) {
1379 array_push($entry_tags, $tag);
1384 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1385 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1387 if ($additional_tags && is_array($additional_tags)) {
1388 foreach ($additional_tags as $tag) {
1389 if (tag_is_valid($tag) &&
1390 array_search($tag, $boring_tags) === FALSE) {
1391 array_push($entry_tags, $tag);
1396 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1398 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1399 print_r($entry_tags);
1402 if (count($entry_tags) > 0) {
1404 db_query($link, "BEGIN");
1406 foreach ($entry_tags as $tag) {
1408 $tag = sanitize_tag($tag);
1409 $tag = db_escape_string($tag);
1411 if (!tag_is_valid($tag)) continue;
1413 $result = db_query($link, "SELECT id FROM ttrss_tags
1414 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1415 owner_uid = '$owner_uid' LIMIT 1");
1417 // print db_fetch_result($result, 0, "id");
1419 if ($result && db_num_rows($result) == 0) {
1421 db_query($link, "INSERT INTO ttrss_tags
1422 (owner_uid,tag_name,post_int_id)
1423 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1427 db_query($link, "COMMIT");
1430 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1431 _debug("update_rss_feed: article processed");
1436 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1437 _debug("update_rss_feed: updating counters cache...");
1440 // disabled, purge_feed() does that...
1441 //ccache_update($link, $feed, $owner_uid);
1444 purge_feed($link, $feed, 0);
1446 db_query($link, "UPDATE ttrss_feeds
1447 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1449 // db_query($link, "COMMIT");
1453 if ($use_simplepie) {
1454 $error_msg = mb_substr($rss->error(), 0, 250);
1456 $error_msg = mb_substr(magpie_error(), 0, 250);
1459 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1460 _debug("update_rss_feed: error fetching feed: $error_msg");
1463 $error_msg = db_escape_string($error_msg);
1466 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1467 last_updated = NOW() WHERE id = '$feed'");
1470 if ($use_simplepie) {
1474 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1475 _debug("update_rss_feed: done");
1480 function print_select($id, $default, $values, $attributes = "") {
1481 print "<select name=\"$id\" id=\"$id\" $attributes>";
1482 foreach ($values as $v) {
1488 print "<option$sel>$v</option>";
1493 function print_select_hash($id, $default, $values, $attributes = "") {
1494 print "<select name=\"$id\" id='$id' $attributes>";
1495 foreach (array_keys($values) as $v) {
1497 $sel = 'selected="selected"';
1501 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1507 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1510 if ($filters["title"]) {
1511 foreach ($filters["title"] as $filter) {
1512 $reg_exp = $filter["reg_exp"];
1513 $inverse = $filter["inverse"];
1514 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1515 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1517 array_push($matches, array($filter["action"], $filter["action_param"]));
1522 if ($filters["content"]) {
1523 foreach ($filters["content"] as $filter) {
1524 $reg_exp = $filter["reg_exp"];
1525 $inverse = $filter["inverse"];
1527 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1528 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1530 array_push($matches, array($filter["action"], $filter["action_param"]));
1535 if ($filters["both"]) {
1536 foreach ($filters["both"] as $filter) {
1537 $reg_exp = $filter["reg_exp"];
1538 $inverse = $filter["inverse"];
1541 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1542 array_push($matches, array($filter["action"], $filter["action_param"]));
1545 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1546 array_push($matches, array($filter["action"], $filter["action_param"]));
1552 if ($filters["link"]) {
1553 $reg_exp = $filter["reg_exp"];
1554 foreach ($filters["link"] as $filter) {
1555 $reg_exp = $filter["reg_exp"];
1556 $inverse = $filter["inverse"];
1558 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1559 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1561 array_push($matches, array($filter["action"], $filter["action_param"]));
1566 if ($filters["date"]) {
1567 $reg_exp = $filter["reg_exp"];
1568 foreach ($filters["date"] as $filter) {
1569 $date_modifier = $filter["filter_param"];
1570 $inverse = $filter["inverse"];
1571 $check_timestamp = strtotime($filter["reg_exp"]);
1573 # no-op when timestamp doesn't parse to prevent misfires
1575 if ($check_timestamp) {
1578 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1579 $date_modifier == "after" && $timestamp > $check_timestamp) {
1583 if ($inverse) $match_ok = !$match_ok;
1586 array_push($matches, array($filter["action"], $filter["action_param"]));
1595 function find_article_filter($filters, $filter_name) {
1596 foreach ($filters as $f) {
1597 if ($f[0] == $filter_name) {
1604 function calculate_article_score($filters) {
1607 foreach ($filters as $f) {
1608 if ($f[0] == "score") {
1615 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1616 foreach ($filters as $f) {
1617 if ($f[0] == "label") {
1618 label_add_article($link, $id, $f[1], $owner_uid);
1623 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1624 $rtl_content = false, $last_updated = false, $last_error = false) {
1626 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1627 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1629 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1633 $rtl_tag = "dir=\"rtl\"";
1635 $rtl_tag = "dir=\"ltr\"";
1638 $error_notify_msg = "";
1641 $link_title = "Error: $last_error ($last_updated)";
1642 $error_notify_msg = "(Error)";
1643 } else if ($last_updated) {
1644 $link_title = "Updated: $last_updated";
1647 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1648 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1650 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1651 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1655 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1658 $fctr_class = "class=\"feedCtrHasUnread\"";
1660 $fctr_class = "class=\"feedCtrNoUnread\"";
1663 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1664 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1666 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1667 $total = getFeedArticles($link, $feed_id);
1668 print "<div class=\"feedExtInfo\">
1669 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1676 function getmicrotime() {
1677 list($usec, $sec) = explode(" ",microtime());
1678 return ((float)$usec +
(float)$sec);
1681 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1682 foreach ($values as $v) {
1689 if ($v == $true_is) {
1690 $sel .= " value=\"1\"";
1692 $sel .= " value=\"0\"";
1695 print "<input class=\"noborder\"
1696 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1701 function initialize_user_prefs($link, $uid) {
1703 $uid = db_escape_string($uid);
1705 db_query($link, "BEGIN");
1707 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1709 $u_result = db_query($link, "SELECT pref_name
1710 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1712 $active_prefs = array();
1714 while ($line = db_fetch_assoc($u_result)) {
1715 array_push($active_prefs, $line["pref_name"]);
1718 while ($line = db_fetch_assoc($result)) {
1719 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1720 // print "adding " . $line["pref_name"] . "<br>";
1722 db_query($link, "INSERT INTO ttrss_user_prefs
1723 (owner_uid,pref_name,value) VALUES
1724 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1729 db_query($link, "COMMIT");
1733 function lookup_user_id($link, $user) {
1735 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1738 if (db_num_rows($result) == 1) {
1739 return db_fetch_result($result, 0, "id");
1745 function http_authenticate_user($link) {
1747 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1749 if (!$_SERVER["PHP_AUTH_USER"]) {
1751 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1752 header('HTTP/1.0 401 Unauthorized');
1756 $auth_result = authenticate_user($link,
1757 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1759 if (!$auth_result) {
1760 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1761 header('HTTP/1.0 401 Unauthorized');
1769 function authenticate_user($link, $login, $password, $force_auth = false) {
1771 if (!SINGLE_USER_MODE
) {
1773 $pwd_hash1 = encrypt_password($password);
1774 $pwd_hash2 = encrypt_password($password, $login);
1776 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1777 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1779 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1781 $query = "SELECT id,login,access_level,pwd_hash
1782 FROM ttrss_users WHERE
1786 $query = "SELECT id,login,access_level,pwd_hash
1787 FROM ttrss_users WHERE
1788 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1789 pwd_hash = '$pwd_hash2')";
1792 $result = db_query($link, $query);
1794 if (db_num_rows($result) == 1) {
1795 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1796 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1797 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1799 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1802 $user_theme = get_user_theme_path($link);
1804 $_SESSION["theme"] = $user_theme;
1805 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1806 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1808 initialize_user_prefs($link, $_SESSION["uid"]);
1817 $_SESSION["uid"] = 1;
1818 $_SESSION["name"] = "admin";
1820 $user_theme = get_user_theme_path($link);
1822 $_SESSION["theme"] = $user_theme;
1823 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1825 initialize_user_prefs($link, $_SESSION["uid"]);
1831 function make_password($length = 8) {
1834 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1838 while ($i < $length) {
1839 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1841 if (!strstr($password, $char)) {
1849 // this is called after user is created to initialize default feeds, labels
1852 // user preferences are checked on every login, not here
1854 function initialize_user($link, $uid) {
1856 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1857 VALUES ('$uid', 'All Articles')");
1859 db_query($link, "INSERT INTO ttrss_filters
1860 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1861 action_id, action_param, filter_param)
1862 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1864 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1865 values ('$uid', 'Tiny Tiny RSS: New Releases',
1866 'http://tt-rss.org/releases.rss')");
1868 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1869 values ('$uid', 'Tiny Tiny RSS: Forum',
1870 'http://tt-rss.org/forum/rss.php')");
1873 function logout_user() {
1875 if (isset($_COOKIE[session_name()])) {
1876 setcookie(session_name(), '', time()-42000, '/');
1880 function get_script_urlpath() {
1881 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1884 function validate_session($link) {
1885 if (SINGLE_USER_MODE
) {
1889 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1890 if ($_SESSION["ip_address"]) {
1891 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1892 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1898 if ($_SESSION["uid"]) {
1900 $result = db_query($link,
1901 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1903 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1905 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1910 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1912 //print_r($_SESSION);
1914 if (time() > $_SESSION["cookie_lifetime"]) {
1922 function login_sequence($link, $mobile = false) {
1923 if (!SINGLE_USER_MODE
) {
1925 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1926 $swu = db_escape_string($_REQUEST["swu"]);
1928 $_SESSION["prefs_cache"] = false;
1929 return authenticate_user($link, $swu, null, true);
1933 $login_action = $_POST["login_action"];
1935 # try to authenticate user if called from login form
1936 if ($login_action == "do_login") {
1937 $login = $_POST["login"];
1938 $password = $_POST["password"];
1939 $remember_me = $_POST["remember_me"];
1941 if (authenticate_user($link, $login, $password)) {
1942 $_POST["password"] = "";
1944 $_SESSION["language"] = $_POST["language"];
1945 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1947 header("Location: " . $_SERVER["REQUEST_URI"]);
1952 $_SESSION["login_error_msg"] = "Incorrect username or password";
1956 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1957 render_login_form($link, $mobile);
1960 /* bump login timestamp */
1961 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1964 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1965 setcookie("ttrss_lang", $_SESSION["language"],
1966 time() + SESSION_COOKIE_LIFETIME
);
1969 /* bump counters stamp since we're getting reloaded anyway */
1971 $_SESSION["get_all_counters_stamp"] = time();
1975 return authenticate_user($link, "admin", null);
1979 function truncate_string($str, $max_len) {
1980 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1981 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1987 function get_user_theme_path($link) {
1988 $result = db_query($link, "SELECT theme_path
1990 ttrss_themes,ttrss_users
1991 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1992 if (db_num_rows($result) != 0) {
1993 return db_fetch_result($result, 0, "theme_path");
1999 function smart_date_time($timestamp) {
2000 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2001 return date("G:i", $timestamp);
2002 } else if (date("Y", $timestamp) == date("Y")) {
2003 return date("M d, G:i", $timestamp);
2005 return date("Y/m/d, G:i", $timestamp);
2009 function smart_date($timestamp) {
2010 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2012 } else if (date("Y", $timestamp) == date("Y")) {
2013 return date("D m", $timestamp);
2015 return date("Y/m/d", $timestamp);
2019 function sql_bool_to_string($s) {
2020 if ($s == "t" ||
$s == "1") {
2027 function sql_bool_to_bool($s) {
2028 if ($s == "t" ||
$s == "1") {
2036 function toggleEvenOdd($a) {
2043 function sanity_check($link) {
2048 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2049 $schema_version = db_fetch_result($result, 0, "schema_version");
2051 if ($schema_version != SCHEMA_VERSION
) {
2055 if (DB_TYPE
== "mysql") {
2056 $result = db_query($link, "SELECT true", false);
2057 if (db_num_rows($result) != 1) {
2062 if (db_escape_string("testTEST") != "testTEST") {
2066 error_reporting (DEFAULT_ERROR_LEVEL
);
2068 if ($error_code != 0) {
2069 print_error_xml($error_code);
2076 function file_is_locked($filename) {
2077 if (function_exists('flock')) {
2079 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2080 error_reporting(DEFAULT_ERROR_LEVEL
);
2082 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2083 flock($fp, LOCK_UN
);
2093 return true; // consider the file always locked and skip the test
2096 function make_lockfile($filename) {
2097 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2099 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2106 function make_stampfile($filename) {
2107 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2109 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2110 fwrite($fp, time() . "\n");
2111 flock($fp, LOCK_UN
);
2119 function read_stampfile($filename) {
2122 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2123 error_reporting (DEFAULT_ERROR_LEVEL
);
2126 if (flock($fp, LOCK_EX
)) {
2127 $stamp = fgets($fp);
2128 flock($fp, LOCK_UN
);
2139 function sql_random_function() {
2140 if (DB_TYPE
== "mysql") {
2147 function catchup_feed($link, $feed, $cat_view) {
2149 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2154 $cat_qpart = "cat_id = '$feed'";
2156 $cat_qpart = "cat_id IS NULL";
2159 $tmp_result = db_query($link, "SELECT id
2160 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2163 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2165 $tmp_feed = $tmp_line["id"];
2167 db_query($link, "UPDATE ttrss_user_entries
2168 SET unread = false,last_read = NOW()
2169 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2172 } else if ($feed > 0) {
2174 $tmp_result = db_query($link, "SELECT id
2175 FROM ttrss_feeds WHERE parent_feed = '$feed'
2176 ORDER BY cat_id,title");
2178 $parent_ids = array();
2180 if (db_num_rows($tmp_result) > 0) {
2181 while ($p = db_fetch_assoc($tmp_result)) {
2182 array_push($parent_ids, "feed_id = " . $p["id"]);
2185 $children_qpart = implode(" OR ", $parent_ids);
2187 db_query($link, "UPDATE ttrss_user_entries
2188 SET unread = false,last_read = NOW()
2189 WHERE (feed_id = '$feed' OR $children_qpart)
2190 AND owner_uid = " . $_SESSION["uid"]);
2193 db_query($link, "UPDATE ttrss_user_entries
2194 SET unread = false,last_read = NOW()
2195 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2198 } else if ($feed < 0 && $feed > -10) { // special, like starred
2201 db_query($link, "UPDATE ttrss_user_entries
2202 SET unread = false,last_read = NOW()
2203 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2207 db_query($link, "UPDATE ttrss_user_entries
2208 SET unread = false,last_read = NOW()
2209 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2214 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2216 if (DB_TYPE
== "pgsql") {
2217 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2219 $match_part = "updated > DATE_SUB(NOW(),
2220 INTERVAL $intl HOUR) ";
2223 $result = db_query($link, "SELECT id FROM ttrss_entries,
2224 ttrss_user_entries WHERE $match_part AND
2226 ttrss_user_entries.ref_id = ttrss_entries.id AND
2227 owner_uid = ".$_SESSION["uid"]);
2229 $affected_ids = array();
2231 while ($line = db_fetch_assoc($result)) {
2232 array_push($affected_ids, $line["id"]);
2235 catchupArticlesById($link, $affected_ids, 0);
2239 db_query($link, "UPDATE ttrss_user_entries
2240 SET unread = false,last_read = NOW()
2241 WHERE owner_uid = ".$_SESSION["uid"]);
2244 } else if ($feed < -10) { // label
2246 $label_id = -$feed - 11;
2248 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2249 SET unread = false WHERE label_id = '$label_id' AND unread = true
2250 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2254 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2257 db_query($link, "BEGIN");
2259 $tag_name = db_escape_string($feed);
2261 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2262 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2264 while ($line = db_fetch_assoc($result)) {
2265 db_query($link, "UPDATE ttrss_user_entries SET
2266 unread = false, last_read = NOW()
2267 WHERE int_id = " . $line["post_int_id"]);
2269 db_query($link, "COMMIT");
2273 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2277 $cat_qpart = "cat_id = '$feed'";
2279 $cat_qpart = "cat_id IS NULL";
2282 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2283 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2285 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2286 $feed_url = $tmp_line["feed_url"];
2287 $feed_id = $tmp_line["id"];
2288 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2292 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2293 WHERE id = '$feed'");
2294 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2295 update_rss_feed($link, $feed_url, $feed, $force_update);
2299 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2301 if (!$omode) $omode = "flc";
2303 getGlobalCounters($link);
2305 if (strchr($omode, "l")) getLabelCounters($link);
2306 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2307 if (strchr($omode, "t")) getTagCounters($link);
2308 if (strchr($omode, "c")) {
2309 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2310 getCategoryCounters($link);
2315 function getCategoryCounters($link) {
2316 # two special categories are -1 and -2 (all virtuals; all labels)
2318 /* $ctr = getCategoryUnread($link, -1);
2320 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2322 $ctr = getCategoryUnread($link, -2);
2324 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2326 $age_qpart = getMaxAgeSubquery();
2328 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2329 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2330 WHERE ttrss_cat_counters_cache.feed_id = id AND
2331 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2333 while ($line = db_fetch_assoc($result)) {
2334 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2336 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2337 $line["unread"]."\"/>";
2340 /* Special case: NULL category doesn't actually exist in the DB */
2342 print "<counter type=\"category\" id=\"0\" counter=\"".
2343 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2347 function getCategoryUnread($link, $cat, $owner_uid = false) {
2349 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2354 $cat_query = "cat_id = '$cat'";
2356 $cat_query = "cat_id IS NULL";
2359 $age_qpart = getMaxAgeSubquery();
2361 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2363 AND owner_uid = " . $owner_uid);
2365 $cat_feeds = array();
2366 while ($line = db_fetch_assoc($result)) {
2367 array_push($cat_feeds, "feed_id = " . $line["id"]);
2370 if (count($cat_feeds) == 0) return 0;
2372 $match_part = implode(" OR ", $cat_feeds);
2374 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2375 FROM ttrss_user_entries,ttrss_entries
2376 WHERE unread = true AND ($match_part) AND id = ref_id
2377 AND $age_qpart AND owner_uid = " . $owner_uid);
2381 # this needs to be rewritten
2382 while ($line = db_fetch_assoc($result)) {
2383 $unread +
= $line["unread"];
2387 } else if ($cat == -1) {
2388 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2389 } else if ($cat == -2) {
2391 $result = db_query($link, "
2392 SELECT COUNT(unread) AS unread FROM
2393 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2394 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2395 ttrss_labels2.owner_uid = '$owner_uid'
2396 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2397 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2399 $unread = db_fetch_result($result, 0, "unread");
2406 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2407 if (DB_TYPE
== "pgsql") {
2408 return "ttrss_entries.date_entered >
2409 NOW() - INTERVAL '$days days'";
2411 return "ttrss_entries.date_entered >
2412 DATE_SUB(NOW(), INTERVAL $days DAY)";
2416 function getFeedUnread($link, $feed, $is_cat = false) {
2417 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2420 function getLabelUnread($link, $label_id, $owner_uid = false) {
2421 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2423 $result = db_query($link, "
2424 SELECT COUNT(unread) AS unread FROM
2425 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2426 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2427 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2428 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2429 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2431 if (db_num_rows($result) != 0) {
2432 return db_fetch_result($result, 0, "unread");
2438 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2439 $owner_uid = false) {
2441 $n_feed = sprintf("%d", $feed);
2443 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2446 $unread_qpart = "unread = true";
2448 $unread_qpart = "true";
2451 $age_qpart = getMaxAgeSubquery();
2454 return getCategoryUnread($link, $n_feed, $owner_uid);
2455 } else if ($n_feed == -1) {
2456 $match_part = "marked = true";
2457 } else if ($n_feed == -2) {
2458 $match_part = "published = true";
2459 } else if ($n_feed == -3) {
2460 $match_part = "unread = true";
2462 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2464 if (DB_TYPE
== "pgsql") {
2465 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2467 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2469 } else if ($n_feed == -4) {
2470 $match_part = "true";
2471 } else if ($n_feed > 0) {
2473 $result = db_query($link, "SELECT id FROM ttrss_feeds
2474 WHERE parent_feed = '$n_feed'
2476 AND owner_uid = " . $owner_uid);
2478 if (db_num_rows($result) > 0) {
2480 $linked_feeds = array();
2481 while ($line = db_fetch_assoc($result)) {
2482 array_push($linked_feeds, "feed_id = " . $line["id"]);
2485 array_push($linked_feeds, "feed_id = $n_feed");
2487 $match_part = implode(" OR ", $linked_feeds);
2489 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2490 FROM ttrss_user_entries,ttrss_entries
2491 WHERE $unread_qpart AND
2492 ttrss_user_entries.ref_id = ttrss_entries.id AND
2495 owner_uid = " . $owner_uid);
2499 # this needs to be rewritten
2500 while ($line = db_fetch_assoc($result)) {
2501 $unread +
= $line["unread"];
2507 $match_part = "feed_id = '$n_feed'";
2509 } else if ($feed < -10) {
2511 $label_id = -$feed - 11;
2513 return getLabelUnread($link, $label_id, $owner_uid);
2519 $result = db_query($link, "SELECT count(int_id) AS unread
2520 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2521 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2522 ttrss_user_entries.ref_id = ttrss_entries.id AND
2523 ttrss_feeds.hidden = false AND
2525 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2529 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2530 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2531 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2532 AND $unread_qpart AND $age_qpart AND
2533 ttrss_tags.owner_uid = " . $owner_uid);
2536 $unread = db_fetch_result($result, 0, "unread");
2541 function getGlobalUnread($link, $user_id = false) {
2544 $user_id = $_SESSION["uid"];
2547 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2548 WHERE owner_uid = '$user_id' AND feed_id > 0");
2550 $c_id = db_fetch_result($result, 0, "c_id");
2555 function getGlobalCounters($link, $global_unread = -1) {
2556 if ($global_unread == -1) {
2557 $global_unread = getGlobalUnread($link);
2559 print "<counter type=\"global\" id='global-unread'
2560 counter='$global_unread'/>";
2562 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2563 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2565 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2567 print "<counter type=\"global\" id='subscribed-feeds'
2568 counter='$subscribed_feeds'/>";
2572 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2575 if (!$_SESSION["tctr_last_value"]) {
2576 $_SESSION["tctr_last_value"] = array();
2580 $old_counters = $_SESSION["tctr_last_value"];
2582 $tctrs_modified = false;
2584 $age_qpart = getMaxAgeSubquery();
2586 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2587 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2588 AND ref_id = id AND $age_qpart
2589 AND unread = true)) AS count FROM ttrss_tags
2590 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2591 ORDER BY count DESC LIMIT 55");
2595 while ($line = db_fetch_assoc($result)) {
2596 $tags[$line["tag_name"]] +
= $line["count"];
2599 foreach (array_keys($tags) as $tag) {
2600 $unread = $tags[$tag];
2602 $tag = htmlspecialchars($tag);
2604 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2605 $old_counters[$tag] = $unread;
2606 $tctrs_modified = true;
2607 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2612 if ($smart_mode && $tctrs_modified) {
2613 $_SESSION["tctr_last_value"] = $old_counters;
2618 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2620 $age_qpart = getMaxAgeSubquery();
2623 if (!$_SESSION["lctr_last_value"]) {
2624 $_SESSION["lctr_last_value"] = array();
2630 for ($i = -1; $i >= -4; $i--) {
2632 $count = getFeedUnread($link, $i);
2636 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2637 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2642 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2644 $ret_arr[$i]["counter"] = $count;
2645 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2650 $old_counters = $_SESSION["lctr_last_value"];
2651 $lctrs_modified = false;
2654 $owner_uid = $_SESSION["uid"];
2656 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2657 WHERE owner_uid = '$owner_uid'");
2659 while ($line = db_fetch_assoc($result)) {
2661 $id = -$line["id"] - 11;
2663 $label_name = $line["caption"];
2664 $count = getFeedUnread($link, $id);
2666 if (!$smart_mode ||
$old_counters[$id] != $count) {
2667 $old_counters[$id] = $count;
2668 $lctrs_modified = true;
2671 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2672 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2677 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2679 $ret_arr[$id]["counter"] = $count;
2680 $ret_arr[$id]["description"] = $label_name;
2684 error_reporting (DEFAULT_ERROR_LEVEL
);
2687 if ($smart_mode && $lctrs_modified) {
2688 $_SESSION["lctr_last_value"] = $old_counters;
2694 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2696 $age_qpart = getMaxAgeSubquery();
2699 if (!$_SESSION["fctr_last_value"]) {
2700 $_SESSION["fctr_last_value"] = array();
2704 $old_counters = $_SESSION["fctr_last_value"];
2706 $query = "SELECT ttrss_feeds.id,
2708 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2709 last_error, value AS count
2710 FROM ttrss_feeds, ttrss_counters_cache
2711 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2712 AND parent_feed IS NULL
2713 AND ttrss_counters_cache.feed_id = id";
2715 $result = db_query($link, $query);
2716 $fctrs_modified = false;
2718 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2720 while ($line = db_fetch_assoc($result)) {
2723 $count = $line["count"];
2724 $last_error = htmlspecialchars($line["last_error"]);
2726 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2727 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2729 $last_updated = date($short_date, strtotime($line["last_updated"]));
2732 $last_updated = htmlspecialchars($last_updated);
2734 $has_img = feed_has_icon($id);
2736 $tmp_result = db_query($link,
2737 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2738 WHERE parent_feed = '$id' AND feed_id = id");
2740 $count +
= db_fetch_result($tmp_result, 0, "unread");
2742 if (!$smart_mode ||
$old_counters[$id] != $count) {
2743 $old_counters[$id] = $count;
2744 $fctrs_modified = true;
2747 $error_part = "error=\"$last_error\"";
2753 $has_img_part = "hi=\"$has_img\"";
2758 if ($active_feed && $id == $active_feed) {
2759 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2761 $has_title_part = "";
2764 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2765 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2768 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2772 if ($smart_mode && $fctrs_modified) {
2773 $_SESSION["fctr_last_value"] = $old_counters;
2777 function get_script_dt_add() {
2778 if (strpos(VERSION
, ".99") === false) {
2785 function get_pgsql_version($link) {
2786 $result = db_query($link, "SELECT version() AS version");
2787 $version = split(" ", db_fetch_result($result, 0, "version"));
2791 function print_error_xml($code, $add_msg = "") {
2794 $error_msg = $ERRORS[$code];
2797 $error_msg = "$error_msg; $add_msg";
2800 print "<rpc-reply>";
2801 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2802 print "</rpc-reply>";
2805 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2806 $auth_login = '', $auth_pass = '') {
2808 # check for feed:http://url
2809 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2811 # check for feed://URL
2812 if (strpos($feed_link, "//") === 0) {
2813 $feed_link = "http:$feed_link";
2816 if ($feed_link == "") return;
2818 if ($cat_id == "0" ||
!$cat_id) {
2819 $cat_qpart = "NULL";
2821 $cat_qpart = "'$cat_id'";
2824 $result = db_query($link,
2825 "SELECT id FROM ttrss_feeds
2826 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2828 if (db_num_rows($result) == 0) {
2830 $result = db_query($link,
2831 "INSERT INTO ttrss_feeds
2832 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2833 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2834 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2836 $result = db_query($link,
2837 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2838 AND owner_uid = " . $_SESSION["uid"]);
2840 $feed_id = db_fetch_result($result, 0, "id");
2843 update_rss_feed($link, $feed_link, $feed_id, true);
2852 function print_feed_select($link, $id, $default_id = "",
2853 $attributes = "", $include_all_feeds = true) {
2855 print "<select id=\"$id\" name=\"$id\" $attributes>";
2856 if ($include_all_feeds) {
2857 print "<option value=\"0\">".__('All feeds')."</option>";
2860 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2861 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2863 if (db_num_rows($result) > 0 && $include_all_feeds) {
2864 print "<option disabled>--------</option>";
2867 while ($line = db_fetch_assoc($result)) {
2868 if ($line["id"] == $default_id) {
2869 $is_selected = "selected";
2873 printf("<option $is_selected value='%d'>%s</option>",
2874 $line["id"], htmlspecialchars($line["title"]));
2880 function print_feed_cat_select($link, $id, $default_id = "",
2881 $attributes = "", $include_all_cats = true) {
2883 print "<select id=\"$id\" name=\"$id\" $attributes>";
2885 if ($include_all_cats) {
2886 print "<option value=\"0\">".__('Uncategorized')."</option>";
2889 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2890 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2892 if (db_num_rows($result) > 0 && $include_all_cats) {
2893 print "<option disabled>--------</option>";
2896 while ($line = db_fetch_assoc($result)) {
2897 if ($line["id"] == $default_id) {
2898 $is_selected = "selected";
2902 printf("<option $is_selected value='%d'>%s</option>",
2903 $line["id"], htmlspecialchars($line["title"]));
2909 function checkbox_to_sql_bool($val) {
2910 return ($val == "on") ?
"true" : "false";
2913 function getFeedCatTitle($link, $id) {
2915 return __("Special");
2916 } else if ($id < -10) {
2917 return __("Labels");
2918 } else if ($id > 0) {
2919 $result = db_query($link, "SELECT ttrss_feed_categories.title
2920 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2921 cat_id = ttrss_feed_categories.id");
2922 if (db_num_rows($result) == 1) {
2923 return db_fetch_result($result, 0, "title");
2925 return __("Uncategorized");
2928 return "getFeedCatTitle($id) failed";
2933 function getFeedTitle($link, $id) {
2935 return __("Starred articles");
2936 } else if ($id == -2) {
2937 return __("Published articles");
2938 } else if ($id == -3) {
2939 return __("Fresh articles");
2940 } else if ($id == -4) {
2941 return __("All articles");
2942 } else if ($id < -10) {
2943 $label_id = -$id - 11;
2944 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2945 if (db_num_rows($result) == 1) {
2946 return db_fetch_result($result, 0, "caption");
2948 return "Unknown label ($label_id)";
2951 } else if ($id > 0) {
2952 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2953 if (db_num_rows($result) == 1) {
2954 return db_fetch_result($result, 0, "title");
2956 return "Unknown feed ($id)";
2959 return "getFeedTitle($id) failed";
2964 function get_session_cookie_name() {
2965 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2968 function print_init_params($link) {
2969 print "<init-params>";
2970 if ($_SESSION["stored-params"]) {
2971 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2973 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2974 print "<param key=\"$key\" value=\"$value\"/>";
2979 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2980 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2981 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2982 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2984 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2985 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2987 print "<param key=\"hide_read_feeds\" value=\"" .
2988 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2990 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2991 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2993 print "<param key=\"confirm_feed_catchup\" value=\"" .
2994 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2996 print "<param key=\"cdm_auto_catchup\" value=\"" .
2997 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2999 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
3001 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
3003 print "<param key=\"default_view_mode\" value=\"" .
3004 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3006 print "<param key=\"default_view_limit\" value=\"" .
3007 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3009 print "<param key=\"default_view_order_by\" value=\"" .
3010 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3012 print "<param key=\"prefs_active_tab\" value=\"" .
3013 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3015 print "<param key=\"infobox_disable_overlay\" value=\"" .
3016 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3018 print "<param key=\"icons_location\" value=\"" .
3021 print "<param key=\"hide_read_shows_special\" value=\"" .
3022 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3024 print "<param key=\"hide_feedlist\" value=\"" .
3025 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3027 print "<param key=\"bw_limit\" value=\"".
3028 (int) $_SESSION["bw_limit"]."\"/>";
3030 // print "<param key=\"sync_counters\" value=\"" .
3031 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3033 print "<param key=\"sync_counters\" value=\"1\"/>";
3035 print "</init-params>";
3038 function print_runtime_info($link) {
3039 print "<runtime-info>";
3041 if (ENABLE_UPDATE_DAEMON
) {
3042 print "<param key=\"daemon_is_running\" value=\"".
3043 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3045 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3047 $stamp = (int)read_stampfile("update_daemon.stamp");
3049 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3052 $stamp_delta = time() - $stamp;
3054 if ($stamp_delta > 1800) {
3058 $_SESSION["daemon_stamp_check"] = time();
3061 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3063 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3065 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3070 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3072 if ($_SESSION["last_version_check"] +
86400 < time()) {
3073 $new_version_details = check_for_update($link);
3075 print "<param key=\"new_version_available\" value=\"".
3076 sprintf("%d", $new_version_details != ""). "\"/>";
3078 $_SESSION["last_version_check"] = time();
3082 // print "<param key=\"new_version_available\" value=\"1\"/>";
3084 print "</runtime-info>";
3087 function getSearchSql($search, $match_on) {
3089 $search_query_part = "";
3091 $keywords = split(" ", $search);
3092 $query_keywords = array();
3094 if ($match_on == "both") {
3096 foreach ($keywords as $k) {
3097 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3098 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3101 $search_query_part = implode("AND", $query_keywords) . " AND ";
3103 } else if ($match_on == "title") {
3105 foreach ($keywords as $k) {
3106 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3109 $search_query_part = implode("AND", $query_keywords) . " AND ";
3111 } else if ($match_on == "content") {
3113 foreach ($keywords as $k) {
3114 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3118 $search_query_part = implode("AND", $query_keywords);
3120 return $search_query_part;
3123 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3125 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3129 $search_query_part = getSearchSql($search, $match_on);
3130 $search_query_part .= " AND ";
3133 $search_query_part = "";
3136 $view_query_part = "";
3138 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3140 $view_query_part = " ";
3141 } else if ($feed != -1) {
3142 $unread = getFeedUnread($link, $feed, $cat_view);
3144 $view_query_part = " unread = true AND ";
3149 if ($view_mode == "marked") {
3150 $view_query_part = " marked = true AND ";
3153 if ($view_mode == "unread") {
3154 $view_query_part = " unread = true AND ";
3157 if ($view_mode == "updated") {
3158 $view_query_part = " (last_read is null and unread = false) AND ";
3162 $limit_query_part = "LIMIT " . $limit;
3165 $vfeed_query_part = "";
3167 // override query strategy and enable feed display when searching globally
3168 if ($search && $search_mode == "all_feeds") {
3169 $query_strategy_part = "ttrss_entries.id > 0";
3170 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3171 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3172 $query_strategy_part = "ttrss_entries.id > 0";
3173 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3174 id = feed_id) as feed_title,";
3175 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3177 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3179 $tmp_result = false;
3182 $tmp_result = db_query($link, "SELECT id
3183 FROM ttrss_feeds WHERE cat_id = '$feed'");
3185 $tmp_result = db_query($link, "SELECT id
3186 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3187 WHERE id = '$feed') AND id != '$feed'");
3190 $cat_siblings = array();
3192 if (db_num_rows($tmp_result) > 0) {
3193 while ($p = db_fetch_assoc($tmp_result)) {
3194 array_push($cat_siblings, "feed_id = " . $p["id"]);
3197 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3198 $feed, implode(" OR ", $cat_siblings));
3201 $query_strategy_part = "ttrss_entries.id > 0";
3204 } else if ($feed >= 0) {
3209 $query_strategy_part = "cat_id = '$feed'";
3211 $query_strategy_part = "cat_id IS NULL";
3214 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3217 $tmp_result = db_query($link, "SELECT id
3218 FROM ttrss_feeds WHERE parent_feed = '$feed'
3219 ORDER BY cat_id,title");
3221 $parent_ids = array();
3223 if (db_num_rows($tmp_result) > 0) {
3224 while ($p = db_fetch_assoc($tmp_result)) {
3225 array_push($parent_ids, "feed_id = " . $p["id"]);
3228 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3229 $feed, implode(" OR ", $parent_ids));
3231 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3233 $query_strategy_part = "feed_id = '$feed'";
3236 } else if ($feed == -1) { // starred virtual feed
3237 $query_strategy_part = "marked = true";
3238 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3239 } else if ($feed == -2) { // published virtual feed OR labels category
3242 $query_strategy_part = "published = true";
3243 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3245 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3247 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3249 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3250 ttrss_user_labels2.article_id = ref_id";
3254 } else if ($feed == -3) { // fresh virtual feed
3255 $query_strategy_part = "unread = true";
3257 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3259 if (DB_TYPE
== "pgsql") {
3260 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3262 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3265 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3266 } else if ($feed == -4) { // all articles virtual feed
3267 $query_strategy_part = "true";
3268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3269 } else if ($feed <= -10) { // labels
3270 $label_id = -$feed - 11;
3272 $query_strategy_part = "label_id = '$label_id' AND
3273 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3274 ttrss_user_labels2.article_id = ref_id";
3276 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3277 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3280 $query_strategy_part = "id > 0"; // dumb
3283 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3284 $order_by = "updated";
3286 $order_by = "updated DESC";
3289 if ($view_mode != "noscores") {
3290 $order_by = "score DESC, $order_by";
3293 if ($override_order) {
3294 $order_by = $override_order;
3299 if ($search && $search_mode == "all_feeds") {
3300 $feed_title = __("Search results")." ($search)";
3301 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3302 $feed_title = __("Search results")." ($search, $feed)";
3303 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3304 $feed_title = $feed;
3305 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3310 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3311 WHERE id = '$feed' AND owner_uid = $owner_uid");
3312 $feed_title = db_fetch_result($result, 0, "title");
3314 $feed_title = __("Uncategorized");
3318 $feed_title = __("Searched for")." $search ($feed_title)";
3323 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3324 WHERE id = '$feed' AND owner_uid = $owner_uid");
3326 $feed_title = db_fetch_result($result, 0, "title");
3327 $feed_site_url = db_fetch_result($result, 0, "site_url");
3328 $last_error = db_fetch_result($result, 0, "last_error");
3331 $feed_title = __("Searched for") . " $search ($feed_title)";
3335 } else if ($feed == -1) {
3336 $feed_title = __("Starred articles");
3337 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3338 } else if ($feed == -2) {
3340 $feed_title = __("Published articles");
3341 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3343 $feed_title = __("Labels");
3345 } else if ($feed == -3) {
3346 $feed_title = __("Fresh articles");
3347 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3348 } else if ($feed == -4) {
3349 $feed_title = __("All articles");
3350 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3351 } else if ($feed < -10) {
3352 $label_id = -$feed - 11;
3353 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3354 WHERE id = '$label_id'");
3355 $feed_title = db_fetch_result($result, 0, "caption");
3358 $feed_title = __("Searched for") . " $search ($feed_title)";
3364 if ($feed < -10) error_reporting (0);
3366 $content_query_part = "content as content_preview,";
3368 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3371 $feed_kind = "Feeds";
3373 $feed_kind = "Labels";
3376 if ($limit_query_part) {
3377 $offset_query_part = "OFFSET $offset";
3380 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3381 if (!$override_order) {
3382 $order_by = "ttrss_feeds.title, $order_by";
3385 // Special output for Fresh feed
3387 /* if ($feed == -3) {
3388 $group_limit_part = "(select count(*) from
3389 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3390 t1.ref_id = t2.id and t1.owner_uid = 2 and
3391 t1.feed_id = ttrss_user_entries.feed_id and
3392 t2.updated > ttrss_entries.updated) <= 5 AND";
3396 $query = "SELECT DISTINCT
3398 ttrss_entries.id,ttrss_entries.title,
3400 unread,feed_id,marked,published,link,last_read,
3401 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3404 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3407 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3410 ttrss_feeds.hidden = false AND
3411 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3412 ttrss_user_entries.ref_id = ttrss_entries.id AND
3413 ttrss_user_entries.owner_uid = '$owner_uid' AND
3416 $query_strategy_part ORDER BY $order_by
3417 $limit_query_part $offset_query_part";
3419 if ($_GET["debug"]) print $query;
3421 $result = db_query($link, $query);
3426 $feed_kind = "Tags";
3428 $result = db_query($link, "SELECT
3430 ttrss_entries.id as id,title,
3433 marked,link,last_read,
3434 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3437 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3440 ttrss_entries,ttrss_user_entries,ttrss_tags
3442 ref_id = ttrss_entries.id AND
3443 ttrss_user_entries.owner_uid = '$owner_uid' AND
3444 post_int_id = int_id AND tag_name = '$feed' AND
3447 $query_strategy_part ORDER BY $order_by
3448 $limit_query_part");
3451 return array($result, $feed_title, $feed_site_url, $last_error);
3455 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3456 $limit, $search, $search_mode, $match_on) {
3458 if (!$limit) $limit = 30;
3460 $qfh_ret = queryFeedHeadlines($link, $feed,
3461 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3464 $result = $qfh_ret[0];
3465 $feed_title = htmlspecialchars($qfh_ret[1]);
3466 $feed_site_url = $qfh_ret[2];
3467 $last_error = $qfh_ret[3];
3469 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3471 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3472 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3473 <rss version=\"2.0\">
3475 <title>$feed_title</title>
3476 <link>$feed_site_url</link>
3477 <description>Feed generated by Tiny Tiny RSS</description>";
3479 while ($line = db_fetch_assoc($result)) {
3481 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3482 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3484 $tags = get_article_tags($link, $line["id"], $owner_uid);
3486 foreach ($tags as $tag) {
3487 print "<category>" . htmlspecialchars($tag) . "</category>";
3490 $rfc822_date = date('r', strtotime($line["updated"]));
3492 print "<pubDate>$rfc822_date</pubDate>";
3495 htmlspecialchars($line["title"]) . "</title>";
3497 print "<description><![CDATA[" .
3498 $line["content_preview"] . "]]></description>";
3503 print "</channel></rss>";
3507 function getCategoryTitle($link, $cat_id) {
3509 if ($cat_id == -1) {
3510 return __("Special");
3511 } else if ($cat_id == -2) {
3512 return __("Labels");
3515 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3518 if (db_num_rows($result) == 1) {
3519 return db_fetch_result($result, 0, "title");
3521 return "Uncategorized";
3526 // http://ru2.php.net/strip-tags
3528 function strip_tags_long($textstring, $allowed){
3529 while($textstring != strip_tags($textstring, $allowed))
3531 while (strlen($textstring) != 0)
3533 if (strlen($textstring) > 1024) {
3536 $otherlen = strlen($textstring);
3538 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3539 $safetext .= $temptext;
3540 $textstring = substr_replace($textstring,'',0,$otherlen);
3542 $textstring = $safetext;
3548 function sanitize_rss($link, $str, $force_strip_tags = false) {
3551 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3553 $res = strip_tags_long($res,
3554 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3556 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3557 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3560 if (get_pref($link, "STRIP_IMAGES")) {
3562 $res = preg_replace('/<img[^>]+>/is', '', $res);
3570 * Send by mail a digest of last articles.
3572 * @param mixed $link The database connection.
3573 * @param integer $limit The maximum number of articles by digest.
3574 * @return boolean Return false if digests are not enabled.
3576 function send_headlines_digests($link, $limit = 100) {
3578 if (!DIGEST_ENABLE
) return false;
3580 $user_limit = DIGEST_EMAIL_LIMIT
;
3583 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3585 if (DB_TYPE
== "pgsql") {
3586 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3587 } else if (DB_TYPE
== "mysql") {
3588 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3591 $result = db_query($link, "SELECT id,email FROM ttrss_users
3592 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3594 while ($line = db_fetch_assoc($result)) {
3596 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3597 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3599 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3601 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3602 $digest = $tuple[0];
3603 $headlines_count = $tuple[1];
3604 $affected_ids = $tuple[2];
3605 $digest_text = $tuple[3];
3607 if ($headlines_count > 0) {
3609 $mail = new PHPMailer();
3611 $mail->PluginDir
= "phpmailer/";
3612 $mail->SetLanguage("en", "phpmailer/language/");
3614 $mail->CharSet
= "UTF-8";
3616 $mail->From
= DIGEST_FROM_ADDRESS
;
3617 $mail->FromName
= DIGEST_FROM_NAME
;
3618 $mail->AddAddress($line["email"], $line["login"]);
3620 if (DIGEST_SMTP_HOST
) {
3621 $mail->Host
= DIGEST_SMTP_HOST
;
3622 $mail->Mailer
= "smtp";
3623 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3624 $mail->Username
= DIGEST_SMTP_LOGIN
;
3625 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3628 $mail->IsHTML(true);
3629 $mail->Subject
= DIGEST_SUBJECT
;
3630 $mail->Body
= $digest;
3631 $mail->AltBody
= $digest_text;
3633 $rc = $mail->Send();
3635 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3639 if ($rc && $do_catchup) {
3640 print "Marking affected articles as read...\n";
3641 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3644 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3645 WHERE id = " . $line["id"]);
3647 print "No headlines\n";
3652 print "All done.\n";
3656 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3658 require_once "MiniTemplator.class.php";
3660 $tpl = new MiniTemplator
;
3661 $tpl_t = new MiniTemplator
;
3663 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3664 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3666 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3667 $tpl->setVariable('CUR_TIME', date('G:i'));
3669 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3670 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3672 $affected_ids = array();
3674 if (DB_TYPE
== "pgsql") {
3675 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3676 } else if (DB_TYPE
== "mysql") {
3677 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3680 $result = db_query($link, "SELECT ttrss_entries.title,
3681 ttrss_feeds.title AS feed_title,
3683 ttrss_user_entries.ref_id,
3685 SUBSTRING(content, 1, 120) AS excerpt,
3686 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3688 ttrss_user_entries,ttrss_entries,ttrss_feeds
3690 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3691 AND include_in_digest = true
3694 AND ttrss_user_entries.owner_uid = $user_id
3696 ORDER BY ttrss_feeds.title, date_entered DESC
3699 $cur_feed_title = "";
3701 $headlines_count = db_num_rows($result);
3703 $headlines = array();
3705 while ($line = db_fetch_assoc($result)) {
3706 array_push($headlines, $line);
3709 for ($i = 0; $i < sizeof($headlines); $i++
) {
3711 $line = $headlines[$i];
3713 array_push($affected_ids, $line["ref_id"]);
3715 $updated = smart_date_time(strtotime($line["last_updated"]));
3717 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3718 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3719 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3720 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3721 $tpl->setVariable('ARTICLE_EXCERPT',
3722 truncate_string(strip_tags($line["excerpt"]), 100));
3724 $tpl->addBlock('article');
3726 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3727 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3728 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3729 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3730 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3731 // truncate_string(strip_tags($line["excerpt"]), 100));
3733 $tpl_t->addBlock('article');
3735 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3736 $tpl->addBlock('feed');
3737 $tpl_t->addBlock('feed');
3742 $tpl->addBlock('digest');
3743 $tpl->generateOutputToString($tmp);
3745 $tpl_t->addBlock('digest');
3746 $tpl_t->generateOutputToString($tmp_t);
3748 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3751 function check_for_update($link, $brief_fmt = true) {
3752 $releases_feed = "http://tt-rss.org/releases.rss";
3754 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3759 if (ENABLE_SIMPLEPIE
) {
3760 $rss = new SimplePie();
3761 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3762 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3763 $rss->set_feed_url($fetch_url);
3764 $rss->set_output_encoding('UTF-8');
3767 $rss = fetch_rss($releases_feed);
3769 error_reporting (DEFAULT_ERROR_LEVEL
);
3773 if (ENABLE_SIMPLEPIE
) {
3774 $items = $rss->get_items();
3776 $items = $rss->items
;
3778 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3779 if (!$items ||
!is_array($items)) $items = $rss;
3782 if (!is_array($items) ||
count($items) == 0) {
3786 $latest_item = $items[0];
3788 if (ENABLE_SIMPLEPIE
) {
3789 $last_title = $latest_item->get_title();
3791 $last_title = $latest_item["title"];
3794 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3796 if (ENABLE_SIMPLEPIE
) {
3797 $release_url = sanitize_rss($link, $latest_item->get_link());
3798 $content = sanitize_rss($link, $latest_item->get_description());
3800 $release_url = sanitize_rss($link, $latest_item["link"]);
3801 $content = sanitize_rss($link, $latest_item["description"]);
3804 if (version_compare(VERSION
, $latest_version) == -1) {
3806 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3807 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3808 <div id=\"milestoneDetails\">$content</div>");
3810 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3811 <div class='milestoneDetails'>$content</div>
3812 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3813 download and update information.";
3820 function markArticlesById($link, $ids, $cmode) {
3824 foreach ($ids as $id) {
3825 array_push($tmp_ids, "ref_id = '$id'");
3828 $ids_qpart = join(" OR ", $tmp_ids);
3831 db_query($link, "UPDATE ttrss_user_entries SET
3832 marked = false,last_read = NOW()
3833 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3834 } else if ($cmode == 1) {
3835 db_query($link, "UPDATE ttrss_user_entries SET
3837 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3839 db_query($link, "UPDATE ttrss_user_entries SET
3840 marked = NOT marked,last_read = NOW()
3841 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3845 function publishArticlesById($link, $ids, $cmode) {
3849 foreach ($ids as $id) {
3850 array_push($tmp_ids, "ref_id = '$id'");
3853 $ids_qpart = join(" OR ", $tmp_ids);
3856 db_query($link, "UPDATE ttrss_user_entries SET
3857 published = false,last_read = NOW()
3858 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3859 } else if ($cmode == 1) {
3860 db_query($link, "UPDATE ttrss_user_entries SET
3862 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3864 db_query($link, "UPDATE ttrss_user_entries SET
3865 published = NOT published,last_read = NOW()
3866 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3870 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3872 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3876 foreach ($ids as $id) {
3877 array_push($tmp_ids, "ref_id = '$id'");
3880 $ids_qpart = join(" OR ", $tmp_ids);
3883 db_query($link, "UPDATE ttrss_user_entries SET
3884 unread = false,last_read = NOW()
3885 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3886 } else if ($cmode == 1) {
3887 db_query($link, "UPDATE ttrss_user_entries SET
3889 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3891 db_query($link, "UPDATE ttrss_user_entries SET
3892 unread = NOT unread,last_read = NOW()
3893 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3898 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3899 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3901 while ($line = db_fetch_assoc($result)) {
3902 ccache_update($link, $line["feed_id"], $owner_uid);
3906 function catchupArticleById($link, $id, $cmode) {
3909 db_query($link, "UPDATE ttrss_user_entries SET
3910 unread = false,last_read = NOW()
3911 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3912 } else if ($cmode == 1) {
3913 db_query($link, "UPDATE ttrss_user_entries SET
3915 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3917 db_query($link, "UPDATE ttrss_user_entries SET
3918 unread = NOT unread,last_read = NOW()
3919 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3923 function make_guid_from_title($title) {
3924 return preg_replace("/[ \"\',.:;]/", "-",
3925 mb_strtolower(strip_tags($title), 'utf-8'));
3928 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3929 $bottom = false, $rtl_content = false, $feed_id = 0,
3930 $is_cat = false, $search = false, $match_on = false,
3931 $search_mode = false, $offset = 0, $limit = 0,
3932 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3934 $user_page_offset = $offset +
1;
3937 $class = "headlinesSubToolbar";
3938 $tid = "headlineActionsTop";
3940 $class = "headlinesSubToolbar";
3941 $tid = "headlineActionsBottom";
3944 print "<nobr><table class=\"$class\" id=\"$tid\"
3945 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3953 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3954 $page_next_link = "javascript:viewFeedGoPage(1)";
3955 $page_first_link = "javascript:viewFeedGoPage(0)";
3957 $catchup_page_link = "javascript:catchupPage()";
3958 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3959 $catchup_sel_link = "javascript:catchupSelection()";
3961 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3963 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3964 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3965 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3966 $sel_inv_link = "javascript:invertHeadlineSelection()";
3968 $tog_unread_link = "javascript:selectionToggleUnread()";
3969 $tog_marked_link = "javascript:selectionToggleMarked()";
3970 $tog_published_link = "javascript:selectionTogglePublished()";
3974 $sel_all_link = "javascript:cdmSelectArticles('all')";
3975 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3976 $sel_none_link = "javascript:cdmSelectArticles('none')";
3978 $sel_inv_link = "javascript:invertHeadlineSelection()";
3980 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3981 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3982 $tog_published_link = "javascript:selectionTogglePublished(true)";
3986 print "<td class=\"headlineActions$rtl_cpart\">";
3989 print __('Select:')."
3990 <a href=\"$sel_all_link\">".__('All')."</a>,
3991 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3992 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3993 <a href=\"$sel_none_link\">".__('None')."</a></li>";
3995 print " ";
3998 onmouseover=\"enable_selection(false)\"
3999 onmouseout=\"enable_selection(true)\"
4000 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4001 __("Actions...") . " <img src=\"images/down_arrow.png\">
4004 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4006 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4007 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4008 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4009 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4010 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4011 <li class=\"insensitive\">".__('Mark as read:')."</li>
4012 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4014 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4017 //print "<li><span class=\"insensitive\">--------</span></li>";
4018 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4020 print "<li onclick=\"javascript:addLabel()\">
4021 ".__("Create label...")."</li>";
4023 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
4024 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4026 while ($line = db_fetch_assoc($result)) {
4028 $label_id = $line["id"];
4029 $label_caption = $line["caption"];
4031 if ($feed_id < -10 && $feed_id == -11-$label_id) {
4032 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
4033 $label_caption ".__('(remove)')."</li>";
4035 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
4036 $label_caption</li>";
4043 print "<td class=\"headlineTitle$rtl_cpart\">";
4045 print "<span id=\"subtoolbar_ftitle\">";
4047 if ($feed_site_url) {
4049 $target = "target=\"_blank\"";
4051 print "<a $target href=\"$feed_site_url\">".
4052 truncate_string($feed_title,30)."</a>";
4058 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4061 if ($user_page_offset > 1) {
4062 print " [$user_page_offset] ";
4065 if (!$bottom && !$disable_feed) {
4067 <a target=\"_blank\"
4068 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4069 <img class=\"noborder\"
4070 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4072 } else if ($feed_small_icon) {
4073 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4079 print "</tr></table></nobr>";
4083 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4085 $tmp_category = getCategoryTitle($link, $cat_id);
4088 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4089 } else if ($cat_id == 0 ||
$cat_id == -2) {
4090 $cat_unread = getCategoryUnread($link, $cat_id);
4094 $holder_style = "display:none;";
4101 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4104 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4105 $inner_title_class = "catTitle";
4107 $browse_cat_link = "";
4108 $inner_title_class = "catTitleNL";
4111 $cat_class = "feedCat";
4113 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4114 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4115 title=\"".__('Click to collapse category')."\"
4116 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4117 id=\"FCATN-$cat_id\" $browse_cat_link
4118 \">$tmp_category</span>";
4120 print "<span id=\"FCAP-$cat_id\">";
4122 print " <span id=\"FCATCTR-$cat_id\"
4123 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4129 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4133 function outputFeedList($link, $tags = false) {
4135 print "<ul class=\"feedList\" id=\"feedList\">";
4137 $owner_uid = $_SESSION["uid"];
4141 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4143 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4146 $cat_hidden = false;
4149 printCategoryHeader($link, -1, $cat_hidden, false);
4152 $num_starred = getFeedUnread($link, -1);
4153 $num_published = getFeedUnread($link, -2);
4154 $num_fresh = getFeedUnread($link, -3);
4155 $num_total = getFeedUnread($link, -4);
4159 if ($num_total > 0) $class .= "Unread";
4161 printFeedEntry(-4, $class, __("All articles"), $num_total,
4162 "images/tag.png", $link);
4166 if ($num_fresh > 0) $class .= "Unread";
4168 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4169 "images/fresh.png", $link);
4173 if ($num_starred > 0) $class .= "Unread";
4175 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4178 $mark_img_ext = "gif";
4180 $mark_img_ext = "png";
4183 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4184 "images/mark_set.$mark_img_ext", $link);
4188 if ($num_published > 0) $class .= "Unread";
4190 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4191 "images/pub_set.gif", $link);
4193 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4200 $result = db_query($link, "SELECT id,caption FROM
4201 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4203 if (db_num_rows($result) > 0) {
4204 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4206 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4209 $cat_hidden = false;
4212 printCategoryHeader($link, -2, $cat_hidden, true);
4215 print "<li><hr></li>";
4219 while ($line = db_fetch_assoc($result)) {
4221 $label_id = -$line['id'] - 11;
4222 $count = getFeedUnread($link, $label_id);
4230 printFeedEntry($label_id,
4231 $class, $line["caption"],
4232 $count, "images/label.png", $link);
4236 if (db_num_rows($result) > 0) {
4237 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4243 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4244 print "<li><hr></li>";
4247 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4248 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4249 $order_by_qpart = "order_id,category,unread DESC,title";
4251 $order_by_qpart = "order_id,category,title";
4254 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4255 $order_by_qpart = "unread DESC,title";
4257 $order_by_qpart = "title";
4261 $age_qpart = getMaxAgeSubquery();
4263 $query = "SELECT ttrss_feeds.*,
4264 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4266 ttrss_feed_categories.title AS category,
4267 ttrss_feed_categories.collapsed,
4269 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4270 ON (ttrss_feed_categories.id = cat_id)
4271 LEFT JOIN ttrss_counters_cache
4273 (ttrss_feeds.id = feed_id)
4275 ttrss_feeds.hidden = false AND
4276 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4277 ORDER BY $order_by_qpart";
4279 $result = db_query($link, $query);
4281 $actid = $_GET["actid"];
4291 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4293 while ($line = db_fetch_assoc($result)) {
4295 $feed = trim($line["title"]);
4297 if (!$feed) $feed = "[Untitled]";
4299 $feed_id = $line["id"];
4300 $unread = $line["unread"];
4302 $subop = $_GET["subop"];
4304 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4305 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4307 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4310 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4313 $rtl_tag = "dir=\"RTL\"";
4318 $tmp_result = db_query($link,
4319 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4320 WHERE parent_feed = '$feed_id' AND feed_id = id");
4322 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4324 $cat_id = $line["cat_id"];
4326 $tmp_category = $line["category"];
4328 if (!$tmp_category) {
4329 $tmp_category = __("Uncategorized");
4332 // $class = ($lnum % 2) ? "even" : "odd";
4334 if ($line["last_error"]) {
4340 if ($unread > 0) $class .= "Unread";
4342 if ($actid == $feed_id) {
4343 $class .= "Selected";
4346 $total_unread +
= $unread;
4348 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4354 $category = $tmp_category;
4356 $collapsed = sql_bool_to_bool($line["collapsed"]);
4358 // workaround for NULL category
4359 if ($category == __("Uncategorized")) {
4360 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4365 $cat_id = sprintf("%d", $cat_id);
4367 printCategoryHeader($link, $cat_id, $collapsed, true);
4371 printFeedEntry($feed_id, $class, $feed, $unread,
4372 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4373 $last_updated, $line["last_error"]);
4378 if (db_num_rows($result) == 0) {
4379 print "<li>".__('No feeds to display.')."</li>";
4386 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4387 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4388 post_int_id = ttrss_user_entries.int_id AND
4389 unread = true AND ref_id = ttrss_entries.id
4390 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4392 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4393 ORDER BY tag_name"); */
4395 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4396 print "<li class=\"feedCat\">".__('Tags')."</li>";
4397 print "<ul class=\"feedCatList\">";
4400 $age_qpart = getMaxAgeSubquery();
4402 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4403 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4404 AND ref_id = id AND $age_qpart
4405 AND unread = true)) AS count FROM ttrss_tags
4406 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4407 ORDER BY count DESC LIMIT 50");
4411 while ($line = db_fetch_assoc($result)) {
4412 $tags[$line["tag_name"]] +
= $line["count"];
4415 foreach (array_keys($tags) as $tag) {
4417 $unread = $tags[$tag];
4425 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4429 if (db_num_rows($result) == 0) {
4430 print "<li>No tags to display.</li>";
4433 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4443 function get_article_tags($link, $id, $owner_uid = 0) {
4445 $a_id = db_escape_string($id);
4447 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4449 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4450 owner_uid as owner FROM
4451 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4452 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4456 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4457 array_push($tags, $tmp_line["tag_name"]);
4463 function trim_value(&$value) {
4464 $value = trim($value);
4467 function trim_array($array) {
4469 array_walk($tmp, 'trim_value');
4473 function tag_is_valid($tag) {
4474 if ($tag == '') return false;
4475 if (preg_match("/^[0-9]*$/", $tag)) return false;
4477 if (function_exists('iconv')) {
4478 $tag = iconv("utf-8", "utf-8", $tag);
4481 if (!$tag) return false;
4486 function render_login_form($link, $mobile = false) {
4488 require_once "login_form.php";
4490 require_once "mobile/login_form.php";
4494 // from http://developer.apple.com/internet/safari/faq.html
4495 function no_cache_incantation() {
4496 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4497 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4498 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4499 header("Cache-Control: post-check=0, pre-check=0", false);
4500 header("Pragma: no-cache"); // HTTP/1.0
4503 function format_warning($msg, $id = "") {
4504 return "<div class=\"warning\" id=\"$id\">
4505 <img src=\"images/sign_excl.gif\">$msg</div>";
4508 function format_notice($msg) {
4509 return "<div class=\"notice\">
4510 <img src=\"images/sign_info.gif\">$msg</div>";
4513 function format_error($msg) {
4514 return "<div class=\"error\">
4515 <img src=\"images/sign_excl.gif\">$msg</div>";
4518 function print_notice($msg) {
4519 return print format_notice($msg);
4522 function print_warning($msg) {
4523 return print format_warning($msg);
4526 function print_error($msg) {
4527 return print format_error($msg);
4531 function T_sprintf() {
4532 $args = func_get_args();
4533 return vsprintf(__(array_shift($args)), $args);
4536 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4537 $zoom_mode = false) {
4539 /* we can figure out feed_id from article id anyway, why do we
4540 * pass feed_id here? */
4542 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4543 WHERE ref_id = '$id'");
4545 $feed_id = db_fetch_result($result, 0, "feed_id");
4547 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4549 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4550 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4552 if (db_num_rows($result) == 1) {
4553 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4555 $rtl_content = false;
4559 $rtl_tag = "dir=\"RTL\"";
4566 if ($mark_as_read) {
4567 $result = db_query($link, "UPDATE ttrss_user_entries
4568 SET unread = false,last_read = NOW()
4569 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4571 ccache_update($link, $feed_id, $_SESSION["uid"]);
4574 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4575 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4576 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4579 FROM ttrss_entries,ttrss_user_entries
4580 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4586 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4587 $link_target = "target=\"_blank\"";
4590 $line = db_fetch_assoc($result);
4592 if ($line["icon_url"]) {
4593 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4595 $feed_icon = " ";
4598 $num_comments = $line["num_comments"];
4599 $entry_comments = "";
4601 if ($num_comments > 0) {
4602 if ($line["comments"]) {
4603 $comments_url = $line["comments"];
4605 $comments_url = $line["link"];
4607 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4609 if ($line["comments"] && $line["link"] != $line["comments"]) {
4610 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4615 header("Content-Type: text/html");
4617 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4618 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4619 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4624 print "<div class=\"postReply\">";
4626 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4627 onmouseout=\"enable_resize(false)\">";
4629 $entry_author = $line["author"];
4631 if ($entry_author) {
4632 $entry_author = __(" - ") . $entry_author;
4635 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4636 strtotime($line["updated"]));
4638 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4640 if ($line["link"]) {
4641 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4642 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4644 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4647 $tags = get_article_tags($link, $id);
4650 $tags_nolinks_str = "";
4655 if ($_SESSION["theme"] == "3pane") {
4661 foreach ($tags as $tag) {
4663 $tag_escaped = str_replace("'", "\\'", $tag);
4665 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4667 if ($num_tags == $tag_limit) {
4668 $tags_str .= "…";
4669 $tags_nolinks_str .= "…";
4671 } else if ($num_tags < $tag_limit) {
4672 $tags_str .= $tag_str;
4673 $tags_nolinks_str .= "$tag, ";
4675 $f_tags_str .= $tag_str;
4678 $tags_str = preg_replace("/, $/", "", $tags_str);
4679 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4680 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4682 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4683 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4685 if (!$entry_comments) $entry_comments = " "; # placeholder
4687 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4688 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4690 print "<div style='float : right'>
4691 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4695 <a title=\"".__('Edit tags for this article')."\"
4696 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4698 if (defined('_ENABLE_INLINE_VIEW')) {
4700 print "<img src=\"images/art-inline.png\" class='tagsPic'
4701 style=\"cursor : pointer\" style=\"cursor : pointer\"
4702 onclick=\"showOriginalArticleInline($id)\"
4703 alt='Inline' title='".__('Display original article content')."'>";
4707 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4708 style=\"cursor : pointer\" style=\"cursor : pointer\"
4709 onclick=\"zoomToArticle($id)\"
4710 alt='Zoom' title='".__('Show article summary in new window')."'>";
4712 print "$tags_nolinks_str";
4715 print "<div clear='both'>$entry_comments</div>";
4719 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4721 print "<div class=\"postContent\">";
4723 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4725 $article_content = sanitize_rss($link, $line["content"]);
4727 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4728 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4732 print $article_content;
4734 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4735 post_id = '$id' AND content_url != ''");
4737 if (db_num_rows($result) > 0) {
4739 $entries_html = array();
4742 while ($line = db_fetch_assoc($result)) {
4744 $url = $line["content_url"];
4745 $ctype = $line["content_type"];
4747 if (!$ctype) $ctype = __("unknown type");
4749 $filename = substr($url, strrpos($url, "/")+
1);
4753 if (($ctype == __("audio/mpeg")) &&
4754 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4756 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
4760 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4761 $filename . " (" . $ctype . ")" . "</a>";
4763 array_push($entries_html, $entry);
4767 $entry["type"] = $ctype;
4768 $entry["filename"] = $filename;
4769 $entry["url"] = $url;
4771 array_push($entries, $entry);
4774 print "<div class=\"postEnclosures\">";
4776 if (!preg_match("/img/i", $article_content)) {
4777 foreach ($entries as $entry) {
4778 if (preg_match("/image/", $entry["type"])) {
4780 alt=\"".htmlspecialchars($entry["filename"])."\"
4781 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4786 print "<div class=\"postEnclosures\">";
4788 if (db_num_rows($result) == 1) {
4789 print __("Attachment:") . " ";
4791 print __("Attachments:") . " ";
4794 print join(", ", $entries_html);
4806 print "]]></article>";
4809 <div style=\"text-align : center\">
4810 <input type=\"submit\" onclick=\"return window.close()\"
4811 value=\"".__("Close this window")."\"></div>";
4812 print "</body></html>";
4818 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4819 $next_unread_feed, $offset, $vgr_last_feed = false,
4820 $override_order = false) {
4822 $disable_cache = false;
4824 $timing_info = getmicrotime();
4826 $topmost_article_ids = array();
4832 if ($subop == "undefined") $subop = "";
4834 $subop_split = split(":", $subop);
4836 if ($subop == "CatchupSelected") {
4837 $ids = split(",", db_escape_string($_GET["ids"]));
4838 $cmode = sprintf("%d", $_GET["cmode"]);
4840 catchupArticlesById($link, $ids, $cmode);
4843 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4844 update_generic_feed($link, $feed, $cat_view, true);
4847 if ($subop == "MarkAllRead") {
4848 catchup_feed($link, $feed, $cat_view);
4850 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4851 if ($next_unread_feed) {
4852 $feed = $next_unread_feed;
4857 if ($subop_split[0] == "MarkAllReadGR") {
4858 catchup_feed($link, $subop_split[1], false);
4863 $result = db_query($link,
4864 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4866 if (db_num_rows($result) == 0) {
4867 print "<div align='center'>".__('Feed not found.')."</div>";
4872 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4874 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4875 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4877 if (db_num_rows($result) == 1) {
4878 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4880 $rtl_content = false;
4884 $rtl_tag = "dir=\"RTL\"";
4890 $rtl_content = false;
4893 $script_dt_add = get_script_dt_add();
4895 /// START /////////////////////////////////////////////////////////////////////////////////
4897 $search = db_escape_string($_GET["query"]);
4900 $disable_cache = true;
4903 $search_mode = db_escape_string($_GET["search_mode"]);
4904 $match_on = db_escape_string($_GET["match_on"]);
4910 $real_offset = $offset * $limit;
4912 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4914 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4915 $search, $search_mode, $match_on, $override_order, $real_offset);
4917 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4919 $result = $qfh_ret[0];
4920 $feed_title = $qfh_ret[1];
4921 $feed_site_url = $qfh_ret[2];
4922 $last_error = $qfh_ret[3];
4924 $vgroup_last_feed = $vgr_last_feed;
4927 $feed_site_url = article_publish_url($link);
4930 /// STOP //////////////////////////////////////////////////////////////////////////////////
4933 print "<div id=\"headlinesContainer\" $rtl_tag>";
4936 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4940 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4941 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4944 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4947 $headlines_count = db_num_rows($result);
4949 if (db_num_rows($result) > 0) {
4951 # print "\{$offset}";
4953 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4954 print "<table class=\"headlinesList\" id=\"headlinesList\"
4955 cellspacing=\"0\">";
4958 $lnum = $limit*$offset;
4960 error_reporting (DEFAULT_ERROR_LEVEL
);
4963 $cur_feed_title = '';
4965 while ($line = db_fetch_assoc($result)) {
4967 $class = ($lnum %
2) ?
"even" : "odd";
4970 $feed_id = $line["feed_id"];
4972 $labels = get_article_labels($link, $id);
4973 $labels_str = "<span id=\"HLLCTR-$id\">";
4975 foreach ($labels as $l) {
4976 $labels_str .= "<span
4977 class='hlLabelRef'>".
4981 $labels_str .= "</span>";
4983 if (count($topmost_article_ids) < 5) {
4984 array_push($topmost_article_ids, $id);
4987 if ($line["last_read"] == "" &&
4988 ($line["unread"] != "t" && $line["unread"] != "1")) {
4990 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4993 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4997 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5005 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5008 $mark_img_ext = "gif";
5010 $mark_img_ext = "png";
5013 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5014 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5016 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5018 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5020 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5023 if ($line["published"] == "t" ||
$line["published"] == "1") {
5024 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5026 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5028 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5030 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5033 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5034 # $line["title"] . "</a>";
5036 # $content_link = "<a
5037 # href=\"" . htmlspecialchars($line["link"]) . "\"
5038 # onclick=\"view($id,$feed_id);\">" .
5039 # $line["title"] . "</a>";
5041 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5042 # $line["title"] . "</a>";
5044 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5045 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5047 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5048 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5051 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5052 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5056 $score = $line["score"];
5058 $score_pic = get_score_pic($score);
5060 /* $score_title = __("(Click to change)");
5061 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5062 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5064 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5069 } else if ($score < -100) {
5075 $entry_author = $line["author"];
5077 if ($entry_author) {
5078 $entry_author = " - $entry_author";
5081 $has_feed_icon = feed_has_icon($feed_id);
5083 if ($has_feed_icon) {
5084 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5086 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5087 $feed_icon_img = "";
5090 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5092 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5093 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5095 $cur_feed_title = $line["feed_title"];
5096 $vgroup_last_feed = $feed_id;
5098 $cur_feed_title = htmlspecialchars($cur_feed_title);
5100 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5102 print "<tr class='feedTitle'><td colspan='7'>".
5103 "<div style=\"float : right\">$feed_icon_img</div>".
5104 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5105 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5109 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5110 onmouseout='postMouseOut($id)'";
5112 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5114 print "<td class='hlUpdPic'>$update_pic</td>";
5116 print "<td class='hlSelectRow'>
5117 <input type=\"checkbox\" onclick=\"tSR(this)\"
5121 print "<td class='hlMarkedPic'>$marked_pic</td>";
5122 print "<td class='hlMarkedPic'>$published_pic</td>";
5124 # if ($line["feed_title"]) {
5125 # print "<td class='hlContent'>$content_link</td>";
5126 # print "<td class='hlFeed'>
5127 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5128 # truncate_string($line["feed_title"],30)."</a> </td>";
5131 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5133 print "<a id=\"RTITLE-$id\"
5134 href=\"" . htmlspecialchars($line["link"]) . "\"
5135 onclick=\"return view($id,$feed_id);\">" .
5138 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5139 if ($content_preview) {
5140 print "<span class=\"contentPreview\"> - $content_preview</span>";
5148 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5149 # $line["feed_title"]."</a>
5151 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5152 if ($line["feed_title"]) {
5153 print "<span class=\"hlFeed\">
5154 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5155 $line["feed_title"]."</a>)
5163 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5165 print "<td class='hlMarkedPic'>$score_pic</td>";
5167 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5168 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5175 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5176 if ($feed_id != $vgroup_last_feed) {
5178 $cur_feed_title = $line["feed_title"];
5179 $vgroup_last_feed = $feed_id;
5181 $cur_feed_title = htmlspecialchars($cur_feed_title);
5183 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5185 $has_feed_icon = feed_has_icon($feed_id);
5187 if ($has_feed_icon) {
5188 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5190 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5193 print "<div class='cdmFeedTitle'>".
5194 "<div style=\"float : right\">$feed_icon_img</div>".
5195 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5196 $line["feed_title"]."</a> $vf_catchup_link</div>";
5201 $add_class = "Unread";
5206 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5207 $show_excerpt = false;
5209 if ($expand_cdm && $score >= -100) {
5211 $show_excerpt = false;
5213 $cdm_cstyle = "style=\"display : none\"";
5214 $show_excerpt = true;
5217 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5218 onmouseout='postMouseOut($id)'";
5220 print "<div class=\"cdmArticle$add_class\"
5222 $mouseover_attrs'>";
5224 print "<div class=\"cdmHeader\">";
5226 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5227 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5230 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5233 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5234 onclick=\"javascript:toggleUnread($id, 0)\"
5235 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5238 print $entry_author;
5240 /* if (!$expand_cdm || $score < -100) {
5241 print " <a id=\"CICH-$id\"
5242 href=\"javascript:cdmExpandArticle($id)\">
5243 (".__('Show article').")</a>";
5248 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5249 if ($line["feed_title"]) {
5250 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5254 print "</span></div>";
5256 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5257 $line["content_preview"] = preg_replace("/href=/i",
5258 "target=\"_blank\" href=", $line["content_preview"]);
5261 if ($show_excerpt) {
5262 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5263 onclick=\"cdmExpandArticle($id)\"
5264 title=\"".__('Click to expand article')."\">";
5265 print truncate_string(strip_tags($line["content_preview"]), 100);
5269 print "<div class=\"cdmContent\"
5270 onclick=\"cdmClicked($id)\"
5271 id=\"CICD-$id\" $cdm_cstyle>";
5273 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5275 print sanitize_rss($link, $line["content_preview"]);
5276 $article_content = $line["content_preview"];
5278 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5279 post_id = '$id' AND content_url != ''");
5281 if (db_num_rows($e_result) > 0) {
5283 $entries_html = array();
5286 while ($e_line = db_fetch_assoc($e_result)) {
5288 $url = $e_line["content_url"];
5289 $ctype = $e_line["content_type"];
5290 if (!$ctype) $ctype = __("unknown type");
5292 $filename = substr($url, strrpos($url, "/")+
1);
5296 if (($ctype == __("audio/mpeg")) &&
5297 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5299 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
5303 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5304 $filename . " (" . $ctype . ")" . "</a>";
5306 array_push($entries_html, $entry);
5310 $entry["type"] = $ctype;
5311 $entry["filename"] = $filename;
5312 $entry["url"] = $url;
5314 array_push($entries, $entry);
5317 if (!preg_match("/img/i", $article_content)) {
5318 foreach ($entries as $entry) {
5319 if (preg_match("/image/", $entry["type"])) {
5321 alt=\"".htmlspecialchars($entry["filename"])."\"
5322 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5327 print "<div class=\"cdmEnclosures\">";
5329 if (db_num_rows($e_result) == 1) {
5330 print __("Attachment:") . " ";
5332 print __("Attachments:") . " ";
5335 print join(", ", $entries_html);
5341 print "<br clear='both'>";
5344 /* if (!$expand_cdm) {
5345 print "<a id=\"CICH-$id\"
5346 href=\"javascript:cdmExpandArticle($id)\">
5352 print "<div class=\"cdmFooter\"><span class='s0'>";
5354 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5356 print __("Select:").
5357 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5358 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5360 print "</span><span class='s1'>$marked_pic</span> ";
5361 print "<span class='s1'>$published_pic</span> ";
5362 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5363 onclick=\"zoomToArticle($id)\"
5364 style=\"cursor : pointer\"
5366 title='".__('Show article summary in new window')."'></span>";
5368 $tags = get_article_tags($link, $id);
5371 $full_tags_str = "";
5374 foreach ($tags as $tag) {
5376 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5377 if ($num_tags < 5) {
5378 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5379 } else if ($num_tags == 5) {
5380 $tags_str .= "…";
5384 $tags_str = preg_replace("/, $/", "", $tags_str);
5385 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5387 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5389 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5392 if ($tags_str == "") $tags_str = "no tags";
5394 // print "<img src='images/tag.png' class='markedPic'>";
5396 print "<span class='s1'>
5397 <img class='tagsPic' src='images/tag.png' alt='Tags'
5398 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5399 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5403 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5404 href=\"javascript:toggleUnread($id)\">
5415 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5422 switch ($view_mode) {
5424 $message = __("No unread articles found to display.");
5427 $message = __("No updated articles found to display.");
5430 $message = __("No starred articles found to display.");
5434 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5436 $message = __("No articles found to display.");
5440 if (!$offset) print "<div class='whiteBox'>$message</div>";
5448 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5451 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5453 function printTagCloud($link) {
5455 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5456 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5457 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5459 $result = db_query($link, $query);
5463 while ($line = db_fetch_assoc($result)) {
5464 $tags[$line["tag_name"]] = $line["count"];
5469 $max_size = 32; // max font size in pixels
5470 $min_size = 11; // min font size in pixels
5472 // largest and smallest array values
5473 $max_qty = max(array_values($tags));
5474 $min_qty = min(array_values($tags));
5476 // find the range of values
5477 $spread = $max_qty - $min_qty;
5478 if ($spread == 0) { // we don't want to divide by zero
5482 // set the font-size increment
5483 $step = ($max_size - $min_size) / ($spread);
5485 // loop through the tag array
5486 foreach ($tags as $key => $value) {
5487 // calculate font-size
5488 // find the $value in excess of $min_qty
5489 // multiply by the font-size increment ($size)
5490 // and add the $min_size set above
5491 $size = round($min_size +
(($value - $min_qty) * $step));
5493 $key_escaped = str_replace("'", "\\'", $key);
5495 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5496 $size . "px\" title=\"$value articles tagged with " .
5497 $key . '">' . $key . '</a> ';
5501 function print_checkpoint($n, $s) {
5502 $ts = getmicrotime();
5503 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5507 function sanitize_tag($tag) {
5510 $tag = mb_strtolower($tag, 'utf-8');
5512 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5514 // $tag = str_replace('"', "", $tag);
5515 // $tag = str_replace("+", " ", $tag);
5516 $tag = str_replace("technorati tag: ", "", $tag);
5521 function generate_publish_key() {
5522 return sha1(uniqid(rand(), true));
5525 function article_publish_url($link) {
5530 if ($_SERVER['HTTPS'] != "on") {
5531 $url_path = "http://";
5533 $url_path = "https://";
5536 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5537 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5543 * Purge a feed contents, marked articles excepted.
5545 * @param mixed $link The database connection.
5546 * @param integer $id The id of the feed to purge.
5549 function clear_feed_articles($link, $id) {
5550 $result = db_query($link, "DELETE FROM ttrss_user_entries
5551 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5553 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5554 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5556 ccache_update($link, $id, $_SESSION['uid']);
5557 } // function clear_feed_articles
5560 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5562 * @return string The Mozilla Firefox feed adding URL.
5564 function add_feed_url() {
5565 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5566 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5568 } // function add_feed_url
5571 * Encrypt a password in SHA1.
5573 * @param string $pass The password to encrypt.
5574 * @param string $login A optionnal login.
5575 * @return string The encrypted password.
5577 function encrypt_password($pass, $login = '') {
5579 return "SHA1X:" . sha1("$login:$pass");
5581 return "SHA1:" . sha1($pass);
5583 } // function encrypt_password
5586 * Update a feed batch.
5587 * Used by daemons to update n feeds by run.
5588 * Only update feed needing a update, and not being processed
5589 * by another process.
5591 * @param mixed $link Database link
5592 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5593 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5594 * @param boolean $debug Set to false to disable debug output. Default to true.
5597 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5598 // Process all other feeds using last_updated and interval parameters
5600 // Test if the user has loggued in recently. If not, it does not update its feeds.
5601 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5602 if (DB_TYPE
== "pgsql") {
5603 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5605 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5608 $login_thresh_qpart = "";
5611 // Test if the feed need a update (update interval exceded).
5612 if (DB_TYPE
== "pgsql") {
5613 $update_limit_qpart = "AND ((
5614 ttrss_feeds.update_interval = 0
5615 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5617 ttrss_feeds.update_interval > 0
5618 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5619 ) OR ttrss_feeds.last_updated IS NULL)";
5621 $update_limit_qpart = "AND ((
5622 ttrss_feeds.update_interval = 0
5623 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5625 ttrss_feeds.update_interval > 0
5626 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5627 ) OR ttrss_feeds.last_updated IS NULL)";
5630 // Test if feed is currently being updated by another process.
5631 if (DB_TYPE
== "pgsql") {
5632 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5634 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5637 // Test if there is a limit to number of updated feeds
5639 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5641 $random_qpart = sql_random_function();
5643 // We search for feed needing update.
5644 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5645 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5646 ttrss_feeds.update_interval
5648 ttrss_feeds, ttrss_users, ttrss_user_prefs
5650 ttrss_feeds.owner_uid = ttrss_users.id
5651 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5652 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5653 $login_thresh_qpart $update_limit_qpart
5654 $updstart_thresh_qpart
5655 ORDER BY $random_qpart $query_limit");
5657 $user_prefs_cache = array();
5659 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5661 // Here is a little cache magic in order to minimize risk of double feed updates.
5662 $feeds_to_update = array();
5663 while ($line = db_fetch_assoc($result)) {
5664 $feeds_to_update[$line['id']] = $line;
5667 // We update the feed last update started date before anything else.
5668 // There is no lag due to feed contents downloads
5669 // It prevent an other process to update the same feed.
5670 $feed_ids = array_keys($feeds_to_update);
5672 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5673 WHERE id IN (%s)", implode(',', $feed_ids)));
5676 // For each feed, we call the feed update function.
5677 while ($line = array_pop($feeds_to_update)) {
5679 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5681 // We setup a alarm to alert if the feed take more than 300s to update.
5683 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5684 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5685 // Cancel the alarm (the update went well)
5686 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5688 sleep(1); // prevent flood (FIXME make this an option?)
5691 // Send feed digests by email if needed.
5692 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5694 purge_orphans($link);
5696 } // function update_daemon_common
5698 function sanitize_article_content($text) {
5699 # we don't support CDATA sections in articles, they break our own escaping
5700 $text = preg_replace("/\[\[CDATA/", "", $text);
5701 $text = preg_replace("/\]\]\>/", "", $text);
5705 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5708 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5710 $result = db_query($link, "SELECT reg_exp,
5711 ttrss_filter_types.name AS name,
5712 ttrss_filter_actions.name AS action,
5716 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5719 owner_uid = $owner_uid AND
5720 ttrss_filter_types.id = filter_type AND
5721 ttrss_filter_actions.id = action_id AND
5722 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5724 while ($line = db_fetch_assoc($result)) {
5725 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5726 $filter["reg_exp"] = $line["reg_exp"];
5727 $filter["action"] = $line["action"];
5728 $filter["action_param"] = $line["action_param"];
5729 $filter["filter_param"] = $line["filter_param"];
5730 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5732 array_push($filters[$line["name"]], $filter);
5738 function get_score_pic($score) {
5740 return "score_high.png";
5741 } else if ($score > 0) {
5742 return "score_half_high.png";
5743 } else if ($score < -100) {
5744 return "score_low.png";
5745 } else if ($score < 0) {
5746 return "score_half_low.png";
5748 return "score_neutral.png";
5752 function rounded_table_start($classname, $header = " ") {
5753 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5754 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5755 print "<tr><td class='left'> </td><td class='content'>";
5758 function rounded_table_end($footer = " ") {
5759 print "</td><td class='right'> </td></tr>";
5760 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5764 function feed_has_icon($id) {
5765 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5768 function init_connection($link) {
5769 if (DB_TYPE
== "pgsql") {
5770 pg_query($link, "set client_encoding = 'UTF-8'");
5771 pg_set_client_encoding("UNICODE");
5772 pg_query($link, "set datestyle = 'ISO, european'");
5774 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5775 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5776 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5781 function update_feedbrowser_cache($link) {
5783 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5784 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5785 WHERE tf.feed_url = ttrss_feeds.feed_url
5786 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5787 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5789 db_query($link, "BEGIN");
5791 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5795 while ($line = db_fetch_assoc($result)) {
5796 $subscribers = db_escape_string($line["subscribers"]);
5797 $feed_url = db_escape_string($line["feed_url"]);
5798 $title = db_escape_string($line["title"]);
5800 $tmp_result = db_query($link, "SELECT subscribers FROM
5801 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5803 if (db_num_rows($tmp_result) == 0) {
5805 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5806 (feed_url, title, subscribers) VALUES ('$feed_url',
5807 '$title', '$subscribers')");
5815 db_query($link, "COMMIT");
5821 function ccache_zero($link, $feed_id, $owner_uid) {
5822 db_query($link, "UPDATE ttrss_counters_cache SET
5823 value = 0, updated = NOW() WHERE
5824 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5827 function ccache_zero_all($link, $owner_uid) {
5828 db_query($link, "UPDATE ttrss_counters_cache SET
5829 value = 0 WHERE owner_uid = '$owner_uid'");
5831 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5832 value = 0 WHERE owner_uid = '$owner_uid'");
5835 function ccache_update_all($link, $owner_uid) {
5837 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5839 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5840 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5842 while ($line = db_fetch_assoc($result)) {
5843 ccache_update($link, $line["feed_id"], $owner_uid, true);
5846 /* We have to manually include category 0 */
5848 ccache_update($link, 0, $owner_uid, true);
5851 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5852 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5854 while ($line = db_fetch_assoc($result)) {
5855 print ccache_update($link, $line["feed_id"], $owner_uid);
5862 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5863 $no_update = false) {
5866 $table = "ttrss_counters_cache";
5868 $table = "ttrss_cat_counters_cache";
5871 if (DB_TYPE
== "pgsql") {
5872 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5873 } else if (DB_TYPE
== "mysql") {
5874 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5877 $result = db_query($link, "SELECT value FROM $table
5878 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5881 if (db_num_rows($result) == 1) {
5882 return db_fetch_result($result, 0, "value");
5887 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5893 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5894 $update_pcat = true) {
5896 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5898 /* When updating a label, all we need to do is recalculate feed counters
5899 * because labels are not cached */
5902 ccache_update_all($link, $owner_uid);
5907 $table = "ttrss_counters_cache";
5909 $table = "ttrss_cat_counters_cache";
5912 if ($is_cat && $feed_id >= 0) {
5913 if ($feed_id != 0) {
5914 $cat_qpart = "cat_id = '$feed_id'";
5916 $cat_qpart = "cat_id IS NULL";
5919 /* Recalculate counters for child feeds */
5921 $result = db_query($link, "SELECT id FROM ttrss_feeds
5922 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5924 while ($line = db_fetch_assoc($result)) {
5925 ccache_update($link, $line["id"], $owner_uid, false, false);
5928 $result = db_query($link, "SELECT SUM(value) AS sv
5929 FROM ttrss_counters_cache, ttrss_feeds
5930 WHERE id = feed_id AND $cat_qpart AND
5931 ttrss_feeds.owner_uid = '$owner_uid'");
5933 $unread = (int) db_fetch_result($result, 0, "sv");
5936 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5939 $result = db_query($link, "SELECT feed_id FROM $table
5940 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5942 if (db_num_rows($result) == 1) {
5943 db_query($link, "UPDATE $table SET
5944 value = '$unread', updated = NOW() WHERE
5945 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5948 db_query($link, "INSERT INTO $table
5949 (feed_id, value, owner_uid, updated)
5951 ($feed_id, $unread, $owner_uid, NOW())");
5954 if ($feed_id > 0 && $prev_unread != $unread) {
5958 /* Update parent category */
5962 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5963 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5965 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5967 ccache_update($link, $cat_id, $owner_uid, true);
5971 } else if ($feed_id < 0) {
5972 ccache_update_all($link, $owner_uid);
5978 function label_find_id($link, $label, $owner_uid) {
5979 $result = db_query($link,
5980 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5981 AND owner_uid = '$owner_uid' LIMIT 1");
5983 if (db_num_rows($result) == 1) {
5984 return db_fetch_result($result, 0, "id");
5990 function get_article_labels($link, $id) {
5991 $result = db_query($link,
5992 "SELECT DISTINCT label_id,caption
5993 FROM ttrss_labels2, ttrss_user_labels2
5995 AND article_id = '$id'
5996 AND owner_uid = ".$_SESSION["uid"] . "
6001 while ($line = db_fetch_assoc($result)) {
6002 $rk = array($line["label_id"], $line["caption"]);
6003 array_push($rv, $rk);
6010 function label_find_caption($link, $label, $owner_uid) {
6011 $result = db_query($link,
6012 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6013 AND owner_uid = '$owner_uid' LIMIT 1");
6015 if (db_num_rows($result) == 1) {
6016 return db_fetch_result($result, 0, "caption");
6022 function label_remove_article($link, $id, $label, $owner_uid) {
6024 $label_id = label_find_id($link, $label, $owner_uid);
6026 if (!$label_id) return;
6028 $result = db_query($link,
6029 "DELETE FROM ttrss_user_labels2
6031 label_id = '$label_id' AND
6032 article_id = '$id'");
6035 function label_add_article($link, $id, $label, $owner_uid) {
6037 $label_id = label_find_id($link, $label, $owner_uid);
6039 if (!$label_id) return;
6041 $result = db_query($link,
6043 article_id FROM ttrss_labels2, ttrss_user_labels2
6046 label_id = '$label_id' AND
6047 article_id = '$id' AND owner_uid = '$owner_uid'
6050 if (db_num_rows($result) == 0) {
6051 db_query($link, "INSERT INTO ttrss_user_labels2
6052 (label_id, article_id) VALUES ('$label_id', '$id')");
6056 function label_remove($link, $id, $owner_uid) {
6058 db_query($link, "BEGIN");
6060 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6063 $caption = db_fetch_result($result, 0, "caption");
6065 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6066 AND owner_uid = " . $_SESSION["uid"]);
6068 if (db_affected_rows($link, $result) != 0 && $caption) {
6070 /* Disable filters that reference label being removed */
6072 db_query($link, "UPDATE ttrss_filters SET
6073 enabled = false WHERE action_param = '$caption'
6075 AND owner_uid = " . $_SESSION["uid"]);
6078 db_query($link, "COMMIT");