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);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if (!$owner_uid) return;
150 if (FORCE_ARTICLE_PURGE
== 0) {
151 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
154 $purge_unread = true;
155 $purge_interval = FORCE_ARTICLE_PURGE
;
158 if (!$purge_unread) $query_limit = " unread = false AND ";
160 if (DB_TYPE
== "pgsql") {
161 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
162 marked = false AND feed_id = '$feed_id' AND
163 (SELECT date_entered FROM ttrss_entries WHERE
164 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
166 $pg_version = get_pgsql_version($link);
168 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
170 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
171 ttrss_entries.id = ref_id AND
173 feed_id = '$feed_id' AND
175 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
179 $result = db_query($link, "DELETE FROM ttrss_user_entries
181 WHERE ttrss_entries.id = ref_id AND
183 feed_id = '$feed_id' AND
185 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
188 $rows = pg_affected_rows($result);
192 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
193 marked = false AND feed_id = '$feed_id' AND
194 (SELECT date_entered FROM ttrss_entries WHERE
195 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
197 $result = db_query($link, "DELETE FROM ttrss_user_entries
198 USING ttrss_user_entries, ttrss_entries
199 WHERE ttrss_entries.id = ref_id AND
201 feed_id = '$feed_id' AND
203 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
205 $rows = mysql_affected_rows($link);
209 ccache_update($link, $feed_id, $owner_uid);
212 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
214 } // function purge_feed
217 * Purge old posts from old feeds.
219 * @param mixed $link A database connection
220 * @param boolean $do_output Set to true to enable printed output, false by default.
221 * @param integer $limit The maximal number of removed posts.
225 function global_purge_old_posts($link, $do_output = false, $limit = false) {
227 $random_qpart = sql_random_function();
230 $limit_qpart = "LIMIT $limit";
235 $result = db_query($link,
236 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
237 ORDER BY $random_qpart $limit_qpart");
239 while ($line = db_fetch_assoc($result)) {
241 $feed_id = $line["id"];
242 $purge_interval = $line["purge_interval"];
243 $owner_uid = $line["owner_uid"];
245 if ($purge_interval == 0) {
247 $tmp_result = db_query($link,
248 "SELECT value FROM ttrss_user_prefs WHERE
249 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
251 if (db_num_rows($tmp_result) != 0) {
252 $purge_interval = db_fetch_result($tmp_result, 0, "value");
257 // print "Feed $feed_id: purge interval = $purge_interval\n";
260 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE
) {
261 purge_feed($link, $feed_id, $purge_interval, $do_output);
265 // purge orphaned posts in main content table
266 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
267 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
270 $rows = db_affected_rows($link, $result);
271 _debug("Purged $rows orphaned posts.");
274 } // function global_purge_old_posts
276 function feed_purge_interval($link, $feed_id) {
278 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
279 WHERE id = '$feed_id'");
281 if (db_num_rows($result) == 1) {
282 $purge_interval = db_fetch_result($result, 0, "purge_interval");
283 $owner_uid = db_fetch_result($result, 0, "owner_uid");
285 if ($purge_interval == 0) $purge_interval = get_pref($link,
286 'PURGE_OLD_DAYS', $owner_uid);
288 return $purge_interval;
295 function purge_old_posts($link) {
297 $user_id = $_SESSION["uid"];
299 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
300 WHERE owner_uid = '$user_id'");
302 while ($line = db_fetch_assoc($result)) {
304 $feed_id = $line["id"];
305 $purge_interval = $line["purge_interval"];
307 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
309 if ($purge_interval > 0) {
310 purge_feed($link, $feed_id, $purge_interval);
314 purge_orphans($link);
317 function purge_orphans($link) {
318 // purge orphaned posts in main content table
319 db_query($link, "DELETE FROM ttrss_entries WHERE
320 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
323 function get_feed_update_interval($link, $feed_id) {
324 $result = db_query($link, "SELECT owner_uid, update_interval FROM
325 ttrss_feeds WHERE id = '$feed_id'");
327 if (db_num_rows($result) == 1) {
328 $update_interval = db_fetch_result($result, 0, "update_interval");
329 $owner_uid = db_fetch_result($result, 0, "owner_uid");
331 if ($update_interval != 0) {
332 return $update_interval;
334 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
342 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
344 if (WEB_DEMO_MODE
) return;
347 $user_id = $_SESSION["uid"];
348 purge_old_posts($link);
351 // db_query($link, "BEGIN");
353 if (MAX_UPDATE_TIME
> 0) {
354 if (DB_TYPE
== "mysql") {
357 $q_order = "RANDOM()";
360 $q_order = "last_updated DESC";
363 $result = db_query($link, "SELECT feed_url,id,
364 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated,
365 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
370 while ($line = db_fetch_assoc($result)) {
371 $upd_intl = $line["update_interval"];
373 if (!$upd_intl ||
$upd_intl == 0) {
374 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
378 // Updates for this feed are disabled
382 if ($fetch ||
(!$line["last_updated"] ||
383 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
385 // print "<!-- feed: ".$line["feed_url"]." -->";
387 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
389 $upd_elapsed = time() - $upd_start;
391 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
397 // db_query($link, "COMMIT");
401 function fetch_file_contents($url) {
402 if (USE_CURL_FOR_ICONS
) {
403 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
405 $ch = curl_init($url);
406 $fp = fopen($tmpfile, "w");
409 curl_setopt($ch, CURLOPT_FILE
, $fp);
410 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
411 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
417 $contents = file_get_contents($tmpfile);
423 return file_get_contents($url);
429 * Try to determine the favicon URL for a feed.
430 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
431 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
433 * @param string $url A feed or page URL
435 * @return mixed The favicon URL, or false if none was found.
437 function get_favicon_url($url) {
439 if ($html = @fetch_file_contents
($url)) {
441 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
442 // Attempt to grab a favicon link from their webpage url
443 $linkUrl = html_entity_decode($matches[1]);
445 if (substr($linkUrl, 0, 1) == '/') {
446 $urlParts = parse_url($url);
447 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
448 } else if (substr($linkUrl, 0, 7) == 'http://') {
449 $faviconURL = $linkUrl;
450 } else if (substr($url, -1, 1) == '/') {
451 $faviconURL = $url.$linkUrl;
453 $faviconURL = $url.'/'.$linkUrl;
457 // If unsuccessful, attempt to "guess" the favicon location
458 $urlParts = parse_url($url);
459 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
463 // Run a test to see if what we have attempted to get actually exists.
464 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
469 } // function get_favicon_url
472 * Check if a link is a valid and working URL.
474 * @param mixed $link A URL to check
476 * @return boolean True if the URL is valid, false otherwise.
478 function url_validate($link) {
480 $url_parts = @parse_url
($link);
482 if ( empty( $url_parts["host"] ) )
485 if ( !empty( $url_parts["path"] ) ) {
486 $documentpath = $url_parts["path"];
491 if ( !empty( $url_parts["query"] ) )
492 $documentpath .= "?" . $url_parts["query"];
494 $host = $url_parts["host"];
495 $port = $url_parts["port"];
500 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
505 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
507 $http_response = fgets( $socket, 22 );
509 $responses = "/(200 OK)|(30[0-9] Moved)/";
510 if ( preg_match($responses, $http_response) ) {
517 } // function url_validate
519 function check_feed_favicon($site_url, $feed, $link) {
520 $favicon_url = get_favicon_url($site_url);
522 # print "FAVICON [$site_url]: $favicon_url\n";
526 $icon_file = ICONS_DIR
. "/$feed.ico";
528 if ($favicon_url && !file_exists($icon_file)) {
529 $contents = fetch_file_contents($favicon_url);
531 $fp = fopen($icon_file, "w");
534 fwrite($fp, $contents);
536 chmod($icon_file, 0644);
540 error_reporting(DEFAULT_ERROR_LEVEL
);
544 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
546 if (!$_GET["daemon"] && !$ignore_daemon) {
550 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
551 _debug("update_rss_feed: start");
554 if (!$ignore_daemon) {
556 if (DB_TYPE
== "pgsql") {
557 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
559 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
562 $result = db_query($link, "SELECT id,update_interval,auth_login,
563 auth_pass,cache_images,update_method
564 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
568 $result = db_query($link, "SELECT id,update_interval,auth_login,
569 auth_pass,cache_images,update_method,hidden
570 FROM ttrss_feeds WHERE id = '$feed'");
574 if (db_num_rows($result) == 0) {
575 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
576 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
581 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
582 $update_method = db_fetch_result($result, 0, "update_method");
584 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
585 WHERE id = '$feed'");
587 $auth_login = db_fetch_result($result, 0, "auth_login");
588 $auth_pass = db_fetch_result($result, 0, "auth_pass");
590 if (ALLOW_SELECT_UPDATE_METHOD
) {
591 if (ENABLE_SIMPLEPIE
) {
592 $use_simplepie = $update_method != 1;
594 $use_simplepie = $update_method == 2;
597 $use_simplepie = ENABLE_SIMPLEPIE
;
600 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
601 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
604 if (!$use_simplepie) {
605 $auth_login = urlencode($auth_login);
606 $auth_pass = urlencode($auth_pass);
609 $update_interval = db_fetch_result($result, 0, "update_interval");
610 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
612 if ($update_interval < 0) { return; }
614 $feed = db_escape_string($feed);
616 $fetch_url = $feed_url;
618 if ($auth_login && $auth_pass) {
619 $url_parts = array();
620 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
622 if ($url_parts[1] && $url_parts[2]) {
623 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
628 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
629 _debug("update_rss_feed: fetching [$fetch_url]...");
632 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
636 if (!$use_simplepie) {
637 $rss = fetch_rss($fetch_url);
639 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
640 mkdir(SIMPLEPIE_CACHE_DIR
);
643 $rss = new SimplePie();
644 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
645 # $rss->set_timeout(10);
646 $rss->set_feed_url($fetch_url);
647 $rss->set_output_encoding('UTF-8');
649 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
650 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
651 _debug("enabling image cache");
654 $rss->set_image_handler('./image.php', 'i');
657 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
658 _debug("feed update interval (sec): " .
659 get_feed_update_interval($link, $feed)*60);
662 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
663 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
664 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
672 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
673 _debug("update_rss_feed: fetch done, parsing...");
675 error_reporting (DEFAULT_ERROR_LEVEL
);
678 $feed = db_escape_string($feed);
680 if ($use_simplepie) {
681 $fetch_ok = !$rss->error();
688 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
689 _debug("update_rss_feed: processing feed data...");
692 // db_query($link, "BEGIN");
694 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
695 FROM ttrss_feeds WHERE id = '$feed'");
697 $registered_title = db_fetch_result($result, 0, "title");
698 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
699 $orig_site_url = db_fetch_result($result, 0, "site_url");
701 $owner_uid = db_fetch_result($result, 0, "owner_uid");
703 if ($use_simplepie) {
704 $site_url = $rss->get_link();
706 $site_url = $rss->channel
["link"];
709 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
710 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
711 _debug("update_rss_feed: checking favicon...");
714 check_feed_favicon($site_url, $feed, $link);
717 if (!$registered_title ||
$registered_title == "[Unknown]") {
719 if ($use_simplepie) {
720 $feed_title = db_escape_string($rss->get_title());
722 $feed_title = db_escape_string($rss->channel
["title"]);
725 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
726 _debug("update_rss_feed: registering title: $feed_title");
729 db_query($link, "UPDATE ttrss_feeds SET
730 title = '$feed_title' WHERE id = '$feed'");
733 // weird, weird Magpie
734 if (!$use_simplepie) {
735 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
738 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
739 db_query($link, "UPDATE ttrss_feeds SET
740 site_url = '$site_url' WHERE id = '$feed'");
743 // print "I: " . $rss->channel["image"]["url"];
745 if (!$use_simplepie) {
746 $icon_url = $rss->image
["url"];
748 $icon_url = $rss->get_image_url();
751 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
752 $icon_url = db_escape_string($icon_url);
753 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
756 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
757 _debug("update_rss_feed: loading filters...");
760 $filters = load_filters($link, $feed, $owner_uid);
762 if ($use_simplepie) {
763 $iterator = $rss->get_items();
765 $iterator = $rss->items
;
766 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
767 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
770 if (!is_array($iterator)) {
771 /* db_query($link, "UPDATE ttrss_feeds
772 SET last_error = 'Parse error: can\'t find any articles.'
773 WHERE id = '$feed'"); */
775 // clear any errors and mark feed as updated if fetched okay
776 // even if it's blank
778 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
779 _debug("update_rss_feed: entry iterator is not an array, no articles?");
782 db_query($link, "UPDATE ttrss_feeds
783 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
785 return; // no articles
788 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
789 _debug("update_rss_feed: processing articles...");
792 foreach ($iterator as $item) {
794 if ($_GET['xdebug']) {
799 if ($use_simplepie) {
800 $entry_guid = $item->get_id();
801 if (!$entry_guid) $entry_guid = $item->get_link();
802 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
806 $entry_guid = $item["id"];
808 if (!$entry_guid) $entry_guid = $item["guid"];
809 if (!$entry_guid) $entry_guid = $item["link"];
810 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
813 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
814 _debug("update_rss_feed: guid $entry_guid");
817 if (!$entry_guid) continue;
819 $entry_timestamp = "";
821 if ($use_simplepie) {
822 $entry_timestamp = strtotime($item->get_date());
824 $rss_2_date = $item['pubdate'];
825 $rss_1_date = $item['dc']['date'];
826 $atom_date = $item['issued'];
827 if (!$atom_date) $atom_date = $item['updated'];
829 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
830 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
831 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
834 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
835 $entry_timestamp = time();
836 $no_orig_date = 'true';
838 $no_orig_date = 'false';
841 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
843 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
844 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
847 if ($use_simplepie) {
848 $entry_title = $item->get_title();
850 $entry_title = trim(strip_tags($item["title"]));
853 if ($use_simplepie) {
854 $entry_link = $item->get_link();
856 // strange Magpie workaround
857 $entry_link = $item["link_"];
858 if (!$entry_link) $entry_link = $item["link"];
861 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
862 _debug("update_rss_feed: title $entry_title");
865 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
867 $entry_link = strip_tags($entry_link);
869 if ($use_simplepie) {
870 $entry_content = $item->get_content();
871 if (!$entry_content) $entry_content = $item->get_description();
873 $entry_content = $item["content:escaped"];
875 if (!$entry_content) $entry_content = $item["content:encoded"];
876 if (!$entry_content) $entry_content = $item["content"]["encoded"];
877 if (!$entry_content) $entry_content = $item["content"];
879 // Magpie bugs are getting ridiculous
880 if (trim($entry_content) == "Array") $entry_content = false;
882 if (!$entry_content) $entry_content = $item["atom_content"];
883 if (!$entry_content) $entry_content = $item["summary"];
885 if (!$entry_content ||
886 strlen($entry_content) < strlen($item["description"])) {
887 $entry_content = $item["description"];
891 if (is_array($entry_content)) {
892 $entry_content = $entry_content["encoded"];
893 if (!$entry_content) $entry_content = $entry_content["escaped"];
897 if ($_GET["xdebug"]) {
898 print "update_rss_feed: content: ";
899 print_r(htmlspecialchars($entry_content));
902 $entry_content_unescaped = $entry_content;
904 if ($use_simplepie) {
905 $entry_comments = strip_tags($item->data
["comments"]);
906 if ($item->get_author()) {
907 $entry_author_item = $item->get_author();
908 $entry_author = $entry_author_item->get_name();
909 if (!$entry_author) $entry_author = $entry_author_item->get_email();
911 $entry_author = db_escape_string($entry_author);
914 $entry_comments = strip_tags($item["comments"]);
916 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
918 if ($item['author']) {
920 if (is_array($item['author'])) {
922 if (!$entry_author) {
923 $entry_author = db_escape_string(strip_tags($item['author']['name']));
926 if (!$entry_author) {
927 $entry_author = db_escape_string(strip_tags($item['author']['email']));
931 if (!$entry_author) {
932 $entry_author = db_escape_string(strip_tags($item['author']));
937 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
939 $entry_guid = db_escape_string(strip_tags($entry_guid));
940 $entry_guid = mb_substr($entry_guid, 0, 250);
942 $result = db_query($link, "SELECT id FROM ttrss_entries
943 WHERE guid = '$entry_guid'");
945 $entry_content = db_escape_string($entry_content);
947 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
949 $entry_title = db_escape_string($entry_title);
950 $entry_link = db_escape_string($entry_link);
951 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
952 $entry_author = mb_substr($entry_author, 0, 250);
954 if ($use_simplepie) {
955 $num_comments = 0; #FIXME#
957 $num_comments = db_escape_string($item["slash"]["comments"]);
960 if (!$num_comments) $num_comments = 0;
962 // parse <category> entries into tags
964 if ($use_simplepie) {
966 $additional_tags = array();
967 $additional_tags_src = $item->get_categories();
969 if (is_array($additional_tags_src)) {
970 foreach ($additional_tags_src as $tobj) {
971 array_push($additional_tags, $tobj->get_term());
975 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
976 _debug("update_rss_feed: category tags:");
977 print_r($additional_tags);
982 $t_ctr = $item['category#'];
984 $additional_tags = false;
987 $additional_tags = false;
988 } else if ($t_ctr > 0) {
989 $additional_tags = array($item['category']);
991 if ($item['category@term']) {
992 array_push($additional_tags, $item['category@term']);
995 for ($i = 0; $i <= $t_ctr; $i++
) {
996 if ($item["category#$i"]) {
997 array_push($additional_tags, $item["category#$i"]);
1000 if ($item["category#$i@term"]) {
1001 array_push($additional_tags, $item["category#$i@term"]);
1006 // parse <dc:subject> elements
1008 $t_ctr = $item['dc']['subject#'];
1011 $additional_tags = array($item['dc']['subject']);
1013 for ($i = 0; $i <= $t_ctr; $i++
) {
1014 if ($item['dc']["subject#$i"]) {
1015 array_push($additional_tags, $item['dc']["subject#$i"]);
1023 $enclosures = array();
1025 if ($use_simplepie) {
1026 $encs = $item->get_enclosures();
1028 if (is_array($encs)) {
1029 foreach ($encs as $e) {
1031 $e->link
, $e->type
, $e->length
);
1033 array_push($enclosures, $e_item);
1040 $e_ctr = $item['enclosure#'];
1043 $e_item = array($item['enclosure@url'],
1044 $item['enclosure@type'],
1045 $item['enclosure@length']);
1047 array_push($enclosures, $e_item);
1049 for ($i = 0; $i <= $e_ctr; $i++
) {
1051 if ($item["enclosure#$i@url"]) {
1052 $e_item = array($item["enclosure#$i@url"],
1053 $item["enclosure#$i@type"],
1054 $item["enclosure#$i@length"]);
1055 array_push($enclosures, $e_item);
1061 // can there be many of those? yes -fox
1063 $m_ctr = $item['media']['content#'];
1066 $e_item = array($item['media']['content@url'],
1067 $item['media']['content@medium'],
1068 $item['media']['content@length']);
1070 array_push($enclosures, $e_item);
1072 for ($i = 0; $i <= $m_ctr; $i++
) {
1074 if ($item["media"]["content#$i@url"]) {
1075 $e_item = array($item["media"]["content#$i@url"],
1076 $item["media"]["content#$i@medium"],
1077 $item["media"]["content#$i@length"]);
1078 array_push($enclosures, $e_item);
1087 $entry_content = sanitize_article_content($entry_content);
1088 $entry_title = sanitize_article_content($entry_title);
1090 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1091 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1094 db_query($link, "BEGIN");
1096 if (db_num_rows($result) == 0) {
1098 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1099 _debug("update_rss_feed: base guid not found");
1102 // base post entry does not exist, create it
1104 $result = db_query($link,
1105 "INSERT INTO ttrss_entries
1121 '$entry_timestamp_fmt',
1130 // we keep encountering the entry in feeds, so we need to
1131 // update date_entered column so that we don't get horrible
1132 // dupes when the entry gets purged and reinserted again e.g.
1133 // in the case of SLOW SLOW OMG SLOW updating feeds
1135 $base_entry_id = db_fetch_result($result, 0, "id");
1137 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1138 WHERE id = '$base_entry_id'");
1141 // now it should exist, if not - bad luck then
1143 $result = db_query($link, "SELECT
1144 id,content_hash,no_orig_date,title,
1145 ".SUBSTRING_FOR_DATE
."(date_entered,1,19) as date_entered,
1146 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1150 WHERE guid = '$entry_guid'");
1155 if (db_num_rows($result) == 1) {
1157 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1158 _debug("update_rss_feed: base guid found, checking for user record");
1161 // this will be used below in update handler
1162 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1163 $orig_title = db_fetch_result($result, 0, "title");
1164 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1165 $orig_date_entered = strtotime(db_fetch_result($result,
1166 0, "date_entered"));
1168 $ref_id = db_fetch_result($result, 0, "id");
1169 $entry_ref_id = $ref_id;
1171 // check for user post link to main table
1173 // do we allow duplicate posts with same GUID in different feeds?
1174 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1175 $dupcheck_qpart = "AND feed_id = '$feed'";
1177 $dupcheck_qpart = "";
1180 // error_reporting(0);
1182 $article_filters = get_article_filters($filters, $entry_title,
1183 $entry_content, $entry_link, $entry_timestamp);
1185 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1186 _debug("update_rss_feed: article filters: ");
1187 if (count($article_filters) != 0) {
1188 print_r($article_filters);
1192 if (find_article_filter($article_filters, "filter")) {
1193 db_query($link, "COMMIT"); // close transaction in progress
1197 // error_reporting (DEFAULT_ERROR_LEVEL);
1199 $score = calculate_article_score($article_filters);
1201 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1202 _debug("update_rss_feed: initial score: $score");
1205 $result = db_query($link,
1206 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1207 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1210 // okay it doesn't exist - create user entry
1211 if (db_num_rows($result) == 0) {
1213 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1214 _debug("update_rss_feed: user record not found, creating...");
1217 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1219 $last_read_qpart = 'NULL';
1222 $last_read_qpart = 'NOW()';
1225 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1231 if (find_article_filter($article_filters, 'publish')) {
1232 $published = 'true';
1234 $published = 'false';
1237 $result = db_query($link,
1238 "INSERT INTO ttrss_user_entries
1239 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1241 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1242 $last_read_qpart, $marked, $published, '$score')");
1244 $result = db_query($link,
1245 "SELECT int_id FROM ttrss_user_entries WHERE
1246 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1247 feed_id = '$feed' LIMIT 1");
1249 if (db_num_rows($result) == 1) {
1250 $entry_int_id = db_fetch_result($result, 0, "int_id");
1253 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1254 $entry_int_id = db_fetch_result($result, 0, "int_id");
1257 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1258 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1261 $post_needs_update = false;
1263 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1264 ($content_hash != $orig_content_hash)) {
1265 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1266 $post_needs_update = true;
1269 if (db_escape_string($orig_title) != $entry_title) {
1270 $post_needs_update = true;
1273 if ($orig_num_comments != $num_comments) {
1274 $post_needs_update = true;
1277 // this doesn't seem to be very reliable
1279 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1280 // $post_needs_update = true;
1283 // if post needs update, update it and mark all user entries
1284 // linking to this post as updated
1285 if ($post_needs_update) {
1287 if (defined('DAEMON_EXTENDED_DEBUG')) {
1288 _debug("update_rss_feed: post $entry_guid needs update...");
1291 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1293 db_query($link, "UPDATE ttrss_entries
1294 SET title = '$entry_title', content = '$entry_content',
1295 content_hash = '$content_hash',
1296 num_comments = '$num_comments'
1297 WHERE id = '$ref_id'");
1299 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1300 db_query($link, "UPDATE ttrss_user_entries
1301 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1303 db_query($link, "UPDATE ttrss_user_entries
1304 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1310 db_query($link, "COMMIT");
1312 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1313 _debug("update_rss_feed: assigning labels...");
1316 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1319 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1320 _debug("update_rss_feed: looking for enclosures...");
1323 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1324 print_r($enclosures);
1327 db_query($link, "BEGIN");
1329 foreach ($enclosures as $enc) {
1330 $enc_url = db_escape_string($enc[0]);
1331 $enc_type = db_escape_string($enc[1]);
1332 $enc_dur = db_escape_string($enc[2]);
1334 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1335 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1337 if (db_num_rows($result) == 0) {
1338 db_query($link, "INSERT INTO ttrss_enclosures
1339 (content_url, content_type, title, duration, post_id) VALUES
1340 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1344 db_query($link, "COMMIT");
1346 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1347 _debug("update_rss_feed: looking for tags...");
1351 // <a href="..." rel="tag">Xorg</a>, //
1355 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1356 $entry_content_unescaped, $entry_tags);
1358 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1359 print_r($entry_tags);
1360 print "<br/></p>"; */
1362 $entry_tags = $entry_tags[1];
1364 # check for manual tags
1366 $tag_filter = find_article_filter($article_filters, "tag");
1370 $manual_tags = trim_array(split(",", $tag_filter[1]));
1372 foreach ($manual_tags as $tag) {
1373 if (tag_is_valid($tag)) {
1374 array_push($entry_tags, $tag);
1379 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1380 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1382 if ($additional_tags && is_array($additional_tags)) {
1383 foreach ($additional_tags as $tag) {
1384 if (tag_is_valid($tag) &&
1385 array_search($tag, $boring_tags) === FALSE) {
1386 array_push($entry_tags, $tag);
1391 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1393 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1394 print_r($entry_tags);
1397 if (count($entry_tags) > 0) {
1399 db_query($link, "BEGIN");
1401 foreach ($entry_tags as $tag) {
1403 $tag = sanitize_tag($tag);
1404 $tag = db_escape_string($tag);
1406 if (!tag_is_valid($tag)) continue;
1408 $result = db_query($link, "SELECT id FROM ttrss_tags
1409 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1410 owner_uid = '$owner_uid' LIMIT 1");
1412 // print db_fetch_result($result, 0, "id");
1414 if ($result && db_num_rows($result) == 0) {
1416 db_query($link, "INSERT INTO ttrss_tags
1417 (owner_uid,tag_name,post_int_id)
1418 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1422 db_query($link, "COMMIT");
1425 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1426 _debug("update_rss_feed: article processed");
1431 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1432 _debug("update_rss_feed: updating counters cache...");
1435 // disabled, purge_feed() does that...
1436 //ccache_update($link, $feed, $owner_uid);
1439 purge_feed($link, $feed, 0);
1441 db_query($link, "UPDATE ttrss_feeds
1442 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1444 // db_query($link, "COMMIT");
1448 if ($use_simplepie) {
1449 $error_msg = mb_substr($rss->error(), 0, 250);
1451 $error_msg = mb_substr(magpie_error(), 0, 250);
1454 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1455 _debug("update_rss_feed: error fetching feed: $error_msg");
1458 $error_msg = db_escape_string($error_msg);
1461 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1462 last_updated = NOW() WHERE id = '$feed'");
1465 if ($use_simplepie) {
1469 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1470 _debug("update_rss_feed: done");
1475 function print_select($id, $default, $values, $attributes = "") {
1476 print "<select name=\"$id\" id=\"$id\" $attributes>";
1477 foreach ($values as $v) {
1483 print "<option$sel>$v</option>";
1488 function print_select_hash($id, $default, $values, $attributes = "") {
1489 print "<select name=\"$id\" id='$id' $attributes>";
1490 foreach (array_keys($values) as $v) {
1492 $sel = 'selected="selected"';
1496 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1502 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1505 if ($filters["title"]) {
1506 foreach ($filters["title"] as $filter) {
1507 $reg_exp = $filter["reg_exp"];
1508 $inverse = $filter["inverse"];
1509 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1510 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1512 array_push($matches, array($filter["action"], $filter["action_param"]));
1517 if ($filters["content"]) {
1518 foreach ($filters["content"] as $filter) {
1519 $reg_exp = $filter["reg_exp"];
1520 $inverse = $filter["inverse"];
1522 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1523 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1525 array_push($matches, array($filter["action"], $filter["action_param"]));
1530 if ($filters["both"]) {
1531 foreach ($filters["both"] as $filter) {
1532 $reg_exp = $filter["reg_exp"];
1533 $inverse = $filter["inverse"];
1536 if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1537 array_push($matches, array($filter["action"], $filter["action_param"]));
1540 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1541 array_push($matches, array($filter["action"], $filter["action_param"]));
1547 if ($filters["link"]) {
1548 $reg_exp = $filter["reg_exp"];
1549 foreach ($filters["link"] as $filter) {
1550 $reg_exp = $filter["reg_exp"];
1551 $inverse = $filter["inverse"];
1553 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1554 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1556 array_push($matches, array($filter["action"], $filter["action_param"]));
1561 if ($filters["date"]) {
1562 $reg_exp = $filter["reg_exp"];
1563 foreach ($filters["date"] as $filter) {
1564 $date_modifier = $filter["filter_param"];
1565 $inverse = $filter["inverse"];
1566 $check_timestamp = strtotime($filter["reg_exp"]);
1568 # no-op when timestamp doesn't parse to prevent misfires
1570 if ($check_timestamp) {
1573 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1574 $date_modifier == "after" && $timestamp > $check_timestamp) {
1578 if ($inverse) $match_ok = !$match_ok;
1581 array_push($matches, array($filter["action"], $filter["action_param"]));
1590 function find_article_filter($filters, $filter_name) {
1591 foreach ($filters as $f) {
1592 if ($f[0] == $filter_name) {
1599 function calculate_article_score($filters) {
1602 foreach ($filters as $f) {
1603 if ($f[0] == "score") {
1610 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1611 foreach ($filters as $f) {
1612 if ($f[0] == "label") {
1613 label_add_article($link, $id, $f[1], $owner_uid);
1618 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1619 $rtl_content = false, $last_updated = false, $last_error = false) {
1621 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1622 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1624 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1628 $rtl_tag = "dir=\"rtl\"";
1630 $rtl_tag = "dir=\"ltr\"";
1633 $error_notify_msg = "";
1636 $link_title = "Error: $last_error ($last_updated)";
1637 $error_notify_msg = "(Error)";
1638 } else if ($last_updated) {
1639 $link_title = "Updated: $last_updated";
1642 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1643 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1645 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1646 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1650 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1653 $fctr_class = "class=\"feedCtrHasUnread\"";
1655 $fctr_class = "class=\"feedCtrNoUnread\"";
1658 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1659 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1661 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1662 $total = getFeedArticles($link, $feed_id);
1663 print "<div class=\"feedExtInfo\">
1664 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1671 function getmicrotime() {
1672 list($usec, $sec) = explode(" ",microtime());
1673 return ((float)$usec +
(float)$sec);
1676 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1677 foreach ($values as $v) {
1684 if ($v == $true_is) {
1685 $sel .= " value=\"1\"";
1687 $sel .= " value=\"0\"";
1690 print "<input class=\"noborder\"
1691 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1696 function initialize_user_prefs($link, $uid) {
1698 $uid = db_escape_string($uid);
1700 db_query($link, "BEGIN");
1702 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1704 $u_result = db_query($link, "SELECT pref_name
1705 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1707 $active_prefs = array();
1709 while ($line = db_fetch_assoc($u_result)) {
1710 array_push($active_prefs, $line["pref_name"]);
1713 while ($line = db_fetch_assoc($result)) {
1714 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1715 // print "adding " . $line["pref_name"] . "<br>";
1717 db_query($link, "INSERT INTO ttrss_user_prefs
1718 (owner_uid,pref_name,value) VALUES
1719 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1724 db_query($link, "COMMIT");
1728 function lookup_user_id($link, $user) {
1730 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1733 if (db_num_rows($result) == 1) {
1734 return db_fetch_result($result, 0, "id");
1740 function http_authenticate_user($link) {
1742 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1744 if (!$_SERVER["PHP_AUTH_USER"]) {
1746 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1747 header('HTTP/1.0 401 Unauthorized');
1751 $auth_result = authenticate_user($link,
1752 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1754 if (!$auth_result) {
1755 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1756 header('HTTP/1.0 401 Unauthorized');
1764 function authenticate_user($link, $login, $password, $force_auth = false) {
1766 if (!SINGLE_USER_MODE
) {
1768 $pwd_hash1 = encrypt_password($password);
1769 $pwd_hash2 = encrypt_password($password, $login);
1771 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1772 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1774 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1776 $query = "SELECT id,login,access_level,pwd_hash
1777 FROM ttrss_users WHERE
1781 $query = "SELECT id,login,access_level,pwd_hash
1782 FROM ttrss_users WHERE
1783 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1784 pwd_hash = '$pwd_hash2')";
1787 $result = db_query($link, $query);
1789 if (db_num_rows($result) == 1) {
1790 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1791 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1792 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1794 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1797 $user_theme = get_user_theme_path($link);
1799 $_SESSION["theme"] = $user_theme;
1800 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1801 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1803 initialize_user_prefs($link, $_SESSION["uid"]);
1812 $_SESSION["uid"] = 1;
1813 $_SESSION["name"] = "admin";
1815 $user_theme = get_user_theme_path($link);
1817 $_SESSION["theme"] = $user_theme;
1818 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1820 initialize_user_prefs($link, $_SESSION["uid"]);
1826 function make_password($length = 8) {
1829 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1833 while ($i < $length) {
1834 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1836 if (!strstr($password, $char)) {
1844 // this is called after user is created to initialize default feeds, labels
1847 // user preferences are checked on every login, not here
1849 function initialize_user($link, $uid) {
1851 /* db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1852 VALUES ('$uid', 'All Articles')");
1854 db_query($link, "INSERT INTO ttrss_filters
1855 (owner_uid, feed_id, filter_type, reg_exp, enabled,
1856 action_id, action_param, filter_param)
1857 VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1859 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1860 values ('$uid', 'Tiny Tiny RSS: New Releases',
1861 'http://tt-rss.org/releases.rss')");
1863 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1864 values ('$uid', 'Tiny Tiny RSS: Forum',
1865 'http://tt-rss.org/forum/rss.php')");
1868 function logout_user() {
1870 if (isset($_COOKIE[session_name()])) {
1871 setcookie(session_name(), '', time()-42000, '/');
1875 function get_script_urlpath() {
1876 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1879 function validate_session($link) {
1880 if (SINGLE_USER_MODE
) {
1884 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1885 if ($_SESSION["ip_address"]) {
1886 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1887 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1893 if ($_SESSION["uid"]) {
1895 $result = db_query($link,
1896 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1898 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1900 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1905 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1907 //print_r($_SESSION);
1909 if (time() > $_SESSION["cookie_lifetime"]) {
1917 function login_sequence($link, $mobile = false) {
1918 if (!SINGLE_USER_MODE
) {
1920 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1921 $swu = db_escape_string($_REQUEST["swu"]);
1923 $_SESSION["prefs_cache"] = false;
1924 return authenticate_user($link, $swu, null, true);
1928 $login_action = $_POST["login_action"];
1930 # try to authenticate user if called from login form
1931 if ($login_action == "do_login") {
1932 $login = $_POST["login"];
1933 $password = $_POST["password"];
1934 $remember_me = $_POST["remember_me"];
1936 if (authenticate_user($link, $login, $password)) {
1937 $_POST["password"] = "";
1939 $_SESSION["language"] = $_POST["language"];
1940 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1942 header("Location: " . $_SERVER["REQUEST_URI"]);
1947 $_SESSION["login_error_msg"] = "Incorrect username or password";
1951 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1952 render_login_form($link, $mobile);
1955 /* bump login timestamp */
1956 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1959 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1960 setcookie("ttrss_lang", $_SESSION["language"],
1961 time() + SESSION_COOKIE_LIFETIME
);
1964 /* bump counters stamp since we're getting reloaded anyway */
1966 $_SESSION["get_all_counters_stamp"] = time();
1970 return authenticate_user($link, "admin", null);
1974 function truncate_string($str, $max_len) {
1975 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1976 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1982 function get_user_theme_path($link) {
1983 $result = db_query($link, "SELECT theme_path
1985 ttrss_themes,ttrss_users
1986 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1987 if (db_num_rows($result) != 0) {
1988 return db_fetch_result($result, 0, "theme_path");
1994 function smart_date_time($timestamp) {
1995 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1996 return date("G:i", $timestamp);
1997 } else if (date("Y", $timestamp) == date("Y")) {
1998 return date("M d, G:i", $timestamp);
2000 return date("Y/m/d, G:i", $timestamp);
2004 function smart_date($timestamp) {
2005 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2007 } else if (date("Y", $timestamp) == date("Y")) {
2008 return date("D m", $timestamp);
2010 return date("Y/m/d", $timestamp);
2014 function sql_bool_to_string($s) {
2015 if ($s == "t" ||
$s == "1") {
2022 function sql_bool_to_bool($s) {
2023 if ($s == "t" ||
$s == "1") {
2031 function toggleEvenOdd($a) {
2038 function sanity_check($link) {
2043 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2044 $schema_version = db_fetch_result($result, 0, "schema_version");
2046 if ($schema_version != SCHEMA_VERSION
) {
2050 if (DB_TYPE
== "mysql") {
2051 $result = db_query($link, "SELECT true", false);
2052 if (db_num_rows($result) != 1) {
2057 if (db_escape_string("testTEST") != "testTEST") {
2061 error_reporting (DEFAULT_ERROR_LEVEL
);
2063 if ($error_code != 0) {
2064 print_error_xml($error_code);
2071 function file_is_locked($filename) {
2072 if (function_exists('flock')) {
2074 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2075 error_reporting(DEFAULT_ERROR_LEVEL
);
2077 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2078 flock($fp, LOCK_UN
);
2088 return true; // consider the file always locked and skip the test
2091 function make_lockfile($filename) {
2092 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2094 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2101 function make_stampfile($filename) {
2102 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2104 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2105 fwrite($fp, time() . "\n");
2106 flock($fp, LOCK_UN
);
2114 function read_stampfile($filename) {
2117 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
2118 error_reporting (DEFAULT_ERROR_LEVEL
);
2121 if (flock($fp, LOCK_EX
)) {
2122 $stamp = fgets($fp);
2123 flock($fp, LOCK_UN
);
2134 function sql_random_function() {
2135 if (DB_TYPE
== "mysql") {
2142 function catchup_feed($link, $feed, $cat_view) {
2144 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2149 $cat_qpart = "cat_id = '$feed'";
2151 $cat_qpart = "cat_id IS NULL";
2154 $tmp_result = db_query($link, "SELECT id
2155 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2158 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2160 $tmp_feed = $tmp_line["id"];
2162 db_query($link, "UPDATE ttrss_user_entries
2163 SET unread = false,last_read = NOW()
2164 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2167 } else if ($feed > 0) {
2169 $tmp_result = db_query($link, "SELECT id
2170 FROM ttrss_feeds WHERE parent_feed = '$feed'
2171 ORDER BY cat_id,title");
2173 $parent_ids = array();
2175 if (db_num_rows($tmp_result) > 0) {
2176 while ($p = db_fetch_assoc($tmp_result)) {
2177 array_push($parent_ids, "feed_id = " . $p["id"]);
2180 $children_qpart = implode(" OR ", $parent_ids);
2182 db_query($link, "UPDATE ttrss_user_entries
2183 SET unread = false,last_read = NOW()
2184 WHERE (feed_id = '$feed' OR $children_qpart)
2185 AND owner_uid = " . $_SESSION["uid"]);
2188 db_query($link, "UPDATE ttrss_user_entries
2189 SET unread = false,last_read = NOW()
2190 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2193 } else if ($feed < 0 && $feed > -10) { // special, like starred
2196 db_query($link, "UPDATE ttrss_user_entries
2197 SET unread = false,last_read = NOW()
2198 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2202 db_query($link, "UPDATE ttrss_user_entries
2203 SET unread = false,last_read = NOW()
2204 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2209 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2211 if (DB_TYPE
== "pgsql") {
2212 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2214 $match_part = "updated > DATE_SUB(NOW(),
2215 INTERVAL $intl HOUR) ";
2218 $result = db_query($link, "SELECT id FROM ttrss_entries,
2219 ttrss_user_entries WHERE $match_part AND
2221 ttrss_user_entries.ref_id = ttrss_entries.id AND
2222 owner_uid = ".$_SESSION["uid"]);
2224 $affected_ids = array();
2226 while ($line = db_fetch_assoc($result)) {
2227 array_push($affected_ids, $line["id"]);
2230 catchupArticlesById($link, $affected_ids, 0);
2234 db_query($link, "UPDATE ttrss_user_entries
2235 SET unread = false,last_read = NOW()
2236 WHERE owner_uid = ".$_SESSION["uid"]);
2239 } else if ($feed < -10) { // label
2241 $label_id = -$feed - 11;
2243 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2244 SET unread = false WHERE label_id = '$label_id' AND unread = true
2245 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2249 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2252 db_query($link, "BEGIN");
2254 $tag_name = db_escape_string($feed);
2256 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2257 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2259 while ($line = db_fetch_assoc($result)) {
2260 db_query($link, "UPDATE ttrss_user_entries SET
2261 unread = false, last_read = NOW()
2262 WHERE int_id = " . $line["post_int_id"]);
2264 db_query($link, "COMMIT");
2268 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2272 $cat_qpart = "cat_id = '$feed'";
2274 $cat_qpart = "cat_id IS NULL";
2277 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2278 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2280 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2281 $feed_url = $tmp_line["feed_url"];
2282 $feed_id = $tmp_line["id"];
2283 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2287 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2288 WHERE id = '$feed'");
2289 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2290 update_rss_feed($link, $feed_url, $feed, $force_update);
2294 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2296 if (!$omode) $omode = "flc";
2298 getGlobalCounters($link);
2300 if (strchr($omode, "l")) getLabelCounters($link);
2301 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2302 if (strchr($omode, "t")) getTagCounters($link);
2303 if (strchr($omode, "c")) {
2304 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2305 getCategoryCounters($link);
2310 function getCategoryCounters($link) {
2311 # two special categories are -1 and -2 (all virtuals; all labels)
2313 /* $ctr = getCategoryUnread($link, -1);
2315 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2317 $ctr = getCategoryUnread($link, -2);
2319 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2321 $age_qpart = getMaxAgeSubquery();
2323 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2324 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2325 WHERE ttrss_cat_counters_cache.feed_id = id AND
2326 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2328 while ($line = db_fetch_assoc($result)) {
2329 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2331 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2332 $line["unread"]."\"/>";
2335 /* Special case: NULL category doesn't actually exist in the DB */
2337 print "<counter type=\"category\" id=\"0\" counter=\"".
2338 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2342 function getCategoryUnread($link, $cat, $owner_uid = false) {
2344 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2349 $cat_query = "cat_id = '$cat'";
2351 $cat_query = "cat_id IS NULL";
2354 $age_qpart = getMaxAgeSubquery();
2356 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2358 AND owner_uid = " . $owner_uid);
2360 $cat_feeds = array();
2361 while ($line = db_fetch_assoc($result)) {
2362 array_push($cat_feeds, "feed_id = " . $line["id"]);
2365 if (count($cat_feeds) == 0) return 0;
2367 $match_part = implode(" OR ", $cat_feeds);
2369 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2370 FROM ttrss_user_entries,ttrss_entries
2371 WHERE unread = true AND ($match_part) AND id = ref_id
2372 AND $age_qpart AND owner_uid = " . $owner_uid);
2376 # this needs to be rewritten
2377 while ($line = db_fetch_assoc($result)) {
2378 $unread +
= $line["unread"];
2382 } else if ($cat == -1) {
2383 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2384 } else if ($cat == -2) {
2386 $result = db_query($link, "
2387 SELECT COUNT(unread) AS unread FROM
2388 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2389 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2390 ttrss_labels2.owner_uid = '$owner_uid'
2391 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2392 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2394 $unread = db_fetch_result($result, 0, "unread");
2401 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2402 if (DB_TYPE
== "pgsql") {
2403 return "ttrss_entries.date_entered >
2404 NOW() - INTERVAL '$days days'";
2406 return "ttrss_entries.date_entered >
2407 DATE_SUB(NOW(), INTERVAL $days DAY)";
2411 function getFeedUnread($link, $feed, $is_cat = false) {
2412 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2415 function getLabelUnread($link, $label_id, $owner_uid = false) {
2416 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2418 $result = db_query($link, "
2419 SELECT COUNT(unread) AS unread FROM
2420 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2421 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2422 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2423 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2424 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2426 if (db_num_rows($result) != 0) {
2427 return db_fetch_result($result, 0, "unread");
2433 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2434 $owner_uid = false) {
2436 $n_feed = sprintf("%d", $feed);
2438 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2441 $unread_qpart = "unread = true";
2443 $unread_qpart = "true";
2446 $age_qpart = getMaxAgeSubquery();
2449 return getCategoryUnread($link, $n_feed, $owner_uid);
2450 } else if ($n_feed == -1) {
2451 $match_part = "marked = true";
2452 } else if ($n_feed == -2) {
2453 $match_part = "published = true";
2454 } else if ($n_feed == -3) {
2455 $match_part = "unread = true";
2457 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2459 if (DB_TYPE
== "pgsql") {
2460 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2462 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2464 } else if ($n_feed == -4) {
2465 $match_part = "true";
2466 } else if ($n_feed > 0) {
2468 $result = db_query($link, "SELECT id FROM ttrss_feeds
2469 WHERE parent_feed = '$n_feed'
2471 AND owner_uid = " . $owner_uid);
2473 if (db_num_rows($result) > 0) {
2475 $linked_feeds = array();
2476 while ($line = db_fetch_assoc($result)) {
2477 array_push($linked_feeds, "feed_id = " . $line["id"]);
2480 array_push($linked_feeds, "feed_id = $n_feed");
2482 $match_part = implode(" OR ", $linked_feeds);
2484 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2485 FROM ttrss_user_entries,ttrss_entries
2486 WHERE $unread_qpart AND
2487 ttrss_user_entries.ref_id = ttrss_entries.id AND
2490 owner_uid = " . $owner_uid);
2494 # this needs to be rewritten
2495 while ($line = db_fetch_assoc($result)) {
2496 $unread +
= $line["unread"];
2502 $match_part = "feed_id = '$n_feed'";
2504 } else if ($feed < -10) {
2506 $label_id = -$feed - 11;
2508 return getLabelUnread($link, $label_id, $owner_uid);
2514 $result = db_query($link, "SELECT count(int_id) AS unread
2515 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2516 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2517 ttrss_user_entries.ref_id = ttrss_entries.id AND
2518 ttrss_feeds.hidden = false AND
2520 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2524 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2525 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2526 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2527 AND $unread_qpart AND $age_qpart AND
2528 ttrss_tags.owner_uid = " . $owner_uid);
2531 $unread = db_fetch_result($result, 0, "unread");
2536 function getGlobalUnread($link, $user_id = false) {
2539 $user_id = $_SESSION["uid"];
2542 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2543 WHERE owner_uid = '$user_id' AND feed_id > 0");
2545 $c_id = db_fetch_result($result, 0, "c_id");
2550 function getGlobalCounters($link, $global_unread = -1) {
2551 if ($global_unread == -1) {
2552 $global_unread = getGlobalUnread($link);
2554 print "<counter type=\"global\" id='global-unread'
2555 counter='$global_unread'/>";
2557 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2558 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2560 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2562 print "<counter type=\"global\" id='subscribed-feeds'
2563 counter='$subscribed_feeds'/>";
2567 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2570 if (!$_SESSION["tctr_last_value"]) {
2571 $_SESSION["tctr_last_value"] = array();
2575 $old_counters = $_SESSION["tctr_last_value"];
2577 $tctrs_modified = false;
2579 $age_qpart = getMaxAgeSubquery();
2581 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2582 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2583 AND ref_id = id AND $age_qpart
2584 AND unread = true)) AS count FROM ttrss_tags
2585 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2586 ORDER BY count DESC LIMIT 55");
2590 while ($line = db_fetch_assoc($result)) {
2591 $tags[$line["tag_name"]] +
= $line["count"];
2594 foreach (array_keys($tags) as $tag) {
2595 $unread = $tags[$tag];
2597 $tag = htmlspecialchars($tag);
2599 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2600 $old_counters[$tag] = $unread;
2601 $tctrs_modified = true;
2602 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2607 if ($smart_mode && $tctrs_modified) {
2608 $_SESSION["tctr_last_value"] = $old_counters;
2613 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2615 $age_qpart = getMaxAgeSubquery();
2618 if (!$_SESSION["lctr_last_value"]) {
2619 $_SESSION["lctr_last_value"] = array();
2625 for ($i = -1; $i >= -4; $i--) {
2627 $count = getFeedUnread($link, $i);
2631 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2632 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2637 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2639 $ret_arr[$i]["counter"] = $count;
2640 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2645 $old_counters = $_SESSION["lctr_last_value"];
2646 $lctrs_modified = false;
2649 $owner_uid = $_SESSION["uid"];
2651 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2652 WHERE owner_uid = '$owner_uid'");
2654 while ($line = db_fetch_assoc($result)) {
2656 $id = -$line["id"] - 11;
2658 $label_name = $line["caption"];
2659 $count = getFeedUnread($link, $id);
2661 if (!$smart_mode ||
$old_counters[$id] != $count) {
2662 $old_counters[$id] = $count;
2663 $lctrs_modified = true;
2666 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2667 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2672 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2674 $ret_arr[$id]["counter"] = $count;
2675 $ret_arr[$id]["description"] = $label_name;
2679 error_reporting (DEFAULT_ERROR_LEVEL
);
2682 if ($smart_mode && $lctrs_modified) {
2683 $_SESSION["lctr_last_value"] = $old_counters;
2689 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2691 $age_qpart = getMaxAgeSubquery();
2694 if (!$_SESSION["fctr_last_value"]) {
2695 $_SESSION["fctr_last_value"] = array();
2699 $old_counters = $_SESSION["fctr_last_value"];
2701 $query = "SELECT ttrss_feeds.id,
2703 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2704 last_error, value AS count
2705 FROM ttrss_feeds, ttrss_counters_cache
2706 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2707 AND parent_feed IS NULL
2708 AND ttrss_counters_cache.feed_id = id";
2710 $result = db_query($link, $query);
2711 $fctrs_modified = false;
2713 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2715 while ($line = db_fetch_assoc($result)) {
2718 $count = $line["count"];
2719 $last_error = htmlspecialchars($line["last_error"]);
2721 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2722 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2724 $last_updated = date($short_date, strtotime($line["last_updated"]));
2727 $last_updated = htmlspecialchars($last_updated);
2729 $has_img = feed_has_icon($id);
2731 $tmp_result = db_query($link,
2732 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2733 WHERE parent_feed = '$id' AND feed_id = id");
2735 $count +
= db_fetch_result($tmp_result, 0, "unread");
2737 if (!$smart_mode ||
$old_counters[$id] != $count) {
2738 $old_counters[$id] = $count;
2739 $fctrs_modified = true;
2742 $error_part = "error=\"$last_error\"";
2748 $has_img_part = "hi=\"$has_img\"";
2753 if ($active_feed && $id == $active_feed) {
2754 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2756 $has_title_part = "";
2759 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2760 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2763 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2767 if ($smart_mode && $fctrs_modified) {
2768 $_SESSION["fctr_last_value"] = $old_counters;
2772 function get_script_dt_add() {
2773 if (strpos(VERSION
, ".99") === false) {
2780 function get_pgsql_version($link) {
2781 $result = db_query($link, "SELECT version() AS version");
2782 $version = split(" ", db_fetch_result($result, 0, "version"));
2786 function print_error_xml($code, $add_msg = "") {
2789 $error_msg = $ERRORS[$code];
2792 $error_msg = "$error_msg; $add_msg";
2795 print "<rpc-reply>";
2796 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2797 print "</rpc-reply>";
2800 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2801 $auth_login = '', $auth_pass = '') {
2803 # check for feed:http://url
2804 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2806 # check for feed://URL
2807 if (strpos($feed_link, "//") === 0) {
2808 $feed_link = "http:$feed_link";
2811 if ($feed_link == "") return;
2813 if ($cat_id == "0" ||
!$cat_id) {
2814 $cat_qpart = "NULL";
2816 $cat_qpart = "'$cat_id'";
2819 $result = db_query($link,
2820 "SELECT id FROM ttrss_feeds
2821 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2823 if (db_num_rows($result) == 0) {
2825 $result = db_query($link,
2826 "INSERT INTO ttrss_feeds
2827 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2828 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2829 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2831 $result = db_query($link,
2832 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2833 AND owner_uid = " . $_SESSION["uid"]);
2835 $feed_id = db_fetch_result($result, 0, "id");
2838 update_rss_feed($link, $feed_link, $feed_id, true);
2847 function print_feed_select($link, $id, $default_id = "",
2848 $attributes = "", $include_all_feeds = true) {
2850 print "<select id=\"$id\" name=\"$id\" $attributes>";
2851 if ($include_all_feeds) {
2852 print "<option value=\"0\">".__('All feeds')."</option>";
2855 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2856 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2858 if (db_num_rows($result) > 0 && $include_all_feeds) {
2859 print "<option disabled>--------</option>";
2862 while ($line = db_fetch_assoc($result)) {
2863 if ($line["id"] == $default_id) {
2864 $is_selected = "selected";
2868 printf("<option $is_selected value='%d'>%s</option>",
2869 $line["id"], htmlspecialchars($line["title"]));
2875 function print_feed_cat_select($link, $id, $default_id = "",
2876 $attributes = "", $include_all_cats = true) {
2878 print "<select id=\"$id\" name=\"$id\" $attributes>";
2880 if ($include_all_cats) {
2881 print "<option value=\"0\">".__('Uncategorized')."</option>";
2884 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2885 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2887 if (db_num_rows($result) > 0 && $include_all_cats) {
2888 print "<option disabled>--------</option>";
2891 while ($line = db_fetch_assoc($result)) {
2892 if ($line["id"] == $default_id) {
2893 $is_selected = "selected";
2897 printf("<option $is_selected value='%d'>%s</option>",
2898 $line["id"], htmlspecialchars($line["title"]));
2904 function checkbox_to_sql_bool($val) {
2905 return ($val == "on") ?
"true" : "false";
2908 function getFeedCatTitle($link, $id) {
2910 return __("Special");
2911 } else if ($id < -10) {
2912 return __("Labels");
2913 } else if ($id > 0) {
2914 $result = db_query($link, "SELECT ttrss_feed_categories.title
2915 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2916 cat_id = ttrss_feed_categories.id");
2917 if (db_num_rows($result) == 1) {
2918 return db_fetch_result($result, 0, "title");
2920 return __("Uncategorized");
2923 return "getFeedCatTitle($id) failed";
2928 function getFeedTitle($link, $id) {
2930 return __("Starred articles");
2931 } else if ($id == -2) {
2932 return __("Published articles");
2933 } else if ($id == -3) {
2934 return __("Fresh articles");
2935 } else if ($id == -4) {
2936 return __("All articles");
2937 } else if ($id < -10) {
2938 $label_id = -$id - 11;
2939 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2940 if (db_num_rows($result) == 1) {
2941 return db_fetch_result($result, 0, "caption");
2943 return "Unknown label ($label_id)";
2946 } else if ($id > 0) {
2947 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2948 if (db_num_rows($result) == 1) {
2949 return db_fetch_result($result, 0, "title");
2951 return "Unknown feed ($id)";
2954 return "getFeedTitle($id) failed";
2959 function get_session_cookie_name() {
2960 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2963 function print_init_params($link) {
2964 print "<init-params>";
2965 if ($_SESSION["stored-params"]) {
2966 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2968 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2969 print "<param key=\"$key\" value=\"$value\"/>";
2974 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2975 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2976 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2977 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2979 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2980 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2982 print "<param key=\"hide_read_feeds\" value=\"" .
2983 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2985 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2986 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2988 print "<param key=\"confirm_feed_catchup\" value=\"" .
2989 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2991 print "<param key=\"cdm_auto_catchup\" value=\"" .
2992 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2994 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2996 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2998 print "<param key=\"default_view_mode\" value=\"" .
2999 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3001 print "<param key=\"default_view_limit\" value=\"" .
3002 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3004 print "<param key=\"default_view_order_by\" value=\"" .
3005 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3007 print "<param key=\"prefs_active_tab\" value=\"" .
3008 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3010 print "<param key=\"infobox_disable_overlay\" value=\"" .
3011 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3013 print "<param key=\"icons_location\" value=\"" .
3016 print "<param key=\"hide_read_shows_special\" value=\"" .
3017 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3019 print "<param key=\"hide_feedlist\" value=\"" .
3020 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3022 print "<param key=\"bw_limit\" value=\"".
3023 (int) $_SESSION["bw_limit"]."\"/>";
3025 // print "<param key=\"sync_counters\" value=\"" .
3026 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3028 print "<param key=\"sync_counters\" value=\"1\"/>";
3030 print "</init-params>";
3033 function print_runtime_info($link) {
3034 print "<runtime-info>";
3036 if (ENABLE_UPDATE_DAEMON
) {
3037 print "<param key=\"daemon_is_running\" value=\"".
3038 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3040 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3042 $stamp = (int)read_stampfile("update_daemon.stamp");
3044 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3047 $stamp_delta = time() - $stamp;
3049 if ($stamp_delta > 1800) {
3053 $_SESSION["daemon_stamp_check"] = time();
3056 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3058 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3060 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3065 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3067 if ($_SESSION["last_version_check"] +
86400 < time()) {
3068 $new_version_details = check_for_update($link);
3070 print "<param key=\"new_version_available\" value=\"".
3071 sprintf("%d", $new_version_details != ""). "\"/>";
3073 $_SESSION["last_version_check"] = time();
3077 // print "<param key=\"new_version_available\" value=\"1\"/>";
3079 print "</runtime-info>";
3082 function getSearchSql($search, $match_on) {
3084 $search_query_part = "";
3086 $keywords = split(" ", $search);
3087 $query_keywords = array();
3089 if ($match_on == "both") {
3091 foreach ($keywords as $k) {
3092 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3093 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3096 $search_query_part = implode("AND", $query_keywords) . " AND ";
3098 } else if ($match_on == "title") {
3100 foreach ($keywords as $k) {
3101 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3104 $search_query_part = implode("AND", $query_keywords) . " AND ";
3106 } else if ($match_on == "content") {
3108 foreach ($keywords as $k) {
3109 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3113 $search_query_part = implode("AND", $query_keywords);
3115 return $search_query_part;
3118 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3120 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3124 $search_query_part = getSearchSql($search, $match_on);
3125 $search_query_part .= " AND ";
3128 $search_query_part = "";
3131 $view_query_part = "";
3133 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3135 $view_query_part = " ";
3136 } else if ($feed != -1) {
3137 $unread = getFeedUnread($link, $feed, $cat_view);
3139 $view_query_part = " unread = true AND ";
3144 if ($view_mode == "marked") {
3145 $view_query_part = " marked = true AND ";
3148 if ($view_mode == "unread") {
3149 $view_query_part = " unread = true AND ";
3152 if ($view_mode == "updated") {
3153 $view_query_part = " (last_read is null and unread = false) AND ";
3157 $limit_query_part = "LIMIT " . $limit;
3160 $vfeed_query_part = "";
3162 // override query strategy and enable feed display when searching globally
3163 if ($search && $search_mode == "all_feeds") {
3164 $query_strategy_part = "ttrss_entries.id > 0";
3165 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3166 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3167 $query_strategy_part = "ttrss_entries.id > 0";
3168 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3169 id = feed_id) as feed_title,";
3170 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3172 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3174 $tmp_result = false;
3177 $tmp_result = db_query($link, "SELECT id
3178 FROM ttrss_feeds WHERE cat_id = '$feed'");
3180 $tmp_result = db_query($link, "SELECT id
3181 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3182 WHERE id = '$feed') AND id != '$feed'");
3185 $cat_siblings = array();
3187 if (db_num_rows($tmp_result) > 0) {
3188 while ($p = db_fetch_assoc($tmp_result)) {
3189 array_push($cat_siblings, "feed_id = " . $p["id"]);
3192 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3193 $feed, implode(" OR ", $cat_siblings));
3196 $query_strategy_part = "ttrss_entries.id > 0";
3199 } else if ($feed >= 0) {
3204 $query_strategy_part = "cat_id = '$feed'";
3206 $query_strategy_part = "cat_id IS NULL";
3209 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3212 $tmp_result = db_query($link, "SELECT id
3213 FROM ttrss_feeds WHERE parent_feed = '$feed'
3214 ORDER BY cat_id,title");
3216 $parent_ids = array();
3218 if (db_num_rows($tmp_result) > 0) {
3219 while ($p = db_fetch_assoc($tmp_result)) {
3220 array_push($parent_ids, "feed_id = " . $p["id"]);
3223 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3224 $feed, implode(" OR ", $parent_ids));
3226 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3228 $query_strategy_part = "feed_id = '$feed'";
3231 } else if ($feed == -1) { // starred virtual feed
3232 $query_strategy_part = "marked = true";
3233 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3234 } else if ($feed == -2) { // published virtual feed OR labels category
3237 $query_strategy_part = "published = true";
3238 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3240 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3242 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3244 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3245 ttrss_user_labels2.article_id = ref_id";
3249 } else if ($feed == -3) { // fresh virtual feed
3250 $query_strategy_part = "unread = true";
3252 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3254 if (DB_TYPE
== "pgsql") {
3255 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3257 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3260 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3261 } else if ($feed == -4) { // all articles virtual feed
3262 $query_strategy_part = "true";
3263 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3264 } else if ($feed <= -10) { // labels
3265 $label_id = -$feed - 11;
3267 $query_strategy_part = "label_id = '$label_id' AND
3268 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3269 ttrss_user_labels2.article_id = ref_id";
3271 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3272 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3275 $query_strategy_part = "id > 0"; // dumb
3278 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3279 $order_by = "updated";
3281 $order_by = "updated DESC";
3284 if ($view_mode != "noscores") {
3285 $order_by = "score DESC, $order_by";
3288 if ($override_order) {
3289 $order_by = $override_order;
3294 if ($search && $search_mode == "all_feeds") {
3295 $feed_title = __("Search results")." ($search)";
3296 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3297 $feed_title = __("Search results")." ($search, $feed)";
3298 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3299 $feed_title = $feed;
3300 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3305 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3306 WHERE id = '$feed' AND owner_uid = $owner_uid");
3307 $feed_title = db_fetch_result($result, 0, "title");
3309 $feed_title = __("Uncategorized");
3313 $feed_title = __("Searched for")." $search ($feed_title)";
3318 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3319 WHERE id = '$feed' AND owner_uid = $owner_uid");
3321 $feed_title = db_fetch_result($result, 0, "title");
3322 $feed_site_url = db_fetch_result($result, 0, "site_url");
3323 $last_error = db_fetch_result($result, 0, "last_error");
3326 $feed_title = __("Searched for") . " $search ($feed_title)";
3330 } else if ($feed == -1) {
3331 $feed_title = __("Starred articles");
3332 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3333 } else if ($feed == -2) {
3335 $feed_title = __("Published articles");
3336 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3338 $feed_title = __("Labels");
3340 } else if ($feed == -3) {
3341 $feed_title = __("Fresh articles");
3342 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3343 } else if ($feed == -4) {
3344 $feed_title = __("All articles");
3345 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3346 } else if ($feed < -10) {
3347 $label_id = -$feed - 11;
3348 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3349 WHERE id = '$label_id'");
3350 $feed_title = db_fetch_result($result, 0, "caption");
3353 $feed_title = __("Searched for") . " $search ($feed_title)";
3359 if ($feed < -10) error_reporting (0);
3361 $content_query_part = "content as content_preview,";
3363 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3366 $feed_kind = "Feeds";
3368 $feed_kind = "Labels";
3371 if ($limit_query_part) {
3372 $offset_query_part = "OFFSET $offset";
3375 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3376 if (!$override_order) {
3377 $order_by = "ttrss_feeds.title, $order_by";
3380 // Special output for Fresh feed
3382 /* if ($feed == -3) {
3383 $group_limit_part = "(select count(*) from
3384 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3385 t1.ref_id = t2.id and t1.owner_uid = 2 and
3386 t1.feed_id = ttrss_user_entries.feed_id and
3387 t2.updated > ttrss_entries.updated) <= 5 AND";
3391 $query = "SELECT DISTINCT
3393 ttrss_entries.id,ttrss_entries.title,
3395 unread,feed_id,marked,published,link,last_read,
3396 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3399 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3402 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3405 ttrss_feeds.hidden = false AND
3406 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3407 ttrss_user_entries.ref_id = ttrss_entries.id AND
3408 ttrss_user_entries.owner_uid = '$owner_uid' AND
3411 $query_strategy_part ORDER BY $order_by
3412 $limit_query_part $offset_query_part";
3414 if ($_GET["debug"]) print $query;
3416 $result = db_query($link, $query);
3421 $feed_kind = "Tags";
3423 $result = db_query($link, "SELECT
3425 ttrss_entries.id as id,title,
3428 marked,link,last_read,
3429 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3432 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3435 ttrss_entries,ttrss_user_entries,ttrss_tags
3437 ref_id = ttrss_entries.id AND
3438 ttrss_user_entries.owner_uid = '$owner_uid' AND
3439 post_int_id = int_id AND tag_name = '$feed' AND
3442 $query_strategy_part ORDER BY $order_by
3443 $limit_query_part");
3446 return array($result, $feed_title, $feed_site_url, $last_error);
3450 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3451 $limit, $search, $search_mode, $match_on) {
3453 if (!$limit) $limit = 30;
3455 $qfh_ret = queryFeedHeadlines($link, $feed,
3456 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3459 $result = $qfh_ret[0];
3460 $feed_title = htmlspecialchars($qfh_ret[1]);
3461 $feed_site_url = $qfh_ret[2];
3462 $last_error = $qfh_ret[3];
3464 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3466 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3467 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3468 <rss version=\"2.0\">
3470 <title>$feed_title</title>
3471 <link>$feed_site_url</link>
3472 <description>Feed generated by Tiny Tiny RSS</description>";
3474 while ($line = db_fetch_assoc($result)) {
3476 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3477 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3479 $tags = get_article_tags($link, $line["id"], $owner_uid);
3481 foreach ($tags as $tag) {
3482 print "<category>" . htmlspecialchars($tag) . "</category>";
3485 $rfc822_date = date('r', strtotime($line["updated"]));
3487 print "<pubDate>$rfc822_date</pubDate>";
3490 htmlspecialchars($line["title"]) . "</title>";
3492 print "<description><![CDATA[" .
3493 $line["content_preview"] . "]]></description>";
3498 print "</channel></rss>";
3502 function getCategoryTitle($link, $cat_id) {
3504 if ($cat_id == -1) {
3505 return __("Special");
3506 } else if ($cat_id == -2) {
3507 return __("Labels");
3510 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3513 if (db_num_rows($result) == 1) {
3514 return db_fetch_result($result, 0, "title");
3516 return "Uncategorized";
3521 // http://ru2.php.net/strip-tags
3523 function strip_tags_long($textstring, $allowed){
3524 while($textstring != strip_tags($textstring, $allowed))
3526 while (strlen($textstring) != 0)
3528 if (strlen($textstring) > 1024) {
3531 $otherlen = strlen($textstring);
3533 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3534 $safetext .= $temptext;
3535 $textstring = substr_replace($textstring,'',0,$otherlen);
3537 $textstring = $safetext;
3543 function sanitize_rss($link, $str, $force_strip_tags = false) {
3546 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3548 $res = strip_tags_long($res,
3549 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3551 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3552 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3555 if (get_pref($link, "STRIP_IMAGES")) {
3557 $res = preg_replace('/<img[^>]+>/is', '', $res);
3565 * Send by mail a digest of last articles.
3567 * @param mixed $link The database connection.
3568 * @param integer $limit The maximum number of articles by digest.
3569 * @return boolean Return false if digests are not enabled.
3571 function send_headlines_digests($link, $limit = 100) {
3573 if (!DIGEST_ENABLE
) return false;
3575 $user_limit = DIGEST_EMAIL_LIMIT
;
3578 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3580 if (DB_TYPE
== "pgsql") {
3581 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3582 } else if (DB_TYPE
== "mysql") {
3583 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3586 $result = db_query($link, "SELECT id,email FROM ttrss_users
3587 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3589 while ($line = db_fetch_assoc($result)) {
3591 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3592 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3594 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3596 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3597 $digest = $tuple[0];
3598 $headlines_count = $tuple[1];
3599 $affected_ids = $tuple[2];
3600 $digest_text = $tuple[3];
3602 if ($headlines_count > 0) {
3604 $mail = new PHPMailer();
3606 $mail->PluginDir
= "phpmailer/";
3607 $mail->SetLanguage("en", "phpmailer/language/");
3609 $mail->CharSet
= "UTF-8";
3611 $mail->From
= DIGEST_FROM_ADDRESS
;
3612 $mail->FromName
= DIGEST_FROM_NAME
;
3613 $mail->AddAddress($line["email"], $line["login"]);
3615 if (DIGEST_SMTP_HOST
) {
3616 $mail->Host
= DIGEST_SMTP_HOST
;
3617 $mail->Mailer
= "smtp";
3618 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3619 $mail->Username
= DIGEST_SMTP_LOGIN
;
3620 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3623 $mail->IsHTML(true);
3624 $mail->Subject
= DIGEST_SUBJECT
;
3625 $mail->Body
= $digest;
3626 $mail->AltBody
= $digest_text;
3628 $rc = $mail->Send();
3630 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3634 if ($rc && $do_catchup) {
3635 print "Marking affected articles as read...\n";
3636 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3639 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3640 WHERE id = " . $line["id"]);
3642 print "No headlines\n";
3647 print "All done.\n";
3651 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3653 require_once "MiniTemplator.class.php";
3655 $tpl = new MiniTemplator
;
3656 $tpl_t = new MiniTemplator
;
3658 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3659 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3661 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3662 $tpl->setVariable('CUR_TIME', date('G:i'));
3664 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3665 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3667 $affected_ids = array();
3669 if (DB_TYPE
== "pgsql") {
3670 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3671 } else if (DB_TYPE
== "mysql") {
3672 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3675 $result = db_query($link, "SELECT ttrss_entries.title,
3676 ttrss_feeds.title AS feed_title,
3678 ttrss_user_entries.ref_id,
3680 SUBSTRING(content, 1, 120) AS excerpt,
3681 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3683 ttrss_user_entries,ttrss_entries,ttrss_feeds
3685 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3686 AND include_in_digest = true
3689 AND ttrss_user_entries.owner_uid = $user_id
3691 ORDER BY ttrss_feeds.title, date_entered DESC
3694 $cur_feed_title = "";
3696 $headlines_count = db_num_rows($result);
3698 $headlines = array();
3700 while ($line = db_fetch_assoc($result)) {
3701 array_push($headlines, $line);
3704 for ($i = 0; $i < sizeof($headlines); $i++
) {
3706 $line = $headlines[$i];
3708 array_push($affected_ids, $line["ref_id"]);
3710 $updated = smart_date_time(strtotime($line["last_updated"]));
3712 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3713 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3714 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3715 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3716 $tpl->setVariable('ARTICLE_EXCERPT',
3717 truncate_string(strip_tags($line["excerpt"]), 100));
3719 $tpl->addBlock('article');
3721 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3722 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3723 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3724 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3725 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3726 // truncate_string(strip_tags($line["excerpt"]), 100));
3728 $tpl_t->addBlock('article');
3730 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3731 $tpl->addBlock('feed');
3732 $tpl_t->addBlock('feed');
3737 $tpl->addBlock('digest');
3738 $tpl->generateOutputToString($tmp);
3740 $tpl_t->addBlock('digest');
3741 $tpl_t->generateOutputToString($tmp_t);
3743 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3746 function check_for_update($link, $brief_fmt = true) {
3747 $releases_feed = "http://tt-rss.org/releases.rss";
3749 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3754 if (ENABLE_SIMPLEPIE
) {
3755 $rss = new SimplePie();
3756 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3757 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3758 $rss->set_feed_url($fetch_url);
3759 $rss->set_output_encoding('UTF-8');
3762 $rss = fetch_rss($releases_feed);
3764 error_reporting (DEFAULT_ERROR_LEVEL
);
3768 if (ENABLE_SIMPLEPIE
) {
3769 $items = $rss->get_items();
3771 $items = $rss->items
;
3773 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3774 if (!$items ||
!is_array($items)) $items = $rss;
3777 if (!is_array($items) ||
count($items) == 0) {
3781 $latest_item = $items[0];
3783 if (ENABLE_SIMPLEPIE
) {
3784 $last_title = $latest_item->get_title();
3786 $last_title = $latest_item["title"];
3789 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3791 if (ENABLE_SIMPLEPIE
) {
3792 $release_url = sanitize_rss($link, $latest_item->get_link());
3793 $content = sanitize_rss($link, $latest_item->get_description());
3795 $release_url = sanitize_rss($link, $latest_item["link"]);
3796 $content = sanitize_rss($link, $latest_item["description"]);
3799 if (version_compare(VERSION
, $latest_version) == -1) {
3801 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3802 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3803 <div id=\"milestoneDetails\">$content</div>");
3805 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3806 <div class='milestoneDetails'>$content</div>
3807 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3808 download and update information.";
3815 function markArticlesById($link, $ids, $cmode) {
3819 foreach ($ids as $id) {
3820 array_push($tmp_ids, "ref_id = '$id'");
3823 $ids_qpart = join(" OR ", $tmp_ids);
3826 db_query($link, "UPDATE ttrss_user_entries SET
3827 marked = false,last_read = NOW()
3828 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3829 } else if ($cmode == 1) {
3830 db_query($link, "UPDATE ttrss_user_entries SET
3832 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3834 db_query($link, "UPDATE ttrss_user_entries SET
3835 marked = NOT marked,last_read = NOW()
3836 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3840 function publishArticlesById($link, $ids, $cmode) {
3844 foreach ($ids as $id) {
3845 array_push($tmp_ids, "ref_id = '$id'");
3848 $ids_qpart = join(" OR ", $tmp_ids);
3851 db_query($link, "UPDATE ttrss_user_entries SET
3852 published = false,last_read = NOW()
3853 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3854 } else if ($cmode == 1) {
3855 db_query($link, "UPDATE ttrss_user_entries SET
3857 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3859 db_query($link, "UPDATE ttrss_user_entries SET
3860 published = NOT published,last_read = NOW()
3861 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3865 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3867 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3871 foreach ($ids as $id) {
3872 array_push($tmp_ids, "ref_id = '$id'");
3875 $ids_qpart = join(" OR ", $tmp_ids);
3878 db_query($link, "UPDATE ttrss_user_entries SET
3879 unread = false,last_read = NOW()
3880 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3881 } else if ($cmode == 1) {
3882 db_query($link, "UPDATE ttrss_user_entries SET
3884 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3886 db_query($link, "UPDATE ttrss_user_entries SET
3887 unread = NOT unread,last_read = NOW()
3888 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3893 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3894 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3896 while ($line = db_fetch_assoc($result)) {
3897 ccache_update($link, $line["feed_id"], $owner_uid);
3901 function catchupArticleById($link, $id, $cmode) {
3904 db_query($link, "UPDATE ttrss_user_entries SET
3905 unread = false,last_read = NOW()
3906 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3907 } else if ($cmode == 1) {
3908 db_query($link, "UPDATE ttrss_user_entries SET
3910 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3912 db_query($link, "UPDATE ttrss_user_entries SET
3913 unread = NOT unread,last_read = NOW()
3914 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3918 function make_guid_from_title($title) {
3919 return preg_replace("/[ \"\',.:;]/", "-",
3920 mb_strtolower(strip_tags($title), 'utf-8'));
3923 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3924 $bottom = false, $rtl_content = false, $feed_id = 0,
3925 $is_cat = false, $search = false, $match_on = false,
3926 $search_mode = false, $offset = 0, $limit = 0,
3927 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3929 $user_page_offset = $offset +
1;
3932 $class = "headlinesSubToolbar";
3933 $tid = "headlineActionsTop";
3935 $class = "headlinesSubToolbar";
3936 $tid = "headlineActionsBottom";
3939 print "<nobr><table class=\"$class\" id=\"$tid\"
3940 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3948 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3949 $page_next_link = "javascript:viewFeedGoPage(1)";
3950 $page_first_link = "javascript:viewFeedGoPage(0)";
3952 $catchup_page_link = "javascript:catchupPage()";
3953 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3954 $catchup_sel_link = "javascript:catchupSelection()";
3956 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3958 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3959 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3960 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3961 $sel_inv_link = "javascript:invertHeadlineSelection()";
3963 $tog_unread_link = "javascript:selectionToggleUnread()";
3964 $tog_marked_link = "javascript:selectionToggleMarked()";
3965 $tog_published_link = "javascript:selectionTogglePublished()";
3969 $sel_all_link = "javascript:cdmSelectArticles('all')";
3970 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3971 $sel_none_link = "javascript:cdmSelectArticles('none')";
3973 $sel_inv_link = "javascript:invertHeadlineSelection()";
3975 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3976 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3977 $tog_published_link = "javascript:selectionTogglePublished(true)";
3981 print "<td class=\"headlineActions$rtl_cpart\">";
3984 /* print"<ul class=\"headlineDropdownMenu\">
3987 <a href=\"$sel_all_link\">".__('All')."</a>,
3988 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3989 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3990 <a href=\"$sel_none_link\">".__('None')."</a></li>
3991 <li class=\"vsep\"> </li>
3992 <li class=\"top\">".__('Actions...')."<ul>
3993 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
3994 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
3995 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
3996 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
3997 <!-- <li><span class=\"insensitive\">--------</span></li> -->
3998 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
3999 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4001 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed')."</li>";
4003 //print "<li><span class=\"insensitive\">--------</span></li>";
4004 print "<li><span class=\"insensitive\">".__('Assign label:')."</span></li>";
4006 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
4007 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4009 while ($line = db_fetch_assoc($result)) {
4011 $label_id = $line["id"];
4012 $label_caption = $line["caption"];
4014 if ($feed_id < -10 && $feed_id == -11-$label_id) {
4015 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
4016 $label_caption ".__('(remove)')."</li>";
4018 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
4019 $label_caption</li>";
4023 print "</ul></li></ul>"; */
4025 print __('Select:')."
4026 <a href=\"$sel_all_link\">".__('All')."</a>,
4027 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4028 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4029 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4031 print " ";
4034 onmouseover=\"enable_selection(false)\"
4035 onmouseout=\"enable_selection(true)\"
4036 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4037 __("Actions...") . " <img src=\"images/down_arrow.png\">
4040 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4042 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4043 <li onclick=\"$tog_unread_link\"> ".__('Unread')."</li>
4044 <li onclick=\"$tog_marked_link\"> ".__('Starred')."</li>
4045 <li onclick=\"$tog_published_link\"> ".__('Published')."</li>
4046 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4047 <li class=\"insensitive\">".__('Mark as read:')."</li>
4048 <li onclick=\"$catchup_sel_link\"> ".__('Selection')."</li>";
4050 print "<li onclick=\"$catchup_feed_link\"> ".__('Entire feed').
4053 //print "<li><span class=\"insensitive\">--------</span></li>";
4054 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4056 print "<li onclick=\"javascript:addLabel()\">
4057 ".__("Create label...")."</li>";
4059 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
4060 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4062 while ($line = db_fetch_assoc($result)) {
4064 $label_id = $line["id"];
4065 $label_caption = $line["caption"];
4067 if ($feed_id < -10 && $feed_id == -11-$label_id) {
4068 print "<li onclick=\"javascript:selectionRemoveLabel($label_id)\">
4069 $label_caption ".__('(remove)')."</li>";
4071 print "<li onclick=\"javascript:selectionAssignLabel($label_id)\">
4072 $label_caption</li>";
4080 print "<td class=\"headlineTitle$rtl_cpart\">";
4082 print "<span id=\"subtoolbar_search\"
4083 style=\"display : none\"><input
4084 id=\"subtoolbar_search_box\"
4085 onblur=\"javascript:enableHotkeys();\"
4086 onfocus=\"javascript:disableHotkeys();\"
4087 onchange=\"subtoolbarSearch()\"
4088 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4090 print "<span id=\"subtoolbar_ftitle\">";
4092 if ($feed_site_url) {
4094 $target = "target=\"_blank\"";
4096 print "<a $target href=\"$feed_site_url\">".
4097 truncate_string($feed_title,30)."</a>";
4103 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4106 if ($user_page_offset > 1) {
4107 print " [$user_page_offset] ";
4110 if (!$bottom && !$disable_feed) {
4112 <a target=\"_blank\"
4113 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4114 <img class=\"noborder\"
4115 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4117 } else if ($feed_small_icon) {
4118 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4124 print "</tr></table></nobr>";
4128 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4130 $tmp_category = getCategoryTitle($link, $cat_id);
4133 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4134 } else if ($cat_id == 0 ||
$cat_id == -2) {
4135 $cat_unread = getCategoryUnread($link, $cat_id);
4139 $holder_style = "display:none;";
4146 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4149 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4150 $inner_title_class = "catTitle";
4152 $browse_cat_link = "";
4153 $inner_title_class = "catTitleNL";
4156 $cat_class = "feedCat";
4158 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4159 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4160 title=\"".__('Click to collapse category')."\"
4161 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4162 id=\"FCATN-$cat_id\" $browse_cat_link
4163 \">$tmp_category</span>";
4165 print "<span id=\"FCAP-$cat_id\">";
4167 print " <span id=\"FCATCTR-$cat_id\"
4168 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4174 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4178 function outputFeedList($link, $tags = false) {
4180 print "<ul class=\"feedList\" id=\"feedList\">";
4182 $owner_uid = $_SESSION["uid"];
4186 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4188 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4191 $cat_hidden = false;
4194 printCategoryHeader($link, -1, $cat_hidden, false);
4197 $num_starred = getFeedUnread($link, -1);
4198 $num_published = getFeedUnread($link, -2);
4199 $num_fresh = getFeedUnread($link, -3);
4200 $num_total = getFeedUnread($link, -4);
4204 if ($num_total > 0) $class .= "Unread";
4206 printFeedEntry(-4, $class, __("All articles"), $num_total,
4207 "images/tag.png", $link);
4211 if ($num_fresh > 0) $class .= "Unread";
4213 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4214 "images/fresh.png", $link);
4218 if ($num_starred > 0) $class .= "Unread";
4220 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4223 $mark_img_ext = "gif";
4225 $mark_img_ext = "png";
4228 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4229 "images/mark_set.$mark_img_ext", $link);
4233 if ($num_published > 0) $class .= "Unread";
4235 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4236 "images/pub_set.gif", $link);
4238 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4245 $result = db_query($link, "SELECT id,caption FROM
4246 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4248 if (db_num_rows($result) > 0) {
4249 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4251 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4254 $cat_hidden = false;
4257 printCategoryHeader($link, -2, $cat_hidden, true);
4260 print "<li><hr></li>";
4264 while ($line = db_fetch_assoc($result)) {
4266 $label_id = -$line['id'] - 11;
4267 $count = getFeedUnread($link, $label_id);
4275 printFeedEntry($label_id,
4276 $class, $line["caption"],
4277 $count, "images/label.png", $link);
4281 if (db_num_rows($result) > 0) {
4282 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4288 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4289 print "<li><hr></li>";
4292 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4293 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4294 $order_by_qpart = "order_id,category,unread DESC,title";
4296 $order_by_qpart = "order_id,category,title";
4299 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4300 $order_by_qpart = "unread DESC,title";
4302 $order_by_qpart = "title";
4306 $age_qpart = getMaxAgeSubquery();
4308 $query = "SELECT ttrss_feeds.*,
4309 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4311 ttrss_feed_categories.title AS category,
4312 ttrss_feed_categories.collapsed,
4314 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4315 ON (ttrss_feed_categories.id = cat_id)
4316 LEFT JOIN ttrss_counters_cache
4318 (ttrss_feeds.id = feed_id)
4320 ttrss_feeds.hidden = false AND
4321 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4322 ORDER BY $order_by_qpart";
4324 $result = db_query($link, $query);
4326 $actid = $_GET["actid"];
4336 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4338 while ($line = db_fetch_assoc($result)) {
4340 $feed = trim($line["title"]);
4342 if (!$feed) $feed = "[Untitled]";
4344 $feed_id = $line["id"];
4345 $unread = $line["unread"];
4347 $subop = $_GET["subop"];
4349 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4350 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4352 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4355 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4358 $rtl_tag = "dir=\"RTL\"";
4363 $tmp_result = db_query($link,
4364 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4365 WHERE parent_feed = '$feed_id' AND feed_id = id");
4367 $unread +
= db_fetch_result($tmp_result, 0, "unread");
4369 $cat_id = $line["cat_id"];
4371 $tmp_category = $line["category"];
4373 if (!$tmp_category) {
4374 $tmp_category = __("Uncategorized");
4377 // $class = ($lnum % 2) ? "even" : "odd";
4379 if ($line["last_error"]) {
4385 if ($unread > 0) $class .= "Unread";
4387 if ($actid == $feed_id) {
4388 $class .= "Selected";
4391 $total_unread +
= $unread;
4393 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4399 $category = $tmp_category;
4401 $collapsed = sql_bool_to_bool($line["collapsed"]);
4403 // workaround for NULL category
4404 if ($category == __("Uncategorized")) {
4405 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4410 $cat_id = sprintf("%d", $cat_id);
4412 printCategoryHeader($link, $cat_id, $collapsed, true);
4416 printFeedEntry($feed_id, $class, $feed, $unread,
4417 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4418 $last_updated, $line["last_error"]);
4423 if (db_num_rows($result) == 0) {
4424 print "<li>".__('No feeds to display.')."</li>";
4431 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4432 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4433 post_int_id = ttrss_user_entries.int_id AND
4434 unread = true AND ref_id = ttrss_entries.id
4435 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4437 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4438 ORDER BY tag_name"); */
4440 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4441 print "<li class=\"feedCat\">".__('Tags')."</li>";
4442 print "<ul class=\"feedCatList\">";
4445 $age_qpart = getMaxAgeSubquery();
4447 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4448 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4449 AND ref_id = id AND $age_qpart
4450 AND unread = true)) AS count FROM ttrss_tags
4451 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4452 ORDER BY count DESC LIMIT 50");
4456 while ($line = db_fetch_assoc($result)) {
4457 $tags[$line["tag_name"]] +
= $line["count"];
4460 foreach (array_keys($tags) as $tag) {
4462 $unread = $tags[$tag];
4470 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4474 if (db_num_rows($result) == 0) {
4475 print "<li>No tags to display.</li>";
4478 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4488 function get_article_tags($link, $id, $owner_uid = 0) {
4490 $a_id = db_escape_string($id);
4492 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4494 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4495 owner_uid as owner FROM
4496 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4497 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4501 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4502 array_push($tags, $tmp_line["tag_name"]);
4508 function trim_value(&$value) {
4509 $value = trim($value);
4512 function trim_array($array) {
4514 array_walk($tmp, 'trim_value');
4518 function tag_is_valid($tag) {
4519 if ($tag == '') return false;
4520 if (preg_match("/^[0-9]*$/", $tag)) return false;
4522 if (function_exists('iconv')) {
4523 $tag = iconv("utf-8", "utf-8", $tag);
4526 if (!$tag) return false;
4531 function render_login_form($link, $mobile = false) {
4533 require_once "login_form.php";
4535 require_once "mobile/login_form.php";
4539 // from http://developer.apple.com/internet/safari/faq.html
4540 function no_cache_incantation() {
4541 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4542 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4543 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4544 header("Cache-Control: post-check=0, pre-check=0", false);
4545 header("Pragma: no-cache"); // HTTP/1.0
4548 function format_warning($msg, $id = "") {
4549 return "<div class=\"warning\" id=\"$id\">
4550 <img src=\"images/sign_excl.gif\">$msg</div>";
4553 function format_notice($msg) {
4554 return "<div class=\"notice\">
4555 <img src=\"images/sign_info.gif\">$msg</div>";
4558 function format_error($msg) {
4559 return "<div class=\"error\">
4560 <img src=\"images/sign_excl.gif\">$msg</div>";
4563 function print_notice($msg) {
4564 return print format_notice($msg);
4567 function print_warning($msg) {
4568 return print format_warning($msg);
4571 function print_error($msg) {
4572 return print format_error($msg);
4576 function T_sprintf() {
4577 $args = func_get_args();
4578 return vsprintf(__(array_shift($args)), $args);
4581 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4582 $zoom_mode = false) {
4584 /* we can figure out feed_id from article id anyway, why do we
4585 * pass feed_id here? */
4587 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4588 WHERE ref_id = '$id'");
4590 $feed_id = db_fetch_result($result, 0, "feed_id");
4592 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4594 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4595 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4597 if (db_num_rows($result) == 1) {
4598 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4600 $rtl_content = false;
4604 $rtl_tag = "dir=\"RTL\"";
4611 if ($mark_as_read) {
4612 $result = db_query($link, "UPDATE ttrss_user_entries
4613 SET unread = false,last_read = NOW()
4614 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4616 ccache_update($link, $feed_id, $_SESSION["uid"]);
4619 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4620 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4621 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4624 FROM ttrss_entries,ttrss_user_entries
4625 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4631 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4632 $link_target = "target=\"_blank\"";
4635 $line = db_fetch_assoc($result);
4637 if ($line["icon_url"]) {
4638 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4640 $feed_icon = " ";
4643 $num_comments = $line["num_comments"];
4644 $entry_comments = "";
4646 if ($num_comments > 0) {
4647 if ($line["comments"]) {
4648 $comments_url = $line["comments"];
4650 $comments_url = $line["link"];
4652 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4654 if ($line["comments"] && $line["link"] != $line["comments"]) {
4655 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4660 header("Content-Type: text/html");
4662 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4663 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4664 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4669 print "<div class=\"postReply\">";
4671 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4672 onmouseout=\"enable_resize(false)\">";
4674 $entry_author = $line["author"];
4676 if ($entry_author) {
4677 $entry_author = __(" - ") . $entry_author;
4680 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4681 strtotime($line["updated"]));
4683 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4685 if ($line["link"]) {
4686 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4687 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4689 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4692 $tags = get_article_tags($link, $id);
4695 $tags_nolinks_str = "";
4700 if ($_SESSION["theme"] == "3pane") {
4706 foreach ($tags as $tag) {
4708 $tag_escaped = str_replace("'", "\\'", $tag);
4710 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4712 if ($num_tags == $tag_limit) {
4713 $tags_str .= "…";
4714 $tags_nolinks_str .= "…";
4716 } else if ($num_tags < $tag_limit) {
4717 $tags_str .= $tag_str;
4718 $tags_nolinks_str .= "$tag, ";
4720 $f_tags_str .= $tag_str;
4723 $tags_str = preg_replace("/, $/", "", $tags_str);
4724 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4725 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4727 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4728 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4730 if (!$entry_comments) $entry_comments = " "; # placeholder
4732 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4733 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4735 print "<div style='float : right'>
4736 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4740 <a title=\"".__('Edit tags for this article')."\"
4741 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4743 if (defined('_ENABLE_INLINE_VIEW')) {
4745 print "<img src=\"images/art-inline.png\" class='tagsPic'
4746 style=\"cursor : pointer\" style=\"cursor : pointer\"
4747 onclick=\"showOriginalArticleInline($id)\"
4748 alt='Inline' title='".__('Display original article content')."'>";
4752 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4753 style=\"cursor : pointer\" style=\"cursor : pointer\"
4754 onclick=\"zoomToArticle($id)\"
4755 alt='Zoom' title='".__('Show article summary in new window')."'>";
4757 print "$tags_nolinks_str";
4760 print "<div clear='both'>$entry_comments</div>";
4764 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4766 print "<div class=\"postContent\">";
4768 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4770 $article_content = sanitize_rss($link, $line["content"]);
4772 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4773 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4777 print $article_content;
4779 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4780 post_id = '$id' AND content_url != ''");
4782 if (db_num_rows($result) > 0) {
4784 $entries_html = array();
4787 while ($line = db_fetch_assoc($result)) {
4789 $url = $line["content_url"];
4790 $ctype = $line["content_type"];
4792 if (!$ctype) $ctype = __("unknown type");
4794 $filename = substr($url, strrpos($url, "/")+
1);
4798 if (($ctype == __("audio/mpeg")) &&
4799 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4801 $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> ";
4805 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4806 $filename . " (" . $ctype . ")" . "</a>";
4808 array_push($entries_html, $entry);
4812 $entry["type"] = $ctype;
4813 $entry["filename"] = $filename;
4814 $entry["url"] = $url;
4816 array_push($entries, $entry);
4819 print "<div class=\"postEnclosures\">";
4821 if (!preg_match("/img/i", $article_content)) {
4822 foreach ($entries as $entry) {
4823 if (preg_match("/image/", $entry["type"])) {
4825 alt=\"".htmlspecialchars($entry["filename"])."\"
4826 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4831 print "<div class=\"postEnclosures\">";
4833 if (db_num_rows($result) == 1) {
4834 print __("Attachment:") . " ";
4836 print __("Attachments:") . " ";
4839 print join(", ", $entries_html);
4851 print "]]></article>";
4854 <div style=\"text-align : center\">
4855 <input type=\"submit\" onclick=\"return window.close()\"
4856 value=\"".__("Close this window")."\"></div>";
4857 print "</body></html>";
4863 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4864 $next_unread_feed, $offset, $vgr_last_feed = false,
4865 $override_order = false) {
4867 $disable_cache = false;
4869 $timing_info = getmicrotime();
4871 $topmost_article_ids = array();
4877 if ($subop == "undefined") $subop = "";
4879 $subop_split = split(":", $subop);
4881 if ($subop == "CatchupSelected") {
4882 $ids = split(",", db_escape_string($_GET["ids"]));
4883 $cmode = sprintf("%d", $_GET["cmode"]);
4885 catchupArticlesById($link, $ids, $cmode);
4888 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4889 update_generic_feed($link, $feed, $cat_view, true);
4892 if ($subop == "MarkAllRead") {
4893 catchup_feed($link, $feed, $cat_view);
4895 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4896 if ($next_unread_feed) {
4897 $feed = $next_unread_feed;
4902 if ($subop_split[0] == "MarkAllReadGR") {
4903 catchup_feed($link, $subop_split[1], false);
4908 $result = db_query($link,
4909 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4911 if (db_num_rows($result) == 0) {
4912 print "<div align='center'>".__('Feed not found.')."</div>";
4917 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4919 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4920 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4922 if (db_num_rows($result) == 1) {
4923 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4925 $rtl_content = false;
4929 $rtl_tag = "dir=\"RTL\"";
4935 $rtl_content = false;
4938 $script_dt_add = get_script_dt_add();
4940 /// START /////////////////////////////////////////////////////////////////////////////////
4942 $search = db_escape_string($_GET["query"]);
4945 $disable_cache = true;
4948 $search_mode = db_escape_string($_GET["search_mode"]);
4949 $match_on = db_escape_string($_GET["match_on"]);
4955 $real_offset = $offset * $limit;
4957 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4959 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4960 $search, $search_mode, $match_on, $override_order, $real_offset);
4962 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4964 $result = $qfh_ret[0];
4965 $feed_title = $qfh_ret[1];
4966 $feed_site_url = $qfh_ret[2];
4967 $last_error = $qfh_ret[3];
4969 $vgroup_last_feed = $vgr_last_feed;
4972 $feed_site_url = article_publish_url($link);
4975 /// STOP //////////////////////////////////////////////////////////////////////////////////
4978 print "<div id=\"headlinesContainer\" $rtl_tag>";
4981 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4985 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4986 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4989 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4992 $headlines_count = db_num_rows($result);
4994 if (db_num_rows($result) > 0) {
4996 # print "\{$offset}";
4998 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4999 print "<table class=\"headlinesList\" id=\"headlinesList\"
5000 cellspacing=\"0\">";
5003 $lnum = $limit*$offset;
5005 error_reporting (DEFAULT_ERROR_LEVEL
);
5008 $cur_feed_title = '';
5010 while ($line = db_fetch_assoc($result)) {
5012 $class = ($lnum %
2) ?
"even" : "odd";
5015 $feed_id = $line["feed_id"];
5017 $labels = get_article_labels($link, $id);
5018 $labels_str = "<span id=\"HLLCTR-$id\">";
5020 foreach ($labels as $l) {
5021 $labels_str .= "<span
5022 class='hlLabelRef'>".
5026 $labels_str .= "</span>";
5028 if (count($topmost_article_ids) < 5) {
5029 array_push($topmost_article_ids, $id);
5032 if ($line["last_read"] == "" &&
5033 ($line["unread"] != "t" && $line["unread"] != "1")) {
5035 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5038 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5042 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5050 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5053 $mark_img_ext = "gif";
5055 $mark_img_ext = "png";
5058 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5059 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5061 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5063 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5065 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5068 if ($line["published"] == "t" ||
$line["published"] == "1") {
5069 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5071 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5073 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5075 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5078 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5079 # $line["title"] . "</a>";
5081 # $content_link = "<a
5082 # href=\"" . htmlspecialchars($line["link"]) . "\"
5083 # onclick=\"view($id,$feed_id);\">" .
5084 # $line["title"] . "</a>";
5086 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5087 # $line["title"] . "</a>";
5089 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5090 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5092 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5093 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5096 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5097 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5101 $score = $line["score"];
5103 $score_pic = get_score_pic($score);
5105 /* $score_title = __("(Click to change)");
5106 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5107 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5109 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5114 } else if ($score < -100) {
5120 $entry_author = $line["author"];
5122 if ($entry_author) {
5123 $entry_author = " - $entry_author";
5126 $has_feed_icon = feed_has_icon($feed_id);
5128 if ($has_feed_icon) {
5129 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5131 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5132 $feed_icon_img = "";
5135 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5137 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5138 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5140 $cur_feed_title = $line["feed_title"];
5141 $vgroup_last_feed = $feed_id;
5143 $cur_feed_title = htmlspecialchars($cur_feed_title);
5145 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5147 print "<tr class='feedTitle'><td colspan='7'>".
5148 "<div style=\"float : right\">$feed_icon_img</div>".
5149 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5150 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5154 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5155 onmouseout='postMouseOut($id)'";
5157 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5159 print "<td class='hlUpdPic'>$update_pic</td>";
5161 print "<td class='hlSelectRow'>
5162 <input type=\"checkbox\" onclick=\"tSR(this)\"
5166 print "<td class='hlMarkedPic'>$marked_pic</td>";
5167 print "<td class='hlMarkedPic'>$published_pic</td>";
5169 # if ($line["feed_title"]) {
5170 # print "<td class='hlContent'>$content_link</td>";
5171 # print "<td class='hlFeed'>
5172 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5173 # truncate_string($line["feed_title"],30)."</a> </td>";
5176 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5178 print "<a id=\"RTITLE-$id\"
5179 href=\"" . htmlspecialchars($line["link"]) . "\"
5180 onclick=\"return view($id,$feed_id);\">" .
5183 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5184 if ($content_preview) {
5185 print "<span class=\"contentPreview\"> - $content_preview</span>";
5193 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5194 # $line["feed_title"]."</a>
5196 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5197 if ($line["feed_title"]) {
5198 print "<span class=\"hlFeed\">
5199 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5200 $line["feed_title"]."</a>)
5208 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt </nobr></td>";
5210 print "<td class='hlMarkedPic'>$score_pic</td>";
5212 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5213 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5220 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5221 if ($feed_id != $vgroup_last_feed) {
5223 $cur_feed_title = $line["feed_title"];
5224 $vgroup_last_feed = $feed_id;
5226 $cur_feed_title = htmlspecialchars($cur_feed_title);
5228 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5230 $has_feed_icon = feed_has_icon($feed_id);
5232 if ($has_feed_icon) {
5233 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5235 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5238 print "<div class='cdmFeedTitle'>".
5239 "<div style=\"float : right\">$feed_icon_img</div>".
5240 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5241 $line["feed_title"]."</a> $vf_catchup_link</div>";
5246 $add_class = "Unread";
5251 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5252 $show_excerpt = false;
5254 if ($expand_cdm && $score >= -100) {
5256 $show_excerpt = false;
5258 $cdm_cstyle = "style=\"display : none\"";
5259 $show_excerpt = true;
5262 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5263 onmouseout='postMouseOut($id)'";
5265 print "<div class=\"cdmArticle$add_class\"
5267 $mouseover_attrs'>";
5269 print "<div class=\"cdmHeader\">";
5271 if (!get_pref($link, "VFEED_GROUP_BY_FEED") ||
!$line["feed_title"]) {
5272 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5275 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5278 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5279 onclick=\"javascript:toggleUnread($id, 0)\"
5280 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5283 print $entry_author;
5285 /* if (!$expand_cdm || $score < -100) {
5286 print " <a id=\"CICH-$id\"
5287 href=\"javascript:cdmExpandArticle($id)\">
5288 (".__('Show article').")</a>";
5293 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5294 if ($line["feed_title"]) {
5295 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5299 print "</span></div>";
5301 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5302 $line["content_preview"] = preg_replace("/href=/i",
5303 "target=\"_blank\" href=", $line["content_preview"]);
5306 if ($show_excerpt) {
5307 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5308 onclick=\"cdmExpandArticle($id)\"
5309 title=\"".__('Click to expand article')."\">";
5310 print truncate_string(strip_tags($line["content_preview"]), 100);
5314 print "<div class=\"cdmContent\"
5315 onclick=\"cdmClicked($id)\"
5316 id=\"CICD-$id\" $cdm_cstyle>";
5318 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5320 print sanitize_rss($link, $line["content_preview"]);
5321 $article_content = $line["content_preview"];
5323 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5324 post_id = '$id' AND content_url != ''");
5326 if (db_num_rows($e_result) > 0) {
5328 $entries_html = array();
5331 while ($e_line = db_fetch_assoc($e_result)) {
5333 $url = $e_line["content_url"];
5334 $ctype = $e_line["content_type"];
5335 if (!$ctype) $ctype = __("unknown type");
5337 $filename = substr($url, strrpos($url, "/")+
1);
5341 if (($ctype == __("audio/mpeg")) &&
5342 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5344 $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> ";
5348 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5349 $filename . " (" . $ctype . ")" . "</a>";
5351 array_push($entries_html, $entry);
5355 $entry["type"] = $ctype;
5356 $entry["filename"] = $filename;
5357 $entry["url"] = $url;
5359 array_push($entries, $entry);
5362 if (!preg_match("/img/i", $article_content)) {
5363 foreach ($entries as $entry) {
5364 if (preg_match("/image/", $entry["type"])) {
5366 alt=\"".htmlspecialchars($entry["filename"])."\"
5367 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5372 print "<div class=\"cdmEnclosures\">";
5374 if (db_num_rows($e_result) == 1) {
5375 print __("Attachment:") . " ";
5377 print __("Attachments:") . " ";
5380 print join(", ", $entries_html);
5386 print "<br clear='both'>";
5389 /* if (!$expand_cdm) {
5390 print "<a id=\"CICH-$id\"
5391 href=\"javascript:cdmExpandArticle($id)\">
5397 print "<div class=\"cdmFooter\"><span class='s0'>";
5399 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5401 print __("Select:").
5402 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5403 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5405 print "</span><span class='s1'>$marked_pic</span> ";
5406 print "<span class='s1'>$published_pic</span> ";
5407 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5408 onclick=\"zoomToArticle($id)\"
5409 style=\"cursor : pointer\"
5411 title='".__('Show article summary in new window')."'></span>";
5413 $tags = get_article_tags($link, $id);
5416 $full_tags_str = "";
5419 foreach ($tags as $tag) {
5421 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5422 if ($num_tags < 5) {
5423 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5424 } else if ($num_tags == 5) {
5425 $tags_str .= "…";
5429 $tags_str = preg_replace("/, $/", "", $tags_str);
5430 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5432 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5434 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5437 if ($tags_str == "") $tags_str = "no tags";
5439 // print "<img src='images/tag.png' class='markedPic'>";
5441 print "<span class='s1'>
5442 <img class='tagsPic' src='images/tag.png' alt='Tags'
5443 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5444 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5448 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5449 href=\"javascript:toggleUnread($id)\">
5460 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5467 switch ($view_mode) {
5469 $message = __("No unread articles found to display.");
5472 $message = __("No updated articles found to display.");
5475 $message = __("No starred articles found to display.");
5479 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5481 $message = __("No articles found to display.");
5485 if (!$offset) print "<div class='whiteBox'>$message</div>";
5493 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5496 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5498 function printTagCloud($link) {
5500 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5501 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5502 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5504 $result = db_query($link, $query);
5508 while ($line = db_fetch_assoc($result)) {
5509 $tags[$line["tag_name"]] = $line["count"];
5514 $max_size = 32; // max font size in pixels
5515 $min_size = 11; // min font size in pixels
5517 // largest and smallest array values
5518 $max_qty = max(array_values($tags));
5519 $min_qty = min(array_values($tags));
5521 // find the range of values
5522 $spread = $max_qty - $min_qty;
5523 if ($spread == 0) { // we don't want to divide by zero
5527 // set the font-size increment
5528 $step = ($max_size - $min_size) / ($spread);
5530 // loop through the tag array
5531 foreach ($tags as $key => $value) {
5532 // calculate font-size
5533 // find the $value in excess of $min_qty
5534 // multiply by the font-size increment ($size)
5535 // and add the $min_size set above
5536 $size = round($min_size +
(($value - $min_qty) * $step));
5538 $key_escaped = str_replace("'", "\\'", $key);
5540 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5541 $size . "px\" title=\"$value articles tagged with " .
5542 $key . '">' . $key . '</a> ';
5546 function print_checkpoint($n, $s) {
5547 $ts = getmicrotime();
5548 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5552 function sanitize_tag($tag) {
5555 $tag = mb_strtolower($tag, 'utf-8');
5557 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5559 // $tag = str_replace('"', "", $tag);
5560 // $tag = str_replace("+", " ", $tag);
5561 $tag = str_replace("technorati tag: ", "", $tag);
5566 function generate_publish_key() {
5567 return sha1(uniqid(rand(), true));
5570 function article_publish_url($link) {
5575 if ($_SERVER['HTTPS'] != "on") {
5576 $url_path = "http://";
5578 $url_path = "https://";
5581 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5582 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5588 * Purge a feed contents, marked articles excepted.
5590 * @param mixed $link The database connection.
5591 * @param integer $id The id of the feed to purge.
5594 function clear_feed_articles($link, $id) {
5595 $result = db_query($link, "DELETE FROM ttrss_user_entries
5596 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5598 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5599 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5601 ccache_update($link, $id, $_SESSION['uid']);
5602 } // function clear_feed_articles
5605 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5607 * @return string The Mozilla Firefox feed adding URL.
5609 function add_feed_url() {
5610 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5611 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5613 } // function add_feed_url
5616 * Encrypt a password in SHA1.
5618 * @param string $pass The password to encrypt.
5619 * @param string $login A optionnal login.
5620 * @return string The encrypted password.
5622 function encrypt_password($pass, $login = '') {
5624 return "SHA1X:" . sha1("$login:$pass");
5626 return "SHA1:" . sha1($pass);
5628 } // function encrypt_password
5631 * Update a feed batch.
5632 * Used by daemons to update n feeds by run.
5633 * Only update feed needing a update, and not being processed
5634 * by another process.
5636 * @param mixed $link Database link
5637 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5638 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5639 * @param boolean $debug Set to false to disable debug output. Default to true.
5642 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5643 // Process all other feeds using last_updated and interval parameters
5645 // Test if the user has loggued in recently. If not, it does not update its feeds.
5646 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5647 if (DB_TYPE
== "pgsql") {
5648 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5650 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5653 $login_thresh_qpart = "";
5656 // Test if the feed need a update (update interval exceded).
5657 if (DB_TYPE
== "pgsql") {
5658 $update_limit_qpart = "AND ((
5659 ttrss_feeds.update_interval = 0
5660 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5662 ttrss_feeds.update_interval > 0
5663 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5664 ) OR ttrss_feeds.last_updated IS NULL)";
5666 $update_limit_qpart = "AND ((
5667 ttrss_feeds.update_interval = 0
5668 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5670 ttrss_feeds.update_interval > 0
5671 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5672 ) OR ttrss_feeds.last_updated IS NULL)";
5675 // Test if feed is currently being updated by another process.
5676 if (DB_TYPE
== "pgsql") {
5677 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5679 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5682 // Test if there is a limit to number of updated feeds
5684 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5686 $random_qpart = sql_random_function();
5688 // We search for feed needing update.
5689 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5690 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5691 ttrss_feeds.update_interval
5693 ttrss_feeds, ttrss_users, ttrss_user_prefs
5695 ttrss_feeds.owner_uid = ttrss_users.id
5696 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5697 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5698 $login_thresh_qpart $update_limit_qpart
5699 $updstart_thresh_qpart
5700 ORDER BY $random_qpart $query_limit");
5702 $user_prefs_cache = array();
5704 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5706 // Here is a little cache magic in order to minimize risk of double feed updates.
5707 $feeds_to_update = array();
5708 while ($line = db_fetch_assoc($result)) {
5709 $feeds_to_update[$line['id']] = $line;
5712 // We update the feed last update started date before anything else.
5713 // There is no lag due to feed contents downloads
5714 // It prevent an other process to update the same feed.
5715 $feed_ids = array_keys($feeds_to_update);
5717 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5718 WHERE id IN (%s)", implode(',', $feed_ids)));
5721 // For each feed, we call the feed update function.
5722 while ($line = array_pop($feeds_to_update)) {
5724 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5726 // We setup a alarm to alert if the feed take more than 300s to update.
5728 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5729 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5730 // Cancel the alarm (the update went well)
5731 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5733 sleep(1); // prevent flood (FIXME make this an option?)
5736 // Send feed digests by email if needed.
5737 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5739 purge_orphans($link);
5741 } // function update_daemon_common
5743 function sanitize_article_content($text) {
5744 # we don't support CDATA sections in articles, they break our own escaping
5745 $text = preg_replace("/\[\[CDATA/", "", $text);
5746 $text = preg_replace("/\]\]\>/", "", $text);
5750 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5753 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5755 $result = db_query($link, "SELECT reg_exp,
5756 ttrss_filter_types.name AS name,
5757 ttrss_filter_actions.name AS action,
5761 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5764 owner_uid = $owner_uid AND
5765 ttrss_filter_types.id = filter_type AND
5766 ttrss_filter_actions.id = action_id AND
5767 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5769 while ($line = db_fetch_assoc($result)) {
5770 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5771 $filter["reg_exp"] = $line["reg_exp"];
5772 $filter["action"] = $line["action"];
5773 $filter["action_param"] = $line["action_param"];
5774 $filter["filter_param"] = $line["filter_param"];
5775 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5777 array_push($filters[$line["name"]], $filter);
5783 function get_score_pic($score) {
5785 return "score_high.png";
5786 } else if ($score > 0) {
5787 return "score_half_high.png";
5788 } else if ($score < -100) {
5789 return "score_low.png";
5790 } else if ($score < 0) {
5791 return "score_half_low.png";
5793 return "score_neutral.png";
5797 function rounded_table_start($classname, $header = " ") {
5798 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5799 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5800 print "<tr><td class='left'> </td><td class='content'>";
5803 function rounded_table_end($footer = " ") {
5804 print "</td><td class='right'> </td></tr>";
5805 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5809 function feed_has_icon($id) {
5810 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5813 function init_connection($link) {
5814 if (DB_TYPE
== "pgsql") {
5815 pg_query($link, "set client_encoding = 'UTF-8'");
5816 pg_set_client_encoding("UNICODE");
5817 pg_query($link, "set datestyle = 'ISO, european'");
5819 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5820 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5821 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5826 function update_feedbrowser_cache($link) {
5828 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5829 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5830 WHERE tf.feed_url = ttrss_feeds.feed_url
5831 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5832 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5834 db_query($link, "BEGIN");
5836 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5840 while ($line = db_fetch_assoc($result)) {
5841 $subscribers = db_escape_string($line["subscribers"]);
5842 $feed_url = db_escape_string($line["feed_url"]);
5843 $title = db_escape_string($line["title"]);
5845 $tmp_result = db_query($link, "SELECT subscribers FROM
5846 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5848 if (db_num_rows($tmp_result) == 0) {
5850 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5851 (feed_url, title, subscribers) VALUES ('$feed_url',
5852 '$title', '$subscribers')");
5860 db_query($link, "COMMIT");
5866 function ccache_zero($link, $feed_id, $owner_uid) {
5867 db_query($link, "UPDATE ttrss_counters_cache SET
5868 value = 0, updated = NOW() WHERE
5869 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5872 function ccache_zero_all($link, $owner_uid) {
5873 db_query($link, "UPDATE ttrss_counters_cache SET
5874 value = 0 WHERE owner_uid = '$owner_uid'");
5876 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5877 value = 0 WHERE owner_uid = '$owner_uid'");
5880 function ccache_update_all($link, $owner_uid) {
5882 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5884 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5885 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5887 while ($line = db_fetch_assoc($result)) {
5888 ccache_update($link, $line["feed_id"], $owner_uid, true);
5891 /* We have to manually include category 0 */
5893 ccache_update($link, 0, $owner_uid, true);
5896 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5897 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5899 while ($line = db_fetch_assoc($result)) {
5900 print ccache_update($link, $line["feed_id"], $owner_uid);
5907 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5908 $no_update = false) {
5911 $table = "ttrss_counters_cache";
5913 $table = "ttrss_cat_counters_cache";
5916 if (DB_TYPE
== "pgsql") {
5917 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5918 } else if (DB_TYPE
== "mysql") {
5919 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5922 $result = db_query($link, "SELECT value FROM $table
5923 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5926 if (db_num_rows($result) == 1) {
5927 return db_fetch_result($result, 0, "value");
5932 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5938 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5939 $update_pcat = true) {
5941 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5943 /* When updating a label, all we need to do is recalculate feed counters
5944 * because labels are not cached */
5947 ccache_update_all($link, $owner_uid);
5952 $table = "ttrss_counters_cache";
5954 $table = "ttrss_cat_counters_cache";
5957 if ($is_cat && $feed_id >= 0) {
5958 if ($feed_id != 0) {
5959 $cat_qpart = "cat_id = '$feed_id'";
5961 $cat_qpart = "cat_id IS NULL";
5964 /* Recalculate counters for child feeds */
5966 $result = db_query($link, "SELECT id FROM ttrss_feeds
5967 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5969 while ($line = db_fetch_assoc($result)) {
5970 ccache_update($link, $line["id"], $owner_uid, false, false);
5973 $result = db_query($link, "SELECT SUM(value) AS sv
5974 FROM ttrss_counters_cache, ttrss_feeds
5975 WHERE id = feed_id AND $cat_qpart AND
5976 ttrss_feeds.owner_uid = '$owner_uid'");
5978 $unread = (int) db_fetch_result($result, 0, "sv");
5981 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5984 $result = db_query($link, "SELECT feed_id FROM $table
5985 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5987 if (db_num_rows($result) == 1) {
5988 db_query($link, "UPDATE $table SET
5989 value = '$unread', updated = NOW() WHERE
5990 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5993 db_query($link, "INSERT INTO $table
5994 (feed_id, value, owner_uid, updated)
5996 ($feed_id, $unread, $owner_uid, NOW())");
5999 if ($feed_id > 0 && $prev_unread != $unread) {
6003 /* Update parent category */
6007 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6008 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6010 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6012 ccache_update($link, $cat_id, $owner_uid, true);
6016 } else if ($feed_id < 0) {
6017 ccache_update_all($link, $owner_uid);
6023 function label_find_id($link, $label, $owner_uid) {
6024 $result = db_query($link,
6025 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6026 AND owner_uid = '$owner_uid' LIMIT 1");
6028 if (db_num_rows($result) == 1) {
6029 return db_fetch_result($result, 0, "id");
6035 function get_article_labels($link, $id) {
6036 $result = db_query($link,
6037 "SELECT DISTINCT label_id,caption
6038 FROM ttrss_labels2, ttrss_user_labels2
6040 AND article_id = '$id'
6041 AND owner_uid = ".$_SESSION["uid"] . "
6046 while ($line = db_fetch_assoc($result)) {
6047 $rk = array($line["label_id"], $line["caption"]);
6048 array_push($rv, $rk);
6055 function label_find_caption($link, $label, $owner_uid) {
6056 $result = db_query($link,
6057 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6058 AND owner_uid = '$owner_uid' LIMIT 1");
6060 if (db_num_rows($result) == 1) {
6061 return db_fetch_result($result, 0, "caption");
6067 function label_remove_article($link, $id, $label, $owner_uid) {
6069 $label_id = label_find_id($link, $label, $owner_uid);
6071 if (!$label_id) return;
6073 $result = db_query($link,
6074 "DELETE FROM ttrss_user_labels2
6076 label_id = '$label_id' AND
6077 article_id = '$id'");
6080 function label_add_article($link, $id, $label, $owner_uid) {
6082 $label_id = label_find_id($link, $label, $owner_uid);
6084 if (!$label_id) return;
6086 $result = db_query($link,
6088 article_id FROM ttrss_labels2, ttrss_user_labels2
6091 label_id = '$label_id' AND
6092 article_id = '$id' AND owner_uid = '$owner_uid'
6095 if (db_num_rows($result) == 0) {
6096 db_query($link, "INSERT INTO ttrss_user_labels2
6097 (label_id, article_id) VALUES ('$label_id', '$id')");
6101 function label_remove($link, $id, $owner_uid) {
6103 db_query($link, "BEGIN");
6105 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6108 $caption = db_fetch_result($result, 0, "caption");
6110 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6111 AND owner_uid = " . $_SESSION["uid"]);
6113 if (db_affected_rows($link, $result) != 0 && $caption) {
6115 /* Disable filters that reference label being removed */
6117 db_query($link, "UPDATE ttrss_filters SET
6118 enabled = false WHERE action_param = '$caption'
6120 AND owner_uid = " . $_SESSION["uid"]);
6123 db_query($link, "COMMIT");