3 date_default_timezone_set('UTC');
4 if (defined('E_DEPRECATED')) {
5 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
7 error_reporting(E_ALL
& ~E_NOTICE
);
10 require_once 'config.php';
12 if (DB_TYPE
== "pgsql") {
13 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 define('THEME_VERSION_REQUIRED', 1.1);
21 * Return available translations names.
24 * @return array A array of available translations.
26 function get_translations() {
28 "auto" => "Detect automatically",
33 "fr_FR" => "Français",
34 "hu_HU" => "Magyar (Hungarian)",
35 "it_IT" => "Italiano",
36 "ja_JP" => "日本語 (Japanese)",
37 "nb_NO" => "Norwegian bokmål",
39 "pt_BR" => "Portuguese/Brazil",
40 "zh_CN" => "Simplified Chinese");
45 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
46 require_once "lib/accept-to-gettext.php";
47 require_once "lib/gettext/gettext.inc";
49 function startup_gettext() {
51 # Get locale from Accept-Language header
52 $lang = al2gt(array_keys(get_translations()), "text/html");
54 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
55 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
58 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
59 $lang = $_COOKIE["ttrss_lang"];
62 /* In login action of mobile version */
63 if ($_POST["language"] && defined('MOBILE_VERSION')) {
64 $lang = $_POST["language"];
65 $_COOKIE["ttrss_lang"] = $lang;
69 if (defined('LC_MESSAGES')) {
70 _setlocale(LC_MESSAGES
, $lang);
71 } else if (defined('LC_ALL')) {
72 _setlocale(LC_ALL
, $lang);
74 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
77 if (defined('MOBILE_VERSION')) {
78 _bindtextdomain("messages", "../locale");
80 _bindtextdomain("messages", "locale");
83 _textdomain("messages");
84 _bind_textdomain_codeset("messages", "UTF-8");
90 } else { // If translations are enabled.
94 function startup_gettext() {
98 } // If translations are enabled.
100 if (defined('MEMCACHE_SERVER')) {
101 $memcache = new Memcache
;
102 $memcache->connect(MEMCACHE_SERVER
, 11211);
105 require_once 'db-prefs.php';
106 require_once 'compat.php';
107 require_once 'errors.php';
108 require_once 'version.php';
110 require_once 'lib/phpmailer/class.phpmailer.php';
111 require_once 'lib/sphinxapi.php';
113 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
114 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
115 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
117 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
118 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
120 require_once "lib/simplepie/simplepie.inc";
121 require_once "lib/magpierss/rss_fetch.inc";
122 require_once 'lib/magpierss/rss_utils.inc';
123 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
125 $config = HTMLPurifier_Config
::createDefault();
127 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4";
129 $config->set('HTML', 'Allowed', $allowed);
130 $purifier = new HTMLPurifier($config);
133 * Print a timestamped debug message.
135 * @param string $msg The debug message.
138 function _debug($msg) {
139 $ts = strftime("%H:%M:%S", time());
140 if (function_exists('posix_getpid')) {
141 $ts = "$ts/" . posix_getpid();
143 print "[$ts] $msg\n";
147 * Purge a feed old posts.
149 * @param mixed $link A database connection.
150 * @param mixed $feed_id The id of the purged feed.
151 * @param mixed $purge_interval Olderness of purged posts.
152 * @param boolean $debug Set to True to enable the debug. False by default.
156 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
158 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
162 $result = db_query($link,
163 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
167 if (db_num_rows($result) == 1) {
168 $owner_uid = db_fetch_result($result, 0, "owner_uid");
171 if ($purge_interval == -1 ||
!$purge_interval) {
173 ccache_update($link, $feed_id, $owner_uid);
178 if (!$owner_uid) return;
180 if (FORCE_ARTICLE_PURGE
== 0) {
181 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
184 $purge_unread = true;
185 $purge_interval = FORCE_ARTICLE_PURGE
;
188 if (!$purge_unread) $query_limit = " unread = false AND ";
190 if (DB_TYPE
== "pgsql") {
191 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
192 marked = false AND feed_id = '$feed_id' AND
193 (SELECT date_updated FROM ttrss_entries WHERE
194 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
196 $pg_version = get_pgsql_version($link);
198 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
200 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
201 ttrss_entries.id = ref_id AND
203 feed_id = '$feed_id' AND
205 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
209 $result = db_query($link, "DELETE FROM ttrss_user_entries
211 WHERE ttrss_entries.id = ref_id AND
213 feed_id = '$feed_id' AND
215 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
218 $rows = pg_affected_rows($result);
222 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
223 marked = false AND feed_id = '$feed_id' AND
224 (SELECT date_updated FROM ttrss_entries WHERE
225 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
227 $result = db_query($link, "DELETE FROM ttrss_user_entries
228 USING ttrss_user_entries, ttrss_entries
229 WHERE ttrss_entries.id = ref_id AND
231 feed_id = '$feed_id' AND
233 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
235 $rows = mysql_affected_rows($link);
239 ccache_update($link, $feed_id, $owner_uid);
242 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
244 } // function purge_feed
247 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
249 * @param mixed $link A database connection
250 * @param boolean $do_output Set to true to enable printed output, false by default.
251 * @param integer $limit The maximal number of removed posts.
255 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
257 $random_qpart = sql_random_function();
260 $limit_qpart = "LIMIT $limit";
265 $result = db_query($link,
266 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
267 ORDER BY $random_qpart $limit_qpart");
269 while ($line = db_fetch_assoc($result)) {
271 $feed_id = $line["id"];
272 $purge_interval = $line["purge_interval"];
273 $owner_uid = $line["owner_uid"];
275 if ($purge_interval == 0) {
277 $tmp_result = db_query($link,
278 "SELECT value FROM ttrss_user_prefs WHERE
279 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
281 if (db_num_rows($tmp_result) != 0) {
282 $purge_interval = db_fetch_result($tmp_result, 0, "value");
287 // print "Feed $feed_id: purge interval = $purge_interval\n";
290 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
291 purge_feed($link, $feed_id, $purge_interval, $do_output);
295 purge_orphans($link, $do_output);
297 } // function global_purge_old_posts */
299 function feed_purge_interval($link, $feed_id) {
301 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
302 WHERE id = '$feed_id'");
304 if (db_num_rows($result) == 1) {
305 $purge_interval = db_fetch_result($result, 0, "purge_interval");
306 $owner_uid = db_fetch_result($result, 0, "owner_uid");
308 if ($purge_interval == 0) $purge_interval = get_pref($link,
309 'PURGE_OLD_DAYS', $owner_uid);
311 return $purge_interval;
318 function purge_old_posts($link) {
320 $user_id = $_SESSION["uid"];
322 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
323 WHERE owner_uid = '$user_id'");
325 while ($line = db_fetch_assoc($result)) {
327 $feed_id = $line["id"];
328 $purge_interval = $line["purge_interval"];
330 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
332 if ($purge_interval > 0) {
333 purge_feed($link, $feed_id, $purge_interval);
337 purge_orphans($link);
340 function purge_orphans($link, $do_output = false) {
342 // purge orphaned posts in main content table
343 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
344 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
347 $rows = db_affected_rows($link, $result);
348 _debug("Purged $rows orphaned posts.");
352 function get_feed_update_interval($link, $feed_id) {
353 $result = db_query($link, "SELECT owner_uid, update_interval FROM
354 ttrss_feeds WHERE id = '$feed_id'");
356 if (db_num_rows($result) == 1) {
357 $update_interval = db_fetch_result($result, 0, "update_interval");
358 $owner_uid = db_fetch_result($result, 0, "owner_uid");
360 if ($update_interval != 0) {
361 return $update_interval;
363 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
371 function fetch_file_contents($url, $type = false) {
372 if (USE_CURL_FOR_ICONS
) {
373 $ch = curl_init($url);
375 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
376 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
377 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
378 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
379 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
380 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
382 $contents = @curl_exec
($ch);
383 if ($contents === false) {
388 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
391 if ($type && strpos($content_type, "$type") === false) {
397 return @file_get_contents
($url);
403 * Try to determine the favicon URL for a feed.
404 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
405 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
407 * @param string $url A feed or page URL
409 * @return mixed The favicon URL, or false if none was found.
411 function get_favicon_url($url) {
413 $favicon_url = false;
415 if ($html = @fetch_file_contents
($url)) {
417 libxml_use_internal_errors(true);
419 $doc = new DOMDocument();
420 $doc->loadHTML($html);
421 $xpath = new DOMXPath($doc);
422 $entries = $xpath->query('/html/head/link[@rel="shortcut icon"]');
424 if (count($entries) > 0) {
425 foreach ($entries as $entry) {
426 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
433 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
435 // Run a test to see if what we have attempted to get actually exists.
436 if(USE_CURL_FOR_ICONS ||
url_validate($favicon_url)) {
441 } // function get_favicon_url
444 * Check if a link is a valid and working URL.
446 * @param mixed $link A URL to check
448 * @return boolean True if the URL is valid, false otherwise.
450 function url_validate($link) {
452 $url_parts = @parse_url
($link);
454 if ( empty( $url_parts["host"] ) )
457 if ( !empty( $url_parts["path"] ) ) {
458 $documentpath = $url_parts["path"];
463 if ( !empty( $url_parts["query"] ) )
464 $documentpath .= "?" . $url_parts["query"];
466 $host = $url_parts["host"];
467 $port = $url_parts["port"];
472 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
477 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
479 $http_response = fgets( $socket, 22 );
481 $responses = "/(200 OK)|(30[123])/";
482 if ( preg_match($responses, $http_response) ) {
489 } // function url_validate
491 function check_feed_favicon($site_url, $feed, $link) {
492 $favicon_url = get_favicon_url($site_url);
494 # print "FAVICON [$site_url]: $favicon_url\n";
496 $icon_file = ICONS_DIR
. "/$feed.ico";
498 if ($favicon_url && !file_exists($icon_file)) {
499 $contents = fetch_file_contents($favicon_url, "image");
502 $fp = fopen($icon_file, "w");
505 fwrite($fp, $contents);
507 chmod($icon_file, 0644);
513 function update_rss_feed($link, $feed, $ignore_daemon = false) {
517 /* Update all feeds with the same URL to utilize memcache */
520 $result = db_query($link, "SELECT f1.id
521 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
522 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
524 while ($line = db_fetch_assoc($result)) {
525 update_rss_feed_real($link, $line["id"], $ignore_daemon);
528 update_rss_feed_real($link, $feed, $ignore_daemon);
532 function update_rss_feed_real($link, $feed, $ignore_daemon = false) {
536 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
540 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
541 _debug("update_rss_feed: start");
544 if (!$ignore_daemon) {
546 if (DB_TYPE
== "pgsql") {
547 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
549 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
552 $result = db_query($link, "SELECT id,update_interval,auth_login,
553 auth_pass,cache_images,update_method
554 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
558 $result = db_query($link, "SELECT id,update_interval,auth_login,
559 feed_url,auth_pass,cache_images,update_method,last_updated
560 FROM ttrss_feeds WHERE id = '$feed'");
564 if (db_num_rows($result) == 0) {
565 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
566 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
571 $update_method = db_fetch_result($result, 0, "update_method");
572 $last_updated = db_fetch_result($result, 0, "last_updated");
574 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
575 WHERE id = '$feed'");
577 $auth_login = db_fetch_result($result, 0, "auth_login");
578 $auth_pass = db_fetch_result($result, 0, "auth_pass");
580 if (DEFAULT_UPDATE_METHOD
== "1") {
581 $use_simplepie = $update_method != 1;
583 $use_simplepie = $update_method == 2;
586 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
587 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
590 if (!$use_simplepie) {
591 $auth_login = urlencode($auth_login);
592 $auth_pass = urlencode($auth_pass);
595 $update_interval = db_fetch_result($result, 0, "update_interval");
596 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
597 $fetch_url = db_fetch_result($result, 0, "feed_url");
599 if ($update_interval < 0) { return; }
601 $feed = db_escape_string($feed);
603 if ($auth_login && $auth_pass) {
604 $url_parts = array();
605 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
607 if ($url_parts[1] && $url_parts[2]) {
608 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
613 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
614 _debug("update_rss_feed: fetching [$fetch_url]...");
617 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
619 if ($memcache && $obj = $memcache->get($obj_id)) {
621 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
622 _debug("update_rss_feed: data found in memcache.");
629 if (!$use_simplepie) {
630 $rss = @fetch_rss
($fetch_url);
632 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
633 mkdir(SIMPLEPIE_CACHE_DIR
);
636 $rss = new SimplePie();
637 $rss->set_useragent(SELF_USER_AGENT
);
638 # $rss->set_timeout(10);
639 $rss->set_feed_url($fetch_url);
640 $rss->set_output_encoding('UTF-8');
642 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
643 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
644 _debug("enabling image cache");
647 $rss->set_image_handler('./image.php', 'i');
650 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
651 _debug("feed update interval (sec): " .
652 get_feed_update_interval($link, $feed)*60);
655 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
656 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
657 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
663 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
668 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
669 _debug("update_rss_feed: fetch done, parsing...");
672 $feed = db_escape_string($feed);
674 if ($use_simplepie) {
675 $fetch_ok = !$rss->error();
682 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
683 _debug("update_rss_feed: processing feed data...");
686 // db_query($link, "BEGIN");
688 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
689 FROM ttrss_feeds WHERE id = '$feed'");
691 $registered_title = db_fetch_result($result, 0, "title");
692 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
693 $orig_site_url = db_fetch_result($result, 0, "site_url");
695 $owner_uid = db_fetch_result($result, 0, "owner_uid");
697 if ($use_simplepie) {
698 $site_url = $rss->get_link();
700 $site_url = $rss->channel
["link"];
703 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
704 _debug("update_rss_feed: checking favicon...");
707 check_feed_favicon($site_url, $feed, $link);
709 if (!$registered_title ||
$registered_title == "[Unknown]") {
711 if ($use_simplepie) {
712 $feed_title = db_escape_string($rss->get_title());
714 $feed_title = db_escape_string($rss->channel
["title"]);
717 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
718 _debug("update_rss_feed: registering title: $feed_title");
721 db_query($link, "UPDATE ttrss_feeds SET
722 title = '$feed_title' WHERE id = '$feed'");
725 // weird, weird Magpie
726 if (!$use_simplepie) {
727 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
730 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
731 db_query($link, "UPDATE ttrss_feeds SET
732 site_url = '$site_url' WHERE id = '$feed'");
735 // print "I: " . $rss->channel["image"]["url"];
737 if (!$use_simplepie) {
738 $icon_url = db_escape_string($rss->image
["url"]);
740 $icon_url = db_escape_string($rss->get_image_url());
743 $icon_url = substr($icon_url, 0, 250);
745 if ($icon_url && $orig_icon_url != $icon_url) {
746 if (USE_CURL_FOR_ICONS ||
url_validate($icon_url)) {
747 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
751 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
752 _debug("update_rss_feed: loading filters...");
755 $filters = load_filters($link, $feed, $owner_uid);
757 if ($use_simplepie) {
758 $iterator = $rss->get_items();
760 $iterator = $rss->items
;
761 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
762 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
765 if (!is_array($iterator)) {
766 /* db_query($link, "UPDATE ttrss_feeds
767 SET last_error = 'Parse error: can\'t find any articles.'
768 WHERE id = '$feed'"); */
770 // clear any errors and mark feed as updated if fetched okay
771 // even if it's blank
773 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
774 _debug("update_rss_feed: entry iterator is not an array, no articles?");
777 db_query($link, "UPDATE ttrss_feeds
778 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
780 return; // no articles
783 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
784 _debug("update_rss_feed: processing articles...");
787 foreach ($iterator as $item) {
789 if ($_REQUEST['xdebug'] == 2) {
793 if ($use_simplepie) {
794 $entry_guid = $item->get_id();
795 if (!$entry_guid) $entry_guid = $item->get_link();
796 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
800 $entry_guid = $item["id"];
802 if (!$entry_guid) $entry_guid = $item["guid"];
803 if (!$entry_guid) $entry_guid = $item["link"];
804 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
807 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
808 _debug("update_rss_feed: guid $entry_guid");
811 if (!$entry_guid) continue;
813 $entry_timestamp = "";
815 if ($use_simplepie) {
816 $entry_timestamp = strtotime($item->get_date());
818 $rss_2_date = $item['pubdate'];
819 $rss_1_date = $item['dc']['date'];
820 $atom_date = $item['issued'];
821 if (!$atom_date) $atom_date = $item['updated'];
823 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
824 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
825 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
829 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
830 $entry_timestamp = time();
831 $no_orig_date = 'true';
833 $no_orig_date = 'false';
836 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
838 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
839 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
842 if ($use_simplepie) {
843 $entry_title = $item->get_title();
845 $entry_title = trim(strip_tags($item["title"]));
848 if ($use_simplepie) {
849 $entry_link = $item->get_link();
851 // strange Magpie workaround
852 $entry_link = $item["link_"];
853 if (!$entry_link) $entry_link = $item["link"];
856 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
857 _debug("update_rss_feed: title $entry_title");
860 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
862 $entry_link = strip_tags($entry_link);
864 if ($use_simplepie) {
865 $entry_content = $item->get_content();
866 if (!$entry_content) $entry_content = $item->get_description();
868 $entry_content = $item["content:escaped"];
870 if (!$entry_content) $entry_content = $item["content:encoded"];
871 if (!$entry_content) $entry_content = $item["content"]["encoded"];
872 if (!$entry_content) $entry_content = $item["content"];
874 // Magpie bugs are getting ridiculous
875 if (trim($entry_content) == "Array") $entry_content = false;
877 if (!$entry_content) $entry_content = $item["atom_content"];
878 if (!$entry_content) $entry_content = $item["summary"];
880 if (!$entry_content ||
881 strlen($entry_content) < strlen($item["description"])) {
882 $entry_content = $item["description"];
886 if (is_array($entry_content)) {
887 $entry_content = $entry_content["encoded"];
888 if (!$entry_content) $entry_content = $entry_content["escaped"];
892 if ($_REQUEST["xdebug"] == 2) {
893 print "update_rss_feed: content: ";
894 print_r(htmlspecialchars($entry_content));
897 $entry_content_unescaped = $entry_content;
899 if ($use_simplepie) {
900 $entry_comments = strip_tags($item->data
["comments"]);
901 if ($item->get_author()) {
902 $entry_author_item = $item->get_author();
903 $entry_author = $entry_author_item->get_name();
904 if (!$entry_author) $entry_author = $entry_author_item->get_email();
906 $entry_author = db_escape_string($entry_author);
909 $entry_comments = strip_tags($item["comments"]);
911 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
913 if ($item['author']) {
915 if (is_array($item['author'])) {
917 if (!$entry_author) {
918 $entry_author = db_escape_string(strip_tags($item['author']['name']));
921 if (!$entry_author) {
922 $entry_author = db_escape_string(strip_tags($item['author']['email']));
926 if (!$entry_author) {
927 $entry_author = db_escape_string(strip_tags($item['author']));
932 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
934 $entry_guid = db_escape_string(strip_tags($entry_guid));
935 $entry_guid = mb_substr($entry_guid, 0, 250);
937 $result = db_query($link, "SELECT id FROM ttrss_entries
938 WHERE guid = '$entry_guid'");
940 $entry_content = db_escape_string($entry_content);
942 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
944 $entry_title = db_escape_string($entry_title);
945 $entry_link = db_escape_string($entry_link);
946 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
947 $entry_author = mb_substr($entry_author, 0, 250);
949 if ($use_simplepie) {
950 $num_comments = 0; #FIXME#
952 $num_comments = db_escape_string($item["slash"]["comments"]);
955 if (!$num_comments) $num_comments = 0;
957 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
958 _debug("update_rss_feed: looking for tags [1]...");
961 // parse <category> entries into tags
963 $additional_tags = array();
965 if ($use_simplepie) {
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') ||
$_REQUEST['xdebug']) {
976 _debug("update_rss_feed: category tags:");
977 print_r($additional_tags);
982 $t_ctr = $item['category#'];
985 $additional_tags = array();
986 } else if ($t_ctr > 0) {
987 $additional_tags = array($item['category']);
989 if ($item['category@term']) {
990 array_push($additional_tags, $item['category@term']);
993 for ($i = 0; $i <= $t_ctr; $i++
) {
994 if ($item["category#$i"]) {
995 array_push($additional_tags, $item["category#$i"]);
998 if ($item["category#$i@term"]) {
999 array_push($additional_tags, $item["category#$i@term"]);
1004 // parse <dc:subject> elements
1006 $t_ctr = $item['dc']['subject#'];
1009 array_push($additional_tags, $item['dc']['subject']);
1011 for ($i = 0; $i <= $t_ctr; $i++
) {
1012 if ($item['dc']["subject#$i"]) {
1013 array_push($additional_tags, $item['dc']["subject#$i"]);
1019 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1020 _debug("update_rss_feed: looking for tags [2]...");
1024 // <a href="..." rel="tag">Xorg</a>, //
1028 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1029 $entry_content_unescaped, $entry_tags);
1031 $entry_tags = $entry_tags[1];
1033 $entry_tags = array_merge($entry_tags, $additional_tags);
1034 $entry_tags = array_unique($entry_tags);
1036 for ($i = 0; $i < count($entry_tags); $i++
)
1037 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1039 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1040 _debug("update_rss_feed: unfiltered tags found:");
1041 print_r($entry_tags);
1046 $entry_content = sanitize_article_content($entry_content);
1047 $entry_title = sanitize_article_content($entry_title);
1049 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1050 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1053 db_query($link, "BEGIN");
1055 if (db_num_rows($result) == 0) {
1057 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1058 _debug("update_rss_feed: base guid not found");
1061 // base post entry does not exist, create it
1063 $result = db_query($link,
1064 "INSERT INTO ttrss_entries
1081 '$entry_timestamp_fmt',
1091 // we keep encountering the entry in feeds, so we need to
1092 // update date_updated column so that we don't get horrible
1093 // dupes when the entry gets purged and reinserted again e.g.
1094 // in the case of SLOW SLOW OMG SLOW updating feeds
1096 $base_entry_id = db_fetch_result($result, 0, "id");
1098 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1099 WHERE id = '$base_entry_id'");
1102 // now it should exist, if not - bad luck then
1104 $result = db_query($link, "SELECT
1105 id,content_hash,no_orig_date,title,
1106 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1107 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1111 WHERE guid = '$entry_guid'");
1116 if (db_num_rows($result) == 1) {
1118 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1119 _debug("update_rss_feed: base guid found, checking for user record");
1122 // this will be used below in update handler
1123 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1124 $orig_title = db_fetch_result($result, 0, "title");
1125 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1126 $orig_date_updated = strtotime(db_fetch_result($result,
1127 0, "date_updated"));
1129 $ref_id = db_fetch_result($result, 0, "id");
1130 $entry_ref_id = $ref_id;
1132 // check for user post link to main table
1134 // do we allow duplicate posts with same GUID in different feeds?
1135 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1136 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1138 $dupcheck_qpart = "";
1141 /* Collect article tags here so we could filter by them: */
1143 $article_filters = get_article_filters($filters, $entry_title,
1144 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1147 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1148 _debug("update_rss_feed: article filters: ");
1149 if (count($article_filters) != 0) {
1150 print_r($article_filters);
1154 if (find_article_filter($article_filters, "filter")) {
1155 db_query($link, "COMMIT"); // close transaction in progress
1159 $score = calculate_article_score($article_filters);
1161 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1162 _debug("update_rss_feed: initial score: $score");
1165 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1166 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1169 // if ($_REQUEST["xdebug"]) print "$query\n";
1171 $result = db_query($link, $query);
1173 // okay it doesn't exist - create user entry
1174 if (db_num_rows($result) == 0) {
1176 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1177 _debug("update_rss_feed: user record not found, creating...");
1180 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1182 $last_read_qpart = 'NULL';
1185 $last_read_qpart = 'NOW()';
1188 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1194 if (find_article_filter($article_filters, 'publish')) {
1195 $published = 'true';
1197 $published = 'false';
1200 $result = db_query($link,
1201 "INSERT INTO ttrss_user_entries
1202 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1203 published, score, tag_cache, label_cache)
1204 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1205 $last_read_qpart, $marked, $published, '$score', '', '')");
1207 $result = db_query($link,
1208 "SELECT int_id FROM ttrss_user_entries WHERE
1209 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1210 feed_id = '$feed' LIMIT 1");
1212 if (db_num_rows($result) == 1) {
1213 $entry_int_id = db_fetch_result($result, 0, "int_id");
1216 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1217 _debug("update_rss_feed: user record FOUND");
1220 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1221 $entry_int_id = db_fetch_result($result, 0, "int_id");
1224 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1225 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1228 $post_needs_update = false;
1230 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1231 ($content_hash != $orig_content_hash)) {
1232 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1233 $post_needs_update = true;
1236 if (db_escape_string($orig_title) != $entry_title) {
1237 $post_needs_update = true;
1240 if ($orig_num_comments != $num_comments) {
1241 $post_needs_update = true;
1244 // this doesn't seem to be very reliable
1246 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1247 // $post_needs_update = true;
1250 // if post needs update, update it and mark all user entries
1251 // linking to this post as updated
1252 if ($post_needs_update) {
1254 if (defined('DAEMON_EXTENDED_DEBUG')) {
1255 _debug("update_rss_feed: post $entry_guid needs update...");
1258 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1260 db_query($link, "UPDATE ttrss_entries
1261 SET title = '$entry_title', content = '$entry_content',
1262 content_hash = '$content_hash',
1263 num_comments = '$num_comments'
1264 WHERE id = '$ref_id'");
1266 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1267 db_query($link, "UPDATE ttrss_user_entries
1268 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1270 db_query($link, "UPDATE ttrss_user_entries
1271 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1277 db_query($link, "COMMIT");
1279 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1280 _debug("update_rss_feed: assigning labels...");
1283 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1286 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1287 _debug("update_rss_feed: looking for enclosures...");
1292 $enclosures = array();
1294 if ($use_simplepie) {
1295 $encs = $item->get_enclosures();
1297 if (is_array($encs)) {
1298 foreach ($encs as $e) {
1300 $e->link
, $e->type
, $e->length
);
1302 array_push($enclosures, $e_item);
1309 $e_ctr = $item['enclosure#'];
1312 $e_item = array($item['enclosure@url'],
1313 $item['enclosure@type'],
1314 $item['enclosure@length']);
1316 array_push($enclosures, $e_item);
1318 for ($i = 0; $i <= $e_ctr; $i++
) {
1320 if ($item["enclosure#$i@url"]) {
1321 $e_item = array($item["enclosure#$i@url"],
1322 $item["enclosure#$i@type"],
1323 $item["enclosure#$i@length"]);
1324 array_push($enclosures, $e_item);
1330 // can there be many of those? yes -fox
1332 $m_ctr = $item['media']['content#'];
1335 $e_item = array($item['media']['content@url'],
1336 $item['media']['content@medium'],
1337 $item['media']['content@length']);
1339 array_push($enclosures, $e_item);
1341 for ($i = 0; $i <= $m_ctr; $i++
) {
1343 if ($item["media"]["content#$i@url"]) {
1344 $e_item = array($item["media"]["content#$i@url"],
1345 $item["media"]["content#$i@medium"],
1346 $item["media"]["content#$i@length"]);
1347 array_push($enclosures, $e_item);
1355 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1356 _debug("update_rss_feed: article enclosures:");
1357 print_r($enclosures);
1360 db_query($link, "BEGIN");
1362 foreach ($enclosures as $enc) {
1363 $enc_url = db_escape_string($enc[0]);
1364 $enc_type = db_escape_string($enc[1]);
1365 $enc_dur = db_escape_string($enc[2]);
1367 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1368 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1370 if (db_num_rows($result) == 0) {
1371 db_query($link, "INSERT INTO ttrss_enclosures
1372 (content_url, content_type, title, duration, post_id) VALUES
1373 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1377 db_query($link, "COMMIT");
1379 // check for manual tags (we have to do it here since they're loaded from filters)
1381 foreach ($article_filters as $f) {
1382 if ($f[0] == "tag") {
1384 $manual_tags = trim_array(split(",", $f[1]));
1386 foreach ($manual_tags as $tag) {
1387 if (tag_is_valid($tag)) {
1388 array_push($entry_tags, $tag);
1396 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1397 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1399 $filtered_tags = array();
1400 $tags_to_cache = array();
1402 if ($entry_tags && is_array($entry_tags)) {
1403 foreach ($entry_tags as $tag) {
1404 if (array_search($tag, $boring_tags) === false) {
1405 array_push($filtered_tags, $tag);
1410 $filtered_tags = array_unique($filtered_tags);
1412 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1413 _debug("update_rss_feed: filtered article tags:");
1414 print_r($filtered_tags);
1417 // Save article tags in the database
1419 if (count($filtered_tags) > 0) {
1421 db_query($link, "BEGIN");
1423 foreach ($filtered_tags as $tag) {
1425 $tag = sanitize_tag($tag);
1426 $tag = db_escape_string($tag);
1428 if (!tag_is_valid($tag)) continue;
1430 $result = db_query($link, "SELECT id FROM ttrss_tags
1431 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1432 owner_uid = '$owner_uid' LIMIT 1");
1434 if ($result && db_num_rows($result) == 0) {
1436 db_query($link, "INSERT INTO ttrss_tags
1437 (owner_uid,tag_name,post_int_id)
1438 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1441 array_push($tags_to_cache, $tag);
1444 /* update the cache */
1446 $tags_to_cache = array_unique($tags_to_cache);
1448 $tags_str = db_escape_string(join(",", $tags_to_cache));
1450 db_query($link, "UPDATE ttrss_user_entries
1451 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1452 AND owner_uid = $owner_uid");
1454 db_query($link, "COMMIT");
1457 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1458 _debug("update_rss_feed: article processed");
1462 if (!$last_updated) {
1463 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1464 _debug("update_rss_feed: new feed, catching it up...");
1466 catchup_feed($link, $feed, false, $owner_uid);
1469 purge_feed($link, $feed, 0);
1471 db_query($link, "UPDATE ttrss_feeds
1472 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1474 // db_query($link, "COMMIT");
1478 if ($use_simplepie) {
1479 $error_msg = mb_substr($rss->error(), 0, 250);
1481 $error_msg = mb_substr(magpie_error(), 0, 250);
1484 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1485 _debug("update_rss_feed: error fetching feed: $error_msg");
1488 $error_msg = db_escape_string($error_msg);
1491 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1492 last_updated = NOW() WHERE id = '$feed'");
1495 if ($use_simplepie) {
1499 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug']) {
1500 _debug("update_rss_feed: done");
1505 function print_select($id, $default, $values, $attributes = "") {
1506 print "<select name=\"$id\" id=\"$id\" $attributes>";
1507 foreach ($values as $v) {
1513 print "<option$sel>$v</option>";
1518 function print_select_hash($id, $default, $values, $attributes = "") {
1519 print "<select name=\"$id\" id='$id' $attributes>";
1520 foreach (array_keys($values) as $v) {
1522 $sel = 'selected="selected"';
1526 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1532 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1535 if ($filters["title"]) {
1536 foreach ($filters["title"] as $filter) {
1537 $reg_exp = $filter["reg_exp"];
1538 $inverse = $filter["inverse"];
1539 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1540 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1542 array_push($matches, array($filter["action"], $filter["action_param"]));
1547 if ($filters["content"]) {
1548 foreach ($filters["content"] as $filter) {
1549 $reg_exp = $filter["reg_exp"];
1550 $inverse = $filter["inverse"];
1552 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1553 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1555 array_push($matches, array($filter["action"], $filter["action_param"]));
1560 if ($filters["both"]) {
1561 foreach ($filters["both"] as $filter) {
1562 $reg_exp = $filter["reg_exp"];
1563 $inverse = $filter["inverse"];
1566 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1567 array_push($matches, array($filter["action"], $filter["action_param"]));
1570 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1571 array_push($matches, array($filter["action"], $filter["action_param"]));
1577 if ($filters["link"]) {
1578 $reg_exp = $filter["reg_exp"];
1579 foreach ($filters["link"] as $filter) {
1580 $reg_exp = $filter["reg_exp"];
1581 $inverse = $filter["inverse"];
1583 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1584 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1586 array_push($matches, array($filter["action"], $filter["action_param"]));
1591 if ($filters["date"]) {
1592 $reg_exp = $filter["reg_exp"];
1593 foreach ($filters["date"] as $filter) {
1594 $date_modifier = $filter["filter_param"];
1595 $inverse = $filter["inverse"];
1596 $check_timestamp = strtotime($filter["reg_exp"]);
1598 # no-op when timestamp doesn't parse to prevent misfires
1600 if ($check_timestamp) {
1603 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1604 $date_modifier == "after" && $timestamp > $check_timestamp) {
1608 if ($inverse) $match_ok = !$match_ok;
1611 array_push($matches, array($filter["action"], $filter["action_param"]));
1617 if ($filters["author"]) {
1618 foreach ($filters["author"] as $filter) {
1619 $reg_exp = $filter["reg_exp"];
1620 $inverse = $filter["inverse"];
1621 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1622 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1624 array_push($matches, array($filter["action"], $filter["action_param"]));
1629 if ($filters["tag"]) {
1631 $tag_string = join(",", $tags);
1633 foreach ($filters["tag"] as $filter) {
1634 $reg_exp = $filter["reg_exp"];
1635 $inverse = $filter["inverse"];
1637 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1638 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1640 array_push($matches, array($filter["action"], $filter["action_param"]));
1649 function find_article_filter($filters, $filter_name) {
1650 foreach ($filters as $f) {
1651 if ($f[0] == $filter_name) {
1658 function calculate_article_score($filters) {
1661 foreach ($filters as $f) {
1662 if ($f[0] == "score") {
1669 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1670 foreach ($filters as $f) {
1671 if ($f[0] == "label") {
1672 label_add_article($link, $id, $f[1], $owner_uid);
1677 function getmicrotime() {
1678 list($usec, $sec) = explode(" ",microtime());
1679 return ((float)$usec +
(float)$sec);
1682 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1683 foreach ($values as $v) {
1690 if ($v == $true_is) {
1691 $sel .= " value=\"1\"";
1693 $sel .= " value=\"0\"";
1696 print "<input class=\"noborder\"
1697 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1702 function initialize_user_prefs($link, $uid, $profile = false) {
1704 $uid = db_escape_string($uid);
1708 $profile_qpart = "AND profile IS NULL";
1710 $profile_qpart = "AND profile = '$profile'";
1713 if (get_schema_version($link) < 63) $profile_qpart = "";
1715 db_query($link, "BEGIN");
1717 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1719 $u_result = db_query($link, "SELECT pref_name
1720 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1722 $active_prefs = array();
1724 while ($line = db_fetch_assoc($u_result)) {
1725 array_push($active_prefs, $line["pref_name"]);
1728 while ($line = db_fetch_assoc($result)) {
1729 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1730 // print "adding " . $line["pref_name"] . "<br>";
1732 if (get_schema_version($link) < 63) {
1733 db_query($link, "INSERT INTO ttrss_user_prefs
1734 (owner_uid,pref_name,value) VALUES
1735 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1738 db_query($link, "INSERT INTO ttrss_user_prefs
1739 (owner_uid,pref_name,value, profile) VALUES
1740 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1746 db_query($link, "COMMIT");
1750 function lookup_user_id($link, $user) {
1752 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1755 if (db_num_rows($result) == 1) {
1756 return db_fetch_result($result, 0, "id");
1762 function http_authenticate_user($link) {
1764 // error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1766 if (!$_SERVER["PHP_AUTH_USER"]) {
1768 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1769 header('HTTP/1.0 401 Unauthorized');
1773 $auth_result = authenticate_user($link,
1774 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1776 if (!$auth_result) {
1777 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1778 header('HTTP/1.0 401 Unauthorized');
1786 function authenticate_user($link, $login, $password, $force_auth = false) {
1788 if (!SINGLE_USER_MODE
) {
1790 $pwd_hash1 = encrypt_password($password);
1791 $pwd_hash2 = encrypt_password($password, $login);
1792 $login = db_escape_string($login);
1794 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1795 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1797 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1799 $query = "SELECT id,login,access_level,pwd_hash
1800 FROM ttrss_users WHERE
1804 $query = "SELECT id,login,access_level,pwd_hash
1805 FROM ttrss_users WHERE
1806 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1807 pwd_hash = '$pwd_hash2')";
1810 $result = db_query($link, $query);
1812 if (db_num_rows($result) == 1) {
1813 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1814 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1815 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1817 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1820 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1821 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1823 $_SESSION["last_version_check"] = time();
1825 initialize_user_prefs($link, $_SESSION["uid"]);
1834 $_SESSION["uid"] = 1;
1835 $_SESSION["name"] = "admin";
1837 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1839 initialize_user_prefs($link, $_SESSION["uid"]);
1845 function make_password($length = 8) {
1848 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1852 while ($i < $length) {
1853 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1855 if (!strstr($password, $char)) {
1863 // this is called after user is created to initialize default feeds, labels
1866 // user preferences are checked on every login, not here
1868 function initialize_user($link, $uid) {
1870 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1871 values ('$uid', 'Tiny Tiny RSS: New Releases',
1872 'http://tt-rss.org/releases.rss')");
1874 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1875 values ('$uid', 'Tiny Tiny RSS: Forum',
1876 'http://tt-rss.org/forum/rss.php')");
1879 function logout_user() {
1881 if (isset($_COOKIE[session_name()])) {
1882 setcookie(session_name(), '', time()-42000, '/');
1886 function get_script_urlpath() {
1887 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1890 function validate_session($link) {
1891 if (SINGLE_USER_MODE
) {
1895 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1896 if ($_SESSION["ip_address"]) {
1897 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1898 $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1904 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true)) {
1908 if ($_SESSION["uid"]) {
1910 $result = db_query($link,
1911 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1913 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1915 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1920 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1922 //print_r($_SESSION);
1924 if (time() > $_SESSION["cookie_lifetime"]) {
1932 function login_sequence($link, $mobile = false) {
1933 if (!SINGLE_USER_MODE
) {
1935 $login_action = $_POST["login_action"];
1937 # try to authenticate user if called from login form
1938 if ($login_action == "do_login") {
1939 $login = $_POST["login"];
1940 $password = $_POST["password"];
1941 $remember_me = $_POST["remember_me"];
1943 if (authenticate_user($link, $login, $password)) {
1944 $_POST["password"] = "";
1946 $_SESSION["language"] = $_POST["language"];
1947 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1948 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1950 if ($_POST["profile"]) {
1952 $profile = db_escape_string($_POST["profile"]);
1954 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
1955 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
1957 if (db_num_rows($result) != 0) {
1958 $_SESSION["profile"] = $profile;
1959 $_SESSION["prefs_cache"] = array();
1963 header("Location: " . $_SERVER["REQUEST_URI"]);
1968 $_SESSION["login_error_msg"] = __("Incorrect username or password");
1972 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1973 render_login_form($link, $mobile);
1974 //header("Location: login.php");
1977 /* bump login timestamp */
1978 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1981 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1982 setcookie("ttrss_lang", $_SESSION["language"],
1983 time() + SESSION_COOKIE_LIFETIME
);
1988 return authenticate_user($link, "admin", null);
1992 function truncate_string($str, $max_len) {
1993 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1994 return mb_substr($str, 0, $max_len, "utf-8") . "…";
2000 function theme_image($link, $filename) {
2002 $theme_path = get_user_theme_path($link);
2004 if ($theme_path && is_file($theme_path.$filename)) {
2005 return $theme_path.$filename;
2014 function get_user_theme($link) {
2016 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2017 $theme_name = get_pref($link, "_THEME_ID");
2018 if (is_dir("themes/$theme_name")) {
2029 function get_user_theme_path($link) {
2032 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2033 $theme_name = get_pref($link, "_THEME_ID");
2035 if ($theme_name && is_dir("themes/$theme_name")) {
2036 $theme_path = "themes/$theme_name/";
2045 if (is_file("$t/theme.ini")) {
2046 $ini = parse_ini_file("$t/theme.ini", true);
2047 if ($ini['theme']['version'] > THEME_VERSION_REQUIRED
) {
2055 function get_user_theme_options($link) {
2056 $t = get_user_theme_path($link);
2059 if (is_file("$t/theme.ini")) {
2060 $ini = parse_ini_file("$t/theme.ini", true);
2061 if ($ini['theme']['version']) {
2062 return $ini['theme']['options'];
2070 function get_all_themes() {
2071 $themes = glob("themes/*");
2077 foreach ($themes as $t) {
2078 if (is_file("$t/theme.ini")) {
2079 $ini = parse_ini_file("$t/theme.ini", true);
2080 if ($ini['theme']['version'] > THEME_VERSION_REQUIRED
&&
2081 !$ini['theme']['disabled']) {
2083 $entry["path"] = $t;
2084 $entry["base"] = basename($t);
2085 $entry["name"] = $ini['theme']['name'];
2086 $entry["version"] = $ini['theme']['version'];
2087 $entry["author"] = $ini['theme']['author'];
2088 $entry["options"] = $ini['theme']['options'];
2089 array_push($rv, $entry);
2097 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2098 $no_smart_dt = false) {
2100 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2101 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2103 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2106 $user_tz = new DateTimeZone($user_tz_string);
2107 } catch (Exception
$e) {
2108 $user_tz = new DateTimeZone('UTC');
2111 # We store date in UTC internally
2112 $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
2113 $user_timestamp = $dt->format('U') +
$user_tz->getOffset($dt);
2115 if (!$no_smart_dt && get_pref($link, 'HEADLINES_SMART_DATE', $owner_uid)) {
2116 return smart_date_time($link, $user_timestamp,
2117 $user_tz->getOffset($dt), $owner_uid);
2120 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2122 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2124 return date($format, $user_timestamp);
2128 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2129 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2131 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2132 return date("G:i", $timestamp);
2133 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2134 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2135 return date($format, $timestamp);
2137 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2138 return date($format, $timestamp);
2142 function smart_date($timestamp) {
2143 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2145 } else if (date("Y", $timestamp) == date("Y")) {
2146 return date("D m", $timestamp);
2148 return date("Y/m/d", $timestamp);
2152 function sql_bool_to_string($s) {
2153 if ($s == "t" ||
$s == "1") {
2160 function sql_bool_to_bool($s) {
2161 if ($s == "t" ||
$s == "1") {
2168 function bool_to_sql_bool($s) {
2176 function toggleEvenOdd($a) {
2183 function get_schema_version($link, $nocache = false) {
2184 if (!$_SESSION["schema_version"] ||
$nocache) {
2185 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2186 $version = db_fetch_result($result, 0, "schema_version");
2187 $_SESSION["schema_version"] = $version;
2190 return $_SESSION["schema_version"];
2194 function sanity_check($link) {
2197 $schema_version = get_schema_version($link);
2199 if ($schema_version != SCHEMA_VERSION
) {
2203 if (DB_TYPE
== "mysql") {
2204 $result = db_query($link, "SELECT true", false);
2205 if (db_num_rows($result) != 1) {
2210 if (db_escape_string("testTEST") != "testTEST") {
2214 if ($error_code != 0) {
2215 print_error_xml($error_code);
2222 function file_is_locked($filename) {
2223 if (function_exists('flock')) {
2224 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2226 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2227 flock($fp, LOCK_UN
);
2237 return true; // consider the file always locked and skip the test
2240 function make_lockfile($filename) {
2241 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2243 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2244 if (function_exists('posix_getpid')) {
2245 fwrite($fp, posix_getpid() . "\n");
2253 function make_stampfile($filename) {
2254 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2256 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2257 fwrite($fp, time() . "\n");
2258 flock($fp, LOCK_UN
);
2266 function sql_random_function() {
2267 if (DB_TYPE
== "mysql") {
2274 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2276 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2278 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2285 $cat_qpart = "cat_id = '$feed'";
2287 $cat_qpart = "cat_id IS NULL";
2290 $tmp_result = db_query($link, "SELECT id
2291 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2293 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2295 $tmp_feed = $tmp_line["id"];
2297 db_query($link, "UPDATE ttrss_user_entries
2298 SET unread = false,last_read = NOW()
2299 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2301 } else if ($feed == -2) {
2304 db_query($link, "UPDATE ttrss_user_entries
2305 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2306 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2307 AND unread = true AND owner_uid = $owner_uid");
2310 } else if ($feed > 0) {
2312 db_query($link, "UPDATE ttrss_user_entries
2313 SET unread = false,last_read = NOW()
2314 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2316 } else if ($feed < 0 && $feed > -10) { // special, like starred
2319 db_query($link, "UPDATE ttrss_user_entries
2320 SET unread = false,last_read = NOW()
2321 WHERE marked = true AND owner_uid = $owner_uid");
2325 db_query($link, "UPDATE ttrss_user_entries
2326 SET unread = false,last_read = NOW()
2327 WHERE published = true AND owner_uid = $owner_uid");
2332 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2334 if (DB_TYPE
== "pgsql") {
2335 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2337 $match_part = "updated > DATE_SUB(NOW(),
2338 INTERVAL $intl HOUR) ";
2341 $result = db_query($link, "SELECT id FROM ttrss_entries,
2342 ttrss_user_entries WHERE $match_part AND
2344 ttrss_user_entries.ref_id = ttrss_entries.id AND
2345 owner_uid = $owner_uid");
2347 $affected_ids = array();
2349 while ($line = db_fetch_assoc($result)) {
2350 array_push($affected_ids, $line["id"]);
2353 catchupArticlesById($link, $affected_ids, 0);
2357 db_query($link, "UPDATE ttrss_user_entries
2358 SET unread = false,last_read = NOW()
2359 WHERE owner_uid = $owner_uid");
2362 } else if ($feed < -10) { // label
2364 $label_id = -$feed - 11;
2366 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2367 SET unread = false, last_read = NOW()
2368 WHERE label_id = '$label_id' AND unread = true
2369 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2373 ccache_update($link, $feed, $owner_uid, $cat_view);
2376 db_query($link, "BEGIN");
2378 $tag_name = db_escape_string($feed);
2380 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2381 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2383 while ($line = db_fetch_assoc($result)) {
2384 db_query($link, "UPDATE ttrss_user_entries SET
2385 unread = false, last_read = NOW()
2386 WHERE int_id = " . $line["post_int_id"]);
2388 db_query($link, "COMMIT");
2392 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2396 $cat_qpart = "cat_id = '$feed'";
2398 $cat_qpart = "cat_id IS NULL";
2401 $tmp_result = db_query($link, "SELECT id FROM ttrss_feeds
2402 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2404 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2405 $feed_id = $tmp_line["id"];
2406 update_rss_feed($link, $feed_id, $force_update);
2410 update_rss_feed($link, $feed, $force_update);
2414 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2416 if (!$omode) $omode = "flc";
2418 $data = getGlobalCounters($link);
2420 $data = array_merge($data, getVirtCounters($link));
2422 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2423 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2424 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2425 if (strchr($omode, "c")) {
2426 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2427 $data = array_merge($data, getCategoryCounters($link));
2434 function getCategoryCounters($link) {
2437 /* Labels category */
2439 $cv = array("id" => -2, "kind" => "cat",
2440 "counter" => getCategoryUnread($link, -2));
2442 array_push($ret_arr, $cv);
2444 $age_qpart = getMaxAgeSubquery();
2446 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2447 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2448 WHERE ttrss_cat_counters_cache.feed_id = id AND
2449 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2451 while ($line = db_fetch_assoc($result)) {
2452 $line["cat_id"] = (int) $line["cat_id"];
2454 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2455 "counter" => $line["unread"]);
2457 array_push($ret_arr, $cv);
2460 /* Special case: NULL category doesn't actually exist in the DB */
2462 $cv = array("id" => 0, "kind" => "cat",
2463 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2465 array_push($ret_arr, $cv);
2470 function getCategoryUnread($link, $cat, $owner_uid = false) {
2472 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2477 $cat_query = "cat_id = '$cat'";
2479 $cat_query = "cat_id IS NULL";
2482 $age_qpart = getMaxAgeSubquery();
2484 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2485 AND owner_uid = " . $owner_uid);
2487 $cat_feeds = array();
2488 while ($line = db_fetch_assoc($result)) {
2489 array_push($cat_feeds, "feed_id = " . $line["id"]);
2492 if (count($cat_feeds) == 0) return 0;
2494 $match_part = implode(" OR ", $cat_feeds);
2496 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2497 FROM ttrss_user_entries,ttrss_entries
2498 WHERE unread = true AND ($match_part) AND id = ref_id
2499 AND $age_qpart AND owner_uid = " . $owner_uid);
2503 # this needs to be rewritten
2504 while ($line = db_fetch_assoc($result)) {
2505 $unread +
= $line["unread"];
2509 } else if ($cat == -1) {
2510 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2511 } else if ($cat == -2) {
2513 $result = db_query($link, "
2514 SELECT COUNT(unread) AS unread FROM
2515 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2516 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2517 ttrss_labels2.owner_uid = '$owner_uid'
2518 AND unread = true AND feed_id = ttrss_feeds.id
2519 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2521 $unread = db_fetch_result($result, 0, "unread");
2528 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2529 if (DB_TYPE
== "pgsql") {
2530 return "ttrss_entries.date_updated >
2531 NOW() - INTERVAL '$days days'";
2533 return "ttrss_entries.date_updated >
2534 DATE_SUB(NOW(), INTERVAL $days DAY)";
2538 function getFeedUnread($link, $feed, $is_cat = false) {
2539 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2542 function getLabelUnread($link, $label_id, $owner_uid = false) {
2543 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2545 $result = db_query($link, "
2546 SELECT COUNT(unread) AS unread FROM
2547 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2548 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2549 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2550 AND unread = true AND feed_id = ttrss_feeds.id
2551 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2553 if (db_num_rows($result) != 0) {
2554 return db_fetch_result($result, 0, "unread");
2560 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2561 $owner_uid = false) {
2563 $n_feed = (int) $feed;
2565 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2568 $unread_qpart = "unread = true";
2570 $unread_qpart = "true";
2573 $age_qpart = getMaxAgeSubquery();
2576 return getCategoryUnread($link, $n_feed, $owner_uid);
2577 } if ($feed != "0" && $n_feed == 0) {
2579 $feed = db_escape_string($feed);
2581 $result = db_query($link, "SELECT 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_qpart)) AS count FROM ttrss_tags
2585 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2586 return db_fetch_result($result, 0, "count");
2588 } else if ($n_feed == -1) {
2589 $match_part = "marked = true";
2590 } else if ($n_feed == -2) {
2591 $match_part = "published = true";
2592 } else if ($n_feed == -3) {
2593 $match_part = "unread = true";
2595 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2597 if (DB_TYPE
== "pgsql") {
2598 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2600 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2602 } else if ($n_feed == -4) {
2603 $match_part = "true";
2604 } else if ($n_feed >= 0) {
2607 $match_part = "feed_id = '$n_feed'";
2609 $match_part = "feed_id IS NULL";
2612 } else if ($feed < -10) {
2614 $label_id = -$feed - 11;
2616 return getLabelUnread($link, $label_id, $owner_uid);
2623 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2624 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2626 $from_qpart = "ttrss_user_entries,ttrss_entries";
2630 $query = "SELECT count(int_id) AS unread
2631 FROM $from_qpart WHERE
2632 ttrss_user_entries.ref_id = ttrss_entries.id AND
2635 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2637 $result = db_query($link, $query);
2641 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2642 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2643 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2644 AND $unread_qpart AND $age_qpart AND
2645 ttrss_tags.owner_uid = " . $owner_uid);
2648 $unread = db_fetch_result($result, 0, "unread");
2653 function getGlobalUnread($link, $user_id = false) {
2656 $user_id = $_SESSION["uid"];
2659 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2660 WHERE owner_uid = '$user_id' AND feed_id > 0");
2662 $c_id = db_fetch_result($result, 0, "c_id");
2667 function getGlobalCounters($link, $global_unread = -1) {
2670 if ($global_unread == -1) {
2671 $global_unread = getGlobalUnread($link);
2674 $cv = array("id" => "global-unread",
2675 "counter" => $global_unread);
2677 array_push($ret_arr, $cv);
2679 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2680 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2682 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2684 $cv = array("id" => "subscribed-feeds",
2685 "counter" => $subscribed_feeds);
2687 array_push($ret_arr, $cv);
2692 function getSubscribedFeeds($link) {
2693 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2694 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2696 return db_fetch_result($result, 0, "fn");
2699 function getTagCounters($link) {
2703 $age_qpart = getMaxAgeSubquery();
2705 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2706 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2707 AND ref_id = id AND $age_qpart
2708 AND unread = true)) AS count FROM ttrss_tags
2709 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2710 ORDER BY count DESC LIMIT 55");
2714 while ($line = db_fetch_assoc($result)) {
2715 $tags[$line["tag_name"]] +
= $line["count"];
2718 foreach (array_keys($tags) as $tag) {
2719 $unread = $tags[$tag];
2720 $tag = htmlspecialchars($tag);
2722 $cv = array("id" => $tag,
2724 "counter" => $unread);
2726 array_push($ret_arr, $cv);
2732 function getVirtCounters($link) {
2736 for ($i = 0; $i >= -4; $i--) {
2738 $count = getFeedUnread($link, $i);
2740 $cv = array("id" => $i,
2741 "counter" => $count);
2743 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2744 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2746 array_push($ret_arr, $cv);
2752 function getLabelCounters($link, $descriptions = false) {
2756 $age_qpart = getMaxAgeSubquery();
2758 $owner_uid = $_SESSION["uid"];
2760 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2761 WHERE owner_uid = '$owner_uid'");
2763 while ($line = db_fetch_assoc($result)) {
2765 $id = -$line["id"] - 11;
2767 $label_name = $line["caption"];
2768 $count = getFeedUnread($link, $id);
2770 $cv = array("id" => $id,
2771 "counter" => $count);
2774 $cv["description"] = $label_name;
2776 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2777 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2779 array_push($ret_arr, $cv);
2785 function getFeedCounters($link, $active_feed = false) {
2789 $age_qpart = getMaxAgeSubquery();
2791 $query = "SELECT ttrss_feeds.id,
2793 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2794 last_error, value AS count
2795 FROM ttrss_feeds, ttrss_counters_cache
2796 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2797 AND ttrss_counters_cache.feed_id = id";
2799 $result = db_query($link, $query);
2800 $fctrs_modified = false;
2802 while ($line = db_fetch_assoc($result)) {
2805 $count = $line["count"];
2806 $last_error = htmlspecialchars($line["last_error"]);
2808 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2810 $has_img = feed_has_icon($id);
2812 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2815 $cv = array("id" => $id,
2816 "updated" => $last_updated,
2817 "counter" => $count,
2818 "has_img" => (int) $has_img);
2821 $cv["error"] = $last_error;
2823 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2824 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2826 if ($active_feed && $id == $active_feed)
2827 $cv["title"] = truncate_string($line["title"], 30);
2829 array_push($ret_arr, $cv);
2836 function get_pgsql_version($link) {
2837 $result = db_query($link, "SELECT version() AS version");
2838 $version = split(" ", db_fetch_result($result, 0, "version"));
2842 function print_error_xml($code, $add_msg = "") {
2845 $error_msg = $ERRORS[$code];
2848 $error_msg = "$error_msg; $add_msg";
2851 print "<rpc-reply>";
2852 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2853 print "</rpc-reply>";
2857 * Subscribes the user to the given feed
2859 * @param resource $link Database connection
2860 * @param string $url Feed URL to subscribe to
2861 * @param integer $cat_id Category ID the feed shall be added to
2862 * @param string $auth_login (optional) Feed username
2863 * @param string $auth_pass (optional) Feed password
2865 * @return integer Status code:
2866 * 0 - OK, Feed already exists
2867 * 1 - OK, Feed added
2869 * 3 - URL content is HTML, no feeds available
2870 * 4 - URL content is HTML which contains multiple feeds.
2871 * Here you should call extractfeedurls in rpc-backend
2872 * to get all possible feeds.
2873 * 5 - Couldn't download the URL content.
2875 function subscribe_to_feed($link, $url, $cat_id = 0,
2876 $auth_login = '', $auth_pass = '') {
2878 $url = fix_url($url);
2879 if (!validate_feed_url($url)) return 2;
2880 if (!fetch_file_contents($url)) return 5;
2882 if (url_is_html($url)) {
2883 $feedUrls = get_feeds_from_html($url);
2884 if (count($feedUrls) == 0) {
2886 } else if (count($feedUrls) > 1) {
2889 //use feed url as new URL
2890 $url = key($feedUrls);
2893 if ($cat_id == "0" ||
!$cat_id) {
2894 $cat_qpart = "NULL";
2896 $cat_qpart = "'$cat_id'";
2899 $result = db_query($link,
2900 "SELECT id FROM ttrss_feeds
2901 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2903 if (db_num_rows($result) == 0) {
2904 $result = db_query($link,
2905 "INSERT INTO ttrss_feeds
2906 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2907 VALUES ('".$_SESSION["uid"]."', '$url',
2908 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2910 $result = db_query($link,
2911 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2912 AND owner_uid = " . $_SESSION["uid"]);
2914 $feed_id = db_fetch_result($result, 0, "id");
2917 update_rss_feed($link, $feed_id, true);
2926 function print_feed_select($link, $id, $default_id = "",
2927 $attributes = "", $include_all_feeds = true) {
2929 print "<select id=\"$id\" name=\"$id\" $attributes>";
2930 if ($include_all_feeds) {
2931 print "<option value=\"0\">".__('All feeds')."</option>";
2934 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2935 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2937 if (db_num_rows($result) > 0 && $include_all_feeds) {
2938 print "<option disabled>--------</option>";
2941 while ($line = db_fetch_assoc($result)) {
2942 if ($line["id"] == $default_id) {
2943 $is_selected = "selected=\"1\"";
2948 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2950 printf("<option $is_selected value='%d'>%s</option>",
2951 $line["id"], $title);
2957 function print_feed_cat_select($link, $id, $default_id = "",
2958 $attributes = "", $include_all_cats = true) {
2960 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
2962 if ($include_all_cats) {
2963 print "<option value=\"0\">".__('Uncategorized')."</option>";
2966 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2967 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2969 if (db_num_rows($result) > 0 && $include_all_cats) {
2970 print "<option disabled=\"1\">--------</option>";
2973 while ($line = db_fetch_assoc($result)) {
2974 if ($line["id"] == $default_id) {
2975 $is_selected = "selected=\"1\"";
2981 printf("<option $is_selected value='%d'>%s</option>",
2982 $line["id"], htmlspecialchars($line["title"]));
2985 print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
2990 function checkbox_to_sql_bool($val) {
2991 return ($val == "on") ?
"true" : "false";
2994 function getFeedCatTitle($link, $id) {
2996 return __("Special");
2997 } else if ($id < -10) {
2998 return __("Labels");
2999 } else if ($id > 0) {
3000 $result = db_query($link, "SELECT ttrss_feed_categories.title
3001 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3002 cat_id = ttrss_feed_categories.id");
3003 if (db_num_rows($result) == 1) {
3004 return db_fetch_result($result, 0, "title");
3006 return __("Uncategorized");
3009 return "getFeedCatTitle($id) failed";
3014 function getFeedIcon($id) {
3017 return "images/archive.png";
3020 return "images/mark_set.png";
3023 return "images/pub_set.png";
3026 return "images/fresh.png";
3029 return "images/tag.png";
3033 return "images/label.png";
3035 return ICONS_URL
. "/$id.ico";
3041 function getFeedTitle($link, $id) {
3043 return __("Starred articles");
3044 } else if ($id == -2) {
3045 return __("Published articles");
3046 } else if ($id == -3) {
3047 return __("Fresh articles");
3048 } else if ($id == -4) {
3049 return __("All articles");
3050 } else if ($id === 0 ||
$id === "0") {
3051 return __("Archived articles");
3052 } else if ($id < -10) {
3053 $label_id = -$id - 11;
3054 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3055 if (db_num_rows($result) == 1) {
3056 return db_fetch_result($result, 0, "caption");
3058 return "Unknown label ($label_id)";
3061 } else if ($id > 0) {
3062 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3063 if (db_num_rows($result) == 1) {
3064 return db_fetch_result($result, 0, "title");
3066 return "Unknown feed ($id)";
3073 function get_session_cookie_name() {
3074 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3077 function make_init_params($link) {
3080 $params["theme"] = get_user_theme($link);
3081 $params["theme_options"] = get_user_theme_options($link);
3082 $params["daemon_enabled"] = ENABLE_UPDATE_DAEMON
;
3084 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3085 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3086 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3087 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3089 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3090 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3091 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3092 "HIDE_READ_SHOWS_SPECIAL", "HIDE_FEEDLIST", "COMBINED_DISPLAY_MODE") as $param) {
3094 $params[strtolower($param)] = (int) get_pref($link, $param);
3097 $params["icons_url"] = ICONS_URL
;
3098 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3099 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3100 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3101 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3102 $params["prefs_active_tab"] = get_pref($link, "_PREFS_ACTIVE_TAB");
3103 $params["infobox_disable_overlay"] = get_pref($link, "_INFOBOX_DISABLE_OVERLAY");
3104 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3105 $params["offline_enabled"] = (int) get_pref($link, "ENABLE_OFFLINE_READING");
3107 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3108 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3110 $num_feeds = db_fetch_result($result, 0, "cf");
3112 $params["num_feeds"] = (int) $num_feeds;
3113 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3118 function print_runtime_info($link) {
3119 print "<runtime-info><![CDATA[";
3120 print json_encode(make_runtime_info($link));
3121 print "]]></runtime-info>";
3124 function make_runtime_info($link) {
3125 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3126 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3128 $num_feeds = db_fetch_result($result, 0, "cf");
3132 $data['num_feeds'] = (int) $num_feeds;
3133 $data['last_article_id'] = getLastArticleId($link);
3134 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3136 if (ENABLE_UPDATE_DAEMON
) {
3138 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3140 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3142 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3145 $stamp_delta = time() - $stamp;
3147 if ($stamp_delta > 1800) {
3151 $_SESSION["daemon_stamp_check"] = time();
3154 $data['daemon_stamp_ok'] = $stamp_check;
3156 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3158 $data['daemon_stamp'] = $stamp_fmt;
3163 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
3165 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3166 $new_version_details = @check_for_update
($link);
3168 $data['new_version_available'] = (int) $new_version_details != "";
3170 $_SESSION["last_version_check"] = time();
3177 function getSearchSql($search, $match_on) {
3179 $search_query_part = "";
3181 $keywords = split(" ", $search);
3182 $query_keywords = array();
3184 if ($match_on == "both") {
3186 foreach ($keywords as $k) {
3187 if (strpos($k, "-") === 0) {
3194 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3195 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3198 $search_query_part = implode("AND", $query_keywords) . " AND ";
3200 } else if ($match_on == "title") {
3202 foreach ($keywords as $k) {
3203 if (strpos($k, "-") === 0) {
3210 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3213 $search_query_part = implode("AND", $query_keywords) . " AND ";
3215 } else if ($match_on == "content") {
3217 foreach ($keywords as $k) {
3218 if (strpos($k, "-") === 0) {
3225 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3229 $search_query_part = implode("AND", $query_keywords);
3231 return $search_query_part;
3234 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3236 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3238 $ext_tables_part = "";
3242 if (SPHINX_ENABLED
) {
3243 $ids = join(",", @sphinx_search
($search, 0, 500));
3246 $search_query_part = "ref_id IN ($ids) AND ";
3248 $search_query_part = "ref_id = -1 AND ";
3251 $search_query_part = getSearchSql($search, $match_on);
3252 $search_query_part .= " AND ";
3256 $search_query_part = "";
3259 $view_query_part = "";
3261 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3263 $view_query_part = " ";
3264 } else if ($feed != -1) {
3265 $unread = getFeedUnread($link, $feed, $cat_view);
3267 $view_query_part = " unread = true AND ";
3272 if ($view_mode == "marked") {
3273 $view_query_part = " marked = true AND ";
3276 if ($view_mode == "published") {
3277 $view_query_part = " published = true AND ";
3280 if ($view_mode == "unread") {
3281 $view_query_part = " unread = true AND ";
3284 if ($view_mode == "updated") {
3285 $view_query_part = " (last_read is null and unread = false) AND ";
3289 $limit_query_part = "LIMIT " . $limit;
3292 $vfeed_query_part = "";
3294 // override query strategy and enable feed display when searching globally
3295 if ($search && $search_mode == "all_feeds") {
3296 $query_strategy_part = "ttrss_entries.id > 0";
3297 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3299 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3300 $query_strategy_part = "ttrss_entries.id > 0";
3301 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3302 id = feed_id) as feed_title,";
3303 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3305 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3307 $tmp_result = false;
3310 $tmp_result = db_query($link, "SELECT id
3311 FROM ttrss_feeds WHERE cat_id = '$feed'");
3313 $tmp_result = db_query($link, "SELECT id
3314 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3315 WHERE id = '$feed') AND id != '$feed'");
3318 $cat_siblings = array();
3320 if (db_num_rows($tmp_result) > 0) {
3321 while ($p = db_fetch_assoc($tmp_result)) {
3322 array_push($cat_siblings, "feed_id = " . $p["id"]);
3325 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3326 $feed, implode(" OR ", $cat_siblings));
3329 $query_strategy_part = "ttrss_entries.id > 0";
3332 } else if ($feed > 0) {
3337 $query_strategy_part = "cat_id = '$feed'";
3339 $query_strategy_part = "cat_id IS NULL";
3342 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3345 $query_strategy_part = "feed_id = '$feed'";
3347 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3348 $query_strategy_part = "feed_id IS NULL";
3349 } else if ($feed == 0 && $cat_view) { // uncategorized
3350 $query_strategy_part = "cat_id IS NULL";
3351 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3352 } else if ($feed == -1) { // starred virtual feed
3353 $query_strategy_part = "marked = true";
3354 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3355 } else if ($feed == -2) { // published virtual feed OR labels category
3358 $query_strategy_part = "published = true";
3359 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3361 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3363 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3365 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3366 ttrss_user_labels2.article_id = ref_id";
3370 } else if ($feed == -3) { // fresh virtual feed
3371 $query_strategy_part = "unread = true";
3373 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3375 if (DB_TYPE
== "pgsql") {
3376 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3378 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3381 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3382 } else if ($feed == -4) { // all articles virtual feed
3383 $query_strategy_part = "true";
3384 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3385 } else if ($feed <= -10) { // labels
3386 $label_id = -$feed - 11;
3388 $query_strategy_part = "label_id = '$label_id' AND
3389 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3390 ttrss_user_labels2.article_id = ref_id";
3392 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3393 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3396 $query_strategy_part = "id > 0"; // dumb
3399 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3400 $date_sort_field = "updated";
3402 $date_sort_field = "date_entered";
3405 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3406 $order_by = "$date_sort_field";
3408 $order_by = "$date_sort_field DESC";
3411 if ($view_mode != "noscores") {
3412 $order_by = "score DESC, $order_by";
3415 if ($override_order) {
3416 $order_by = $override_order;
3422 $feed_title = "Search results";
3425 $feed_title = getCategoryTitle($link, $feed);
3427 if ((int)$feed == $feed && $feed > 0) {
3428 $result = db_query($link, "SELECT title,site_url,last_error
3429 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3431 $feed_title = db_fetch_result($result, 0, "title");
3432 $feed_site_url = db_fetch_result($result, 0, "site_url");
3433 $last_error = db_fetch_result($result, 0, "last_error");
3435 $feed_title = getFeedTitle($link, $feed);
3440 $content_query_part = "content as content_preview,";
3442 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3445 $feed_kind = "Feeds";
3447 $feed_kind = "Labels";
3450 if ($limit_query_part) {
3451 $offset_query_part = "OFFSET $offset";
3454 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3455 if (!$override_order) {
3456 $order_by = "ttrss_feeds.title, $order_by";
3461 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3462 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3465 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3466 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3469 $query = "SELECT DISTINCT
3472 ttrss_entries.id,ttrss_entries.title,
3475 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3476 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3479 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3485 ttrss_user_entries.ref_id = ttrss_entries.id AND
3486 ttrss_user_entries.owner_uid = '$owner_uid' AND
3489 $query_strategy_part ORDER BY $order_by
3490 $limit_query_part $offset_query_part";
3492 if ($_REQUEST["debug"]) print $query;
3494 $result = db_query($link, $query);
3499 $feed_kind = "Tags";
3501 $result = db_query($link, "SELECT
3504 ttrss_entries.id as id,title,
3506 unread,feed_id,orig_feed_id,
3507 marked,link,last_read,
3508 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3511 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3514 ttrss_entries,ttrss_user_entries,ttrss_tags
3516 ref_id = ttrss_entries.id AND
3517 ttrss_user_entries.owner_uid = '$owner_uid' AND
3518 post_int_id = int_id AND tag_name = '$feed' AND
3521 $query_strategy_part ORDER BY $order_by
3522 $limit_query_part");
3525 return array($result, $feed_title, $feed_site_url, $last_error);
3529 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3530 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3532 $note_style = "float : right; background-color : #fff7d5; border-width : 1px; ".
3533 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3534 "margin-bottom : 1em; color : #9a8c59;";
3536 if (!$limit) $limit = 30;
3538 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3539 $date_sort_field = "updated";
3541 $date_sort_field = "date_entered";
3544 $qfh_ret = queryFeedHeadlines($link, $feed,
3545 $limit, $view_mode, $is_cat, $search, $search_mode,
3546 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3548 $result = $qfh_ret[0];
3549 $feed_title = htmlspecialchars($qfh_ret[1]);
3550 $feed_site_url = $qfh_ret[2];
3551 $last_error = $qfh_ret[3];
3553 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3555 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3556 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3557 <rss version=\"2.0\">
3559 <title>$feed_title</title>
3560 <link>$feed_site_url</link>
3561 <description>Feed generated by Tiny Tiny RSS</description>";
3563 while ($line = db_fetch_assoc($result)) {
3565 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3566 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3568 $tags = get_article_tags($link, $line["id"], $owner_uid);
3570 foreach ($tags as $tag) {
3571 print "<category>" . htmlspecialchars($tag) . "</category>";
3574 $rfc822_date = date('r', strtotime($line["updated"]));
3576 print "<pubDate>$rfc822_date</pubDate>";
3578 if ($line["author"]) {
3579 print "<author>" . htmlspecialchars($line["author"]) . "</author>";
3582 print "<title><![CDATA[" .
3583 htmlspecialchars($line["title"]) . "]]></title>";
3585 print "<description><![CDATA[";
3587 if ($line["note"]) {
3588 print "<div style='$note_style'>";
3589 print $line["note"];
3593 print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3594 print "]]></description>";
3596 $enclosures = get_article_enclosures($link, $line["id"]);
3598 foreach ($enclosures as $e) {
3599 $type = htmlspecialchars($e['content_type']);
3600 $url = htmlspecialchars($e['content_url']);
3601 $length = $e['duration'];
3602 print "<enclosure url=\"$url\" type=\"$type\" length=\"$length\"/>";
3608 print "</channel></rss>";
3612 function getCategoryTitle($link, $cat_id) {
3614 if ($cat_id == -1) {
3615 return __("Special");
3616 } else if ($cat_id == -2) {
3617 return __("Labels");
3620 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3623 if (db_num_rows($result) == 1) {
3624 return db_fetch_result($result, 0, "title");
3626 return "Uncategorized";
3631 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3634 if (!$owner) $owner = $_SESSION["uid"];
3636 $res = trim($str); if (!$res) return '';
3638 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) ||
$force_strip_tags) {
3639 $res = $purifier->purify($res);
3642 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3643 $res = preg_replace('/<img[^>]+>/is', '', $res);
3646 $charset_hack = '<head>
3647 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3650 $res = trim($res); if (!$res) return '';
3652 libxml_use_internal_errors(true);
3654 $doc = new DOMDocument();
3655 $doc->loadHTML($charset_hack . $res);
3656 $xpath = new DOMXPath($doc);
3658 $entries = $xpath->query('(//a[@href]|//img[@src])');
3661 foreach ($entries as $entry) {
3665 if ($entry->hasAttribute('href'))
3666 $entry->setAttribute('href',
3667 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3669 if ($entry->hasAttribute('src'))
3670 $entry->setAttribute('src',
3671 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3674 if (strtolower($entry->nodeName
) == "a") {
3675 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW', $owner)) {
3676 $entry->setAttribute("target", "_blank");
3680 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3681 $br = $doc->createElement("br");
3683 if ($entry->parentNode
->nextSibling
) {
3684 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3691 $node = $doc->getElementsByTagName('body')->item(0);
3693 return $doc->saveXML($node);
3697 * Send by mail a digest of last articles.
3699 * @param mixed $link The database connection.
3700 * @param integer $limit The maximum number of articles by digest.
3701 * @return boolean Return false if digests are not enabled.
3703 function send_headlines_digests($link, $limit = 100) {
3705 if (!DIGEST_ENABLE
) return false;
3707 $user_limit = DIGEST_EMAIL_LIMIT
;
3710 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3712 if (DB_TYPE
== "pgsql") {
3713 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3714 } else if (DB_TYPE
== "mysql") {
3715 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3718 $result = db_query($link, "SELECT id,email FROM ttrss_users
3719 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3721 while ($line = db_fetch_assoc($result)) {
3723 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3724 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3726 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3728 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3729 $digest = $tuple[0];
3730 $headlines_count = $tuple[1];
3731 $affected_ids = $tuple[2];
3732 $digest_text = $tuple[3];
3734 if ($headlines_count > 0) {
3736 $mail = new PHPMailer();
3738 $mail->PluginDir
= "lib/phpmailer/";
3739 $mail->SetLanguage("en", "lib/phpmailer/language/");
3741 $mail->CharSet
= "UTF-8";
3743 $mail->From
= DIGEST_FROM_ADDRESS
;
3744 $mail->FromName
= DIGEST_FROM_NAME
;
3745 $mail->AddAddress($line["email"], $line["login"]);
3747 if (DIGEST_SMTP_HOST
) {
3748 $mail->Host
= DIGEST_SMTP_HOST
;
3749 $mail->Mailer
= "smtp";
3750 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3751 $mail->Username
= DIGEST_SMTP_LOGIN
;
3752 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3755 $mail->IsHTML(true);
3756 $mail->Subject
= DIGEST_SUBJECT
;
3757 $mail->Body
= $digest;
3758 $mail->AltBody
= $digest_text;
3760 $rc = $mail->Send();
3762 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3766 if ($rc && $do_catchup) {
3767 print "Marking affected articles as read...\n";
3768 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3771 print "No headlines\n";
3774 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3775 WHERE id = " . $line["id"]);
3779 print "All done.\n";
3783 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3785 require_once "lib/MiniTemplator.class.php";
3787 $tpl = new MiniTemplator
;
3788 $tpl_t = new MiniTemplator
;
3790 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3791 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3793 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3794 $tpl->setVariable('CUR_TIME', date('G:i'));
3796 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3797 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3799 $affected_ids = array();
3801 if (DB_TYPE
== "pgsql") {
3802 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3803 } else if (DB_TYPE
== "mysql") {
3804 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3807 $result = db_query($link, "SELECT ttrss_entries.title,
3808 ttrss_feeds.title AS feed_title,
3810 ttrss_user_entries.ref_id,
3812 SUBSTRING(content, 1, 120) AS excerpt,
3813 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3815 ttrss_user_entries,ttrss_entries,ttrss_feeds
3817 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3818 AND include_in_digest = true
3820 AND ttrss_user_entries.owner_uid = $user_id
3822 ORDER BY ttrss_feeds.title, date_updated DESC
3825 $cur_feed_title = "";
3827 $headlines_count = db_num_rows($result);
3829 $headlines = array();
3831 while ($line = db_fetch_assoc($result)) {
3832 array_push($headlines, $line);
3835 for ($i = 0; $i < sizeof($headlines); $i++
) {
3837 $line = $headlines[$i];
3839 array_push($affected_ids, $line["ref_id"]);
3841 $updated = make_local_datetime($link, $line['last_updated'], false,
3844 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3845 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3846 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3847 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3848 $tpl->setVariable('ARTICLE_EXCERPT',
3849 truncate_string(strip_tags($line["excerpt"]), 100));
3851 $tpl->addBlock('article');
3853 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3854 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3855 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3856 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3857 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3858 // truncate_string(strip_tags($line["excerpt"]), 100));
3860 $tpl_t->addBlock('article');
3862 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3863 $tpl->addBlock('feed');
3864 $tpl_t->addBlock('feed');
3869 $tpl->addBlock('digest');
3870 $tpl->generateOutputToString($tmp);
3872 $tpl_t->addBlock('digest');
3873 $tpl_t->generateOutputToString($tmp_t);
3875 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3878 function check_for_update($link) {
3879 $releases_feed = "http://tt-rss.org/releases.rss";
3881 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3885 if (DEFAULT_UPDATE_METHOD
== "1") {
3886 $rss = new SimplePie();
3887 $rss->set_useragent(SELF_USER_AGENT
);
3888 $rss->set_feed_url($fetch_url);
3889 $rss->set_output_encoding('UTF-8');
3892 $rss = fetch_rss($releases_feed);
3897 if (DEFAULT_UPDATE_METHOD
== "1") {
3898 $items = $rss->get_items();
3900 $items = $rss->items
;
3902 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3903 if (!$items ||
!is_array($items)) $items = $rss;
3906 if (!is_array($items) ||
count($items) == 0) {
3910 $latest_item = $items[0];
3912 if (DEFAULT_UPDATE_METHOD
== "1") {
3913 $last_title = $latest_item->get_title();
3915 $last_title = $latest_item["title"];
3918 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3920 if (DEFAULT_UPDATE_METHOD
== "1") {
3921 $release_url = sanitize_rss($link, $latest_item->get_link());
3922 $content = sanitize_rss($link, $latest_item->get_description());
3924 $release_url = sanitize_rss($link, $latest_item["link"]);
3925 $content = sanitize_rss($link, $latest_item["description"]);
3928 if (version_compare(VERSION
, $latest_version) == -1) {
3929 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3930 $latest_version)."<div class='milestoneDetails'>$content</div>";
3937 function markArticlesById($link, $ids, $cmode) {
3941 foreach ($ids as $id) {
3942 array_push($tmp_ids, "ref_id = '$id'");
3945 $ids_qpart = join(" OR ", $tmp_ids);
3948 db_query($link, "UPDATE ttrss_user_entries SET
3949 marked = false,last_read = NOW()
3950 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3951 } else if ($cmode == 1) {
3952 db_query($link, "UPDATE ttrss_user_entries SET
3954 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3956 db_query($link, "UPDATE ttrss_user_entries SET
3957 marked = NOT marked,last_read = NOW()
3958 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3962 function publishArticlesById($link, $ids, $cmode) {
3966 foreach ($ids as $id) {
3967 array_push($tmp_ids, "ref_id = '$id'");
3970 $ids_qpart = join(" OR ", $tmp_ids);
3973 db_query($link, "UPDATE ttrss_user_entries SET
3974 published = false,last_read = NOW()
3975 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3976 } else if ($cmode == 1) {
3977 db_query($link, "UPDATE ttrss_user_entries SET
3979 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3981 db_query($link, "UPDATE ttrss_user_entries SET
3982 published = NOT published,last_read = NOW()
3983 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3987 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3989 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3990 if (count($ids) == 0) return;
3994 foreach ($ids as $id) {
3995 array_push($tmp_ids, "ref_id = '$id'");
3998 $ids_qpart = join(" OR ", $tmp_ids);
4001 db_query($link, "UPDATE ttrss_user_entries SET
4002 unread = false,last_read = NOW()
4003 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4004 } else if ($cmode == 1) {
4005 db_query($link, "UPDATE ttrss_user_entries SET
4007 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4009 db_query($link, "UPDATE ttrss_user_entries SET
4010 unread = NOT unread,last_read = NOW()
4011 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4016 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4017 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4019 while ($line = db_fetch_assoc($result)) {
4020 ccache_update($link, $line["feed_id"], $owner_uid);
4024 function catchupArticleById($link, $id, $cmode) {
4027 db_query($link, "UPDATE ttrss_user_entries SET
4028 unread = false,last_read = NOW()
4029 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4030 } else if ($cmode == 1) {
4031 db_query($link, "UPDATE ttrss_user_entries SET
4033 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4035 db_query($link, "UPDATE ttrss_user_entries SET
4036 unread = NOT unread,last_read = NOW()
4037 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4040 $feed_id = getArticleFeed($link, $id);
4041 ccache_update($link, $feed_id, $_SESSION["uid"]);
4044 function make_guid_from_title($title) {
4045 return preg_replace("/[ \"\',.:;]/", "-",
4046 mb_strtolower(strip_tags($title), 'utf-8'));
4049 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4050 $feed_id, $is_cat, $search, $match_on,
4051 $search_mode, $view_mode) {
4053 # print "<div class=\"headlinesSubToolbar\">";
4055 $page_prev_link = "viewFeedGoPage(-1)";
4056 $page_next_link = "viewFeedGoPage(1)";
4057 $page_first_link = "viewFeedGoPage(0)";
4059 $catchup_page_link = "catchupPage()";
4060 $catchup_feed_link = "catchupCurrentFeed()";
4061 $catchup_sel_link = "catchupSelection()";
4063 $archive_sel_link = "archiveSelection()";
4064 $delete_sel_link = "deleteSelection()";
4066 $sel_all_link = "selectArticles('all')";
4067 $sel_unread_link = "selectArticles('unread')";
4068 $sel_none_link = "selectArticles('none')";
4069 $sel_inv_link = "selectArticles('invert')";
4071 $tog_unread_link = "selectionToggleUnread()";
4072 $tog_marked_link = "selectionToggleMarked()";
4073 $tog_published_link = "selectionTogglePublished()";
4075 print "<div id=\"subtoolbar_main\">";
4077 print __('Select:')."
4078 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4079 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4080 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4081 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4085 print "<select dojoType=\"dijit.form.Select\"
4086 onchange=\"headlineActionsChange(this)\">";
4087 print "<option value=\"\">".__('Actions...')."</option>";
4089 # print "<optgroup label=\"".__("Selection toggle:")."\">";
4091 print "<option value=\"$tog_unread_link\">".__('Toggle unread')."</option>
4092 <option value=\"$tog_marked_link\">".__('Toggle starred')."</option>
4093 <option value=\"$tog_published_link\">".__('Toggle published')."</option>";
4095 # print "</optgroup>
4096 # <optgroup label=\"".__("Selection:")."\">";
4098 print "<option>----------</option>";
4100 print "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4102 if ($feed_id != "0") {
4103 print "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4105 print "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4106 print "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4110 print "<option value=\"emailArticle(false)\">".__('Forward by email').
4113 # print "<optgroup label=\"".__("Assign label:")."\">";
4114 print "<option>----------</option>";
4116 print_labels_headlines_dropdown($link, $feed_id);
4118 print "<option>----------</option>";
4120 # print "</optgroup>";
4122 print "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4128 print "<div id=\"subtoolbar_ftitle\">";
4130 if ($feed_site_url) {
4131 $target = "target=\"_blank\"";
4132 print "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4133 truncate_string($feed_title,30)."</a>";
4135 if ($feed_id < -10) {
4136 $label_id = -11-$feed_id;
4138 $result = db_query($link, "SELECT fg_color, bg_color
4139 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4142 if (db_num_rows($result) != 0) {
4143 $fg_color = db_fetch_result($result, 0, "fg_color");
4144 $bg_color = db_fetch_result($result, 0, "bg_color");
4146 print "<span style='background : $bg_color; color : $fg_color'>";
4159 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4164 // Adaptive doesn't really make any sense for generated feeds
4165 // All Articles is the default, so no need to insert it either
4166 if ($view_mode == "adaptive" ||
$view_mode == "all_articles")
4169 $view_mode = "&view-mode=$view_mode";
4171 $rss_link = htmlspecialchars(get_self_url_prefix() .
4172 "/backend.php?op=rss&id=$feed_id&is_cat=$is_cat$view_mode$search_q");
4175 # <a target=\"_blank\"
4176 # title=\"".__("View as RSS feed")."\"
4177 # href=\"$rss_link\">
4178 # <img class=\"noborder\" src=\"images/feed-icon-12x12.png\"></a>";
4182 title=\"".__("View as RSS feed")."\"
4183 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4184 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4190 function outputFeedList($link) {
4192 $feedlist = array();
4194 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4196 $feedlist['identifier'] = 'id';
4197 $feedlist['label'] = 'name';
4198 $feedlist['items'] = array();
4200 $owner_uid = $_SESSION["uid"];
4205 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4206 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4208 $cat['items'] = array();
4211 foreach (array(-4, -3, -1, -2, 0) as $i) {
4212 array_push($cat['items'], feedlist_init_feed($link, $i));
4216 array_push($feedlist['items'], $cat);
4218 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4221 $result = db_query($link, "SELECT * FROM
4222 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4224 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4225 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4226 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4228 $cat['items'] = array();
4231 while ($line = db_fetch_assoc($result)) {
4233 $label_id = -$line['id'] - 11;
4234 $count = getFeedUnread($link, $label_id);
4236 array_push($cat['items'], feedlist_init_feed($link, $label_id,
4241 array_push($feedlist['items'], $cat);
4243 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4246 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4247 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4248 $order_by_qpart = "order_id,category,unread DESC,title";
4250 $order_by_qpart = "order_id,category,title";
4253 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4254 $order_by_qpart = "unread DESC,title";
4256 $order_by_qpart = "title";
4260 $age_qpart = getMaxAgeSubquery();
4262 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4263 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4265 ttrss_feed_categories.title AS category,
4266 ttrss_feed_categories.collapsed,
4268 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4269 ON (ttrss_feed_categories.id = cat_id)
4270 LEFT JOIN ttrss_counters_cache
4272 (ttrss_feeds.id = feed_id)
4274 ttrss_feeds.owner_uid = '$owner_uid'
4275 ORDER BY $order_by_qpart";
4277 $result = db_query($link, $query);
4279 $actid = $_REQUEST["actid"];
4286 $cat['items'] = array();
4290 while ($line = db_fetch_assoc($result)) {
4292 $feed = htmlspecialchars(trim($line["title"]));
4294 if (!$feed) $feed = "[Untitled]";
4296 $feed_id = $line["id"];
4297 $unread = $line["unread"];
4299 $cat_id = $line["cat_id"];
4300 $tmp_category = $line["category"];
4301 if (!$tmp_category) $tmp_category = __("Uncategorized");
4303 if ($category != $tmp_category && $enable_cats) {
4305 $category = $tmp_category;
4307 $collapsed = sql_bool_to_bool($line["collapsed"]);
4309 // workaround for NULL category
4310 if ($category == __("Uncategorized")) {
4311 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4314 if ($cat) array_push($feedlist['items'], $cat);
4316 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4319 $updated = make_local_datetime($link, $line["updated_noms"], false);
4321 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4322 $feed, $unread, $line['last_error'], $updated));
4325 if (!$enable_cats) {
4326 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4332 function get_article_tags($link, $id, $owner_uid = 0) {
4336 $a_id = db_escape_string($id);
4338 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4340 $query = "SELECT DISTINCT tag_name,
4341 owner_uid as owner FROM
4342 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4343 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4345 $obj_id = md5("TAGS:$owner_uid:$id");
4348 if ($memcache && $obj = $memcache->get($obj_id)) {
4351 /* check cache first */
4353 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4354 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4356 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4359 $tags = explode(",", $tag_cache);
4362 /* do it the hard way */
4364 $tmp_result = db_query($link, $query);
4366 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4367 array_push($tags, $tmp_line["tag_name"]);
4370 /* update the cache */
4372 $tags_str = db_escape_string(join(",", $tags));
4374 db_query($link, "UPDATE ttrss_user_entries
4375 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4376 AND owner_uid = " . $_SESSION["uid"]);
4379 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4385 function trim_value(&$value) {
4386 $value = trim($value);
4389 function trim_array($array) {
4391 array_walk($tmp, 'trim_value');
4395 function tag_is_valid($tag) {
4396 if ($tag == '') return false;
4397 if (preg_match("/^[0-9]*$/", $tag)) return false;
4398 if (mb_strlen($tag) > 250) return false;
4400 if (function_exists('iconv')) {
4401 $tag = iconv("utf-8", "utf-8", $tag);
4404 if (!$tag) return false;
4409 function render_login_form($link, $mobile = 0) {
4412 require_once "login_form.php";
4415 require_once "mobile/login_form.php";
4418 require_once "mobile/classic/login_form.php";
4422 // from http://developer.apple.com/internet/safari/faq.html
4423 function no_cache_incantation() {
4424 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4425 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4426 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4427 header("Cache-Control: post-check=0, pre-check=0", false);
4428 header("Pragma: no-cache"); // HTTP/1.0
4431 function format_warning($msg, $id = "") {
4433 return "<div class=\"warning\" id=\"$id\">
4434 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4437 function format_notice($msg) {
4439 return "<div class=\"notice\" id=\"$id\">
4440 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4443 function format_error($msg) {
4445 return "<div class=\"error\" id=\"$id\">
4446 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4449 function print_notice($msg) {
4450 return print format_notice($msg);
4453 function print_warning($msg) {
4454 return print format_warning($msg);
4457 function print_error($msg) {
4458 return print format_error($msg);
4462 function T_sprintf() {
4463 $args = func_get_args();
4464 return vsprintf(__(array_shift($args)), $args);
4467 function format_inline_player($link, $url, $ctype) {
4471 if (($ctype == __("audio/mpeg")) && (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4473 $entry .= "<object type=\"application/x-shockwave-flash\"
4474 data=\"extras/button/musicplayer.swf?song_url=$url\"
4475 width=\"17\" height=\"17\">
4476 <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object>";
4481 if (substr($ctype,0,6)=="audio/" || $ctype=="application/ogg" || $ctype=="application/x-ogg") {
4482 $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4483 if (($ctype == __("audio/mpeg")) &&
4484 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4485 $entry .= "<span><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></span>";
4487 $entry .= "</audio> ";
4488 if (($ctype == __("audio/mpeg")) &&
4489 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4490 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a>";
4491 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>";
4493 } elseif (substr($ctype,0,6)=="video/") {
4494 $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4495 $entry .= "</video>";
4503 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4504 $zoom_mode = false) {
4506 /* we can figure out feed_id from article id anyway, why do we
4507 * pass feed_id here? let's ignore the argument :( */
4509 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4510 WHERE ref_id = '$id'");
4512 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4514 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4516 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4517 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4519 if (db_num_rows($result) == 1) {
4520 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4521 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4523 $rtl_content = false;
4524 $always_display_enclosures = false;
4528 $rtl_tag = "dir=\"RTL\"";
4535 if ($mark_as_read) {
4536 $result = db_query($link, "UPDATE ttrss_user_entries
4537 SET unread = false,last_read = NOW()
4538 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4540 ccache_update($link, $feed_id, $_SESSION["uid"]);
4543 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4544 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4545 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4546 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4551 FROM ttrss_entries,ttrss_user_entries
4552 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4556 $line = db_fetch_assoc($result);
4558 if ($line["icon_url"]) {
4559 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4561 $feed_icon = " ";
4564 $feed_site_url = $line['site_url'];
4566 $num_comments = $line["num_comments"];
4567 $entry_comments = "";
4569 if ($num_comments > 0) {
4570 if ($line["comments"]) {
4571 $comments_url = $line["comments"];
4573 $comments_url = $line["link"];
4575 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4577 if ($line["comments"] && $line["link"] != $line["comments"]) {
4578 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4583 header("Content-Type: text/html");
4585 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4586 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4587 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4591 print "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4592 truncate_string(strip_tags($line['title']), 15) . "</div>";
4594 print "<div class=\"postReply\" id=\"POST-$id\">";
4595 print "<div class=\"postHeader\">";
4597 $entry_author = $line["author"];
4599 if ($entry_author) {
4600 $entry_author = __(" - ") . $entry_author;
4603 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4606 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4608 if ($line["link"]) {
4609 print "<div clear='both'><a target='_blank' href=\"" . $line["link"] . "\">" .
4610 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4612 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4615 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4617 if (!$entry_comments) $entry_comments = " "; # placeholder
4619 print "<div style='float : right'>
4620 <img src='".theme_image($link, 'images/tag.png')."'
4621 class='tagsPic' alt='Tags' title='Tags'> ";
4624 print "<span id=\"ATSTR-$id\">$tags_str</span>
4625 <a title=\"".__('Edit tags for this article')."\"
4626 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4628 print "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4629 class='tagsPic' style=\"cursor : pointer\"
4630 onclick=\"zoomToArticle($id)\"
4631 alt='Zoom' title='".__('Open article in new tab')."'>";
4633 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
4635 print "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4636 class='tagsPic' style=\"cursor : pointer\"
4637 onclick=\"publishWithNote($id, '$note_escaped')\"
4638 alt='PubNote' title='".__('Publish article with a note')."'>";
4640 if (DIGEST_ENABLE
) {
4641 print "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4642 class='tagsPic' style=\"cursor : pointer\"
4643 onclick=\"emailArticle($id)\"
4644 alt='Zoom' title='".__('Forward by email')."'>";
4647 print "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4648 class='tagsPic' style=\"cursor : pointer\"
4649 onclick=\"closeArticlePanel($id)\"
4650 alt='Zoom' title='".__('Close this panel')."'>";
4653 $tags_str = strip_tags($tags_str);
4654 print "<span id=\"ATSTR-$id\">$tags_str</span>";
4657 print "<div clear='both'>$entry_comments</div>";
4659 if ($line["orig_feed_id"]) {
4661 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4662 WHERE id = ".$line["orig_feed_id"]);
4664 if (db_num_rows($tmp_result) != 0) {
4666 print "<div clear='both'>";
4667 print __("Originally from:");
4671 $tmp_line = db_fetch_assoc($tmp_result);
4673 print "<a target='_blank'
4674 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4675 $tmp_line['title'] . "</a>";
4679 print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4680 print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4688 print "<div class=\"postIcon\">" .
4689 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4690 href=\"".htmlspecialchars($feed_site_url)."\">".
4691 $feed_icon . "</a></div>";
4693 print "<div class=\"postContent\">";
4695 $article_content = sanitize_rss($link, $line["content"], false, false,
4698 print "<div id=\"POSTNOTE-$id\">";
4699 if ($line['note']) {
4700 print format_article_note($id, $line['note']);
4704 print $article_content;
4706 print_article_enclosures($link, $id, $always_display_enclosures,
4716 print "]]></article>";
4719 <div style=\"text-align : center\">
4720 <button onclick=\"return window.close()\">".
4721 __("Close this window")."</button></div>";
4722 print "</body></html>";
4728 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4729 $next_unread_feed, $offset, $vgr_last_feed = false,
4730 $override_order = false) {
4732 $disable_cache = false;
4734 $timing_info = getmicrotime();
4736 $topmost_article_ids = array();
4742 if ($subop == "undefined") $subop = "";
4744 $subop_split = split(":", $subop);
4746 if ($subop == "CatchupSelected") {
4747 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4748 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4750 catchupArticlesById($link, $ids, $cmode);
4753 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0 && !$cat_view) {
4754 update_generic_feed($link, $feed, $cat_view, true);
4757 if ($subop == "MarkAllRead") {
4758 catchup_feed($link, $feed, $cat_view);
4760 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4761 if ($next_unread_feed) {
4762 $feed = $next_unread_feed;
4767 if ($subop_split[0] == "MarkAllReadGR") {
4768 catchup_feed($link, $subop_split[1], false);
4771 // FIXME: might break tag display?
4773 if ($feed > 0 && !$cat_view) {
4774 $result = db_query($link,
4775 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4777 if (db_num_rows($result) == 0) {
4778 print "<div align='center'>".__('Feed not found.')."</div>";
4783 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4785 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4786 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4788 if (db_num_rows($result) == 1) {
4789 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4791 $rtl_content = false;
4795 $rtl_tag = "dir=\"RTL\"";
4801 $rtl_content = false;
4804 /// START /////////////////////////////////////////////////////////////////////////////////
4806 @$search = db_escape_string($_REQUEST["query"]);
4809 $disable_cache = true;
4812 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4813 @$match_on = db_escape_string($_REQUEST["match_on"]);
4819 $real_offset = $offset * $limit;
4821 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4823 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4824 $search, $search_mode, $match_on, $override_order, $real_offset);
4826 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4828 $result = $qfh_ret[0];
4829 $feed_title = $qfh_ret[1];
4830 $feed_site_url = $qfh_ret[2];
4831 $last_error = $qfh_ret[3];
4833 $vgroup_last_feed = $vgr_last_feed;
4835 /* if ($feed == -2) {
4836 $feed_site_url = article_publish_url($link);
4839 /// STOP //////////////////////////////////////////////////////////////////////////////////
4841 print "<toolbar><![CDATA[";
4844 // print "<div id=\"headlinesContainer\" $rtl_tag>";
4847 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4851 if (db_num_rows($result) > 0) {
4852 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4853 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode);
4855 // print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4860 print "]]></toolbar><content><![CDATA[";
4862 $headlines_count = db_num_rows($result);
4864 if (db_num_rows($result) > 0) {
4866 $lnum = $limit*$offset;
4869 $cur_feed_title = '';
4871 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4873 while ($line = db_fetch_assoc($result)) {
4875 $class = ($lnum %
2) ?
"even" : "odd";
4878 $feed_id = $line["feed_id"];
4880 $labels = get_article_labels($link, $id);
4882 $labels_str = "<span id=\"HLLCTR-$id\">";
4883 $labels_str .= format_article_labels($labels, $id);
4884 $labels_str .= "</span>";
4886 if (count($topmost_article_ids) < 3) {
4887 array_push($topmost_article_ids, $id);
4890 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4892 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4893 theme_image($link, 'images/updated.png')."\"
4896 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4900 if (sql_bool_to_bool($line["unread"]) &&
4901 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4903 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4904 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
4907 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4908 $class .= " Unread";
4915 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4916 $marked_pic = "<img id=\"FMPIC-$id\"
4917 src=\"".theme_image($link, 'images/mark_set.png')."\"
4918 class=\"markedPic\" alt=\"Unstar article\"
4919 onclick='javascript:tMark($id)'>";
4921 $marked_pic = "<img id=\"FMPIC-$id\"
4922 src=\"".theme_image($link, 'images/mark_unset.png')."\"
4923 class=\"markedPic\" alt=\"Star article\"
4924 onclick='javascript:tMark($id)'>";
4927 if ($line["published"] == "t" ||
$line["published"] == "1") {
4928 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4929 'images/pub_set.png')."\"
4931 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4933 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4934 'images/pub_unset.png')."\"
4936 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4939 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4940 # $line["title"] . "</a>";
4942 # $content_link = "<a
4943 # href=\"" . htmlspecialchars($line["link"]) . "\"
4944 # onclick=\"view($id,$feed_id);\">" .
4945 # $line["title"] . "</a>";
4947 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4948 # $line["title"] . "</a>";
4950 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
4952 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4953 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4957 $score = $line["score"];
4959 $score_pic = theme_image($link,
4960 "images/" . get_score_pic($score));
4962 /* $score_title = __("(Click to change)");
4963 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4964 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4966 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
4971 } else if ($score < -100) {
4977 $entry_author = $line["author"];
4979 if ($entry_author) {
4980 $entry_author = " - $entry_author";
4983 $has_feed_icon = feed_has_icon($feed_id);
4985 if ($has_feed_icon) {
4986 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
4988 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
4989 $feed_icon_img = "";
4992 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4994 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4995 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4997 $cur_feed_title = $line["feed_title"];
4998 $vgroup_last_feed = $feed_id;
5000 $cur_feed_title = htmlspecialchars($cur_feed_title);
5002 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5004 print "<div class='cdmFeedTitle'>".
5005 "<div style=\"float : right\">$feed_icon_img</div>".
5006 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5007 $line["feed_title"]."</a> $vf_catchup_link</div>";
5012 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5013 onmouseout='postMouseOut($id)'";
5015 print "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5017 print "<div class='hlUpdPic'>$update_pic</div>";
5019 print "<div class='hlLeft'>";
5021 print "<input type=\"checkbox\" onclick=\"tSR(this)\"
5024 print "$marked_pic";
5025 print "$published_pic";
5029 print "<div onclick='return hlClicked(event, $id)'
5030 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5031 print "<a id=\"RTITLE-$id\"
5032 href=\"" . htmlspecialchars($line["link"]) . "\"
5033 onclick=\"return false;\">" .
5036 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5037 if ($content_preview) {
5038 print "<span class=\"contentPreview\"> - $content_preview</span>";
5042 print "</a></span>";
5046 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5047 if (@$line["feed_title"]) {
5048 print "<span class=\"hlFeed\">
5049 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5050 $line["feed_title"]."</a>)
5057 print "<div class=\"hlRight\">";
5058 print "<span class=\"hlUpdated\">$updated_fmt</span>";
5061 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5063 print "<span onclick=\"viewfeed($feed_id)\"
5064 title=\"".htmlspecialchars($line['feed_title'])."\">
5065 $feed_icon_img<span>";
5073 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5074 if ($feed_id != $vgroup_last_feed) {
5076 $cur_feed_title = $line["feed_title"];
5077 $vgroup_last_feed = $feed_id;
5079 $cur_feed_title = htmlspecialchars($cur_feed_title);
5081 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5083 $has_feed_icon = feed_has_icon($feed_id);
5085 if ($has_feed_icon) {
5086 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5088 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5091 print "<div class='cdmFeedTitle'>".
5092 "<div style=\"float : right\">$feed_icon_img</div>".
5093 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5094 $line["feed_title"]."</a> $vf_catchup_link</div>";
5098 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5100 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5101 onmouseout='postMouseOut($id)'";
5103 print "<div class=\"$class\"
5104 id=\"RROW-$id\" $mouseover_attrs'>";
5106 print "<div class=\"cdmHeader\">";
5108 print "<div style='float : right'>";
5109 print "<span class='updated'>$updated_fmt</span>";
5112 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5113 print "<span style=\"cursor : pointer\"
5114 title=\"".htmlspecialchars($line["feed_title"])."\"
5115 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5117 print "<div class=\"updPic\">$update_pic</div>";
5121 print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5122 'RROW-$id')\" id=\"RCHK-$id\"/>";
5124 print "$marked_pic";
5125 print "$published_pic";
5127 print "<span id=\"RTITLE-$id\"
5128 onclick=\"return cdmClicked(event, $id);\"
5129 class=\"titleWrap$hlc_suffix\">
5131 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5137 $content_hidden = "style=\"display : none\"";
5139 $excerpt_hidden = "style=\"display : none\"";
5141 print "<span $excerpt_hidden
5142 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5148 print "<div class=\"cdmContent\" $content_hidden
5149 onclick=\"return cdmClicked(event, $id);\"
5152 print "<div class=\"cdmContentInner\">";
5154 if ($line["orig_feed_id"]) {
5156 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5157 WHERE id = ".$line["orig_feed_id"]);
5159 if (db_num_rows($tmp_result) != 0) {
5161 print "<div clear='both'>";
5162 print __("Originally from:");
5166 $tmp_line = db_fetch_assoc($tmp_result);
5168 print "<a target='_blank'
5169 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5170 $tmp_line['title'] . "</a>";
5174 print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5175 print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5181 // FIXME: make this less of a hack
5183 $feed_site_url = false;
5185 if ($line["feed_id"]) {
5186 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5187 WHERE id = " . $line["feed_id"]);
5189 if (db_num_rows($tmp_result) == 1) {
5190 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5195 $article_content = sanitize_rss($link, $line["content_preview"],
5196 false, false, $feed_site_url);
5198 if (!$article_content) $article_content = " ";
5200 $article_content = '';
5203 print "<div id=\"POSTNOTE-$id\">";
5204 if ($line['note']) {
5205 print format_article_note($id, $line['note']);
5209 print "<span id=\"CWRAP-$id\">$article_content</span>";
5211 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5212 ttrss_feeds WHERE id = ".
5213 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5214 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5216 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5217 0, "always_display_enclosures"));
5219 print_article_enclosures($link, $id, $always_display_enclosures,
5224 print "<div class=\"cdmFooter\">";
5226 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5228 print "<img src='".theme_image($link,
5229 'images/tag.png')."' alt='Tags' title='Tags'>
5230 <span id=\"ATSTR-$id\">$tags_str</span>
5231 <a title=\"".__('Edit tags for this article')."\"
5232 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5234 print "<div style=\"float : right\">";
5236 print "<img src=\"images/art-zoom.png\"
5237 onclick=\"zoomToArticle($id)\"
5238 style=\"cursor : pointer\"
5240 title='".__('Open article in new tab')."'>";
5242 if (DIGEST_ENABLE
) {
5243 print "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5244 style=\"cursor : pointer\"
5245 onclick=\"emailArticle($id)\"
5246 alt='Zoom' title='".__('Forward by email')."'>";
5249 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES
);
5251 print "<img src=\"images/art-pub-note.png\"
5252 style=\"cursor : pointer\" style=\"cursor : pointer\"
5253 onclick=\"publishWithNote($id, '$note_escaped')\"
5254 alt='PubNote' title='".__('Publish article with a note')."'>";
5256 print "<img src=\"images/digest_checkbox.png\"
5257 style=\"cursor : pointer\" style=\"cursor : pointer\"
5258 onclick=\"dismissArticle($id)\"
5259 alt='Dismiss' title='".__('Dismiss article')."'>";
5276 switch ($view_mode) {
5278 $message = __("No unread articles found to display.");
5281 $message = __("No updated articles found to display.");
5284 $message = __("No starred articles found to display.");
5288 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5290 $message = __("No articles found to display.");
5294 if (!$offset && $message) {
5295 print "<div class='whiteBox'>$message";
5297 print "<p class=\"small\"><span class=\"insensitive\">";
5299 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5300 WHERE owner_uid = " . $_SESSION['uid']);
5302 $last_updated = db_fetch_result($result, 0, "last_updated");
5303 $last_updated = make_local_datetime($link, $last_updated, false);
5305 printf(__("Feeds last updated at %s"), $last_updated);
5307 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5308 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5310 $num_errors = db_fetch_result($result, 0, "num_errors");
5312 if ($num_errors > 0) {
5314 print "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5315 __('Some feeds have update errors (click for details)')."</a>";
5317 print "</span></p></div>";
5322 # if ($headlines_count > 0) print "</div>";
5326 print "]]></content>";
5328 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5331 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5333 function printTagCloud($link) {
5335 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5336 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5337 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5339 $result = db_query($link, $query);
5343 while ($line = db_fetch_assoc($result)) {
5344 $tags[$line["tag_name"]] = $line["count"];
5349 $max_size = 32; // max font size in pixels
5350 $min_size = 11; // min font size in pixels
5352 // largest and smallest array values
5353 $max_qty = max(array_values($tags));
5354 $min_qty = min(array_values($tags));
5356 // find the range of values
5357 $spread = $max_qty - $min_qty;
5358 if ($spread == 0) { // we don't want to divide by zero
5362 // set the font-size increment
5363 $step = ($max_size - $min_size) / ($spread);
5365 // loop through the tag array
5366 foreach ($tags as $key => $value) {
5367 // calculate font-size
5368 // find the $value in excess of $min_qty
5369 // multiply by the font-size increment ($size)
5370 // and add the $min_size set above
5371 $size = round($min_size +
(($value - $min_qty) * $step));
5373 $key_escaped = str_replace("'", "\\'", $key);
5375 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5376 $size . "px\" title=\"$value articles tagged with " .
5377 $key . '">' . $key . '</a> ';
5381 function print_checkpoint($n, $s) {
5382 $ts = getmicrotime();
5383 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5387 function sanitize_tag($tag) {
5390 $tag = mb_strtolower($tag, 'utf-8');
5392 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5394 // $tag = str_replace('"', "", $tag);
5395 // $tag = str_replace("+", " ", $tag);
5396 $tag = str_replace("technorati tag: ", "", $tag);
5401 function get_self_url_prefix() {
5405 if ($_SERVER['HTTPS'] != "on") {
5406 $url_path = "http://";
5408 $url_path = "https://";
5411 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5416 function opml_publish_url($link){
5418 $url_path = get_self_url_prefix();
5419 $url_path .= "/opml.php?op=publish&key=" .
5420 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5426 * Purge a feed contents, marked articles excepted.
5428 * @param mixed $link The database connection.
5429 * @param integer $id The id of the feed to purge.
5432 function clear_feed_articles($link, $id) {
5435 $result = db_query($link, "DELETE FROM ttrss_user_entries
5436 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5438 $result = db_query($link, "DELETE FROM ttrss_user_entries
5439 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5442 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5443 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5445 ccache_update($link, $id, $_SESSION['uid']);
5446 } // function clear_feed_articles
5449 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5451 * @return string The Mozilla Firefox feed adding URL.
5453 function add_feed_url() {
5454 $url_path = ($_SERVER['HTTPS'] != "on" ?
'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5455 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5457 } // function add_feed_url
5460 * Encrypt a password in SHA1.
5462 * @param string $pass The password to encrypt.
5463 * @param string $login A optionnal login.
5464 * @return string The encrypted password.
5466 function encrypt_password($pass, $login = '') {
5468 return "SHA1X:" . sha1("$login:$pass");
5470 return "SHA1:" . sha1($pass);
5472 } // function encrypt_password
5475 * Update a feed batch.
5476 * Used by daemons to update n feeds by run.
5477 * Only update feed needing a update, and not being processed
5478 * by another process.
5480 * @param mixed $link Database link
5481 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5482 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5483 * @param boolean $debug Set to false to disable debug output. Default to true.
5486 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5487 // Process all other feeds using last_updated and interval parameters
5489 // Test if the user has loggued in recently. If not, it does not update its feeds.
5490 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5491 if (DB_TYPE
== "pgsql") {
5492 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5494 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5497 $login_thresh_qpart = "";
5500 // Test if the feed need a update (update interval exceded).
5501 if (DB_TYPE
== "pgsql") {
5502 $update_limit_qpart = "AND ((
5503 ttrss_feeds.update_interval = 0
5504 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5506 ttrss_feeds.update_interval > 0
5507 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5508 ) OR ttrss_feeds.last_updated IS NULL)";
5510 $update_limit_qpart = "AND ((
5511 ttrss_feeds.update_interval = 0
5512 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5514 ttrss_feeds.update_interval > 0
5515 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5516 ) OR ttrss_feeds.last_updated IS NULL)";
5519 // Test if feed is currently being updated by another process.
5520 if (DB_TYPE
== "pgsql") {
5521 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5523 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5526 // Test if there is a limit to number of updated feeds
5528 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5530 $random_qpart = sql_random_function();
5532 // We search for feed needing update.
5533 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5534 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5535 ttrss_feeds.update_interval
5537 ttrss_feeds, ttrss_users, ttrss_user_prefs
5539 ttrss_feeds.owner_uid = ttrss_users.id
5540 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5541 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5542 $login_thresh_qpart $update_limit_qpart
5543 $updstart_thresh_qpart
5544 ORDER BY $random_qpart $query_limit");
5546 $user_prefs_cache = array();
5548 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5550 // Here is a little cache magic in order to minimize risk of double feed updates.
5551 $feeds_to_update = array();
5552 while ($line = db_fetch_assoc($result)) {
5553 $feeds_to_update[$line['id']] = $line;
5556 // We update the feed last update started date before anything else.
5557 // There is no lag due to feed contents downloads
5558 // It prevent an other process to update the same feed.
5559 $feed_ids = array_keys($feeds_to_update);
5561 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5562 WHERE id IN (%s)", implode(',', $feed_ids)));
5565 // For each feed, we call the feed update function.
5566 while ($line = array_pop($feeds_to_update)) {
5568 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5570 update_rss_feed($link, $line["id"], true);
5572 sleep(1); // prevent flood (FIXME make this an option?)
5575 // Send feed digests by email if needed.
5576 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5578 } // function update_daemon_common
5580 function sanitize_article_content($text) {
5581 # we don't support CDATA sections in articles, they break our own escaping
5582 $text = preg_replace("/\[\[CDATA/", "", $text);
5583 $text = preg_replace("/\]\]\>/", "", $text);
5587 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5592 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5594 if ($memcache && $obj = $memcache->get($obj_id)) {
5600 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5602 $result = db_query($link, "SELECT reg_exp,
5603 ttrss_filter_types.name AS name,
5604 ttrss_filter_actions.name AS action,
5608 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5611 owner_uid = $owner_uid AND
5612 ttrss_filter_types.id = filter_type AND
5613 ttrss_filter_actions.id = action_id AND
5614 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5616 while ($line = db_fetch_assoc($result)) {
5617 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5618 $filter["reg_exp"] = $line["reg_exp"];
5619 $filter["action"] = $line["action"];
5620 $filter["action_param"] = $line["action_param"];
5621 $filter["filter_param"] = $line["filter_param"];
5622 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5624 array_push($filters[$line["name"]], $filter);
5627 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5633 function get_score_pic($score) {
5635 return "score_high.png";
5636 } else if ($score > 0) {
5637 return "score_half_high.png";
5638 } else if ($score < -100) {
5639 return "score_low.png";
5640 } else if ($score < 0) {
5641 return "score_half_low.png";
5643 return "score_neutral.png";
5647 function rounded_table_start($classname, $header = " ") {
5648 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5649 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5650 print "<tr><td class='left'> </td><td class='content'>";
5653 function rounded_table_end($footer = " ") {
5654 print "</td><td class='right'> </td></tr>";
5655 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5659 function feed_has_icon($id) {
5660 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5663 function init_connection($link) {
5664 if (DB_TYPE
== "pgsql") {
5665 pg_query($link, "set client_encoding = 'UTF-8'");
5666 pg_set_client_encoding("UNICODE");
5667 pg_query($link, "set datestyle = 'ISO, european'");
5668 pg_query($link, "set TIME ZONE 0");
5670 db_query($link, "SET time_zone = '+0:0'");
5672 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5673 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5674 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5679 function update_feedbrowser_cache($link) {
5681 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5682 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5683 WHERE tf.feed_url = ttrss_feeds.feed_url
5684 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5685 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5687 db_query($link, "BEGIN");
5689 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5693 while ($line = db_fetch_assoc($result)) {
5694 $subscribers = db_escape_string($line["subscribers"]);
5695 $feed_url = db_escape_string($line["feed_url"]);
5696 $title = db_escape_string($line["title"]);
5698 $tmp_result = db_query($link, "SELECT subscribers FROM
5699 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5701 if (db_num_rows($tmp_result) == 0) {
5703 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5704 (feed_url, title, subscribers) VALUES ('$feed_url',
5705 '$title', '$subscribers')");
5713 db_query($link, "COMMIT");
5719 function ccache_zero($link, $feed_id, $owner_uid) {
5720 db_query($link, "UPDATE ttrss_counters_cache SET
5721 value = 0, updated = NOW() WHERE
5722 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5725 function ccache_zero_all($link, $owner_uid) {
5726 db_query($link, "UPDATE ttrss_counters_cache SET
5727 value = 0 WHERE owner_uid = '$owner_uid'");
5729 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5730 value = 0 WHERE owner_uid = '$owner_uid'");
5733 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5736 $table = "ttrss_counters_cache";
5738 $table = "ttrss_cat_counters_cache";
5741 db_query($link, "DELETE FROM $table WHERE
5742 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5746 function ccache_update_all($link, $owner_uid) {
5748 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5750 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5751 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5753 while ($line = db_fetch_assoc($result)) {
5754 ccache_update($link, $line["feed_id"], $owner_uid, true);
5757 /* We have to manually include category 0 */
5759 ccache_update($link, 0, $owner_uid, true);
5762 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5763 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5765 while ($line = db_fetch_assoc($result)) {
5766 print ccache_update($link, $line["feed_id"], $owner_uid);
5773 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5774 $no_update = false) {
5776 if (!is_numeric($feed_id)) return;
5779 $table = "ttrss_counters_cache";
5781 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5782 WHERE id = '$feed_id'");
5783 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5786 $table = "ttrss_cat_counters_cache";
5789 if (DB_TYPE
== "pgsql") {
5790 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5791 } else if (DB_TYPE
== "mysql") {
5792 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5795 $result = db_query($link, "SELECT value FROM $table
5796 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5799 if (db_num_rows($result) == 1) {
5800 return db_fetch_result($result, 0, "value");
5805 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5811 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5812 $update_pcat = true) {
5814 if (!is_numeric($feed_id)) return;
5816 if (!$is_cat && $feed_id > 0) {
5817 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5818 WHERE id = '$feed_id'");
5819 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5822 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5824 /* When updating a label, all we need to do is recalculate feed counters
5825 * because labels are not cached */
5828 ccache_update_all($link, $owner_uid);
5833 $table = "ttrss_counters_cache";
5835 $table = "ttrss_cat_counters_cache";
5838 if ($is_cat && $feed_id >= 0) {
5839 if ($feed_id != 0) {
5840 $cat_qpart = "cat_id = '$feed_id'";
5842 $cat_qpart = "cat_id IS NULL";
5845 /* Recalculate counters for child feeds */
5847 $result = db_query($link, "SELECT id FROM ttrss_feeds
5848 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5850 while ($line = db_fetch_assoc($result)) {
5851 ccache_update($link, $line["id"], $owner_uid, false, false);
5854 $result = db_query($link, "SELECT SUM(value) AS sv
5855 FROM ttrss_counters_cache, ttrss_feeds
5856 WHERE id = feed_id AND $cat_qpart AND
5857 ttrss_feeds.owner_uid = '$owner_uid'");
5859 $unread = (int) db_fetch_result($result, 0, "sv");
5862 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5865 db_query($link, "BEGIN");
5867 $result = db_query($link, "SELECT feed_id FROM $table
5868 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5870 if (db_num_rows($result) == 1) {
5871 db_query($link, "UPDATE $table SET
5872 value = '$unread', updated = NOW() WHERE
5873 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5876 db_query($link, "INSERT INTO $table
5877 (feed_id, value, owner_uid, updated)
5879 ($feed_id, $unread, $owner_uid, NOW())");
5882 db_query($link, "COMMIT");
5884 if ($feed_id > 0 && $prev_unread != $unread) {
5888 /* Update parent category */
5892 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5893 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5895 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5897 ccache_update($link, $cat_id, $owner_uid, true);
5901 } else if ($feed_id < 0) {
5902 ccache_update_all($link, $owner_uid);
5908 function label_find_id($link, $label, $owner_uid) {
5909 $result = db_query($link,
5910 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5911 AND owner_uid = '$owner_uid' LIMIT 1");
5913 if (db_num_rows($result) == 1) {
5914 return db_fetch_result($result, 0, "id");
5920 function get_article_labels($link, $id) {
5923 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
5927 if ($memcache && $obj = $memcache->get($obj_id)) {
5931 $result = db_query($link, "SELECT label_cache FROM
5932 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
5935 $label_cache = db_fetch_result($result, 0, "label_cache");
5939 $label_cache = json_decode($label_cache, true);
5941 if ($label_cache["no-labels"] == 1)
5944 return $label_cache;
5947 $result = db_query($link,
5948 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5949 FROM ttrss_labels2, ttrss_user_labels2
5951 AND article_id = '$id'
5952 AND owner_uid = ".$_SESSION["uid"] . "
5955 while ($line = db_fetch_assoc($result)) {
5956 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5958 array_push($rv, $rk);
5960 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
5963 label_update_cache($link, $id, $rv);
5965 label_update_cache($link, $id, array("no-labels" => 1));
5972 function label_find_caption($link, $label, $owner_uid) {
5973 $result = db_query($link,
5974 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5975 AND owner_uid = '$owner_uid' LIMIT 1");
5977 if (db_num_rows($result) == 1) {
5978 return db_fetch_result($result, 0, "caption");
5984 function label_update_cache($link, $id, $labels = false, $force = false) {
5987 label_clear_cache($link, $id);
5990 $labels = get_article_labels($link, $id);
5992 $labels = db_escape_string(json_encode($labels));
5994 db_query($link, "UPDATE ttrss_user_entries SET
5995 label_cache = '$labels' WHERE ref_id = '$id'");
5999 function label_clear_cache($link, $id) {
6001 db_query($link, "UPDATE ttrss_user_entries SET
6002 label_cache = '' WHERE ref_id = '$id'");
6006 function label_remove_article($link, $id, $label, $owner_uid) {
6008 $label_id = label_find_id($link, $label, $owner_uid);
6010 if (!$label_id) return;
6012 $result = db_query($link,
6013 "DELETE FROM ttrss_user_labels2
6015 label_id = '$label_id' AND
6016 article_id = '$id'");
6018 label_clear_cache($link, $id);
6021 function label_add_article($link, $id, $label, $owner_uid) {
6026 $obj_id = md5("LABELS:$id:$owner_uid");
6027 $memcache->delete($obj_id);
6030 $label_id = label_find_id($link, $label, $owner_uid);
6032 if (!$label_id) return;
6034 $result = db_query($link,
6036 article_id FROM ttrss_labels2, ttrss_user_labels2
6039 label_id = '$label_id' AND
6040 article_id = '$id' AND owner_uid = '$owner_uid'
6043 if (db_num_rows($result) == 0) {
6044 db_query($link, "INSERT INTO ttrss_user_labels2
6045 (label_id, article_id) VALUES ('$label_id', '$id')");
6048 label_clear_cache($link, $id);
6052 function label_remove($link, $id, $owner_uid) {
6055 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6058 $obj_id = md5("LABELS:$id:$owner_uid");
6059 $memcache->delete($obj_id);
6062 db_query($link, "BEGIN");
6064 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6067 $caption = db_fetch_result($result, 0, "caption");
6069 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6070 AND owner_uid = " . $owner_uid);
6072 if (db_affected_rows($link, $result) != 0 && $caption) {
6074 /* Remove access key for the label */
6076 $ext_id = -11 - $id;
6078 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6079 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6081 /* Disable filters that reference label being removed */
6083 db_query($link, "UPDATE ttrss_filters SET
6084 enabled = false WHERE action_param = '$caption'
6086 AND owner_uid = " . $owner_uid);
6088 /* Remove cached data */
6090 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6091 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6095 db_query($link, "COMMIT");
6098 function label_create($link, $caption) {
6100 db_query($link, "BEGIN");
6104 $result = db_query($link, "SELECT id FROM ttrss_labels2
6105 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6107 if (db_num_rows($result) == 0) {
6108 $result = db_query($link,
6109 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6110 VALUES ('$caption', '".$_SESSION["uid"]."')");
6112 $result = db_affected_rows($link, $result) != 0;
6115 db_query($link, "COMMIT");
6120 function print_labels_headlines_dropdown($link, $feed_id) {
6121 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6123 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6124 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6126 while ($line = db_fetch_assoc($result)) {
6128 $label_id = $line["id"];
6129 $label_caption = $line["caption"];
6132 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6133 print "<option id=\"LHDL-$id\"
6134 value=\"selectionRemoveLabel($label_id)\">".
6135 __('Remove:') . " $label_caption</option>";
6137 print "<option id=\"LHDL-$id\"
6138 value=\"selectionAssignLabel($label_id)\">".
6139 __('Assign:') . " $label_caption</option>";
6144 function format_tags_string($tags, $id) {
6147 $tags_nolinks_str = "";
6151 /* if (get_user_theme($link) == "3pane") {
6159 $formatted_tags = array();
6161 foreach ($tags as $tag) {
6163 $tag_escaped = str_replace("'", "\\'", $tag);
6165 if (mb_strlen($tag) > 30) {
6166 $tag = truncate_string($tag, 30);
6169 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6171 array_push($formatted_tags, $tag_str);
6173 $tmp_tags_str = implode(", ", $formatted_tags);
6175 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6180 $tags_str = implode(", ", $formatted_tags);
6182 if ($num_tags < count($tags)) {
6183 $tags_str .= ", …";
6186 if ($num_tags == 0) {
6187 $tags_str = __("no tags");
6194 function format_article_labels($labels, $id) {
6198 foreach ($labels as $l) {
6199 $labels_str .= sprintf("<span class='hlLabelRef'
6200 style='color : %s; background-color : %s'>%s</span>",
6201 $l[2], $l[3], $l[1]);
6208 function format_article_note($id, $note) {
6210 $note_escaped = htmlspecialchars($note, ENT_QUOTES
);
6212 $str = "<div class='articleNote'>";
6214 $str .= "<div class='articleNoteOps'>";
6215 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6216 __('edit note')."</a>";
6223 function toggle_collapse_cat($link, $cat_id, $mode) {
6225 $mode = bool_to_sql_bool($mode);
6227 db_query($link, "UPDATE ttrss_feed_categories SET
6228 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6235 $pref_name = '_COLLAPSED_SPECIAL';
6238 $pref_name = '_COLLAPSED_LABELS';
6241 $pref_name = '_COLLAPSED_UNCAT';
6247 set_pref($link, $pref_name, 'true');
6249 set_pref($link, $pref_name, 'false');
6255 function remove_feed($link, $id, $owner_uid) {
6259 /* save starred articles in Archived feed */
6261 db_query($link, "BEGIN");
6263 /* prepare feed if necessary */
6265 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6268 if (db_num_rows($result) == 0) {
6269 db_query($link, "INSERT INTO ttrss_archived_feeds
6270 (id, owner_uid, title, feed_url, site_url)
6271 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6275 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6276 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6277 marked = true AND owner_uid = $owner_uid");
6279 /* Remove access key for the feed */
6281 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6282 feed_id = '$id' AND owner_uid = $owner_uid");
6284 /* remove the feed */
6286 db_query($link, "DELETE FROM ttrss_feeds
6287 WHERE id = '$id' AND owner_uid = $owner_uid");
6289 db_query($link, "COMMIT");
6291 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6292 unlink(ICONS_DIR . "/$id.ico");
6295 ccache_remove($link, $id, $owner_uid);
6298 label_remove($link, -11-$id, $owner_uid);
6299 ccache_remove($link, -11-$id, $owner_uid);
6303 function add_feed_category($link, $feed_cat) {
6305 if (!$feed_cat) return false;
6307 db_query($link, "BEGIN");
6309 $result = db_query($link,
6310 "SELECT id FROM ttrss_feed_categories
6311 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6313 if (db_num_rows($result) == 0) {
6315 $result = db_query($link,
6316 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6317 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6319 db_query($link, "COMMIT");
6327 function remove_feed_category($link, $id, $owner_uid) {
6329 db_query($link, "DELETE FROM ttrss_feed_categories
6330 WHERE id = '$id' AND owner_uid = $owner_uid");
6332 ccache_remove($link, $id, $owner_uid, true);
6335 function archive_article($link, $id, $owner_uid) {
6336 db_query($link, "BEGIN");
6338 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6339 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6341 if (db_num_rows($result) != 0) {
6343 /* prepare the archived table */
6345 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6348 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6349 WHERE id = '$feed_id'");
6351 if (db_num_rows($result) == 0) {
6352 db_query($link, "INSERT INTO ttrss_archived_feeds
6353 (id, owner_uid, title, feed_url, site_url)
6354 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6355 WHERE id = '$feed_id'");
6358 db_query($link, "UPDATE ttrss_user_entries
6359 SET orig_feed_id = feed_id, feed_id = NULL
6360 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6364 db_query($link, "COMMIT");
6367 function getArticleFeed($link, $id) {
6368 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6369 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6371 if (db_num_rows($result) != 0) {
6372 return db_fetch_result($result, 0, "feed_id");
6378 function make_url_from_parts($parts) {
6379 $url = $parts['scheme'] . '://' . $parts['host'];
6381 if ($parts['path']) $url .= $parts['path'];
6382 if ($parts['query']) $url .= '?' . $parts['query'];
6388 * Fixes incomplete URLs by prepending "http://".
6389 * Also replaces feed:// with http://, and
6390 * prepends a trailing slash if the url is a domain name only.
6392 * @param string $url Possibly incomplete URL
6394 * @return string Fixed URL.
6396 function fix_url($url) {
6397 if (strpos($url, '://') === false) {
6398 $url = 'http://' . $url;
6399 } else if (substr($url, 0, 5) == 'feed:') {
6400 $url = 'http:' . substr($url, 5);
6403 //prepend slash if the URL has no slash in it
6404 // "http://www.example" -> "http://www.example/"
6405 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6411 function validate_feed_url($url) {
6412 $parts = parse_url($url);
6414 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6418 function get_article_enclosures($link, $id) {
6422 $query = "SELECT * FROM ttrss_enclosures
6423 WHERE post_id = '$id' AND content_url != ''";
6425 $obj_id = md5("ENCLOSURES:$id");
6429 if ($memcache && $obj = $memcache->get($obj_id)) {
6432 $result = db_query($link, $query);
6434 if (db_num_rows($result) > 0) {
6435 while ($line = db_fetch_assoc($result)) {
6436 array_push($rv, $line);
6438 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6445 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6451 if ($cat_id == -4 ||
$cat_id == -2) {
6452 $counters = getLabelCounters($link, true);
6454 foreach (array_values($counters) as $cv) {
6456 $unread = $cv["counter"];
6458 if ($unread ||
!$unread_only) {
6462 "title" => $cv["description"],
6463 "unread" => $cv["counter"],
6467 array_push($feeds, $row);
6474 if ($cat_id == -4 ||
$cat_id == -1) {
6475 foreach (array(-1, -2, -3, -4, 0) as $i) {
6476 $unread = getFeedUnread($link, $i);
6478 if ($unread ||
!$unread_only) {
6479 $title = getFeedTitle($link, $i);
6484 "unread" => $unread,
6487 array_push($feeds, $row);
6496 $limit_qpart = "LIMIT $limit OFFSET $offset";
6501 if ($cat_id == -4 ||
$cat_id == -3) {
6502 $result = db_query($link, "SELECT
6503 id, feed_url, cat_id, title, ".
6504 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6505 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6506 " ORDER BY cat_id, title " . $limit_qpart);
6510 $cat_qpart = "cat_id = '$cat_id'";
6512 $cat_qpart = "cat_id IS NULL";
6514 $result = db_query($link, "SELECT
6515 id, feed_url, cat_id, title, ".
6516 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6517 FROM ttrss_feeds WHERE
6518 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6519 " ORDER BY cat_id, title " . $limit_qpart);
6522 while ($line = db_fetch_assoc($result)) {
6524 $unread = getFeedUnread($link, $line["id"]);
6526 $has_icon = feed_has_icon($line['id']);
6528 if ($unread ||
!$unread_only) {
6531 "feed_url" => $line["feed_url"],
6532 "title" => $line["title"],
6533 "id" => (int)$line["id"],
6534 "unread" => (int)$unread,
6535 "has_icon" => $has_icon,
6536 "cat_id" => (int)$line["cat_id"],
6537 "last_updated" => strtotime($line["last_updated"])
6540 array_push($feeds, $row);
6547 function api_get_headlines($link, $feed_id, $limit, $offset,
6548 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6550 /* do not rely on params below */
6552 $search = db_escape_string($_REQUEST["search"]);
6553 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6554 $match_on = db_escape_string($_REQUEST["match_on"]);
6556 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6557 $view_mode, $is_cat, $search, $search_mode, $match_on,
6560 $result = $qfh_ret[0];
6561 $feed_title = $qfh_ret[1];
6563 $headlines = array();
6565 while ($line = db_fetch_assoc($result)) {
6566 $is_updated = ($line["last_read"] == "" &&
6567 ($line["unread"] != "t" && $line["unread"] != "1"));
6569 $headline_row = array(
6570 "id" => (int)$line["id"],
6571 "unread" => sql_bool_to_bool($line["unread"]),
6572 "marked" => sql_bool_to_bool($line["marked"]),
6573 "published" => sql_bool_to_bool($line["published"]),
6574 "updated" => strtotime($line["updated"]),
6575 "is_updated" => $is_updated,
6576 "title" => $line["title"],
6577 "link" => $line["link"],
6578 "feed_id" => $line["feed_id"],
6579 "tags" => get_article_tags($link, $line["id"]),
6582 if ($show_excerpt) {
6583 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6584 $headline_row["excerpt"] = $excerpt;
6587 if ($show_content) {
6588 $headline_row["content"] = $line["content_preview"];
6591 array_push($headlines, $headline_row);
6597 function generate_dashboard_feed($link) {
6598 print "<headlines id=\"-5\" is_cat=\"\">";
6600 print "<toolbar><![CDATA[]]></toolbar>";
6602 print '<content><![CDATA[';
6604 print "<div class='whiteBox'>".__('No feed selected.');
6606 print "<p class=\"small\"><span class=\"insensitive\">";
6608 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6609 WHERE owner_uid = " . $_SESSION['uid']);
6611 $last_updated = db_fetch_result($result, 0, "last_updated");
6612 $last_updated = make_local_datetime($link, $last_updated, false);
6614 printf(__("Feeds last updated at %s"), $last_updated);
6616 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6617 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6619 $num_errors = db_fetch_result($result, 0, "num_errors");
6621 if ($num_errors > 0) {
6623 print "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6624 __('Some feeds have update errors (click for details)')."</a>";
6626 print "</span></p>";
6628 print "]]></content>";
6629 print "</headlines>";
6631 print "<headlines-info><![CDATA[";
6633 $info = array("count" => 0,
6634 "vgroup_last_feed" => '',
6636 "disable_cache" => true);
6638 print json_encode($info);
6640 print "]]></headlines-info>";
6644 function save_email_address($link, $email) {
6645 // FIXME: implement persistent storage of emails
6647 if (!$_SESSION['stored_emails'])
6648 $_SESSION['stored_emails'] = array();
6650 if (!in_array($email, $_SESSION['stored_emails']))
6651 array_push($_SESSION['stored_emails'], $email);
6654 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6655 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6657 $sql_is_cat = bool_to_sql_bool($is_cat);
6659 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6660 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6661 AND owner_uid = " . $owner_uid);
6663 if (db_num_rows($result) == 1) {
6664 $key = db_escape_string(sha1(uniqid(rand(), true)));
6666 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6667 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6668 AND owner_uid = " . $owner_uid);
6673 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6677 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6679 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6681 $sql_is_cat = bool_to_sql_bool($is_cat);
6683 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6684 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6685 AND owner_uid = " . $owner_uid);
6687 if (db_num_rows($result) == 1) {
6688 return db_fetch_result($result, 0, "access_key");
6690 $key = db_escape_string(sha1(uniqid(rand(), true)));
6692 $result = db_query($link, "INSERT INTO ttrss_access_keys
6693 (access_key, feed_id, is_cat, owner_uid)
6694 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6702 * Extracts RSS/Atom feed URLs from the given HTML URL.
6704 * @param string $url HTML page URL
6706 * @return array Array of feeds. Key is the full URL, value the title
6708 function get_feeds_from_html($url)
6710 $url = fix_url($url);
6711 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6713 libxml_use_internal_errors(true);
6715 $doc = new DOMDocument();
6716 $doc->loadHTMLFile($url);
6717 $xpath = new DOMXPath($doc);
6718 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6719 $feedUrls = array();
6720 foreach ($entries as $entry) {
6721 if ($entry->hasAttribute('href')) {
6722 $title = $entry->getAttribute('title');
6724 $title = $entry->getAttribute('type');
6726 $feedUrl = rewrite_relative_url(
6727 $baseUrl, $entry->getAttribute('href')
6729 $feedUrls[$feedUrl] = $title;
6736 * Checks if the content behind the given URL is a HTML file
6738 * @param string $url URL to check
6740 * @return boolean True if the URL contains HTML content
6742 function url_is_html($url) {
6743 $content = substr(fetch_file_contents($url, false), 0, 1000);
6744 if (stripos($content, '<html>') === false
6745 && stripos($content, '<html ') === false
6753 function print_label_select($link, $name, $value, $style = "") {
6755 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6756 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6758 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6759 "\" style=\"$style\" onchange=\"labelSelectOnChange(this)\" >";
6761 while ($line = db_fetch_assoc($result)) {
6763 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6765 print "<option $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6769 print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6776 function print_article_enclosures($link, $id, $always_display_enclosures,
6779 $result = get_article_enclosures($link, $id);
6781 if (count($result) > 0) {
6783 $entries_html = array();
6786 foreach ($result as $line) {
6788 $url = $line["content_url"];
6789 $ctype = $line["content_type"];
6791 if (!$ctype) $ctype = __("unknown type");
6793 $filename = substr($url, strrpos($url, "/")+
1);
6795 $entry = format_inline_player($link, $url, $ctype);
6797 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6798 $filename . " (" . $ctype . ")" . "</a>";
6800 array_push($entries_html, $entry);
6804 $entry["type"] = $ctype;
6805 $entry["filename"] = $filename;
6806 $entry["url"] = $url;
6808 array_push($entries, $entry);
6811 print "<div class=\"postEnclosures\">";
6813 if (!get_pref($link, "STRIP_IMAGES")) {
6814 if ($always_display_enclosures ||
6815 !preg_match("/<img/i", $article_content)) {
6817 foreach ($entries as $entry) {
6819 if (preg_match("/image/", $entry["type"]) ||
6820 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6823 alt=\"".htmlspecialchars($entry["filename"])."\"
6824 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6830 if (count($entries) == 1) {
6831 print __("Attachment:") . " ";
6833 print __("Attachments:") . " ";
6836 print join(", ", $entries_html);
6842 function getLastArticleId($link) {
6843 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
6844 WHERE owner_uid = " . $_SESSION["uid"]);
6846 if (db_num_rows($result) == 1) {
6847 return db_fetch_result($result, 0, "id");
6853 function build_url($parts) {
6854 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
6858 * Converts a (possibly) relative URL to a absolute one.
6860 * @param string $url Base URL (i.e. from where the document is)
6861 * @param string $rel_url Possibly relative URL in the document
6863 * @return string Absolute URL
6865 function rewrite_relative_url($url, $rel_url) {
6866 if (strpos($rel_url, "://") !== false) {
6868 } else if (strpos($rel_url, "/") === 0)
6870 $parts = parse_url($url);
6871 $parts['path'] = $rel_url;
6873 return build_url($parts);
6876 $parts = parse_url($url);
6877 if (!isset($parts['path'])) {
6878 $parts['path'] = '/';
6880 $dir = $parts['path'];
6881 if (substr($dir, -1) !== '/') {
6882 $dir = dirname($parts['path']);
6883 $dir !== '/' && $dir .= '/';
6885 $parts['path'] = $dir . $rel_url;
6887 return build_url($parts);
6891 function sphinx_search($query, $offset = 0, $limit = 30) {
6892 $sphinxClient = new SphinxClient();
6894 $sphinxClient->SetServer('localhost', 9312);
6895 $sphinxClient->SetConnectTimeout(1);
6897 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
6898 'feed_title' => 20));
6900 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
6901 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
6902 $sphinxClient->SetLimits($offset, $limit, 1000);
6903 $sphinxClient->SetArrayResult(false);
6904 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
6906 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
6910 if (is_array($result['matches'])) {
6911 foreach (array_keys($result['matches']) as $int_id) {
6912 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
6913 array_push($ids, $ref_id);
6920 function cleanup_tags($link, $days = 14, $limit = 1000) {
6922 if (DB_TYPE
== "pgsql") {
6923 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
6924 } else if (DB_TYPE
== "mysql") {
6925 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
6930 while ($limit > 0) {
6933 $query = "SELECT ttrss_tags.id AS id
6934 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
6935 WHERE post_int_id = int_id AND $interval_query AND
6936 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
6938 $result = db_query($link, $query);
6942 while ($line = db_fetch_assoc($result)) {
6943 array_push($ids, $line['id']);
6946 if (count($ids) > 0) {
6947 $ids = join(",", $ids);
6950 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
6951 $tags_deleted +
= db_affected_rows($link, $tmp_result);
6956 $limit -= $limit_part;
6961 return $tags_deleted;
6964 function feedlist_init_cat($link, $cat_id, $hidden = false) {
6966 $cat_id = (int) $cat_id;
6969 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
6970 } else if ($cat_id == 0 ||
$cat_id == -2) {
6971 $cat_unread = getCategoryUnread($link, $cat_id);
6974 $obj['id'] = 'CAT:' . ((int)$cat_id);
6975 $obj['items'] = array();
6976 $obj['name'] = getCategoryTitle($link, $cat_id);
6977 $obj['type'] = 'feed';
6978 $obj['unread'] = (int) $cat_unread;
6979 $obj['hidden'] = $hidden;
6984 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
6988 $title = getFeedTitle($link, $feed_id, false);
6991 $unread = getFeedUnread($link, $feed_id, false);
6993 $obj['id'] = 'FEED:' . $feed_id;
6994 $obj['name'] = $title;
6995 $obj['unread'] = (int) $unread;
6996 $obj['type'] = 'feed';
6997 $obj['error'] = $error;
6998 $obj['updated'] = $updated;
6999 $obj['icon'] = getFeedIcon($feed_id);