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 require_once "lib/accept-to-gettext.php";
46 require_once "lib/gettext/gettext.inc";
48 function startup_gettext() {
50 # Get locale from Accept-Language header
51 $lang = al2gt(array_keys(get_translations()), "text/html");
53 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
54 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
57 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
58 $lang = $_COOKIE["ttrss_lang"];
61 /* In login action of mobile version */
62 if ($_POST["language"] && defined('MOBILE_VERSION')) {
63 $lang = $_POST["language"];
64 $_COOKIE["ttrss_lang"] = $lang;
68 if (defined('LC_MESSAGES')) {
69 _setlocale(LC_MESSAGES
, $lang);
70 } else if (defined('LC_ALL')) {
71 _setlocale(LC_ALL
, $lang);
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
77 _bindtextdomain("messages", "locale");
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
87 if (defined('MEMCACHE_SERVER')) {
88 $memcache = new Memcache
;
89 $memcache->connect(MEMCACHE_SERVER
, 11211);
92 require_once 'db-prefs.php';
93 require_once 'errors.php';
94 require_once 'version.php';
96 require_once 'lib/phpmailer/class.phpmailer.php';
97 require_once 'lib/sphinxapi.php';
98 require_once 'lib/tmhoauth/tmhOAuth.php';
100 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
101 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
104 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
106 ini_set('user_agent', SELF_USER_AGENT
);
108 require_once "lib/simplepie/simplepie.inc";
109 require_once "lib/magpierss/rss_fetch.inc";
110 require_once 'lib/magpierss/rss_utils.inc';
111 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
112 require_once 'lib/pubsubhubbub/publisher.php';
113 require_once 'lib/pubsubhubbub/subscriber.php';
115 $config = HTMLPurifier_Config
::createDefault();
117 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
119 $config->set('HTML.SafeObject', true);
120 @$config->set('HTML', 'Allowed', $allowed);
121 $config->set('Output.FlashCompat', true);
122 $config->set('Attr.EnableID', true);
123 if (!defined('MOBILE_VERSION')) {
124 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
126 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
129 $purifier = new HTMLPurifier($config);
132 $utc_tz = new DateTimeZone('UTC');
133 $schema_version = false;
136 * Print a timestamped debug message.
138 * @param string $msg The debug message.
141 function _debug($msg) {
142 $ts = strftime("%H:%M:%S", time());
143 if (function_exists('posix_getpid')) {
144 $ts = "$ts/" . posix_getpid();
146 print "[$ts] $msg\n";
150 * Purge a feed old posts.
152 * @param mixed $link A database connection.
153 * @param mixed $feed_id The id of the purged feed.
154 * @param mixed $purge_interval Olderness of purged posts.
155 * @param boolean $debug Set to True to enable the debug. False by default.
159 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
161 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
165 $result = db_query($link,
166 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
170 if (db_num_rows($result) == 1) {
171 $owner_uid = db_fetch_result($result, 0, "owner_uid");
174 if ($purge_interval == -1 ||
!$purge_interval) {
176 ccache_update($link, $feed_id, $owner_uid);
181 if (!$owner_uid) return;
183 if (FORCE_ARTICLE_PURGE
== 0) {
184 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
187 $purge_unread = true;
188 $purge_interval = FORCE_ARTICLE_PURGE
;
191 if (!$purge_unread) $query_limit = " unread = false AND ";
193 if (DB_TYPE
== "pgsql") {
194 $pg_version = get_pgsql_version($link);
196 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
198 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
199 ttrss_entries.id = ref_id AND
201 feed_id = '$feed_id' AND
203 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
207 $result = db_query($link, "DELETE FROM ttrss_user_entries
209 WHERE ttrss_entries.id = ref_id AND
211 feed_id = '$feed_id' AND
213 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
216 $rows = pg_affected_rows($result);
220 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
221 marked = false AND feed_id = '$feed_id' AND
222 (SELECT date_updated FROM ttrss_entries WHERE
223 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
225 $result = db_query($link, "DELETE FROM ttrss_user_entries
226 USING ttrss_user_entries, ttrss_entries
227 WHERE ttrss_entries.id = ref_id AND
229 feed_id = '$feed_id' AND
231 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
233 $rows = mysql_affected_rows($link);
237 ccache_update($link, $feed_id, $owner_uid);
240 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
242 } // function purge_feed
244 function feed_purge_interval($link, $feed_id) {
246 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
247 WHERE id = '$feed_id'");
249 if (db_num_rows($result) == 1) {
250 $purge_interval = db_fetch_result($result, 0, "purge_interval");
251 $owner_uid = db_fetch_result($result, 0, "owner_uid");
253 if ($purge_interval == 0) $purge_interval = get_pref($link,
254 'PURGE_OLD_DAYS', $owner_uid);
256 return $purge_interval;
263 function purge_orphans($link, $do_output = false) {
265 // purge orphaned posts in main content table
266 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
267 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
270 $rows = db_affected_rows($link, $result);
271 _debug("Purged $rows orphaned posts.");
275 function get_feed_update_interval($link, $feed_id) {
276 $result = db_query($link, "SELECT owner_uid, update_interval FROM
277 ttrss_feeds WHERE id = '$feed_id'");
279 if (db_num_rows($result) == 1) {
280 $update_interval = db_fetch_result($result, 0, "update_interval");
281 $owner_uid = db_fetch_result($result, 0, "owner_uid");
283 if ($update_interval != 0) {
284 return $update_interval;
286 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
294 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
295 $login = urlencode($login);
296 $pass = urlencode($pass);
298 if (function_exists('curl_init') && !ini_get("open_basedir")) {
299 $ch = curl_init($url);
301 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
302 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
303 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
304 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
305 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
306 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
307 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
308 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
309 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
310 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
313 curl_setopt($ch, CURLOPT_POST
, true);
314 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
318 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
320 $contents = @curl_exec
($ch);
322 if ($contents === false) {
327 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
328 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
331 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
337 if ($login && $pass ){
338 $url_parts = array();
340 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
342 if ($url_parts[1] && $url_parts[2]) {
343 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
347 return @file_get_contents
($url);
353 * Try to determine the favicon URL for a feed.
354 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
355 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
357 * @param string $url A feed or page URL
359 * @return mixed The favicon URL, or false if none was found.
361 function get_favicon_url($url) {
363 $favicon_url = false;
365 if ($html = @fetch_file_contents
($url)) {
367 libxml_use_internal_errors(true);
369 $doc = new DOMDocument();
370 $doc->loadHTML($html);
371 $xpath = new DOMXPath($doc);
373 $base = $xpath->query('/html/head/base');
374 foreach ($base as $b) {
375 $url = $b->getAttribute("href");
379 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
380 if (count($entries) > 0) {
381 foreach ($entries as $entry) {
382 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
389 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
392 } // function get_favicon_url
394 function check_feed_favicon($site_url, $feed, $link) {
395 # print "FAVICON [$site_url]: $favicon_url\n";
397 $icon_file = ICONS_DIR
. "/$feed.ico";
399 if (!file_exists($icon_file)) {
400 $favicon_url = get_favicon_url($site_url);
403 $contents = fetch_file_contents($favicon_url, "image");
406 $fp = @fopen
($icon_file, "w");
409 fwrite($fp, $contents);
411 chmod($icon_file, 0644);
418 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
422 /* Update all feeds with the same URL to utilize memcache */
425 $result = db_query($link, "SELECT f1.id
426 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
427 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
429 while ($line = db_fetch_assoc($result)) {
430 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
433 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
437 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
438 $override_url = false) {
442 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
444 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
448 if ($debug_enabled) {
449 _debug("update_rss_feed: start");
452 if (!$ignore_daemon) {
454 if (DB_TYPE
== "pgsql") {
455 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
457 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
460 $result = db_query($link, "SELECT id,update_interval,auth_login,
461 auth_pass,cache_images,update_method
462 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
466 $result = db_query($link, "SELECT id,update_interval,auth_login,
467 feed_url,auth_pass,cache_images,update_method,last_updated,
468 mark_unread_on_update, owner_uid, update_on_checksum_change,
470 FROM ttrss_feeds WHERE id = '$feed'");
474 if (db_num_rows($result) == 0) {
475 if ($debug_enabled) {
476 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
481 $update_method = db_fetch_result($result, 0, "update_method");
482 $last_updated = db_fetch_result($result, 0, "last_updated");
483 $owner_uid = db_fetch_result($result, 0, "owner_uid");
484 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
485 0, "mark_unread_on_update"));
486 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
487 0, "update_on_checksum_change"));
488 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
490 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
491 WHERE id = '$feed'");
493 $auth_login = db_fetch_result($result, 0, "auth_login");
494 $auth_pass = db_fetch_result($result, 0, "auth_pass");
496 if ($update_method == 0)
497 $update_method = DEFAULT_UPDATE_METHOD +
1;
503 if ($update_method == 2)
504 $use_simplepie = true;
506 $use_simplepie = false;
508 if ($debug_enabled) {
509 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
512 if ($update_method == 1) {
513 $auth_login = urlencode($auth_login);
514 $auth_pass = urlencode($auth_pass);
517 $update_interval = db_fetch_result($result, 0, "update_interval");
518 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
519 $fetch_url = db_fetch_result($result, 0, "feed_url");
521 if ($update_interval < 0) { return false; }
523 $feed = db_escape_string($feed);
525 if ($auth_login && $auth_pass ){
526 $url_parts = array();
527 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
529 if ($url_parts[1] && $url_parts[2]) {
530 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
536 $fetch_url = $override_url;
538 if ($debug_enabled) {
539 _debug("update_rss_feed: fetching [$fetch_url]...");
542 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
544 if ($memcache && $obj = $memcache->get($obj_id)) {
546 if ($debug_enabled) {
547 _debug("update_rss_feed: data found in memcache.");
554 if ($update_method == 3) {
555 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
556 } else if ($update_method == 1) {
558 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
559 define('MAGPIE_CACHE_ON', !$no_cache);
560 define('MAGPIE_FETCH_TIME_OUT', 60);
561 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
563 $rss = @fetch_rss
($fetch_url);
565 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
567 if (!is_dir($simplepie_cache_dir)) {
568 mkdir($simplepie_cache_dir);
571 $rss = new SimplePie();
572 $rss->set_useragent(SELF_USER_AGENT
);
573 # $rss->set_timeout(10);
574 $rss->set_feed_url($fetch_url);
575 $rss->set_output_encoding('UTF-8');
576 $rss->force_feed(true);
578 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
580 if ($debug_enabled) {
581 _debug("enabling image cache");
584 $rss->set_image_handler("image.php", 'i');
587 if ($debug_enabled) {
588 _debug("feed update interval (sec): " .
589 get_feed_update_interval($link, $feed)*60);
592 $rss->enable_cache(!$no_cache);
595 $rss->set_cache_location($simplepie_cache_dir);
596 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
602 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
607 if ($debug_enabled) {
608 _debug("update_rss_feed: fetch done, parsing...");
611 $feed = db_escape_string($feed);
613 if ($update_method == 2) {
614 $fetch_ok = !$rss->error();
621 if ($debug_enabled) {
622 _debug("update_rss_feed: processing feed data...");
625 // db_query($link, "BEGIN");
627 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
628 FROM ttrss_feeds WHERE id = '$feed'");
630 $registered_title = db_fetch_result($result, 0, "title");
631 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
632 $orig_site_url = db_fetch_result($result, 0, "site_url");
634 $owner_uid = db_fetch_result($result, 0, "owner_uid");
636 if ($use_simplepie) {
637 $site_url = $rss->get_link();
639 $site_url = $rss->channel
["link"];
642 $site_url = rewrite_relative_url($fetch_url, $site_url);
644 if ($debug_enabled) {
645 _debug("update_rss_feed: checking favicon...");
648 check_feed_favicon($site_url, $feed, $link);
650 if (!$registered_title ||
$registered_title == "[Unknown]") {
652 if ($use_simplepie) {
653 $feed_title = db_escape_string($rss->get_title());
655 $feed_title = db_escape_string($rss->channel
["title"]);
658 if ($debug_enabled) {
659 _debug("update_rss_feed: registering title: $feed_title");
662 db_query($link, "UPDATE ttrss_feeds SET
663 title = '$feed_title' WHERE id = '$feed'");
666 // weird, weird Magpie
667 if (!$use_simplepie) {
668 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
671 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
672 db_query($link, "UPDATE ttrss_feeds SET
673 site_url = '$site_url' WHERE id = '$feed'");
676 // print "I: " . $rss->channel["image"]["url"];
678 if (!$use_simplepie) {
679 $icon_url = db_escape_string($rss->image
["url"]);
681 $icon_url = db_escape_string($rss->get_image_url());
684 $icon_url = substr($icon_url, 0, 250);
686 if ($icon_url && $orig_icon_url != $icon_url) {
687 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
690 if ($debug_enabled) {
691 _debug("update_rss_feed: loading filters...");
694 $filters = load_filters($link, $feed, $owner_uid);
696 // if ($debug_enabled) {
697 // print_r($filters);
700 if ($use_simplepie) {
701 $iterator = $rss->get_items();
703 $iterator = $rss->items
;
704 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
705 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
708 if (!is_array($iterator)) {
709 /* db_query($link, "UPDATE ttrss_feeds
710 SET last_error = 'Parse error: can\'t find any articles.'
711 WHERE id = '$feed'"); */
713 // clear any errors and mark feed as updated if fetched okay
714 // even if it's blank
716 if ($debug_enabled) {
717 _debug("update_rss_feed: entry iterator is not an array, no articles?");
720 db_query($link, "UPDATE ttrss_feeds
721 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
723 return; // no articles
726 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
728 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
730 $feed_hub_url = false;
731 if ($use_simplepie) {
732 $links = $rss->get_links('hub');
734 if ($links && is_array($links)) {
735 foreach ($links as $l) {
742 $atom = $rss->channel
['atom'];
745 if ($atom['link@rel'] == 'hub') {
746 $feed_hub_url = $atom['link@href'];
749 if (!$feed_hub_url && $atom['link#'] > 1) {
750 for ($i = 2; $i <= $atom['link#']; $i++
) {
751 if ($atom["link#$i@rel"] == 'hub') {
752 $feed_hub_url = $atom["link#$i@href"];
758 $feed_hub_url = $rss->channel
['link_hub'];
762 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
764 if ($feed_hub_url && function_exists('curl_init') &&
765 !ini_get("open_basedir")) {
767 $callback_url = get_self_url_prefix() .
768 "/public.php?op=pubsub&id=$feed";
770 $s = new Subscriber($feed_hub_url, $callback_url);
772 $rc = $s->subscribe($fetch_url);
775 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
777 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
778 WHERE id = '$feed'");
782 if ($debug_enabled) {
783 _debug("update_rss_feed: processing articles...");
786 foreach ($iterator as $item) {
788 if ($_REQUEST['xdebug'] == 2) {
792 if ($use_simplepie) {
793 $entry_guid = $item->get_id();
794 if (!$entry_guid) $entry_guid = $item->get_link();
795 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
799 $entry_guid = $item["id"];
801 if (!$entry_guid) $entry_guid = $item["guid"];
802 if (!$entry_guid) $entry_guid = $item["about"];
803 if (!$entry_guid) $entry_guid = $item["link"];
804 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
807 if ($debug_enabled) {
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 ($debug_enabled) {
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 $entry_link = rewrite_relative_url($site_url, $entry_link);
858 if ($debug_enabled) {
859 _debug("update_rss_feed: title $entry_title");
860 _debug("update_rss_feed: link $entry_link");
863 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
865 $entry_link = strip_tags($entry_link);
867 if ($use_simplepie) {
868 $entry_content = $item->get_content();
869 if (!$entry_content) $entry_content = $item->get_description();
871 $entry_content = $item["content:escaped"];
873 if (!$entry_content) $entry_content = $item["content:encoded"];
874 if (!$entry_content) $entry_content = $item["content"]["encoded"];
875 if (!$entry_content) $entry_content = $item["content"];
877 // Magpie bugs are getting ridiculous
878 if (trim($entry_content) == "Array") $entry_content = false;
880 if (!$entry_content) $entry_content = $item["atom_content"];
881 if (!$entry_content) $entry_content = $item["summary"];
883 if (!$entry_content ||
884 strlen($entry_content) < strlen($item["description"])) {
885 $entry_content = $item["description"];
889 if (is_array($entry_content)) {
890 $entry_content = $entry_content["encoded"];
891 if (!$entry_content) $entry_content = $entry_content["escaped"];
895 if ($_REQUEST["xdebug"] == 2) {
896 print "update_rss_feed: content: ";
897 print_r(htmlspecialchars($entry_content));
900 $entry_content_unescaped = $entry_content;
902 if ($use_simplepie) {
903 $entry_comments = strip_tags($item->data
["comments"]);
904 if ($item->get_author()) {
905 $entry_author_item = $item->get_author();
906 $entry_author = $entry_author_item->get_name();
907 if (!$entry_author) $entry_author = $entry_author_item->get_email();
909 $entry_author = db_escape_string($entry_author);
912 $entry_comments = strip_tags($item["comments"]);
914 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
916 if ($item['author']) {
918 if (is_array($item['author'])) {
920 if (!$entry_author) {
921 $entry_author = db_escape_string(strip_tags($item['author']['name']));
924 if (!$entry_author) {
925 $entry_author = db_escape_string(strip_tags($item['author']['email']));
929 if (!$entry_author) {
930 $entry_author = db_escape_string(strip_tags($item['author']));
935 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
937 $entry_guid = db_escape_string(strip_tags($entry_guid));
938 $entry_guid = mb_substr($entry_guid, 0, 250);
940 $result = db_query($link, "SELECT id FROM ttrss_entries
941 WHERE guid = '$entry_guid'");
943 $entry_content = db_escape_string($entry_content, false);
945 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
947 $entry_title = db_escape_string($entry_title);
948 $entry_link = db_escape_string($entry_link);
949 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
950 $entry_author = mb_substr($entry_author, 0, 250);
952 if ($use_simplepie) {
953 $num_comments = 0; #FIXME#
955 $num_comments = db_escape_string($item["slash"]["comments"]);
958 if (!$num_comments) $num_comments = 0;
960 if ($debug_enabled) {
961 _debug("update_rss_feed: looking for tags [1]...");
964 // parse <category> entries into tags
966 $additional_tags = array();
968 if ($use_simplepie) {
970 $additional_tags_src = $item->get_categories();
972 if (is_array($additional_tags_src)) {
973 foreach ($additional_tags_src as $tobj) {
974 array_push($additional_tags, $tobj->get_term());
978 if ($debug_enabled) {
979 _debug("update_rss_feed: category tags:");
980 print_r($additional_tags);
985 $t_ctr = $item['category#'];
988 $additional_tags = array();
989 } else if ($t_ctr > 0) {
990 $additional_tags = array($item['category']);
992 if ($item['category@term']) {
993 array_push($additional_tags, $item['category@term']);
996 for ($i = 0; $i <= $t_ctr; $i++
) {
997 if ($item["category#$i"]) {
998 array_push($additional_tags, $item["category#$i"]);
1001 if ($item["category#$i@term"]) {
1002 array_push($additional_tags, $item["category#$i@term"]);
1007 // parse <dc:subject> elements
1009 $t_ctr = $item['dc']['subject#'];
1012 array_push($additional_tags, $item['dc']['subject']);
1014 for ($i = 0; $i <= $t_ctr; $i++
) {
1015 if ($item['dc']["subject#$i"]) {
1016 array_push($additional_tags, $item['dc']["subject#$i"]);
1022 if ($debug_enabled) {
1023 _debug("update_rss_feed: looking for tags [2]...");
1027 // <a href="..." rel="tag">Xorg</a>, //
1031 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1032 $entry_content_unescaped, $entry_tags);
1034 $entry_tags = $entry_tags[1];
1036 $entry_tags = array_merge($entry_tags, $additional_tags);
1037 $entry_tags = array_unique($entry_tags);
1039 for ($i = 0; $i < count($entry_tags); $i++
)
1040 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1042 if ($debug_enabled) {
1043 _debug("update_rss_feed: unfiltered tags found:");
1044 print_r($entry_tags);
1049 $entry_content = sanitize_article_content($entry_content);
1050 $entry_title = sanitize_article_content($entry_title);
1052 if ($debug_enabled) {
1053 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1056 db_query($link, "BEGIN");
1058 if (db_num_rows($result) == 0) {
1060 if ($debug_enabled) {
1061 _debug("update_rss_feed: base guid not found");
1064 // base post entry does not exist, create it
1066 $result = db_query($link,
1067 "INSERT INTO ttrss_entries
1084 '$entry_timestamp_fmt',
1094 // we keep encountering the entry in feeds, so we need to
1095 // update date_updated column so that we don't get horrible
1096 // dupes when the entry gets purged and reinserted again e.g.
1097 // in the case of SLOW SLOW OMG SLOW updating feeds
1099 $base_entry_id = db_fetch_result($result, 0, "id");
1101 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1102 WHERE id = '$base_entry_id'");
1105 // now it should exist, if not - bad luck then
1107 $result = db_query($link, "SELECT
1108 id,content_hash,no_orig_date,title,
1109 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1110 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1114 WHERE guid = '$entry_guid'");
1119 if (db_num_rows($result) == 1) {
1121 if ($debug_enabled) {
1122 _debug("update_rss_feed: base guid found, checking for user record");
1125 // this will be used below in update handler
1126 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1127 $orig_title = db_fetch_result($result, 0, "title");
1128 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1129 $orig_date_updated = strtotime(db_fetch_result($result,
1130 0, "date_updated"));
1132 $ref_id = db_fetch_result($result, 0, "id");
1133 $entry_ref_id = $ref_id;
1135 // check for user post link to main table
1137 // do we allow duplicate posts with same GUID in different feeds?
1138 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1139 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1141 $dupcheck_qpart = "";
1144 /* Collect article tags here so we could filter by them: */
1146 $article_filters = get_article_filters($filters, $entry_title,
1147 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1150 if ($debug_enabled) {
1151 _debug("update_rss_feed: article filters: ");
1152 if (count($article_filters) != 0) {
1153 print_r($article_filters);
1157 if (find_article_filter($article_filters, "filter")) {
1158 db_query($link, "COMMIT"); // close transaction in progress
1162 $score = calculate_article_score($article_filters);
1164 if ($debug_enabled) {
1165 _debug("update_rss_feed: initial score: $score");
1168 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1169 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1172 // if ($_REQUEST["xdebug"]) print "$query\n";
1174 $result = db_query($link, $query);
1176 // okay it doesn't exist - create user entry
1177 if (db_num_rows($result) == 0) {
1179 if ($debug_enabled) {
1180 _debug("update_rss_feed: user record not found, creating...");
1183 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1185 $last_read_qpart = 'NULL';
1188 $last_read_qpart = 'NOW()';
1191 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1197 if (find_article_filter($article_filters, 'publish')) {
1198 $published = 'true';
1200 $published = 'false';
1203 $result = db_query($link,
1204 "INSERT INTO ttrss_user_entries
1205 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1206 published, score, tag_cache, label_cache, uuid)
1207 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1208 $last_read_qpart, $marked, $published, '$score', '', '', '')");
1210 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1211 $rss_link = get_self_url_prefix() .
1212 "/public.php?op=rss&id=-2&key=" .
1213 get_feed_access_key($link, -2, false, $owner_uid);
1215 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1217 $pubsub_result = $p->publish_update($rss_link);
1220 $result = db_query($link,
1221 "SELECT int_id FROM ttrss_user_entries WHERE
1222 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1223 feed_id = '$feed' LIMIT 1");
1225 if (db_num_rows($result) == 1) {
1226 $entry_int_id = db_fetch_result($result, 0, "int_id");
1229 if ($debug_enabled) {
1230 _debug("update_rss_feed: user record FOUND");
1233 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1234 $entry_int_id = db_fetch_result($result, 0, "int_id");
1237 if ($debug_enabled) {
1238 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1241 $post_needs_update = false;
1242 $update_insignificant = false;
1244 if ($orig_num_comments != $num_comments) {
1245 $post_needs_update = true;
1246 $update_insignificant = true;
1249 if ($content_hash != $orig_content_hash) {
1250 $post_needs_update = true;
1251 $update_insignificant = false;
1254 if (db_escape_string($orig_title) != $entry_title) {
1255 $post_needs_update = true;
1256 $update_insignificant = false;
1259 // if post needs update, update it and mark all user entries
1260 // linking to this post as updated
1261 if ($post_needs_update) {
1263 if (defined('DAEMON_EXTENDED_DEBUG')) {
1264 _debug("update_rss_feed: post $entry_guid needs update...");
1267 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1269 db_query($link, "UPDATE ttrss_entries
1270 SET title = '$entry_title', content = '$entry_content',
1271 content_hash = '$content_hash',
1272 updated = '$entry_timestamp_fmt',
1273 num_comments = '$num_comments'
1274 WHERE id = '$ref_id'");
1276 if (!$update_insignificant) {
1277 if ($mark_unread_on_update) {
1278 db_query($link, "UPDATE ttrss_user_entries
1279 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1280 } else if ($update_on_checksum_change) {
1281 db_query($link, "UPDATE ttrss_user_entries
1282 SET last_read = null WHERE ref_id = '$ref_id'
1283 AND unread = false");
1289 db_query($link, "COMMIT");
1291 if ($debug_enabled) {
1292 _debug("update_rss_feed: assigning labels...");
1295 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1298 if ($debug_enabled) {
1299 _debug("update_rss_feed: looking for enclosures...");
1304 $enclosures = array();
1306 if ($use_simplepie) {
1307 $encs = $item->get_enclosures();
1309 if (is_array($encs)) {
1310 foreach ($encs as $e) {
1312 $e->link
, $e->type
, $e->length
);
1314 array_push($enclosures, $e_item);
1321 $e_ctr = $item['enclosure#'];
1324 $e_item = array($item['enclosure@url'],
1325 $item['enclosure@type'],
1326 $item['enclosure@length']);
1328 array_push($enclosures, $e_item);
1330 for ($i = 0; $i <= $e_ctr; $i++
) {
1332 if ($item["enclosure#$i@url"]) {
1333 $e_item = array($item["enclosure#$i@url"],
1334 $item["enclosure#$i@type"],
1335 $item["enclosure#$i@length"]);
1336 array_push($enclosures, $e_item);
1342 // can there be many of those? yes -fox
1344 $m_ctr = $item['media']['content#'];
1347 $e_item = array($item['media']['content@url'],
1348 $item['media']['content@medium'],
1349 $item['media']['content@length']);
1351 array_push($enclosures, $e_item);
1353 for ($i = 0; $i <= $m_ctr; $i++
) {
1355 if ($item["media"]["content#$i@url"]) {
1356 $e_item = array($item["media"]["content#$i@url"],
1357 $item["media"]["content#$i@medium"],
1358 $item["media"]["content#$i@length"]);
1359 array_push($enclosures, $e_item);
1367 if ($debug_enabled) {
1368 _debug("update_rss_feed: article enclosures:");
1369 print_r($enclosures);
1372 db_query($link, "BEGIN");
1374 foreach ($enclosures as $enc) {
1375 $enc_url = db_escape_string($enc[0]);
1376 $enc_type = db_escape_string($enc[1]);
1377 $enc_dur = db_escape_string($enc[2]);
1379 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1380 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1382 if (db_num_rows($result) == 0) {
1383 db_query($link, "INSERT INTO ttrss_enclosures
1384 (content_url, content_type, title, duration, post_id) VALUES
1385 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1389 db_query($link, "COMMIT");
1391 // check for manual tags (we have to do it here since they're loaded from filters)
1393 foreach ($article_filters as $f) {
1394 if ($f[0] == "tag") {
1396 $manual_tags = trim_array(explode(",", $f[1]));
1398 foreach ($manual_tags as $tag) {
1399 if (tag_is_valid($tag)) {
1400 array_push($entry_tags, $tag);
1408 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1409 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1411 $filtered_tags = array();
1412 $tags_to_cache = array();
1414 if ($entry_tags && is_array($entry_tags)) {
1415 foreach ($entry_tags as $tag) {
1416 if (array_search($tag, $boring_tags) === false) {
1417 array_push($filtered_tags, $tag);
1422 $filtered_tags = array_unique($filtered_tags);
1424 if ($debug_enabled) {
1425 _debug("update_rss_feed: filtered article tags:");
1426 print_r($filtered_tags);
1429 // Save article tags in the database
1431 if (count($filtered_tags) > 0) {
1433 db_query($link, "BEGIN");
1435 foreach ($filtered_tags as $tag) {
1437 $tag = sanitize_tag($tag);
1438 $tag = db_escape_string($tag);
1440 if (!tag_is_valid($tag)) continue;
1442 $result = db_query($link, "SELECT id FROM ttrss_tags
1443 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1444 owner_uid = '$owner_uid' LIMIT 1");
1446 if ($result && db_num_rows($result) == 0) {
1448 db_query($link, "INSERT INTO ttrss_tags
1449 (owner_uid,tag_name,post_int_id)
1450 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1453 array_push($tags_to_cache, $tag);
1456 /* update the cache */
1458 $tags_to_cache = array_unique($tags_to_cache);
1460 $tags_str = db_escape_string(join(",", $tags_to_cache));
1462 db_query($link, "UPDATE ttrss_user_entries
1463 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1464 AND owner_uid = $owner_uid");
1466 db_query($link, "COMMIT");
1469 if ($debug_enabled) {
1470 _debug("update_rss_feed: article processed");
1474 if (!$last_updated) {
1475 if ($debug_enabled) {
1476 _debug("update_rss_feed: new feed, catching it up...");
1478 catchup_feed($link, $feed, false, $owner_uid);
1481 if ($debug_enabled) {
1482 _debug("purging feed...");
1485 purge_feed($link, $feed, 0, $debug_enabled);
1487 db_query($link, "UPDATE ttrss_feeds
1488 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1490 // db_query($link, "COMMIT");
1494 if ($use_simplepie) {
1495 $error_msg = mb_substr($rss->error(), 0, 250);
1497 $error_msg = mb_substr(magpie_error(), 0, 250);
1500 if ($debug_enabled) {
1501 _debug("update_rss_feed: error fetching feed: $error_msg");
1504 $error_msg = db_escape_string($error_msg);
1507 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1508 last_updated = NOW() WHERE id = '$feed'");
1511 if ($use_simplepie) {
1515 if ($debug_enabled) {
1516 _debug("update_rss_feed: done");
1521 function print_select($id, $default, $values, $attributes = "") {
1522 print "<select name=\"$id\" id=\"$id\" $attributes>";
1523 foreach ($values as $v) {
1525 $sel = "selected=\"1\"";
1529 print "<option value=\"$v\" $sel>$v</option>";
1534 function print_select_hash($id, $default, $values, $attributes = "") {
1535 print "<select name=\"$id\" id='$id' $attributes>";
1536 foreach (array_keys($values) as $v) {
1538 $sel = 'selected="selected"';
1542 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1548 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1551 if ($filters["title"]) {
1552 foreach ($filters["title"] as $filter) {
1553 $reg_exp = $filter["reg_exp"];
1554 $inverse = $filter["inverse"];
1555 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1556 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1558 array_push($matches, array($filter["action"], $filter["action_param"]));
1563 if ($filters["content"]) {
1564 foreach ($filters["content"] as $filter) {
1565 $reg_exp = $filter["reg_exp"];
1566 $inverse = $filter["inverse"];
1568 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1569 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1571 array_push($matches, array($filter["action"], $filter["action_param"]));
1576 if ($filters["both"]) {
1577 foreach ($filters["both"] as $filter) {
1578 $reg_exp = $filter["reg_exp"];
1579 $inverse = $filter["inverse"];
1582 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1583 array_push($matches, array($filter["action"], $filter["action_param"]));
1586 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1587 array_push($matches, array($filter["action"], $filter["action_param"]));
1593 if ($filters["link"]) {
1594 $reg_exp = $filter["reg_exp"];
1595 foreach ($filters["link"] as $filter) {
1596 $reg_exp = $filter["reg_exp"];
1597 $inverse = $filter["inverse"];
1599 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1600 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1602 array_push($matches, array($filter["action"], $filter["action_param"]));
1607 if ($filters["date"]) {
1608 $reg_exp = $filter["reg_exp"];
1609 foreach ($filters["date"] as $filter) {
1610 $date_modifier = $filter["filter_param"];
1611 $inverse = $filter["inverse"];
1612 $check_timestamp = strtotime($filter["reg_exp"]);
1614 # no-op when timestamp doesn't parse to prevent misfires
1616 if ($check_timestamp) {
1619 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1620 $date_modifier == "after" && $timestamp > $check_timestamp) {
1624 if ($inverse) $match_ok = !$match_ok;
1627 array_push($matches, array($filter["action"], $filter["action_param"]));
1633 if ($filters["author"]) {
1634 foreach ($filters["author"] as $filter) {
1635 $reg_exp = $filter["reg_exp"];
1636 $inverse = $filter["inverse"];
1637 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1638 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1640 array_push($matches, array($filter["action"], $filter["action_param"]));
1645 if ($filters["tag"]) {
1647 $tag_string = join(",", $tags);
1649 foreach ($filters["tag"] as $filter) {
1650 $reg_exp = $filter["reg_exp"];
1651 $inverse = $filter["inverse"];
1653 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1654 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1656 array_push($matches, array($filter["action"], $filter["action_param"]));
1665 function find_article_filter($filters, $filter_name) {
1666 foreach ($filters as $f) {
1667 if ($f[0] == $filter_name) {
1674 function calculate_article_score($filters) {
1677 foreach ($filters as $f) {
1678 if ($f[0] == "score") {
1685 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1686 foreach ($filters as $f) {
1687 if ($f[0] == "label") {
1688 label_add_article($link, $id, $f[1], $owner_uid);
1693 function getmicrotime() {
1694 list($usec, $sec) = explode(" ",microtime());
1695 return ((float)$usec +
(float)$sec);
1698 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1699 foreach ($values as $v) {
1706 if ($v == $true_is) {
1707 $sel .= " value=\"1\"";
1709 $sel .= " value=\"0\"";
1712 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1713 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1718 function initialize_user_prefs($link, $uid, $profile = false) {
1720 $uid = db_escape_string($uid);
1724 $profile_qpart = "AND profile IS NULL";
1726 $profile_qpart = "AND profile = '$profile'";
1729 if (get_schema_version($link) < 63) $profile_qpart = "";
1731 db_query($link, "BEGIN");
1733 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1735 $u_result = db_query($link, "SELECT pref_name
1736 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1738 $active_prefs = array();
1740 while ($line = db_fetch_assoc($u_result)) {
1741 array_push($active_prefs, $line["pref_name"]);
1744 while ($line = db_fetch_assoc($result)) {
1745 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1746 // print "adding " . $line["pref_name"] . "<br>";
1748 if (get_schema_version($link) < 63) {
1749 db_query($link, "INSERT INTO ttrss_user_prefs
1750 (owner_uid,pref_name,value) VALUES
1751 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1754 db_query($link, "INSERT INTO ttrss_user_prefs
1755 (owner_uid,pref_name,value, profile) VALUES
1756 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1762 db_query($link, "COMMIT");
1766 function get_ssl_certificate_id() {
1767 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1768 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1769 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1770 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1771 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1776 function get_login_by_ssl_certificate($link) {
1778 $cert_serial = db_escape_string(get_ssl_certificate_id());
1781 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1782 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1783 owner_uid = ttrss_users.id");
1785 if (db_num_rows($result) != 0) {
1786 return db_escape_string(db_fetch_result($result, 0, "login"));
1793 function get_remote_user($link) {
1795 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
1796 return db_escape_string($_SERVER["REMOTE_USER"]);
1799 return db_escape_string(get_login_by_ssl_certificate($link));
1802 function get_remote_fakepass($link) {
1803 if (get_remote_user($link))
1809 function authenticate_user($link, $login, $password, $force_auth = false) {
1811 if (!SINGLE_USER_MODE
) {
1813 $pwd_hash1 = encrypt_password($password);
1814 $pwd_hash2 = encrypt_password($password, $login);
1815 $login = db_escape_string($login);
1817 $remote_user = get_remote_user($link);
1819 if ($remote_user && $remote_user == $login && $login != "admin") {
1821 $login = $remote_user;
1823 $query = "SELECT id,login,access_level,pwd_hash
1824 FROM ttrss_users WHERE
1827 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1828 && $_SERVER["REMOTE_USER"]) {
1829 $result = db_query($link, $query);
1832 if (db_num_rows($result) == 0) {
1833 $query2 = "INSERT INTO ttrss_users
1834 (login,access_level,last_login,created)
1835 VALUES ('$login', 0, null, NOW())";
1836 db_query($link, $query2);
1841 $query = "SELECT id,login,access_level,pwd_hash
1842 FROM ttrss_users WHERE
1843 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1844 pwd_hash = '$pwd_hash2')";
1847 $result = db_query($link, $query);
1849 if (db_num_rows($result) == 1) {
1850 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1851 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1852 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1854 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1858 // LemonLDAP can send user informations via HTTP HEADER
1859 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
1861 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1863 $fullname = db_escape_string($fullname);
1864 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1868 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1870 $email = db_escape_string($email);
1871 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1876 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1877 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1879 $_SESSION["last_version_check"] = time();
1881 initialize_user_prefs($link, $_SESSION["uid"]);
1890 $_SESSION["uid"] = 1;
1891 $_SESSION["name"] = "admin";
1893 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1895 initialize_user_prefs($link, $_SESSION["uid"]);
1901 function make_password($length = 8) {
1904 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1908 while ($i < $length) {
1909 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1911 if (!strstr($password, $char)) {
1919 // this is called after user is created to initialize default feeds, labels
1922 // user preferences are checked on every login, not here
1924 function initialize_user($link, $uid) {
1926 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1927 values ('$uid', 'Tiny Tiny RSS: New Releases',
1928 'http://tt-rss.org/releases.rss')");
1930 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1931 values ('$uid', 'Tiny Tiny RSS: Forum',
1932 'http://tt-rss.org/forum/rss.php')");
1935 function logout_user() {
1937 if (isset($_COOKIE[session_name()])) {
1938 setcookie(session_name(), '', time()-42000, '/');
1942 function validate_session($link) {
1943 if (SINGLE_USER_MODE
) return true;
1945 $check_ip = $_SESSION['ip_address'];
1947 switch (SESSION_CHECK_ADDRESS
) {
1952 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1955 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1956 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1960 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
1961 $_SESSION["login_error_msg"] =
1962 __("Session failed to validate (incorrect IP)");
1966 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
1969 if ($_SESSION["uid"]) {
1971 $result = db_query($link,
1972 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1974 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1976 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1981 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1983 //print_r($_SESSION);
1985 if (time() > $_SESSION["cookie_lifetime"]) {
1993 function login_sequence($link, $mobile = false) {
1994 $_SESSION["prefs_cache"] = array();
1996 if (!SINGLE_USER_MODE
) {
1998 $login_action = $_POST["login_action"];
2000 # try to authenticate user if called from login form
2001 if ($login_action == "do_login") {
2002 $login = db_escape_string($_POST["login"]);
2003 $password = $_POST["password"];
2004 $remember_me = $_POST["remember_me"];
2006 if (authenticate_user($link, $login, $password)) {
2007 $_POST["password"] = "";
2009 $_SESSION["language"] = $_POST["language"];
2010 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2011 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
2013 if ($_POST["profile"]) {
2015 $profile = db_escape_string($_POST["profile"]);
2017 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2018 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2020 if (db_num_rows($result) != 0) {
2021 $_SESSION["profile"] = $profile;
2022 $_SESSION["prefs_cache"] = array();
2026 if ($_REQUEST['return']) {
2027 header("Location: " . $_REQUEST['return']);
2029 header("Location: " . $_SERVER["REQUEST_URI"]);
2036 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2040 if (!$_SESSION["uid"] ||
!validate_session($link)) {
2042 if (get_remote_user($link) && AUTO_LOGIN
) {
2043 authenticate_user($link, get_remote_user($link), null);
2044 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2046 render_login_form($link, $mobile);
2047 //header("Location: login.php");
2051 /* bump login timestamp */
2052 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2055 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
2056 setcookie("ttrss_lang", $_SESSION["language"],
2057 time() + SESSION_COOKIE_LIFETIME
);
2060 // try to remove possible duplicates from feed counter cache
2061 // ccache_cleanup($link, $_SESSION["uid"]);
2065 return authenticate_user($link, "admin", null);
2069 function truncate_string($str, $max_len, $suffix = '…') {
2070 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2071 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2077 function theme_image($link, $filename) {
2079 $theme_path = get_user_theme_path($link);
2081 if ($theme_path && is_file($theme_path.$filename)) {
2082 return $theme_path.$filename;
2091 function get_user_theme($link) {
2093 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2094 $theme_name = get_pref($link, "_THEME_ID");
2095 if (is_dir("themes/$theme_name")) {
2106 function get_user_theme_path($link) {
2109 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2110 $theme_name = get_pref($link, "_THEME_ID");
2112 if ($theme_name && is_dir("themes/$theme_name")) {
2113 $theme_path = "themes/$theme_name/";
2122 if (is_file("$theme_path/theme.ini")) {
2123 $ini = parse_ini_file("$theme_path/theme.ini", true);
2124 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2132 function get_user_theme_options($link) {
2133 $t = get_user_theme_path($link);
2136 if (is_file("$t/theme.ini")) {
2137 $ini = parse_ini_file("$t/theme.ini", true);
2138 if ($ini['theme']['version']) {
2139 return $ini['theme']['options'];
2146 function print_theme_includes($link) {
2148 $t = get_user_theme_path($link);
2152 print "<link rel=\"stylesheet\" type=\"text/css\"
2153 href=\"$t/theme.css?$time \">";
2154 if (file_exists("$t/theme.js")) {
2155 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2161 function get_all_themes() {
2162 $themes = glob("themes/*");
2168 foreach ($themes as $t) {
2169 if (is_file("$t/theme.ini")) {
2170 $ini = parse_ini_file("$t/theme.ini", true);
2171 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2172 !$ini['theme']['disabled']) {
2174 $entry["path"] = $t;
2175 $entry["base"] = basename($t);
2176 $entry["name"] = $ini['theme']['name'];
2177 $entry["version"] = $ini['theme']['version'];
2178 $entry["author"] = $ini['theme']['author'];
2179 $entry["options"] = $ini['theme']['options'];
2180 array_push($rv, $entry);
2188 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2191 $source_tz = new DateTimeZone($source_tz);
2192 } catch (Exception
$e) {
2193 $source_tz = new DateTimeZone('UTC');
2197 $dest_tz = new DateTimeZone($dest_tz);
2198 } catch (Exception
$e) {
2199 $dest_tz = new DateTimeZone('UTC');
2202 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2203 return $dt->format('U') +
$dest_tz->getOffset($dt);
2206 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2207 $no_smart_dt = false) {
2209 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2210 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2215 # We store date in UTC internally
2216 $dt = new DateTime($timestamp, $utc_tz);
2218 if ($tz_offset == -1) {
2220 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2223 $user_tz = new DateTimeZone($user_tz_string);
2224 } catch (Exception
$e) {
2228 $tz_offset = $user_tz->getOffset($dt);
2231 $user_timestamp = $dt->format('U') +
$tz_offset;
2233 if (!$no_smart_dt) {
2234 return smart_date_time($link, $user_timestamp,
2235 $tz_offset, $owner_uid);
2238 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2240 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2242 return date($format, $user_timestamp);
2246 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2247 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2249 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2250 return date("G:i", $timestamp);
2251 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2252 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2253 return date($format, $timestamp);
2255 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2256 return date($format, $timestamp);
2260 function sql_bool_to_bool($s) {
2261 if ($s == "t" ||
$s == "1" ||
$s == "true") {
2268 function bool_to_sql_bool($s) {
2276 function toggleEvenOdd($a) {
2283 // Session caching removed due to causing wrong redirects to upgrade
2284 // script when get_schema_version() is called on an obsolete session
2285 // created on a previous schema version.
2286 function get_schema_version($link, $nocache = false) {
2287 global $schema_version;
2289 if (!$schema_version) {
2290 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2291 $version = db_fetch_result($result, 0, "schema_version");
2292 $schema_version = $version;
2295 return $schema_version;
2299 function sanity_check($link) {
2304 $schema_version = get_schema_version($link, true);
2306 if ($schema_version != SCHEMA_VERSION
) {
2310 if (DB_TYPE
== "mysql") {
2311 $result = db_query($link, "SELECT true", false);
2312 if (db_num_rows($result) != 1) {
2317 if (db_escape_string("testTEST") != "testTEST") {
2321 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2324 function file_is_locked($filename) {
2325 if (function_exists('flock')) {
2326 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2328 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2329 flock($fp, LOCK_UN
);
2339 return true; // consider the file always locked and skip the test
2342 function make_lockfile($filename) {
2343 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2345 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2346 if (function_exists('posix_getpid')) {
2347 fwrite($fp, posix_getpid() . "\n");
2355 function make_stampfile($filename) {
2356 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2358 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2359 fwrite($fp, time() . "\n");
2360 flock($fp, LOCK_UN
);
2368 function sql_random_function() {
2369 if (DB_TYPE
== "mysql") {
2376 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2378 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2380 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2382 if (is_numeric($feed)) {
2388 $cat_qpart = "cat_id = '$feed'";
2390 $cat_qpart = "cat_id IS NULL";
2393 $tmp_result = db_query($link, "SELECT id
2394 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2396 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2398 $tmp_feed = $tmp_line["id"];
2400 db_query($link, "UPDATE ttrss_user_entries
2401 SET unread = false,last_read = NOW()
2402 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2404 } else if ($feed == -2) {
2406 db_query($link, "UPDATE ttrss_user_entries
2407 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2408 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2409 AND unread = true AND owner_uid = $owner_uid");
2412 } else if ($feed > 0) {
2414 db_query($link, "UPDATE ttrss_user_entries
2415 SET unread = false,last_read = NOW()
2416 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2418 } else if ($feed < 0 && $feed > -10) { // special, like starred
2421 db_query($link, "UPDATE ttrss_user_entries
2422 SET unread = false,last_read = NOW()
2423 WHERE marked = true AND owner_uid = $owner_uid");
2427 db_query($link, "UPDATE ttrss_user_entries
2428 SET unread = false,last_read = NOW()
2429 WHERE published = true AND owner_uid = $owner_uid");
2434 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2436 if (DB_TYPE
== "pgsql") {
2437 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2439 $match_part = "updated > DATE_SUB(NOW(),
2440 INTERVAL $intl HOUR) ";
2443 $result = db_query($link, "SELECT id FROM ttrss_entries,
2444 ttrss_user_entries WHERE $match_part AND
2446 ttrss_user_entries.ref_id = ttrss_entries.id AND
2447 owner_uid = $owner_uid");
2449 $affected_ids = array();
2451 while ($line = db_fetch_assoc($result)) {
2452 array_push($affected_ids, $line["id"]);
2455 catchupArticlesById($link, $affected_ids, 0);
2459 db_query($link, "UPDATE ttrss_user_entries
2460 SET unread = false,last_read = NOW()
2461 WHERE owner_uid = $owner_uid");
2464 } else if ($feed < -10) { // label
2466 $label_id = -$feed - 11;
2468 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2469 SET unread = false, last_read = NOW()
2470 WHERE label_id = '$label_id' AND unread = true
2471 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2475 ccache_update($link, $feed, $owner_uid, $cat_view);
2478 db_query($link, "BEGIN");
2480 $tag_name = db_escape_string($feed);
2482 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2483 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2485 while ($line = db_fetch_assoc($result)) {
2486 db_query($link, "UPDATE ttrss_user_entries SET
2487 unread = false, last_read = NOW()
2488 WHERE int_id = " . $line["post_int_id"]);
2490 db_query($link, "COMMIT");
2494 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2496 if (!$omode) $omode = "flc";
2498 $data = getGlobalCounters($link);
2500 $data = array_merge($data, getVirtCounters($link));
2502 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2503 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2504 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2505 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
2510 function getCategoryCounters($link) {
2513 /* Labels category */
2515 $cv = array("id" => -2, "kind" => "cat",
2516 "counter" => getCategoryUnread($link, -2));
2518 array_push($ret_arr, $cv);
2520 $age_qpart = getMaxAgeSubquery();
2522 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2523 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2524 WHERE ttrss_cat_counters_cache.feed_id = id AND
2525 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2527 while ($line = db_fetch_assoc($result)) {
2528 $line["cat_id"] = (int) $line["cat_id"];
2530 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2531 "counter" => $line["unread"]);
2533 array_push($ret_arr, $cv);
2536 /* Special case: NULL category doesn't actually exist in the DB */
2538 $cv = array("id" => 0, "kind" => "cat",
2539 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2541 array_push($ret_arr, $cv);
2546 function getCategoryUnread($link, $cat, $owner_uid = false) {
2548 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2553 $cat_query = "cat_id = '$cat'";
2555 $cat_query = "cat_id IS NULL";
2558 $age_qpart = getMaxAgeSubquery();
2560 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2561 AND owner_uid = " . $owner_uid);
2563 $cat_feeds = array();
2564 while ($line = db_fetch_assoc($result)) {
2565 array_push($cat_feeds, "feed_id = " . $line["id"]);
2568 if (count($cat_feeds) == 0) return 0;
2570 $match_part = implode(" OR ", $cat_feeds);
2572 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2573 FROM ttrss_user_entries,ttrss_entries
2574 WHERE unread = true AND ($match_part) AND id = ref_id
2575 AND $age_qpart AND owner_uid = " . $owner_uid);
2579 # this needs to be rewritten
2580 while ($line = db_fetch_assoc($result)) {
2581 $unread +
= $line["unread"];
2585 } else if ($cat == -1) {
2586 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2587 } else if ($cat == -2) {
2589 $result = db_query($link, "
2590 SELECT COUNT(unread) AS unread FROM
2591 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2592 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2593 ttrss_labels2.owner_uid = '$owner_uid'
2594 AND unread = true AND feed_id = ttrss_feeds.id
2595 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2597 $unread = db_fetch_result($result, 0, "unread");
2604 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2605 if (DB_TYPE
== "pgsql") {
2606 return "ttrss_entries.date_updated >
2607 NOW() - INTERVAL '$days days'";
2609 return "ttrss_entries.date_updated >
2610 DATE_SUB(NOW(), INTERVAL $days DAY)";
2614 function getFeedUnread($link, $feed, $is_cat = false) {
2615 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2618 function getLabelUnread($link, $label_id, $owner_uid = false) {
2619 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2621 $result = db_query($link, "
2622 SELECT COUNT(unread) AS unread FROM
2623 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2624 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2625 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2626 AND unread = true AND feed_id = ttrss_feeds.id
2627 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2629 if (db_num_rows($result) != 0) {
2630 return db_fetch_result($result, 0, "unread");
2636 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2637 $owner_uid = false) {
2639 $n_feed = (int) $feed;
2641 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2644 $unread_qpart = "unread = true";
2646 $unread_qpart = "true";
2649 $age_qpart = getMaxAgeSubquery();
2652 return getCategoryUnread($link, $n_feed, $owner_uid);
2653 } if ($feed != "0" && $n_feed == 0) {
2655 $feed = db_escape_string($feed);
2657 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2658 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2659 AND ref_id = id AND $age_qpart
2660 AND $unread_qpart)) AS count FROM ttrss_tags
2661 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2662 return db_fetch_result($result, 0, "count");
2664 } else if ($n_feed == -1) {
2665 $match_part = "marked = true";
2666 } else if ($n_feed == -2) {
2667 $match_part = "published = true";
2668 } else if ($n_feed == -3) {
2669 $match_part = "unread = true AND score >= 0";
2671 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2673 if (DB_TYPE
== "pgsql") {
2674 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2676 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2678 } else if ($n_feed == -4) {
2679 $match_part = "true";
2680 } else if ($n_feed >= 0) {
2683 $match_part = "feed_id = '$n_feed'";
2685 $match_part = "feed_id IS NULL";
2688 } else if ($feed < -10) {
2690 $label_id = -$feed - 11;
2692 return getLabelUnread($link, $label_id, $owner_uid);
2699 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2700 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2702 $from_qpart = "ttrss_user_entries,ttrss_entries";
2706 $query = "SELECT count(int_id) AS unread
2707 FROM $from_qpart WHERE
2708 ttrss_user_entries.ref_id = ttrss_entries.id AND
2711 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2713 $result = db_query($link, $query);
2717 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2718 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2719 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2720 AND $unread_qpart AND $age_qpart AND
2721 ttrss_tags.owner_uid = " . $owner_uid);
2724 $unread = db_fetch_result($result, 0, "unread");
2729 function getGlobalUnread($link, $user_id = false) {
2732 $user_id = $_SESSION["uid"];
2735 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2736 WHERE owner_uid = '$user_id' AND feed_id > 0");
2738 $c_id = db_fetch_result($result, 0, "c_id");
2743 function getGlobalCounters($link, $global_unread = -1) {
2746 if ($global_unread == -1) {
2747 $global_unread = getGlobalUnread($link);
2750 $cv = array("id" => "global-unread",
2751 "counter" => $global_unread);
2753 array_push($ret_arr, $cv);
2755 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2756 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2758 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2760 $cv = array("id" => "subscribed-feeds",
2761 "counter" => $subscribed_feeds);
2763 array_push($ret_arr, $cv);
2768 function getTagCounters($link) {
2772 $age_qpart = getMaxAgeSubquery();
2774 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2775 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2776 AND ref_id = id AND $age_qpart
2777 AND unread = true)) AS count FROM ttrss_tags
2778 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2779 ORDER BY count DESC LIMIT 55");
2783 while ($line = db_fetch_assoc($result)) {
2784 $tags[$line["tag_name"]] +
= $line["count"];
2787 foreach (array_keys($tags) as $tag) {
2788 $unread = $tags[$tag];
2789 $tag = htmlspecialchars($tag);
2791 $cv = array("id" => $tag,
2793 "counter" => $unread);
2795 array_push($ret_arr, $cv);
2801 function getVirtCounters($link) {
2805 for ($i = 0; $i >= -4; $i--) {
2807 $count = getFeedUnread($link, $i);
2809 $cv = array("id" => $i,
2810 "counter" => $count);
2812 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2813 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2815 array_push($ret_arr, $cv);
2821 function getLabelCounters($link, $descriptions = false) {
2825 $age_qpart = getMaxAgeSubquery();
2827 $owner_uid = $_SESSION["uid"];
2829 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2830 WHERE owner_uid = '$owner_uid'");
2832 while ($line = db_fetch_assoc($result)) {
2834 $id = -$line["id"] - 11;
2836 $label_name = $line["caption"];
2837 $count = getFeedUnread($link, $id);
2839 $cv = array("id" => $id,
2840 "counter" => $count);
2843 $cv["description"] = $label_name;
2845 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2846 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2848 array_push($ret_arr, $cv);
2854 function getFeedCounters($link, $active_feed = false) {
2858 $age_qpart = getMaxAgeSubquery();
2860 $query = "SELECT ttrss_feeds.id,
2862 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2863 last_error, value AS count
2864 FROM ttrss_feeds, ttrss_counters_cache
2865 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2866 AND ttrss_counters_cache.feed_id = id";
2868 $result = db_query($link, $query);
2869 $fctrs_modified = false;
2871 while ($line = db_fetch_assoc($result)) {
2874 $count = $line["count"];
2875 $last_error = htmlspecialchars($line["last_error"]);
2877 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2879 $has_img = feed_has_icon($id);
2881 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2884 $cv = array("id" => $id,
2885 "updated" => $last_updated,
2886 "counter" => $count,
2887 "has_img" => (int) $has_img);
2890 $cv["error"] = $last_error;
2892 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2893 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2895 if ($active_feed && $id == $active_feed)
2896 $cv["title"] = truncate_string($line["title"], 30);
2898 array_push($ret_arr, $cv);
2905 function get_pgsql_version($link) {
2906 $result = db_query($link, "SELECT version() AS version");
2907 $version = explode(" ", db_fetch_result($result, 0, "version"));
2912 * Subscribes the user to the given feed
2914 * @param resource $link Database connection
2915 * @param string $url Feed URL to subscribe to
2916 * @param integer $cat_id Category ID the feed shall be added to
2917 * @param string $auth_login (optional) Feed username
2918 * @param string $auth_pass (optional) Feed password
2920 * @return integer Status code:
2921 * 0 - OK, Feed already exists
2922 * 1 - OK, Feed added
2924 * 3 - URL content is HTML, no feeds available
2925 * 4 - URL content is HTML which contains multiple feeds.
2926 * Here you should call extractfeedurls in rpc-backend
2927 * to get all possible feeds.
2928 * 5 - Couldn't download the URL content.
2930 function subscribe_to_feed($link, $url, $cat_id = 0,
2931 $auth_login = '', $auth_pass = '') {
2933 $url = fix_url($url);
2935 if (!$url ||
!validate_feed_url($url)) return 2;
2939 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
2940 WHERE id = ".$_SESSION['uid']);
2942 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2944 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
2945 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
2947 if (url_is_html($url, $auth_login, $auth_pass)) {
2948 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
2949 if (count($feedUrls) == 0) {
2951 } else if (count($feedUrls) > 1) {
2954 //use feed url as new URL
2955 $url = key($feedUrls);
2959 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
2964 if ($cat_id == "0" ||
!$cat_id) {
2965 $cat_qpart = "NULL";
2967 $cat_qpart = "'$cat_id'";
2970 $result = db_query($link,
2971 "SELECT id FROM ttrss_feeds
2972 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2974 if (db_num_rows($result) == 0) {
2975 $result = db_query($link,
2976 "INSERT INTO ttrss_feeds
2977 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2978 VALUES ('".$_SESSION["uid"]."', '$url',
2979 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
2981 $result = db_query($link,
2982 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2983 AND owner_uid = " . $_SESSION["uid"]);
2985 $feed_id = db_fetch_result($result, 0, "id");
2988 update_rss_feed($link, $feed_id, true);
2997 function print_feed_select($link, $id, $default_id = "",
2998 $attributes = "", $include_all_feeds = true) {
3000 print "<select id=\"$id\" name=\"$id\" $attributes>";
3001 if ($include_all_feeds) {
3002 print "<option value=\"0\">".__('All feeds')."</option>";
3005 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
3006 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3008 if (db_num_rows($result) > 0 && $include_all_feeds) {
3009 print "<option disabled>--------</option>";
3012 while ($line = db_fetch_assoc($result)) {
3013 if ($line["id"] == $default_id) {
3014 $is_selected = "selected=\"1\"";
3019 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3021 printf("<option $is_selected value='%d'>%s</option>",
3022 $line["id"], $title);
3028 function print_feed_cat_select($link, $id, $default_id = "",
3029 $attributes = "", $include_all_cats = true) {
3031 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3033 if ($include_all_cats) {
3034 print "<option value=\"0\">".__('Uncategorized')."</option>";
3037 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3038 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3040 if (db_num_rows($result) > 0 && $include_all_cats) {
3041 print "<option disabled=\"1\">--------</option>";
3044 while ($line = db_fetch_assoc($result)) {
3045 if ($line["id"] == $default_id) {
3046 $is_selected = "selected=\"1\"";
3052 printf("<option $is_selected value='%d'>%s</option>",
3053 $line["id"], htmlspecialchars($line["title"]));
3056 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3061 function checkbox_to_sql_bool($val) {
3062 return ($val == "on") ?
"true" : "false";
3065 function getFeedCatTitle($link, $id) {
3067 return __("Special");
3068 } else if ($id < -10) {
3069 return __("Labels");
3070 } else if ($id > 0) {
3071 $result = db_query($link, "SELECT ttrss_feed_categories.title
3072 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3073 cat_id = ttrss_feed_categories.id");
3074 if (db_num_rows($result) == 1) {
3075 return db_fetch_result($result, 0, "title");
3077 return __("Uncategorized");
3080 return "getFeedCatTitle($id) failed";
3085 function getFeedIcon($id) {
3088 return "images/archive.png";
3091 return "images/mark_set.png";
3094 return "images/pub_set.png";
3097 return "images/fresh.png";
3100 return "images/tag.png";
3104 return "images/label.png";
3106 if (file_exists(ICONS_DIR
. "/$id.ico"))
3107 return ICONS_URL
. "/$id.ico";
3113 function getFeedTitle($link, $id) {
3115 return __("Starred articles");
3116 } else if ($id == -2) {
3117 return __("Published articles");
3118 } else if ($id == -3) {
3119 return __("Fresh articles");
3120 } else if ($id == -4) {
3121 return __("All articles");
3122 } else if ($id === 0 ||
$id === "0") {
3123 return __("Archived articles");
3124 } else if ($id < -10) {
3125 $label_id = -$id - 11;
3126 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3127 if (db_num_rows($result) == 1) {
3128 return db_fetch_result($result, 0, "caption");
3130 return "Unknown label ($label_id)";
3133 } else if (is_numeric($id) && $id > 0) {
3134 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3135 if (db_num_rows($result) == 1) {
3136 return db_fetch_result($result, 0, "title");
3138 return "Unknown feed ($id)";
3145 function make_init_params($link) {
3148 $params["theme"] = get_user_theme($link);
3149 $params["theme_options"] = get_user_theme_options($link);
3151 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3152 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3153 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3154 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3156 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3157 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3158 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3159 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3161 $params[strtolower($param)] = (int) get_pref($link, $param);
3164 $params["icons_url"] = ICONS_URL
;
3165 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3166 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3167 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3168 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3169 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3171 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3172 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3174 $max_feed_id = db_fetch_result($result, 0, "mid");
3175 $num_feeds = db_fetch_result($result, 0, "nf");
3177 $params["max_feed_id"] = (int) $max_feed_id;
3178 $params["num_feeds"] = (int) $num_feeds;
3180 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3185 function make_runtime_info($link) {
3188 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3189 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3191 $max_feed_id = db_fetch_result($result, 0, "mid");
3192 $num_feeds = db_fetch_result($result, 0, "nf");
3194 $data["max_feed_id"] = (int) $max_feed_id;
3195 $data["num_feeds"] = (int) $num_feeds;
3197 $data['last_article_id'] = getLastArticleId($link);
3198 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3200 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
3202 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3204 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3206 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3209 $stamp_delta = time() - $stamp;
3211 if ($stamp_delta > 1800) {
3215 $_SESSION["daemon_stamp_check"] = time();
3218 $data['daemon_stamp_ok'] = $stamp_check;
3220 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3222 $data['daemon_stamp'] = $stamp_fmt;
3227 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3228 $new_version_details = @check_for_update
($link);
3230 $data['new_version_available'] = (int) ($new_version_details != false);
3232 $_SESSION["last_version_check"] = time();
3238 function search_to_sql($link, $search, $match_on) {
3240 $search_query_part = "";
3242 $keywords = explode(" ", $search);
3243 $query_keywords = array();
3245 foreach ($keywords as $k) {
3246 if (strpos($k, "-") === 0) {
3253 $commandpair = explode(":", mb_strtolower($k), 2);
3255 if ($commandpair[0] == "note" && $commandpair[1]) {
3257 if ($commandpair[1] == "true")
3258 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3260 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3262 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3264 if ($commandpair[1] == "true")
3265 array_push($query_keywords, "($not (marked = true))");
3267 array_push($query_keywords, "($not (marked = false))");
3269 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3271 if ($commandpair[1] == "true")
3272 array_push($query_keywords, "($not (published = true))");
3274 array_push($query_keywords, "($not (published = false))");
3276 } else if (strpos($k, "@") === 0) {
3278 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3279 $orig_ts = strtotime(substr($k, 1));
3280 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3282 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3284 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3285 } else if ($match_on == "both") {
3286 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3287 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3288 } else if ($match_on == "title") {
3289 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3290 } else if ($match_on == "content") {
3291 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3295 $search_query_part = implode("AND", $query_keywords);
3297 return $search_query_part;
3301 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
3303 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3305 $ext_tables_part = "";
3309 if (SPHINX_ENABLED
) {
3310 $ids = join(",", @sphinx_search
($search, 0, 500));
3313 $search_query_part = "ref_id IN ($ids) AND ";
3315 $search_query_part = "ref_id = -1 AND ";
3318 $search_query_part = search_to_sql($link, $search, $match_on);
3319 $search_query_part .= " AND ";
3323 $search_query_part = "";
3327 $filter_query_part = filter_to_sql($filter);
3329 $filter_query_part = "";
3333 $since_id_part = "ttrss_entries.id > $since_id AND ";
3335 $since_id_part = "";
3338 $view_query_part = "";
3340 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3342 $view_query_part = " ";
3343 } else if ($feed != -1) {
3344 $unread = getFeedUnread($link, $feed, $cat_view);
3346 $view_query_part = " unread = true AND ";
3351 if ($view_mode == "marked") {
3352 $view_query_part = " marked = true AND ";
3355 if ($view_mode == "published") {
3356 $view_query_part = " published = true AND ";
3359 if ($view_mode == "unread") {
3360 $view_query_part = " unread = true AND ";
3363 if ($view_mode == "updated") {
3364 $view_query_part = " (last_read is null and unread = false) AND ";
3368 $limit_query_part = "LIMIT " . $limit;
3371 $vfeed_query_part = "";
3373 // override query strategy and enable feed display when searching globally
3374 if ($search && $search_mode == "all_feeds") {
3375 $query_strategy_part = "ttrss_entries.id > 0";
3376 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3378 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3379 $query_strategy_part = "ttrss_entries.id > 0";
3380 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3381 id = feed_id) as feed_title,";
3382 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3384 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3386 $tmp_result = false;
3389 $tmp_result = db_query($link, "SELECT id
3390 FROM ttrss_feeds WHERE cat_id = '$feed'");
3392 $tmp_result = db_query($link, "SELECT id
3393 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3394 WHERE id = '$feed') AND id != '$feed'");
3397 $cat_siblings = array();
3399 if (db_num_rows($tmp_result) > 0) {
3400 while ($p = db_fetch_assoc($tmp_result)) {
3401 array_push($cat_siblings, "feed_id = " . $p["id"]);
3404 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3405 $feed, implode(" OR ", $cat_siblings));
3408 $query_strategy_part = "ttrss_entries.id > 0";
3411 } else if ($feed > 0) {
3416 $query_strategy_part = "cat_id = '$feed'";
3418 $query_strategy_part = "cat_id IS NULL";
3421 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3424 $query_strategy_part = "feed_id = '$feed'";
3426 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3427 $query_strategy_part = "feed_id IS NULL";
3428 } else if ($feed == 0 && $cat_view) { // uncategorized
3429 $query_strategy_part = "cat_id IS NULL";
3430 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3431 } else if ($feed == -1) { // starred virtual feed
3432 $query_strategy_part = "marked = true";
3433 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3434 } else if ($feed == -2) { // published virtual feed OR labels category
3437 $query_strategy_part = "published = true";
3438 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3440 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3442 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3444 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3445 ttrss_user_labels2.article_id = ref_id";
3449 } else if ($feed == -3) { // fresh virtual feed
3450 $query_strategy_part = "unread = true AND score >= 0";
3452 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3454 if (DB_TYPE
== "pgsql") {
3455 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3457 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3460 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3461 } else if ($feed == -4) { // all articles virtual feed
3462 $query_strategy_part = "true";
3463 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3464 } else if ($feed <= -10) { // labels
3465 $label_id = -$feed - 11;
3467 $query_strategy_part = "label_id = '$label_id' AND
3468 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3469 ttrss_user_labels2.article_id = ref_id";
3471 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3472 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3475 $query_strategy_part = "id > 0"; // dumb
3478 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3479 $date_sort_field = "updated";
3481 $date_sort_field = "date_entered";
3484 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3485 $order_by = "$date_sort_field";
3487 $order_by = "$date_sort_field DESC";
3490 if ($view_mode != "noscores") {
3491 $order_by = "score DESC, $order_by";
3494 if ($override_order) {
3495 $order_by = $override_order;
3501 $feed_title = "Search results";
3504 $feed_title = getCategoryTitle($link, $feed);
3506 if (is_numeric($feed) && $feed > 0) {
3507 $result = db_query($link, "SELECT title,site_url,last_error
3508 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3510 $feed_title = db_fetch_result($result, 0, "title");
3511 $feed_site_url = db_fetch_result($result, 0, "site_url");
3512 $last_error = db_fetch_result($result, 0, "last_error");
3514 $feed_title = getFeedTitle($link, $feed);
3519 $content_query_part = "content as content_preview,";
3521 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3524 $feed_kind = "Feeds";
3526 $feed_kind = "Labels";
3529 if ($limit_query_part) {
3530 $offset_query_part = "OFFSET $offset";
3533 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3534 if (!$override_order) {
3535 $order_by = "ttrss_feeds.title, $order_by";
3540 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3541 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3544 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3545 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3548 $query = "SELECT DISTINCT
3551 ttrss_entries.id,ttrss_entries.title,
3555 always_display_enclosures,
3561 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3562 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3565 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3571 ttrss_user_entries.ref_id = ttrss_entries.id AND
3572 ttrss_user_entries.owner_uid = '$owner_uid' AND
3577 $query_strategy_part ORDER BY $order_by
3578 $limit_query_part $offset_query_part";
3580 if ($_REQUEST["debug"]) print $query;
3582 $result = db_query($link, $query);
3587 $select_qpart = "SELECT DISTINCT " .
3591 "ttrss_entries.id as id," .
3598 "always_display_enclosures, ".
3606 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
3609 $content_query_part .
3610 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
3613 $feed_kind = "Tags";
3614 $all_tags = explode(",", $feed);
3615 if ($search_mode == 'any') {
3616 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3617 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3618 $where_qpart = " WHERE " .
3619 "ref_id = ttrss_entries.id AND " .
3620 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3621 "post_int_id = int_id AND $tag_sql AND " .
3623 $search_query_part .
3624 $query_strategy_part . " ORDER BY $order_by " .
3629 $sub_selects = array();
3630 $sub_ands = array();
3631 foreach ($all_tags as $term) {
3632 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
3639 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3644 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3645 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3646 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3647 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3649 // error_log("TAG SQL: " . $tag_sql);
3650 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3652 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3653 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
3656 return array($result, $feed_title, $feed_site_url, $last_error);
3660 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3661 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3663 require_once "lib/MiniTemplator.class.php";
3665 $note_style = "background-color : #fff7d5;
3666 border-width : 1px; ".
3667 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3668 "margin-bottom : 1em; color : #9a8c59;";
3670 if (!$limit) $limit = 30;
3672 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3673 $date_sort_field = "updated";
3675 $date_sort_field = "date_entered";
3678 $qfh_ret = queryFeedHeadlines($link, $feed,
3679 $limit, $view_mode, $is_cat, $search, $search_mode,
3680 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3682 $result = $qfh_ret[0];
3683 $feed_title = htmlspecialchars($qfh_ret[1]);
3684 $feed_site_url = $qfh_ret[2];
3685 $last_error = $qfh_ret[3];
3687 $feed_self_url = get_self_url_prefix() .
3688 "/public.php?op=rss&id=-2&key=" .
3689 get_feed_access_key($link, -2, false);
3691 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3693 $tpl = new MiniTemplator
;
3695 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3697 $tpl->setVariable('FEED_TITLE', $feed_title);
3698 $tpl->setVariable('VERSION', VERSION
);
3699 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3701 if (PUBSUBHUBBUB_HUB
&& $feed == -2) {
3702 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB
));
3703 $tpl->addBlock('feed_hub');
3706 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3708 while ($line = db_fetch_assoc($result)) {
3709 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3710 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3711 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3712 $tpl->setVariable('ARTICLE_EXCERPT',
3713 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3715 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3717 if ($line['note']) {
3718 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
3722 $tpl->setVariable('ARTICLE_CONTENT', $content);
3724 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3725 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3727 $tags = get_article_tags($link, $line["id"], $owner_uid);
3729 foreach ($tags as $tag) {
3730 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3731 $tpl->addBlock('category');
3734 $enclosures = get_article_enclosures($link, $line["id"]);
3736 foreach ($enclosures as $e) {
3737 $type = htmlspecialchars($e['content_type']);
3738 $url = htmlspecialchars($e['content_url']);
3739 $length = $e['duration'];
3741 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3742 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3743 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3745 $tpl->addBlock('enclosure');
3748 $tpl->addBlock('entry');
3753 $tpl->addBlock('feed');
3754 $tpl->generateOutputToString($tmp);
3759 function getCategoryTitle($link, $cat_id) {
3761 if ($cat_id == -1) {
3762 return __("Special");
3763 } else if ($cat_id == -2) {
3764 return __("Labels");
3767 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3770 if (db_num_rows($result) == 1) {
3771 return db_fetch_result($result, 0, "title");
3773 return "Uncategorized";
3778 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3781 if (!$owner) $owner = $_SESSION["uid"];
3783 $res = trim($str); if (!$res) return '';
3785 // if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3786 $res = $purifier->purify($res);
3789 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3790 $res = preg_replace('/<img[^>]+>/is', '', $res);
3793 if (strpos($res, "href=") === false)
3794 $res = rewrite_urls($res);
3796 $charset_hack = '<head>
3797 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3800 $res = trim($res); if (!$res) return '';
3802 libxml_use_internal_errors(true);
3804 $doc = new DOMDocument();
3805 $doc->loadHTML($charset_hack . $res);
3806 $xpath = new DOMXPath($doc);
3808 $entries = $xpath->query('(//a[@href]|//img[@src])');
3811 foreach ($entries as $entry) {
3815 if ($entry->hasAttribute('href'))
3816 $entry->setAttribute('href',
3817 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3819 if ($entry->hasAttribute('src'))
3820 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3821 $entry->setAttribute('src',
3822 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3825 if (strtolower($entry->nodeName
) == "a") {
3826 $entry->setAttribute("target", "_blank");
3829 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3830 $br = $doc->createElement("br");
3832 if ($entry->parentNode
->nextSibling
) {
3833 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3840 $node = $doc->getElementsByTagName('body')->item(0);
3842 return $doc->saveXML($node);
3846 * Send by mail a digest of last articles.
3848 * @param mixed $link The database connection.
3849 * @param integer $limit The maximum number of articles by digest.
3850 * @return boolean Return false if digests are not enabled.
3852 function send_headlines_digests($link, $limit = 100) {
3854 if (!DIGEST_ENABLE
) return false;
3856 $user_limit = DIGEST_EMAIL_LIMIT
;
3859 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3861 if (DB_TYPE
== "pgsql") {
3862 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3863 } else if (DB_TYPE
== "mysql") {
3864 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3867 $result = db_query($link, "SELECT id,email FROM ttrss_users
3868 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3870 while ($line = db_fetch_assoc($result)) {
3872 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3873 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3875 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3877 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3878 $digest = $tuple[0];
3879 $headlines_count = $tuple[1];
3880 $affected_ids = $tuple[2];
3881 $digest_text = $tuple[3];
3883 if ($headlines_count > 0) {
3885 $mail = new PHPMailer();
3887 $mail->PluginDir
= "lib/phpmailer/";
3888 $mail->SetLanguage("en", "lib/phpmailer/language/");
3890 $mail->CharSet
= "UTF-8";
3892 $mail->From
= DIGEST_FROM_ADDRESS
;
3893 $mail->FromName
= DIGEST_FROM_NAME
;
3894 $mail->AddAddress($line["email"], $line["login"]);
3896 if (DIGEST_SMTP_HOST
) {
3897 $mail->Host
= DIGEST_SMTP_HOST
;
3898 $mail->Mailer
= "smtp";
3899 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3900 $mail->Username
= DIGEST_SMTP_LOGIN
;
3901 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3904 $mail->IsHTML(true);
3905 $mail->Subject
= DIGEST_SUBJECT
;
3906 $mail->Body
= $digest;
3907 $mail->AltBody
= $digest_text;
3909 $rc = $mail->Send();
3911 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3915 if ($rc && $do_catchup) {
3916 print "Marking affected articles as read...\n";
3917 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3920 print "No headlines\n";
3923 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3924 WHERE id = " . $line["id"]);
3928 print "All done.\n";
3932 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3934 require_once "lib/MiniTemplator.class.php";
3936 $tpl = new MiniTemplator
;
3937 $tpl_t = new MiniTemplator
;
3939 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3940 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3942 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3943 $tpl->setVariable('CUR_TIME', date('G:i'));
3945 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3946 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3948 $affected_ids = array();
3950 if (DB_TYPE
== "pgsql") {
3951 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3952 } else if (DB_TYPE
== "mysql") {
3953 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3956 $result = db_query($link, "SELECT ttrss_entries.title,
3957 ttrss_feeds.title AS feed_title,
3959 ttrss_user_entries.ref_id,
3961 SUBSTRING(content, 1, 120) AS excerpt,
3962 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3964 ttrss_user_entries,ttrss_entries,ttrss_feeds
3966 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3967 AND include_in_digest = true
3969 AND ttrss_user_entries.owner_uid = $user_id
3971 ORDER BY ttrss_feeds.title, date_updated DESC
3974 $cur_feed_title = "";
3976 $headlines_count = db_num_rows($result);
3978 $headlines = array();
3980 while ($line = db_fetch_assoc($result)) {
3981 array_push($headlines, $line);
3984 for ($i = 0; $i < sizeof($headlines); $i++
) {
3986 $line = $headlines[$i];
3988 array_push($affected_ids, $line["ref_id"]);
3990 $updated = make_local_datetime($link, $line['last_updated'], false,
3993 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3994 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3995 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3996 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3997 $tpl->setVariable('ARTICLE_EXCERPT',
3998 truncate_string(strip_tags($line["excerpt"]), 100));
4000 $tpl->addBlock('article');
4002 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
4003 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4004 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4005 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4006 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4007 // truncate_string(strip_tags($line["excerpt"]), 100));
4009 $tpl_t->addBlock('article');
4011 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
4012 $tpl->addBlock('feed');
4013 $tpl_t->addBlock('feed');
4018 $tpl->addBlock('digest');
4019 $tpl->generateOutputToString($tmp);
4021 $tpl_t->addBlock('digest');
4022 $tpl_t->generateOutputToString($tmp_t);
4024 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4027 function check_for_update($link) {
4028 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
4029 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
4031 $version_data = @fetch_file_contents
($version_url);
4033 if ($version_data) {
4034 $version_data = json_decode($version_data, true);
4035 if ($version_data && $version_data['version']) {
4037 if (version_compare(VERSION
, $version_data['version']) == -1) {
4038 return $version_data;
4046 function markArticlesById($link, $ids, $cmode) {
4050 foreach ($ids as $id) {
4051 array_push($tmp_ids, "ref_id = '$id'");
4054 $ids_qpart = join(" OR ", $tmp_ids);
4057 db_query($link, "UPDATE ttrss_user_entries SET
4058 marked = false,last_read = NOW()
4059 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4060 } else if ($cmode == 1) {
4061 db_query($link, "UPDATE ttrss_user_entries SET
4063 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4065 db_query($link, "UPDATE ttrss_user_entries SET
4066 marked = NOT marked,last_read = NOW()
4067 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4071 function publishArticlesById($link, $ids, $cmode) {
4075 foreach ($ids as $id) {
4076 array_push($tmp_ids, "ref_id = '$id'");
4079 $ids_qpart = join(" OR ", $tmp_ids);
4082 db_query($link, "UPDATE ttrss_user_entries SET
4083 published = false,last_read = NOW()
4084 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4085 } else if ($cmode == 1) {
4086 db_query($link, "UPDATE ttrss_user_entries SET
4088 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4090 db_query($link, "UPDATE ttrss_user_entries SET
4091 published = NOT published,last_read = NOW()
4092 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4095 if (PUBSUBHUBBUB_HUB
) {
4096 $rss_link = get_self_url_prefix() .
4097 "/public.php?op=rss&id=-2&key=" .
4098 get_feed_access_key($link, -2, false);
4100 $p = new Publisher(PUBSUBHUBBUB_HUB
);
4102 $pubsub_result = $p->publish_update($rss_link);
4106 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4108 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4109 if (count($ids) == 0) return;
4113 foreach ($ids as $id) {
4114 array_push($tmp_ids, "ref_id = '$id'");
4117 $ids_qpart = join(" OR ", $tmp_ids);
4120 db_query($link, "UPDATE ttrss_user_entries SET
4121 unread = false,last_read = NOW()
4122 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4123 } else if ($cmode == 1) {
4124 db_query($link, "UPDATE ttrss_user_entries SET
4126 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4128 db_query($link, "UPDATE ttrss_user_entries SET
4129 unread = NOT unread,last_read = NOW()
4130 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4135 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4136 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4138 while ($line = db_fetch_assoc($result)) {
4139 ccache_update($link, $line["feed_id"], $owner_uid);
4143 function catchupArticleById($link, $id, $cmode) {
4146 db_query($link, "UPDATE ttrss_user_entries SET
4147 unread = false,last_read = NOW()
4148 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4149 } else if ($cmode == 1) {
4150 db_query($link, "UPDATE ttrss_user_entries SET
4152 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4154 db_query($link, "UPDATE ttrss_user_entries SET
4155 unread = NOT unread,last_read = NOW()
4156 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4159 $feed_id = getArticleFeed($link, $id);
4160 ccache_update($link, $feed_id, $_SESSION["uid"]);
4163 function make_guid_from_title($title) {
4164 return preg_replace("/[ \"\',.:;]/", "-",
4165 mb_strtolower(strip_tags($title), 'utf-8'));
4168 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4169 $feed_id, $is_cat, $search, $match_on,
4170 $search_mode, $view_mode, $error) {
4172 $page_prev_link = "viewFeedGoPage(-1)";
4173 $page_next_link = "viewFeedGoPage(1)";
4174 $page_first_link = "viewFeedGoPage(0)";
4176 $catchup_page_link = "catchupPage()";
4177 $catchup_feed_link = "catchupCurrentFeed()";
4178 $catchup_sel_link = "catchupSelection()";
4180 $archive_sel_link = "archiveSelection()";
4181 $delete_sel_link = "deleteSelection()";
4183 $sel_all_link = "selectArticles('all')";
4184 $sel_unread_link = "selectArticles('unread')";
4185 $sel_none_link = "selectArticles('none')";
4186 $sel_inv_link = "selectArticles('invert')";
4188 $tog_unread_link = "selectionToggleUnread()";
4189 $tog_marked_link = "selectionToggleMarked()";
4190 $tog_published_link = "selectionTogglePublished()";
4192 $reply = "<div id=\"subtoolbar_main\">";
4194 $reply .= __('Select:')."
4195 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4196 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4197 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4198 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4202 $reply .= "<select dojoType=\"dijit.form.Select\"
4203 onchange=\"headlineActionsChange(this)\">";
4204 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4206 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4208 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4209 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4210 <option value=\"$tog_published_link\">".__('Published')."</option>";
4212 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4214 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4216 if ($feed_id != "0") {
4217 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4219 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4220 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4224 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4227 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4230 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4235 $rss_link = htmlspecialchars(get_self_url_prefix() .
4236 "/public.php?op=rss&id=$feed_id$cat_q$search_q");
4238 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4240 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4242 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4244 $reply .= "</select>";
4248 $reply .= "<div id=\"subtoolbar_ftitle\">";
4250 if ($feed_site_url) {
4251 $target = "target=\"_blank\"";
4252 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4253 truncate_string($feed_title,30)."</a>";
4256 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4260 if ($feed_id < -10) {
4261 $label_id = -11-$feed_id;
4263 $result = db_query($link, "SELECT fg_color, bg_color
4264 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4267 if (db_num_rows($result) != 0) {
4268 $fg_color = db_fetch_result($result, 0, "fg_color");
4269 $bg_color = db_fetch_result($result, 0, "bg_color");
4271 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
4272 $reply .= $feed_title;
4273 $reply .= "</span>";
4275 $reply .= $feed_title;
4279 $reply .= $feed_title;
4285 title=\"".__("View as RSS feed")."\"
4286 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4287 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4294 function outputFeedList($link, $special = true) {
4296 $feedlist = array();
4298 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4300 $feedlist['identifier'] = 'id';
4301 $feedlist['label'] = 'name';
4302 $feedlist['items'] = array();
4304 $owner_uid = $_SESSION["uid"];
4311 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4312 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4314 $cat['items'] = array();
4317 foreach (array(-4, -3, -1, -2, 0) as $i) {
4318 array_push($cat['items'], feedlist_init_feed($link, $i));
4322 array_push($feedlist['items'], $cat);
4324 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4327 $result = db_query($link, "SELECT * FROM
4328 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4330 if (db_num_rows($result) > 0) {
4332 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4333 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4334 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4336 $cat['items'] = array();
4339 while ($line = db_fetch_assoc($result)) {
4341 $label_id = -$line['id'] - 11;
4342 $count = getFeedUnread($link, $label_id);
4344 $feed = feedlist_init_feed($link, $label_id, false, $count);
4346 $feed['fg_color'] = $line['fg_color'];
4347 $feed['bg_color'] = $line['bg_color'];
4349 array_push($cat['items'], $feed);
4353 array_push($feedlist['items'], $cat);
4355 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4360 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4361 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4362 $order_by_qpart = "order_id,category,unread DESC,title";
4364 $order_by_qpart = "order_id,category,title";
4367 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4368 $order_by_qpart = "unread DESC,title";
4370 $order_by_qpart = "title";
4377 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4378 ttrss_feeds.order_id,title";
4380 $order_by_qpart = "title";
4382 $age_qpart = getMaxAgeSubquery();
4384 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4385 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4387 ttrss_feed_categories.title AS category,
4388 ttrss_feed_categories.collapsed,
4390 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4391 ON (ttrss_feed_categories.id = cat_id)
4392 LEFT JOIN ttrss_counters_cache
4394 (ttrss_feeds.id = feed_id)
4396 ttrss_feeds.owner_uid = '$owner_uid'
4397 ORDER BY $order_by_qpart";
4399 $result = db_query($link, $query);
4401 $actid = $_REQUEST["actid"];
4403 if (db_num_rows($result) > 0) {
4408 $cat['items'] = array();
4412 while ($line = db_fetch_assoc($result)) {
4414 $feed = htmlspecialchars(trim($line["title"]));
4416 if (!$feed) $feed = "[Untitled]";
4418 $feed_id = $line["id"];
4419 $unread = $line["unread"];
4421 $cat_id = $line["cat_id"];
4422 $tmp_category = $line["category"];
4423 if (!$tmp_category) $tmp_category = __("Uncategorized");
4425 if ($category != $tmp_category && $enable_cats) {
4427 $category = $tmp_category;
4429 $collapsed = sql_bool_to_bool($line["collapsed"]);
4431 // workaround for NULL category
4432 if ($category == __("Uncategorized")) {
4433 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4436 if ($cat) array_push($feedlist['items'], $cat);
4438 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4441 $updated = make_local_datetime($link, $line["updated_noms"], false);
4443 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4444 $feed, $unread, $line['last_error'], $updated));
4448 array_push($feedlist['items'], $cat);
4450 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4458 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
4462 $a_id = db_escape_string($id);
4464 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4466 $query = "SELECT DISTINCT tag_name,
4467 owner_uid as owner FROM
4468 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4469 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4471 $obj_id = md5("TAGS:$owner_uid:$id");
4474 if ($memcache && $obj = $memcache->get($obj_id)) {
4477 /* check cache first */
4479 if ($tag_cache === false) {
4480 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4481 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4483 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4487 $tags = explode(",", $tag_cache);
4490 /* do it the hard way */
4492 $tmp_result = db_query($link, $query);
4494 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4495 array_push($tags, $tmp_line["tag_name"]);
4498 /* update the cache */
4500 $tags_str = db_escape_string(join(",", $tags));
4502 db_query($link, "UPDATE ttrss_user_entries
4503 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4504 AND owner_uid = " . $_SESSION["uid"]);
4507 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4513 function trim_array($array) {
4515 array_walk($tmp, 'trim');
4519 function tag_is_valid($tag) {
4520 if ($tag == '') return false;
4521 if (preg_match("/^[0-9]*$/", $tag)) return false;
4522 if (mb_strlen($tag) > 250) return false;
4524 if (function_exists('iconv')) {
4525 $tag = iconv("utf-8", "utf-8", $tag);
4528 if (!$tag) return false;
4533 function render_login_form($link, $mobile = 0) {
4536 require_once "login_form.php";
4539 require_once "mobile/login_form.php";
4542 require_once "mobile/classic/login_form.php";
4546 // from http://developer.apple.com/internet/safari/faq.html
4547 function no_cache_incantation() {
4548 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4549 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4550 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4551 header("Cache-Control: post-check=0, pre-check=0", false);
4552 header("Pragma: no-cache"); // HTTP/1.0
4555 function format_warning($msg, $id = "") {
4557 return "<div class=\"warning\" id=\"$id\">
4558 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4561 function format_notice($msg, $id = "") {
4563 return "<div class=\"notice\" id=\"$id\">
4564 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4567 function format_error($msg, $id = "") {
4569 return "<div class=\"error\" id=\"$id\">
4570 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4573 function print_notice($msg) {
4574 return print format_notice($msg);
4577 function print_warning($msg) {
4578 return print format_warning($msg);
4581 function print_error($msg) {
4582 return print format_error($msg);
4586 function T_sprintf() {
4587 $args = func_get_args();
4588 return vsprintf(__(array_shift($args)), $args);
4591 function format_inline_player($link, $url, $ctype) {
4595 if (strpos($ctype, "audio/") === 0) {
4597 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4598 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4599 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4601 $id = 'AUDIO-' . uniqid();
4603 $entry .= "<audio id=\"$id\"\">
4604 <source src=\"$url\"></source>
4607 $entry .= "<span onclick=\"player(this)\"
4608 title=\"".__("Click to play")."\" status=\"0\"
4609 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4613 $entry .= "<object type=\"application/x-shockwave-flash\"
4614 data=\"lib/button/musicplayer.swf?song_url=$url\"
4615 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4616 <param name=\"movie\"
4617 value=\"lib/button/musicplayer.swf?song_url=$url\" />
4622 $filename = substr($url, strrpos($url, "/")+
1);
4624 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4625 $filename . " (" . $ctype . ")" . "</a>";
4630 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
4636 /* we can figure out feed_id from article id anyway, why do we
4637 * pass feed_id here? let's ignore the argument :( */
4639 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4640 WHERE ref_id = '$id'");
4642 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4644 $rv['feed_id'] = $feed_id;
4646 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4648 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4649 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4651 if (db_num_rows($result) == 1) {
4652 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4653 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4655 $rtl_content = false;
4656 $always_display_enclosures = false;
4660 $rtl_tag = "dir=\"RTL\"";
4667 if ($mark_as_read) {
4668 $result = db_query($link, "UPDATE ttrss_user_entries
4669 SET unread = false,last_read = NOW()
4670 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4672 ccache_update($link, $feed_id, $_SESSION["uid"]);
4675 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4676 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4677 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4678 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4684 FROM ttrss_entries,ttrss_user_entries
4685 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4689 $line = db_fetch_assoc($result);
4691 if ($line["icon_url"]) {
4692 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4694 $feed_icon = " ";
4697 $feed_site_url = $line['site_url'];
4699 $num_comments = $line["num_comments"];
4700 $entry_comments = "";
4702 if ($num_comments > 0) {
4703 if ($line["comments"]) {
4704 $comments_url = $line["comments"];
4706 $comments_url = $line["link"];
4708 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4710 if ($line["comments"] && $line["link"] != $line["comments"]) {
4711 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4716 header("Content-Type: text/html");
4717 $rv['content'] .= "<html><head>
4718 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4719 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4720 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4724 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4725 truncate_string(strip_tags($line['title']), 15) . "</div>";
4727 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4729 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4730 class=\"postHeader\" id=\"POSTHDR-$id\">";
4732 $entry_author = $line["author"];
4734 if ($entry_author) {
4735 $entry_author = __(" - ") . $entry_author;
4738 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4741 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4743 if ($line["link"]) {
4744 $rv['content'] .= "<div clear='both'><a target='_blank'
4745 title=\"".htmlspecialchars($line['title'])."\"
4747 $line["link"] . "\">" .
4748 truncate_string($line["title"], 100) .
4749 "<span class='author'>$entry_author</span></a></div>";
4751 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4754 $tag_cache = $line["tag_cache"];
4757 $tags = get_article_tags($link, $id);
4759 $tags = explode(",", $tag_cache);
4761 $tags_str = format_tags_string($tags, $id);
4762 $tags_str_full = join(", ", $tags);
4764 if (!$tags_str_full) $tags_str_full = __("no tags");
4766 if (!$entry_comments) $entry_comments = " "; # placeholder
4768 $rv['content'] .= "<div style='float : right'>
4769 <img src='".theme_image($link, 'images/tag.png')."'
4770 class='tagsPic' alt='Tags' title='Tags'> ";
4773 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4774 <a title=\"".__('Edit tags for this article')."\"
4775 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4777 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4778 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4779 position=\"below\">$tags_str_full</div>";
4781 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4782 class='tagsPic' style=\"cursor : pointer\"
4783 onclick=\"postOpenInNewTab(event, $id)\"
4784 alt='Zoom' title='".__('Open article in new tab')."'>";
4786 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4788 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4789 class='tagsPic' style=\"cursor : pointer\"
4790 onclick=\"editArticleNote($id)\"
4791 alt='PubNote' title='".__('Edit article note')."'>";
4793 if (DIGEST_ENABLE
) {
4794 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4795 class='tagsPic' style=\"cursor : pointer\"
4796 onclick=\"emailArticle($id)\"
4797 alt='Zoom' title='".__('Forward by email')."'>";
4800 if (ENABLE_TWEET_BUTTON
) {
4801 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4802 class='tagsPic' style=\"cursor : pointer\"
4803 onclick=\"tweetArticle($id)\"
4804 alt='Zoom' title='".__('Share on Twitter')."'>";
4807 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
4808 class='tagsPic' style=\"cursor : pointer\"
4809 onclick=\"shareArticle(".$line['int_id'].")\"
4810 alt='Zoom' title='".__('Share by URL')."'>";
4812 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4813 class='tagsPic' style=\"cursor : pointer\"
4814 onclick=\"closeArticlePanel($id)\"
4815 alt='Zoom' title='".__('Close this panel')."'>";
4818 $tags_str = strip_tags($tags_str);
4819 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4821 $rv['content'] .= "</div>";
4822 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4824 if ($line["orig_feed_id"]) {
4826 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4827 WHERE id = ".$line["orig_feed_id"]);
4829 if (db_num_rows($tmp_result) != 0) {
4831 $rv['content'] .= "<div clear='both'>";
4832 $rv['content'] .= __("Originally from:");
4834 $rv['content'] .= " ";
4836 $tmp_line = db_fetch_assoc($tmp_result);
4838 $rv['content'] .= "<a target='_blank'
4839 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4840 $tmp_line['title'] . "</a>";
4842 $rv['content'] .= " ";
4844 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4845 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4847 $rv['content'] .= "</div>";
4851 $rv['content'] .= "</div>";
4853 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4854 if ($line['note']) {
4855 $rv['content'] .= format_article_note($id, $line['note']);
4857 $rv['content'] .= "</div>";
4859 $rv['content'] .= "<div class=\"postIcon\">" .
4860 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4861 href=\"".htmlspecialchars($feed_site_url)."\">".
4862 $feed_icon . "</a></div>";
4864 $rv['content'] .= "<div class=\"postContent\">";
4866 $article_content = sanitize_rss($link, $line["content"], false, false,
4869 $rv['content'] .= $article_content;
4871 $rv['content'] .= format_article_enclosures($link, $id,
4872 $always_display_enclosures, $article_content);
4874 $rv['content'] .= "</div>";
4876 $rv['content'] .= "</div>";
4882 <div style=\"text-align : center\">
4883 <button onclick=\"return window.close()\">".
4884 __("Close this window")."</button></div>";
4885 $rv['content'] .= "</body></html>";
4892 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4893 $next_unread_feed, $offset, $vgr_last_feed = false,
4894 $override_order = false) {
4896 $disable_cache = false;
4900 $timing_info = getmicrotime();
4902 $topmost_article_ids = array();
4904 if (!$offset) $offset = 0;
4905 if ($subop == "undefined") $subop = "";
4907 $subop_split = explode(":", $subop);
4909 /* if ($subop == "CatchupSelected") {
4910 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
4911 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4913 catchupArticlesById($link, $ids, $cmode);
4916 if ($subop == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
4917 update_rss_feed($link, $feed, true);
4920 if ($subop == "MarkAllRead") {
4921 catchup_feed($link, $feed, $cat_view);
4923 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4924 if ($next_unread_feed) {
4925 $feed = $next_unread_feed;
4930 if ($subop_split[0] == "MarkAllReadGR") {
4931 catchup_feed($link, $subop_split[1], false);
4934 // FIXME: might break tag display?
4936 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
4937 $result = db_query($link,
4938 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4940 if (db_num_rows($result) == 0) {
4941 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4945 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4947 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4948 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4950 if (db_num_rows($result) == 1) {
4951 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4953 $rtl_content = false;
4957 $rtl_tag = "dir=\"RTL\"";
4963 $rtl_content = false;
4966 @$search = db_escape_string($_REQUEST["query"]);
4969 $disable_cache = true;
4972 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4973 @$match_on = db_escape_string($_REQUEST["match_on"]);
4979 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4981 // error_log("format_headlines_list: [" . $feed . "] subop [" . $subop . "]");
4982 if( $search_mode == '' && $subop != '' ){
4983 $search_mode = $subop;
4985 // error_log("search_mode: " . $search_mode);
4986 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4987 $search, $search_mode, $match_on, $override_order, $offset);
4989 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4991 $result = $qfh_ret[0];
4992 $feed_title = $qfh_ret[1];
4993 $feed_site_url = $qfh_ret[2];
4994 $last_error = $qfh_ret[3];
4996 $vgroup_last_feed = $vgr_last_feed;
5000 if (db_num_rows($result) > 0) {
5001 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
5003 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5008 $headlines_count = db_num_rows($result);
5010 if (db_num_rows($result) > 0) {
5015 $cur_feed_title = '';
5017 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5019 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5021 while ($line = db_fetch_assoc($result)) {
5023 $class = ($lnum %
2) ?
"even" : "odd";
5026 $feed_id = $line["feed_id"];
5027 $label_cache = $line["label_cache"];
5031 $label_cache = json_decode($label_cache, true);
5034 if ($label_cache["no-labels"] == 1)
5037 $labels = $label_cache;
5041 if (!is_array($labels)) $labels = get_article_labels($link, $id);
5043 $labels_str = "<span id=\"HLLCTR-$id\">";
5044 $labels_str .= format_article_labels($labels, $id);
5045 $labels_str .= "</span>";
5047 if (count($topmost_article_ids) < 3) {
5048 array_push($topmost_article_ids, $id);
5051 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5053 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5054 theme_image($link, 'images/updated.png')."\"
5057 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5061 if (sql_bool_to_bool($line["unread"]) &&
5062 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5064 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5065 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5068 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5069 $class .= " Unread";
5076 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5077 $marked_pic = "<img id=\"FMPIC-$id\"
5078 src=\"".theme_image($link, 'images/mark_set.png')."\"
5079 class=\"markedPic\" alt=\"Unstar article\"
5080 onclick='javascript:toggleMark($id)'>";
5082 $marked_pic = "<img id=\"FMPIC-$id\"
5083 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5084 class=\"markedPic\" alt=\"Star article\"
5085 onclick='javascript:toggleMark($id)'>";
5088 if ($line["published"] == "t" ||
$line["published"] == "1") {
5089 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5090 'images/pub_set.png')."\"
5092 alt=\"Unpublish article\" onclick='javascript:togglePub($id)'>";
5094 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5095 'images/pub_unset.png')."\"
5097 alt=\"Publish article\" onclick='javascript:togglePub($id)'>";
5100 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5101 # $line["title"] . "</a>";
5103 # $content_link = "<a
5104 # href=\"" . htmlspecialchars($line["link"]) . "\"
5105 # onclick=\"view($id,$feed_id);\">" .
5106 # $line["title"] . "</a>";
5108 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5109 # $line["title"] . "</a>";
5111 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5113 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5114 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5118 $score = $line["score"];
5120 $score_pic = theme_image($link,
5121 "images/" . get_score_pic($score));
5123 /* $score_title = __("(Click to change)");
5124 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5125 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5127 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5132 } else if ($score < -100) {
5138 $entry_author = $line["author"];
5140 if ($entry_author) {
5141 $entry_author = " - $entry_author";
5144 $has_feed_icon = feed_has_icon($feed_id);
5146 if ($has_feed_icon) {
5147 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5149 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5152 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5154 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5155 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5157 $cur_feed_title = $line["feed_title"];
5158 $vgroup_last_feed = $feed_id;
5160 $cur_feed_title = htmlspecialchars($cur_feed_title);
5162 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5164 $reply['content'] .= "<div class='cdmFeedTitle'>".
5165 "<div style=\"float : right\">$feed_icon_img</div>".
5166 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5167 $line["feed_title"]."</a> $vf_catchup_link</div>";
5172 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5173 onmouseout='postMouseOut($id)'";
5175 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5177 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5179 $reply['content'] .= "<div class='hlLeft'>";
5181 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5184 $reply['content'] .= "$marked_pic";
5185 $reply['content'] .= "$published_pic";
5187 $reply['content'] .= "</div>";
5189 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5190 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5191 $reply['content'] .= "<a id=\"RTITLE-$id\"
5192 href=\"" . htmlspecialchars($line["link"]) . "\"
5194 truncate_string($line["title"], 200);
5196 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5197 if ($content_preview) {
5198 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5202 $reply['content'] .= "</a></span>";
5204 $reply['content'] .= $labels_str;
5206 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5207 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5208 if (@$line["feed_title"]) {
5209 $reply['content'] .= "<span class=\"hlFeed\">
5210 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5211 $line["feed_title"]."</a>)
5216 $reply['content'] .= "</div>";
5218 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5219 $reply['content'] .= "<div class=\"hlRight\">";
5221 $reply['content'] .= $score_pic;
5223 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5225 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5226 style=\"cursor : pointer\"
5227 title=\"".htmlspecialchars($line['feed_title'])."\">
5228 $feed_icon_img<span>";
5231 $reply['content'] .= "</div>";
5232 $reply['content'] .= "</div>";
5236 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5237 if ($feed_id != $vgroup_last_feed) {
5239 $cur_feed_title = $line["feed_title"];
5240 $vgroup_last_feed = $feed_id;
5242 $cur_feed_title = htmlspecialchars($cur_feed_title);
5244 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5246 $has_feed_icon = feed_has_icon($feed_id);
5248 if ($has_feed_icon) {
5249 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5251 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5254 $reply['content'] .= "<div class='cdmFeedTitle'>".
5255 "<div style=\"float : right\">$feed_icon_img</div>".
5256 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5257 $line["feed_title"]."</a> $vf_catchup_link</div>";
5261 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5263 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5264 onmouseout='postMouseOut($id)'";
5266 $reply['content'] .= "<div class=\"$class\"
5267 id=\"RROW-$id\" $mouseover_attrs'>";
5269 $reply['content'] .= "<div class=\"cdmHeader\">";
5271 $reply['content'] .= "<div>";
5273 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5274 'RROW-$id')\" id=\"RCHK-$id\"/>";
5276 $reply['content'] .= "$marked_pic";
5277 $reply['content'] .= "$published_pic";
5279 $reply['content'] .= "</div>";
5281 $reply['content'] .= "<span id=\"RTITLE-$id\"
5282 onclick=\"return cdmClicked(event, $id);\"
5283 class=\"titleWrap$hlc_suffix\">
5285 title=\"".htmlspecialchars($line['title'])."\"
5286 target=\"_blank\" href=\"".
5287 htmlspecialchars($line["link"])."\">".
5288 truncate_string($line["title"], 100) .
5289 " $entry_author</a>";
5291 $reply['content'] .= $labels_str;
5293 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5294 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5295 if (@$line["feed_title"]) {
5296 $reply['content'] .= "<span class=\"hlFeed\">
5297 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5298 $line["feed_title"]."</a>)
5304 $content_hidden = "style=\"display : none\"";
5306 $excerpt_hidden = "style=\"display : none\"";
5308 $reply['content'] .= "<span $excerpt_hidden
5309 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5311 $reply['content'] .= "</span>";
5313 $reply['content'] .= "<div>";
5314 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5315 $reply['content'] .= "$score_pic";
5317 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5318 $reply['content'] .= "<span style=\"cursor : pointer\"
5319 title=\"".htmlspecialchars($line["feed_title"])."\"
5320 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5322 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5323 $reply['content'] .= "</div>";
5325 $reply['content'] .= "</div>";
5327 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5328 onclick=\"return cdmClicked(event, $id);\"
5331 $reply['content'] .= "<div class=\"cdmContentInner\">";
5333 if ($line["orig_feed_id"]) {
5335 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5336 WHERE id = ".$line["orig_feed_id"]);
5338 if (db_num_rows($tmp_result) != 0) {
5340 $reply['content'] .= "<div clear='both'>";
5341 $reply['content'] .= __("Originally from:");
5343 $reply['content'] .= " ";
5345 $tmp_line = db_fetch_assoc($tmp_result);
5347 $reply['content'] .= "<a target='_blank'
5348 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5349 $tmp_line['title'] . "</a>";
5351 $reply['content'] .= " ";
5353 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5354 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5356 $reply['content'] .= "</div>";
5360 $feed_site_url = $line["site_url"];
5362 $article_content = sanitize_rss($link, $line["content_preview"],
5363 false, false, $feed_site_url);
5365 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5366 if ($line['note']) {
5367 $reply['content'] .= format_article_note($id, $line['note']);
5369 $reply['content'] .= "</div>";
5371 $reply['content'] .= "<span id=\"CWRAP-$id\">";
5372 $reply['content'] .= $expand_cdm ?
$article_content : '';
5373 $reply['content'] .= "</span>";
5375 /* $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5376 ttrss_feeds WHERE id = ".
5377 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
5378 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5380 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5381 0, "always_display_enclosures")); */
5383 $always_display_enclosures = sql_bool_to_bool($line["always_display_enclosures"]);
5385 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5388 $reply['content'] .= "</div>";
5390 $reply['content'] .= "<div class=\"cdmFooter\">";
5392 $tag_cache = $line["tag_cache"];
5394 $tags_str = format_tags_string(
5395 get_article_tags($link, $id, $_SESSION["uid"], $tag_cache),
5398 $reply['content'] .= "<img src='".theme_image($link,
5399 'images/tag.png')."' alt='Tags' title='Tags'>
5400 <span id=\"ATSTR-$id\">$tags_str</span>
5401 <a title=\"".__('Edit tags for this article')."\"
5402 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5404 $num_comments = $line["num_comments"];
5405 $entry_comments = "";
5407 if ($num_comments > 0) {
5408 if ($line["comments"]) {
5409 $comments_url = $line["comments"];
5411 $comments_url = $line["link"];
5413 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
5415 if ($line["comments"] && $line["link"] != $line["comments"]) {
5416 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
5420 if ($entry_comments) $reply['content'] .= " ($entry_comments)";
5422 $reply['content'] .= "<div style=\"float : right\">";
5424 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5425 onclick=\"zoomToArticle(event, $id)\"
5426 style=\"cursor : pointer\"
5428 title='".__('Open article in new tab')."'>";
5430 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5432 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5433 style=\"cursor : pointer\" style=\"cursor : pointer\"
5434 onclick=\"editArticleNote($id)\"
5435 alt='PubNote' title='".__('Edit article note')."'>";
5437 if (DIGEST_ENABLE
) {
5438 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5439 style=\"cursor : pointer\"
5440 onclick=\"emailArticle($id)\"
5441 alt='Zoom' title='".__('Forward by email')."'>";
5444 if (ENABLE_TWEET_BUTTON
) {
5445 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5446 class='tagsPic' style=\"cursor : pointer\"
5447 onclick=\"tweetArticle($id)\"
5448 alt='Zoom' title='".__('Share on Twitter')."'>";
5451 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
5452 class='tagsPic' style=\"cursor : pointer\"
5453 onclick=\"shareArticle(".$line['int_id'].")\"
5454 alt='Zoom' title='".__('Share by URL')."'>";
5456 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5457 style=\"cursor : pointer\" style=\"cursor : pointer\"
5458 onclick=\"dismissArticle($id)\"
5459 alt='Dismiss' title='".__('Dismiss article')."'>";
5461 $reply['content'] .= "</div>";
5462 $reply['content'] .= "</div>";
5464 $reply['content'] .= "</div>";
5466 $reply['content'] .= "</div>";
5473 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5478 switch ($view_mode) {
5480 $message = __("No unread articles found to display.");
5483 $message = __("No updated articles found to display.");
5486 $message = __("No starred articles found to display.");
5490 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5492 $message = __("No articles found to display.");
5496 if (!$offset && $message) {
5497 $reply['content'] .= "<div class='whiteBox'>$message";
5499 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5501 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5502 WHERE owner_uid = " . $_SESSION['uid']);
5504 $last_updated = db_fetch_result($result, 0, "last_updated");
5505 $last_updated = make_local_datetime($link, $last_updated, false);
5507 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5509 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5510 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5512 $num_errors = db_fetch_result($result, 0, "num_errors");
5514 if ($num_errors > 0) {
5515 $reply['content'] .= "<br/>";
5516 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5517 __('Some feeds have update errors (click for details)')."</a>";
5519 $reply['content'] .= "</span></p></div>";
5523 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5525 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5526 $vgroup_last_feed, $reply);
5529 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5531 function printTagCloud($link) {
5533 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5534 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5535 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5537 $result = db_query($link, $query);
5541 while ($line = db_fetch_assoc($result)) {
5542 $tags[$line["tag_name"]] = $line["count"];
5545 if( count($tags) == 0 ){ return; }
5549 $max_size = 32; // max font size in pixels
5550 $min_size = 11; // min font size in pixels
5552 // largest and smallest array values
5553 $max_qty = max(array_values($tags));
5554 $min_qty = min(array_values($tags));
5556 // find the range of values
5557 $spread = $max_qty - $min_qty;
5558 if ($spread == 0) { // we don't want to divide by zero
5562 // set the font-size increment
5563 $step = ($max_size - $min_size) / ($spread);
5565 // loop through the tag array
5566 foreach ($tags as $key => $value) {
5567 // calculate font-size
5568 // find the $value in excess of $min_qty
5569 // multiply by the font-size increment ($size)
5570 // and add the $min_size set above
5571 $size = round($min_size +
(($value - $min_qty) * $step));
5573 $key_escaped = str_replace("'", "\\'", $key);
5575 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5576 $size . "px\" title=\"$value articles tagged with " .
5577 $key . '">' . $key . '</a> ';
5581 function print_checkpoint($n, $s) {
5582 $ts = getmicrotime();
5583 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5587 function sanitize_tag($tag) {
5590 $tag = mb_strtolower($tag, 'utf-8');
5592 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5594 // $tag = str_replace('"', "", $tag);
5595 // $tag = str_replace("+", " ", $tag);
5596 $tag = str_replace("technorati tag: ", "", $tag);
5601 function get_self_url_prefix() {
5602 return SELF_URL_PATH
;
5605 function opml_publish_url($link){
5607 $url_path = get_self_url_prefix();
5608 $url_path .= "/opml.php?op=publish&key=" .
5609 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5615 * Purge a feed contents, marked articles excepted.
5617 * @param mixed $link The database connection.
5618 * @param integer $id The id of the feed to purge.
5621 function clear_feed_articles($link, $id) {
5624 $result = db_query($link, "DELETE FROM ttrss_user_entries
5625 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5627 $result = db_query($link, "DELETE FROM ttrss_user_entries
5628 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5631 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5632 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5634 ccache_update($link, $id, $_SESSION['uid']);
5635 } // function clear_feed_articles
5638 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5640 * @return string The Mozilla Firefox feed adding URL.
5642 function add_feed_url() {
5643 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5645 $url_path = get_self_url_prefix() .
5646 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5648 } // function add_feed_url
5651 * Encrypt a password in SHA1.
5653 * @param string $pass The password to encrypt.
5654 * @param string $login A optionnal login.
5655 * @return string The encrypted password.
5657 function encrypt_password($pass, $login = '') {
5659 return "SHA1X:" . sha1("$login:$pass");
5661 return "SHA1:" . sha1($pass);
5663 } // function encrypt_password
5666 * Update a feed batch.
5667 * Used by daemons to update n feeds by run.
5668 * Only update feed needing a update, and not being processed
5669 * by another process.
5671 * @param mixed $link Database link
5672 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5673 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5674 * @param boolean $debug Set to false to disable debug output. Default to true.
5677 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5678 // Process all other feeds using last_updated and interval parameters
5680 // Test if the user has loggued in recently. If not, it does not update its feeds.
5681 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5682 if (DB_TYPE
== "pgsql") {
5683 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5685 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5688 $login_thresh_qpart = "";
5691 // Test if the feed need a update (update interval exceded).
5692 if (DB_TYPE
== "pgsql") {
5693 $update_limit_qpart = "AND ((
5694 ttrss_feeds.update_interval = 0
5695 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5697 ttrss_feeds.update_interval > 0
5698 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5699 ) OR ttrss_feeds.last_updated IS NULL)";
5701 $update_limit_qpart = "AND ((
5702 ttrss_feeds.update_interval = 0
5703 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5705 ttrss_feeds.update_interval > 0
5706 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5707 ) OR ttrss_feeds.last_updated IS NULL)";
5710 // Test if feed is currently being updated by another process.
5711 if (DB_TYPE
== "pgsql") {
5712 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
5714 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
5717 // Test if there is a limit to number of updated feeds
5719 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5721 $random_qpart = sql_random_function();
5723 // We search for feed needing update.
5724 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5725 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5726 ttrss_feeds.update_interval
5728 ttrss_feeds, ttrss_users, ttrss_user_prefs
5730 ttrss_feeds.owner_uid = ttrss_users.id
5731 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5732 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5733 $login_thresh_qpart $update_limit_qpart
5734 $updstart_thresh_qpart
5735 ORDER BY $random_qpart $query_limit");
5737 $user_prefs_cache = array();
5739 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5741 // Here is a little cache magic in order to minimize risk of double feed updates.
5742 $feeds_to_update = array();
5743 while ($line = db_fetch_assoc($result)) {
5744 $feeds_to_update[$line['id']] = $line;
5747 // We update the feed last update started date before anything else.
5748 // There is no lag due to feed contents downloads
5749 // It prevent an other process to update the same feed.
5750 $feed_ids = array_keys($feeds_to_update);
5752 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5753 WHERE id IN (%s)", implode(',', $feed_ids)));
5756 // For each feed, we call the feed update function.
5757 while ($line = array_pop($feeds_to_update)) {
5759 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5761 update_rss_feed($link, $line["id"], true);
5763 sleep(1); // prevent flood (FIXME make this an option?)
5766 // Send feed digests by email if needed.
5767 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5769 } // function update_daemon_common
5771 function sanitize_article_content($text) {
5772 # we don't support CDATA sections in articles, they break our own escaping
5773 $text = preg_replace("/\[\[CDATA/", "", $text);
5774 $text = preg_replace("/\]\]\>/", "", $text);
5778 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5783 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5785 if ($memcache && $obj = $memcache->get($obj_id)) {
5791 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5793 $result = db_query($link, "SELECT reg_exp,
5794 ttrss_filter_types.name AS name,
5795 ttrss_filter_actions.name AS action,
5799 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5802 owner_uid = $owner_uid AND
5803 ttrss_filter_types.id = filter_type AND
5804 ttrss_filter_actions.id = action_id AND
5805 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5807 while ($line = db_fetch_assoc($result)) {
5808 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5809 $filter["reg_exp"] = $line["reg_exp"];
5810 $filter["action"] = $line["action"];
5811 $filter["action_param"] = $line["action_param"];
5812 $filter["filter_param"] = $line["filter_param"];
5813 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5815 array_push($filters[$line["name"]], $filter);
5818 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5824 function get_score_pic($score) {
5826 return "score_high.png";
5827 } else if ($score > 0) {
5828 return "score_half_high.png";
5829 } else if ($score < -100) {
5830 return "score_low.png";
5831 } else if ($score < 0) {
5832 return "score_half_low.png";
5834 return "score_neutral.png";
5838 function feed_has_icon($id) {
5839 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5842 function init_connection($link) {
5843 if (DB_TYPE
== "pgsql") {
5844 pg_query($link, "set client_encoding = 'UTF-8'");
5845 pg_set_client_encoding("UNICODE");
5846 pg_query($link, "set datestyle = 'ISO, european'");
5847 pg_query($link, "set TIME ZONE 0");
5849 db_query($link, "SET time_zone = '+0:0'");
5851 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5852 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5853 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5858 function update_feedbrowser_cache($link) {
5860 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
5861 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5862 WHERE tf.feed_url = ttrss_feeds.feed_url
5863 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
5864 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
5866 db_query($link, "BEGIN");
5868 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5872 while ($line = db_fetch_assoc($result)) {
5873 $subscribers = db_escape_string($line["subscribers"]);
5874 $feed_url = db_escape_string($line["feed_url"]);
5875 $title = db_escape_string($line["title"]);
5876 $site_url = db_escape_string($line["site_url"]);
5878 $tmp_result = db_query($link, "SELECT subscribers FROM
5879 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5881 if (db_num_rows($tmp_result) == 0) {
5883 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5884 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5885 '$site_url', '$title', '$subscribers')");
5893 db_query($link, "COMMIT");
5899 /* function ccache_zero($link, $feed_id, $owner_uid) {
5900 db_query($link, "UPDATE ttrss_counters_cache SET
5901 value = 0, updated = NOW() WHERE
5902 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5905 function ccache_zero_all($link, $owner_uid) {
5906 db_query($link, "UPDATE ttrss_counters_cache SET
5907 value = 0 WHERE owner_uid = '$owner_uid'");
5909 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5910 value = 0 WHERE owner_uid = '$owner_uid'");
5913 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5916 $table = "ttrss_counters_cache";
5918 $table = "ttrss_cat_counters_cache";
5921 db_query($link, "DELETE FROM $table WHERE
5922 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5926 function ccache_update_all($link, $owner_uid) {
5928 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5930 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5931 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5933 while ($line = db_fetch_assoc($result)) {
5934 ccache_update($link, $line["feed_id"], $owner_uid, true);
5937 /* We have to manually include category 0 */
5939 ccache_update($link, 0, $owner_uid, true);
5942 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5943 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5945 while ($line = db_fetch_assoc($result)) {
5946 print ccache_update($link, $line["feed_id"], $owner_uid);
5953 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5954 $no_update = false) {
5956 if (!is_numeric($feed_id)) return;
5959 $table = "ttrss_counters_cache";
5961 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5962 WHERE id = '$feed_id'");
5963 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5966 $table = "ttrss_cat_counters_cache";
5969 if (DB_TYPE
== "pgsql") {
5970 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5971 } else if (DB_TYPE
== "mysql") {
5972 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5975 $result = db_query($link, "SELECT value FROM $table
5976 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5979 if (db_num_rows($result) == 1) {
5980 return db_fetch_result($result, 0, "value");
5985 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5991 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5992 $update_pcat = true) {
5994 if (!is_numeric($feed_id)) return;
5996 if (!$is_cat && $feed_id > 0) {
5997 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5998 WHERE id = '$feed_id'");
5999 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6002 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6004 /* When updating a label, all we need to do is recalculate feed counters
6005 * because labels are not cached */
6008 ccache_update_all($link, $owner_uid);
6013 $table = "ttrss_counters_cache";
6015 $table = "ttrss_cat_counters_cache";
6018 if ($is_cat && $feed_id >= 0) {
6019 if ($feed_id != 0) {
6020 $cat_qpart = "cat_id = '$feed_id'";
6022 $cat_qpart = "cat_id IS NULL";
6025 /* Recalculate counters for child feeds */
6027 $result = db_query($link, "SELECT id FROM ttrss_feeds
6028 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6030 while ($line = db_fetch_assoc($result)) {
6031 ccache_update($link, $line["id"], $owner_uid, false, false);
6034 $result = db_query($link, "SELECT SUM(value) AS sv
6035 FROM ttrss_counters_cache, ttrss_feeds
6036 WHERE id = feed_id AND $cat_qpart AND
6037 ttrss_feeds.owner_uid = '$owner_uid'");
6039 $unread = (int) db_fetch_result($result, 0, "sv");
6042 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6045 db_query($link, "BEGIN");
6047 $result = db_query($link, "SELECT feed_id FROM $table
6048 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6050 if (db_num_rows($result) == 1) {
6051 db_query($link, "UPDATE $table SET
6052 value = '$unread', updated = NOW() WHERE
6053 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6056 db_query($link, "INSERT INTO $table
6057 (feed_id, value, owner_uid, updated)
6059 ($feed_id, $unread, $owner_uid, NOW())");
6062 db_query($link, "COMMIT");
6064 if ($feed_id > 0 && $prev_unread != $unread) {
6068 /* Update parent category */
6072 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6073 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6075 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6077 ccache_update($link, $cat_id, $owner_uid, true);
6081 } else if ($feed_id < 0) {
6082 ccache_update_all($link, $owner_uid);
6088 /* function ccache_cleanup($link, $owner_uid) {
6090 if (DB_TYPE == "pgsql") {
6091 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6092 (SELECT count(*) FROM ttrss_counters_cache AS c2
6093 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6094 AND owner_uid = '$owner_uid'");
6096 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6097 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6098 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6099 AND owner_uid = '$owner_uid'");
6101 db_query($link, "DELETE c1 FROM
6102 ttrss_counters_cache AS c1,
6103 ttrss_counters_cache AS c2
6105 c1.owner_uid = '$owner_uid' AND
6106 c1.owner_uid = c2.owner_uid AND
6107 c1.feed_id = c2.feed_id");
6109 db_query($link, "DELETE c1 FROM
6110 ttrss_cat_counters_cache AS c1,
6111 ttrss_cat_counters_cache AS c2
6113 c1.owner_uid = '$owner_uid' AND
6114 c1.owner_uid = c2.owner_uid AND
6115 c1.feed_id = c2.feed_id");
6120 function label_find_id($link, $label, $owner_uid) {
6121 $result = db_query($link,
6122 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6123 AND owner_uid = '$owner_uid' LIMIT 1");
6125 if (db_num_rows($result) == 1) {
6126 return db_fetch_result($result, 0, "id");
6132 function get_article_labels($link, $id) {
6135 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6139 if ($memcache && $obj = $memcache->get($obj_id)) {
6143 $result = db_query($link, "SELECT label_cache FROM
6144 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6147 $label_cache = db_fetch_result($result, 0, "label_cache");
6151 $label_cache = json_decode($label_cache, true);
6153 if ($label_cache["no-labels"] == 1)
6156 return $label_cache;
6159 $result = db_query($link,
6160 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6161 FROM ttrss_labels2, ttrss_user_labels2
6163 AND article_id = '$id'
6164 AND owner_uid = ".$_SESSION["uid"] . "
6167 while ($line = db_fetch_assoc($result)) {
6168 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6170 array_push($rv, $rk);
6172 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6175 label_update_cache($link, $id, $rv);
6177 label_update_cache($link, $id, array("no-labels" => 1));
6184 function label_find_caption($link, $label, $owner_uid) {
6185 $result = db_query($link,
6186 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6187 AND owner_uid = '$owner_uid' LIMIT 1");
6189 if (db_num_rows($result) == 1) {
6190 return db_fetch_result($result, 0, "caption");
6196 function label_update_cache($link, $id, $labels = false, $force = false) {
6199 label_clear_cache($link, $id);
6202 $labels = get_article_labels($link, $id);
6204 $labels = db_escape_string(json_encode($labels));
6206 db_query($link, "UPDATE ttrss_user_entries SET
6207 label_cache = '$labels' WHERE ref_id = '$id'");
6211 function label_clear_cache($link, $id) {
6213 db_query($link, "UPDATE ttrss_user_entries SET
6214 label_cache = '' WHERE ref_id = '$id'");
6218 function label_remove_article($link, $id, $label, $owner_uid) {
6220 $label_id = label_find_id($link, $label, $owner_uid);
6222 if (!$label_id) return;
6224 $result = db_query($link,
6225 "DELETE FROM ttrss_user_labels2
6227 label_id = '$label_id' AND
6228 article_id = '$id'");
6230 label_clear_cache($link, $id);
6233 function label_add_article($link, $id, $label, $owner_uid) {
6238 $obj_id = md5("LABELS:$id:$owner_uid");
6239 $memcache->delete($obj_id);
6242 $label_id = label_find_id($link, $label, $owner_uid);
6244 if (!$label_id) return;
6246 $result = db_query($link,
6248 article_id FROM ttrss_labels2, ttrss_user_labels2
6251 label_id = '$label_id' AND
6252 article_id = '$id' AND owner_uid = '$owner_uid'
6255 if (db_num_rows($result) == 0) {
6256 db_query($link, "INSERT INTO ttrss_user_labels2
6257 (label_id, article_id) VALUES ('$label_id', '$id')");
6260 label_clear_cache($link, $id);
6264 function label_remove($link, $id, $owner_uid) {
6267 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6270 $obj_id = md5("LABELS:$id:$owner_uid");
6271 $memcache->delete($obj_id);
6274 db_query($link, "BEGIN");
6276 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6279 $caption = db_fetch_result($result, 0, "caption");
6281 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6282 AND owner_uid = " . $owner_uid);
6284 if (db_affected_rows($link, $result) != 0 && $caption) {
6286 /* Remove access key for the label */
6288 $ext_id = -11 - $id;
6290 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6291 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6293 /* Disable filters that reference label being removed */
6295 db_query($link, "UPDATE ttrss_filters SET
6296 enabled = false WHERE action_param = '$caption'
6298 AND owner_uid = " . $owner_uid);
6300 /* Remove cached data */
6302 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6303 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6307 db_query($link, "COMMIT");
6310 function label_create($link, $caption) {
6312 db_query($link, "BEGIN");
6316 $result = db_query($link, "SELECT id FROM ttrss_labels2
6317 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6319 if (db_num_rows($result) == 0) {
6320 $result = db_query($link,
6321 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6322 VALUES ('$caption', '".$_SESSION["uid"]."')");
6324 $result = db_affected_rows($link, $result) != 0;
6327 db_query($link, "COMMIT");
6332 function format_tags_string($tags, $id) {
6335 $tags_nolinks_str = "";
6341 $formatted_tags = array();
6343 foreach ($tags as $tag) {
6345 $tag_escaped = str_replace("'", "\\'", $tag);
6347 if (mb_strlen($tag) > 30) {
6348 $tag = truncate_string($tag, 30);
6351 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6353 array_push($formatted_tags, $tag_str);
6355 $tmp_tags_str = implode(", ", $formatted_tags);
6357 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6362 $tags_str = implode(", ", $formatted_tags);
6364 if ($num_tags < count($tags)) {
6365 $tags_str .= ", …";
6368 if ($num_tags == 0) {
6369 $tags_str = __("no tags");
6376 function format_article_labels($labels, $id) {
6380 foreach ($labels as $l) {
6381 $labels_str .= sprintf("<span class='hlLabelRef'
6382 style='color : %s; background-color : %s'>%s</span>",
6383 $l[2], $l[3], $l[1]);
6390 function format_article_note($id, $note) {
6392 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6393 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6394 __('(edit note)')."</div>$note</div>";
6399 function toggle_collapse_cat($link, $cat_id, $mode) {
6401 $mode = bool_to_sql_bool($mode);
6403 db_query($link, "UPDATE ttrss_feed_categories SET
6404 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6411 $pref_name = '_COLLAPSED_SPECIAL';
6414 $pref_name = '_COLLAPSED_LABELS';
6417 $pref_name = '_COLLAPSED_UNCAT';
6423 set_pref($link, $pref_name, 'true');
6425 set_pref($link, $pref_name, 'false');
6431 function remove_feed($link, $id, $owner_uid) {
6435 /* save starred articles in Archived feed */
6437 db_query($link, "BEGIN");
6439 /* prepare feed if necessary */
6441 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6444 if (db_num_rows($result) == 0) {
6445 db_query($link, "INSERT INTO ttrss_archived_feeds
6446 (id, owner_uid, title, feed_url, site_url)
6447 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6451 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6452 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6453 marked = true AND owner_uid = $owner_uid");
6455 /* Remove access key for the feed */
6457 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6458 feed_id = '$id' AND owner_uid = $owner_uid");
6460 /* remove the feed */
6462 db_query($link, "DELETE FROM ttrss_feeds
6463 WHERE id = '$id' AND owner_uid = $owner_uid");
6465 db_query($link, "COMMIT");
6467 if (file_exists(ICONS_DIR
. "/$id.ico")) {
6468 unlink(ICONS_DIR
. "/$id.ico");
6471 ccache_remove($link, $id, $owner_uid);
6474 label_remove($link, -11-$id, $owner_uid);
6475 ccache_remove($link, -11-$id, $owner_uid);
6479 function add_feed_category($link, $feed_cat) {
6481 if (!$feed_cat) return false;
6483 db_query($link, "BEGIN");
6485 $result = db_query($link,
6486 "SELECT id FROM ttrss_feed_categories
6487 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6489 if (db_num_rows($result) == 0) {
6491 $result = db_query($link,
6492 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6493 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6495 db_query($link, "COMMIT");
6503 function remove_feed_category($link, $id, $owner_uid) {
6505 db_query($link, "DELETE FROM ttrss_feed_categories
6506 WHERE id = '$id' AND owner_uid = $owner_uid");
6508 ccache_remove($link, $id, $owner_uid, true);
6511 function archive_article($link, $id, $owner_uid) {
6512 db_query($link, "BEGIN");
6514 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6515 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6517 if (db_num_rows($result) != 0) {
6519 /* prepare the archived table */
6521 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6524 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6525 WHERE id = '$feed_id'");
6527 if (db_num_rows($result) == 0) {
6528 db_query($link, "INSERT INTO ttrss_archived_feeds
6529 (id, owner_uid, title, feed_url, site_url)
6530 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6531 WHERE id = '$feed_id'");
6534 db_query($link, "UPDATE ttrss_user_entries
6535 SET orig_feed_id = feed_id, feed_id = NULL
6536 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6540 db_query($link, "COMMIT");
6543 function getArticleFeed($link, $id) {
6544 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6545 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6547 if (db_num_rows($result) != 0) {
6548 return db_fetch_result($result, 0, "feed_id");
6555 * Fixes incomplete URLs by prepending "http://".
6556 * Also replaces feed:// with http://, and
6557 * prepends a trailing slash if the url is a domain name only.
6559 * @param string $url Possibly incomplete URL
6561 * @return string Fixed URL.
6563 function fix_url($url) {
6564 if (strpos($url, '://') === false) {
6565 $url = 'http://' . $url;
6566 } else if (substr($url, 0, 5) == 'feed:') {
6567 $url = 'http:' . substr($url, 5);
6570 //prepend slash if the URL has no slash in it
6571 // "http://www.example" -> "http://www.example/"
6572 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6576 if ($url != "http:///")
6582 function validate_feed_url($url) {
6583 $parts = parse_url($url);
6585 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6589 function get_article_enclosures($link, $id) {
6593 $query = "SELECT * FROM ttrss_enclosures
6594 WHERE post_id = '$id' AND content_url != ''";
6596 $obj_id = md5("ENCLOSURES:$id");
6600 if ($memcache && $obj = $memcache->get($obj_id)) {
6603 $result = db_query($link, $query);
6605 if (db_num_rows($result) > 0) {
6606 while ($line = db_fetch_assoc($result)) {
6607 array_push($rv, $line);
6609 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6616 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6622 if ($cat_id == -4 ||
$cat_id == -2) {
6623 $counters = getLabelCounters($link, true);
6625 foreach (array_values($counters) as $cv) {
6627 $unread = $cv["counter"];
6629 if ($unread ||
!$unread_only) {
6633 "title" => $cv["description"],
6634 "unread" => $cv["counter"],
6638 array_push($feeds, $row);
6645 if ($cat_id == -4 ||
$cat_id == -1) {
6646 foreach (array(-1, -2, -3, -4, 0) as $i) {
6647 $unread = getFeedUnread($link, $i);
6649 if ($unread ||
!$unread_only) {
6650 $title = getFeedTitle($link, $i);
6655 "unread" => $unread,
6658 array_push($feeds, $row);
6667 $limit_qpart = "LIMIT $limit OFFSET $offset";
6672 if ($cat_id == -4 ||
$cat_id == -3) {
6673 $result = db_query($link, "SELECT
6674 id, feed_url, cat_id, title, ".
6675 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6676 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6677 " ORDER BY cat_id, title " . $limit_qpart);
6681 $cat_qpart = "cat_id = '$cat_id'";
6683 $cat_qpart = "cat_id IS NULL";
6685 $result = db_query($link, "SELECT
6686 id, feed_url, cat_id, title, ".
6687 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6688 FROM ttrss_feeds WHERE
6689 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6690 " ORDER BY cat_id, title " . $limit_qpart);
6693 while ($line = db_fetch_assoc($result)) {
6695 $unread = getFeedUnread($link, $line["id"]);
6697 $has_icon = feed_has_icon($line['id']);
6699 if ($unread ||
!$unread_only) {
6702 "feed_url" => $line["feed_url"],
6703 "title" => $line["title"],
6704 "id" => (int)$line["id"],
6705 "unread" => (int)$unread,
6706 "has_icon" => $has_icon,
6707 "cat_id" => (int)$line["cat_id"],
6708 "last_updated" => strtotime($line["last_updated"])
6711 array_push($feeds, $row);
6718 function api_get_headlines($link, $feed_id, $limit, $offset,
6719 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6720 $include_attachments, $since_id) {
6722 /* do not rely on params below */
6724 $search = db_escape_string($_REQUEST["search"]);
6725 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6726 $match_on = db_escape_string($_REQUEST["match_on"]);
6728 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6729 $view_mode, $is_cat, $search, $search_mode, $match_on,
6730 $order, $offset, 0, false, $since_id);
6732 $result = $qfh_ret[0];
6733 $feed_title = $qfh_ret[1];
6735 $headlines = array();
6737 while ($line = db_fetch_assoc($result)) {
6738 $is_updated = ($line["last_read"] == "" &&
6739 ($line["unread"] != "t" && $line["unread"] != "1"));
6741 $tags = explode(",", $line["tag_cache"]);
6742 $labels = json_decode($line["label_cache"], true);
6744 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
6745 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
6747 $headline_row = array(
6748 "id" => (int)$line["id"],
6749 "unread" => sql_bool_to_bool($line["unread"]),
6750 "marked" => sql_bool_to_bool($line["marked"]),
6751 "published" => sql_bool_to_bool($line["published"]),
6752 "updated" => strtotime($line["updated"]),
6753 "is_updated" => $is_updated,
6754 "title" => $line["title"],
6755 "link" => $line["link"],
6756 "feed_id" => $line["feed_id"],
6760 if ($include_attachments)
6761 $headline_row['attachments'] = get_article_enclosures($link,
6764 if ($show_excerpt) {
6765 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6766 $headline_row["excerpt"] = $excerpt;
6769 if ($show_content) {
6770 $headline_row["content"] = $line["content_preview"];
6773 // unify label output to ease parsing
6774 if ($labels["no-labels"] == 1) $labels = array();
6776 $headline_row["labels"] = $labels;
6778 array_push($headlines, $headline_row);
6784 function generate_error_feed($link, $error) {
6787 $reply['headlines']['id'] = -6;
6788 $reply['headlines']['is_cat'] = false;
6790 $reply['headlines']['toolbar'] = '';
6791 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6793 $reply['headlines-info'] = array("count" => 0,
6794 "vgroup_last_feed" => '',
6796 "disable_cache" => true);
6802 function generate_dashboard_feed($link) {
6805 $reply['headlines']['id'] = -5;
6806 $reply['headlines']['is_cat'] = false;
6808 $reply['headlines']['toolbar'] = '';
6809 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6811 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6813 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6814 WHERE owner_uid = " . $_SESSION['uid']);
6816 $last_updated = db_fetch_result($result, 0, "last_updated");
6817 $last_updated = make_local_datetime($link, $last_updated, false);
6819 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6821 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6822 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6824 $num_errors = db_fetch_result($result, 0, "num_errors");
6826 if ($num_errors > 0) {
6827 $reply['headlines']['content'] .= "<br/>";
6828 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6829 __('Some feeds have update errors (click for details)')."</a>";
6831 $reply['headlines']['content'] .= "</span></p>";
6833 $reply['headlines-info'] = array("count" => 0,
6834 "vgroup_last_feed" => '',
6836 "disable_cache" => true);
6841 function save_email_address($link, $email) {
6842 // FIXME: implement persistent storage of emails
6844 if (!$_SESSION['stored_emails'])
6845 $_SESSION['stored_emails'] = array();
6847 if (!in_array($email, $_SESSION['stored_emails']))
6848 array_push($_SESSION['stored_emails'], $email);
6851 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6852 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6854 $sql_is_cat = bool_to_sql_bool($is_cat);
6856 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6857 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6858 AND owner_uid = " . $owner_uid);
6860 if (db_num_rows($result) == 1) {
6861 $key = db_escape_string(sha1(uniqid(rand(), true)));
6863 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6864 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6865 AND owner_uid = " . $owner_uid);
6870 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6874 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6876 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6878 $sql_is_cat = bool_to_sql_bool($is_cat);
6880 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6881 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6882 AND owner_uid = " . $owner_uid);
6884 if (db_num_rows($result) == 1) {
6885 return db_fetch_result($result, 0, "access_key");
6887 $key = db_escape_string(sha1(uniqid(rand(), true)));
6889 $result = db_query($link, "INSERT INTO ttrss_access_keys
6890 (access_key, feed_id, is_cat, owner_uid)
6891 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6899 * Extracts RSS/Atom feed URLs from the given HTML URL.
6901 * @param string $url HTML page URL
6903 * @return array Array of feeds. Key is the full URL, value the title
6905 function get_feeds_from_html($url, $login = false, $pass = false)
6907 $url = fix_url($url);
6908 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6910 libxml_use_internal_errors(true);
6912 $content = @fetch_file_contents
($url, false, $login, $pass);
6914 $doc = new DOMDocument();
6915 $doc->loadHTML($content);
6916 $xpath = new DOMXPath($doc);
6917 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6918 $feedUrls = array();
6919 foreach ($entries as $entry) {
6920 if ($entry->hasAttribute('href')) {
6921 $title = $entry->getAttribute('title');
6923 $title = $entry->getAttribute('type');
6925 $feedUrl = rewrite_relative_url(
6926 $baseUrl, $entry->getAttribute('href')
6928 $feedUrls[$feedUrl] = $title;
6935 * Checks if the content behind the given URL is a HTML file
6937 * @param string $url URL to check
6939 * @return boolean True if the URL contains HTML content
6941 function url_is_html($url, $login = false, $pass = false) {
6942 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6944 if (stripos($content, '<html>') === false
6945 && stripos($content, '<html ') === false
6953 function print_label_select($link, $name, $value, $attributes = "") {
6955 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6956 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6958 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6959 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6961 while ($line = db_fetch_assoc($result)) {
6963 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6965 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6966 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6970 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6977 function format_article_enclosures($link, $id, $always_display_enclosures,
6980 $result = get_article_enclosures($link, $id);
6983 if (count($result) > 0) {
6985 $entries_html = array();
6988 foreach ($result as $line) {
6990 $url = $line["content_url"];
6991 $ctype = $line["content_type"];
6993 if (!$ctype) $ctype = __("unknown type");
6995 # $filename = substr($url, strrpos($url, "/")+1);
6997 $entry = format_inline_player($link, $url, $ctype);
6999 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
7000 # $filename . " (" . $ctype . ")" . "</a>";
7002 array_push($entries_html, $entry);
7006 $entry["type"] = $ctype;
7007 $entry["filename"] = $filename;
7008 $entry["url"] = $url;
7010 array_push($entries, $entry);
7013 $rv .= "<div class=\"postEnclosures\">";
7015 if (!get_pref($link, "STRIP_IMAGES")) {
7016 if ($always_display_enclosures ||
7017 !preg_match("/<img/i", $article_content)) {
7019 foreach ($entries as $entry) {
7021 if (preg_match("/image/", $entry["type"]) ||
7022 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
7025 alt=\"".htmlspecialchars($entry["filename"])."\"
7026 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7032 if (count($entries) == 1) {
7033 $rv .= __("Attachment:") . " ";
7035 $rv .= __("Attachments:") . " ";
7038 $rv .= join(", ", $entries_html);
7046 function getLastArticleId($link) {
7047 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7048 WHERE owner_uid = " . $_SESSION["uid"]);
7050 if (db_num_rows($result) == 1) {
7051 return db_fetch_result($result, 0, "id");
7057 function build_url($parts) {
7058 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7062 * Converts a (possibly) relative URL to a absolute one.
7064 * @param string $url Base URL (i.e. from where the document is)
7065 * @param string $rel_url Possibly relative URL in the document
7067 * @return string Absolute URL
7069 function rewrite_relative_url($url, $rel_url) {
7070 if (strpos($rel_url, "://") !== false) {
7072 } else if (strpos($rel_url, "/") === 0)
7074 $parts = parse_url($url);
7075 $parts['path'] = $rel_url;
7077 return build_url($parts);
7080 $parts = parse_url($url);
7081 if (!isset($parts['path'])) {
7082 $parts['path'] = '/';
7084 $dir = $parts['path'];
7085 if (substr($dir, -1) !== '/') {
7086 $dir = dirname($parts['path']);
7087 $dir !== '/' && $dir .= '/';
7089 $parts['path'] = $dir . $rel_url;
7091 return build_url($parts);
7095 function sphinx_search($query, $offset = 0, $limit = 30) {
7096 $sphinxClient = new SphinxClient();
7098 $sphinxClient->SetServer('localhost', 9312);
7099 $sphinxClient->SetConnectTimeout(1);
7101 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7102 'feed_title' => 20));
7104 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
7105 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
7106 $sphinxClient->SetLimits($offset, $limit, 1000);
7107 $sphinxClient->SetArrayResult(false);
7108 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7110 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
7114 if (is_array($result['matches'])) {
7115 foreach (array_keys($result['matches']) as $int_id) {
7116 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7117 array_push($ids, $ref_id);
7124 function cleanup_tags($link, $days = 14, $limit = 1000) {
7126 if (DB_TYPE
== "pgsql") {
7127 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7128 } else if (DB_TYPE
== "mysql") {
7129 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7134 while ($limit > 0) {
7137 $query = "SELECT ttrss_tags.id AS id
7138 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7139 WHERE post_int_id = int_id AND $interval_query AND
7140 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7142 $result = db_query($link, $query);
7146 while ($line = db_fetch_assoc($result)) {
7147 array_push($ids, $line['id']);
7150 if (count($ids) > 0) {
7151 $ids = join(",", $ids);
7154 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7155 $tags_deleted +
= db_affected_rows($link, $tmp_result);
7160 $limit -= $limit_part;
7165 return $tags_deleted;
7168 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7170 $cat_id = (int) $cat_id;
7173 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7174 } else if ($cat_id == 0 ||
$cat_id == -2) {
7175 $cat_unread = getCategoryUnread($link, $cat_id);
7178 $obj['id'] = 'CAT:' . $cat_id;
7179 $obj['items'] = array();
7180 $obj['name'] = getCategoryTitle($link, $cat_id);
7181 $obj['type'] = 'feed';
7182 $obj['unread'] = (int) $cat_unread;
7183 $obj['hidden'] = $hidden;
7184 $obj['bare_id'] = $cat_id;
7189 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7191 $feed_id = (int) $feed_id;
7194 $title = getFeedTitle($link, $feed_id, false);
7196 if ($unread === false)
7197 $unread = getFeedUnread($link, $feed_id, false);
7199 $obj['id'] = 'FEED:' . $feed_id;
7200 $obj['name'] = $title;
7201 $obj['unread'] = (int) $unread;
7202 $obj['type'] = 'feed';
7203 $obj['error'] = $error;
7204 $obj['updated'] = $updated;
7205 $obj['icon'] = getFeedIcon($feed_id);
7206 $obj['bare_id'] = $feed_id;
7212 function fetch_twitter_rss($link, $url, $owner_uid) {
7213 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7214 WHERE id = $owner_uid");
7216 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7217 $url_escaped = db_escape_string($url);
7219 if ($access_token) {
7221 $tmhOAuth = new tmhOAuth(array(
7222 'consumer_key' => CONSUMER_KEY
,
7223 'consumer_secret' => CONSUMER_SECRET
,
7224 'user_token' => $access_token['oauth_token'],
7225 'user_secret' => $access_token['oauth_token_secret'],
7228 $code = $tmhOAuth->request('GET', $url);
7232 $content = $tmhOAuth->response
['response'];
7234 define('MAGPIE_CACHE_ON', false);
7236 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7237 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7243 db_query($link, "UPDATE ttrss_feeds
7244 SET last_error = 'OAuth authorization failed ($code).'
7245 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7250 db_query($link, "UPDATE ttrss_feeds
7251 SET last_error = 'OAuth information not found.'
7252 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7258 function print_user_stylesheet($link) {
7259 $value = get_pref($link, 'USER_STYLESHEET');
7262 print "<style type=\"text/css\">";
7263 print str_replace("<br/>", "\n", $value);
7269 function rewrite_urls($line) {
7274 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7275 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7280 function filter_to_sql($filter) {
7283 if (DB_TYPE
== "pgsql")
7286 $reg_qpart = "REGEXP";
7288 switch ($filter["type"]) {
7290 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7291 $filter['reg_exp'] . "')";
7294 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7295 $filter['reg_exp'] . "')";
7298 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7299 $filter['reg_exp'] . "') OR LOWER(" .
7300 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7303 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7304 $filter['reg_exp'] . "')";
7307 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7308 $filter['reg_exp'] . "')";
7312 if ($filter["filter_param"] == "before")
7317 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7318 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7321 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7322 $filter['reg_exp'] . "')";
7326 if ($filter["inverse"])
7327 $query = "NOT ($query)";
7330 if (DB_TYPE
== "pgsql") {
7331 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
7333 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
7343 // -1 - never connected
7344 // 0 - no data received
7345 // 1 - data received successfully
7346 // 2 - did not receive valid data
7347 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7349 function get_linked_feeds($link, $instance_id = false) {
7351 $instance_qpart = "id = '$instance_id' AND ";
7353 $instance_qpart = "";
7355 if (DB_TYPE
== "pgsql") {
7356 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
7358 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
7361 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7362 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7364 while ($line = db_fetch_assoc($result)) {
7367 _debug("Updating: " . $line['access_url'] . " ($id)");
7369 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
7370 $post_query = 'key=' . $line['access_key'];
7372 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7374 // try doing it the old way
7376 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7377 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7381 $feeds = json_decode($feeds, true);
7384 if ($feeds['error']) {
7385 $status = $feeds['error']['code'] +
10;
7389 if (count($feeds['feeds']) > 0) {
7391 db_query($link, "DELETE FROM ttrss_linked_feeds
7392 WHERE instance_id = '$id'");
7394 foreach ($feeds['feeds'] as $feed) {
7395 $feed_url = db_escape_string($feed['feed_url']);
7396 $title = db_escape_string($feed['title']);
7397 $subscribers = db_escape_string($feed['subscribers']);
7398 $site_url = db_escape_string($feed['site_url']);
7400 db_query($link, "INSERT INTO ttrss_linked_feeds
7401 (feed_url, site_url, title, subscribers, instance_id, created, updated)
7403 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
7406 // received 0 feeds, this might indicate that
7407 // the instance on the other hand is rebuilding feedbrowser cache
7408 // we will try again later
7410 // TODO: maybe perform expiration based on updated here?
7413 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7423 _debug("Status: $status");
7425 db_query($link, "UPDATE ttrss_linked_instances SET
7426 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
7431 function handle_public_request($link, $op) {
7435 $login = db_escape_string($_REQUEST["login"]);
7436 $fresh = $_REQUEST["fresh"] == "1";
7438 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$login'");
7440 if (db_num_rows($result) == 1) {
7441 $uid = db_fetch_result($result, 0, "id");
7443 print getGlobalUnread($link, $uid);
7447 print getFeedArticles($link, -3, false, true, $uid);
7451 print "-1;User not found";
7457 $login = db_escape_string($_REQUEST["login"]);
7458 $password = db_escape_string($_REQUEST["password"]);
7460 if (authenticate_user($link, $login, $password)) {
7461 $result = db_query($link, "SELECT * FROM ttrss_settings_profiles
7462 WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY title");
7464 print "<select style='width: 100%' name='profile'>";
7466 print "<option value='0'>" . __("Default profile") . "</option>";
7468 while ($line = db_fetch_assoc($result)) {
7470 $title = $line["title"];
7472 print "<option value='$id'>$title</option>";
7477 $_SESSION = array();
7479 break; // getprofiles
7482 $mode = db_escape_string($_REQUEST['hub_mode']);
7483 $feed_id = (int) db_escape_string($_REQUEST['id']);
7484 $feed_url = db_escape_string($_REQUEST['hub_topic']);
7486 if (!PUBSUBHUBBUB_ENABLED
) {
7487 header('HTTP/1.0 404 Not Found');
7488 echo "404 Not found";
7492 // TODO: implement hub_verifytoken checking
7494 $result = db_query($link, "SELECT feed_url FROM ttrss_feeds
7495 WHERE id = '$feed_id'");
7497 if (db_num_rows($result) != 0) {
7499 $check_feed_url = db_fetch_result($result, 0, "feed_url");
7501 if ($check_feed_url && ($check_feed_url == $feed_url ||
!$feed_url)) {
7502 if ($mode == "subscribe") {
7504 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 2
7505 WHERE id = '$feed_id'");
7507 print $_REQUEST['hub_challenge'];
7510 } else if ($mode == "unsubscribe") {
7512 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 0
7513 WHERE id = '$feed_id'");
7515 print $_REQUEST['hub_challenge'];
7518 } else if (!$mode) {
7520 // Received update ping, schedule feed update.
7521 //update_rss_feed($link, $feed_id, true, true);
7523 db_query($link, "UPDATE ttrss_feeds SET
7524 last_update_started = '1970-01-01',
7525 last_updated = '1970-01-01' WHERE id = '$feed_id'");
7529 header('HTTP/1.0 404 Not Found');
7530 echo "404 Not found";
7533 header('HTTP/1.0 404 Not Found');
7534 echo "404 Not found";
7541 header("Location: tt-rss.php");
7546 $access_key = db_escape_string($_POST["key"]);
7548 // TODO: rate limit checking using last_connected
7549 $result = db_query($link, "SELECT id FROM ttrss_linked_instances
7550 WHERE access_key = '$access_key'");
7552 if (db_num_rows($result) == 1) {
7554 $instance_id = db_fetch_result($result, 0, "id");
7556 $result = db_query($link, "SELECT feed_url, site_url, title, subscribers
7557 FROM ttrss_feedbrowser_cache ORDER BY subscribers DESC LIMIT 100");
7561 while ($line = db_fetch_assoc($result)) {
7562 array_push($feeds, $line);
7565 db_query($link, "UPDATE ttrss_linked_instances SET
7566 last_status_in = 1 WHERE id = '$instance_id'");
7568 print json_encode(array("feeds" => $feeds));
7570 print json_encode(array("error" => array("code" => 6)));
7575 $uuid = db_escape_string($_REQUEST["key"]);
7577 $result = db_query($link, "SELECT ref_id, owner_uid FROM ttrss_user_entries WHERE
7580 if (db_num_rows($result) != 0) {
7581 header("Content-Type: text/html");
7583 $id = db_fetch_result($result, 0, "ref_id");
7584 $owner_uid = db_fetch_result($result, 0, "owner_uid");
7586 $_SESSION["uid"] = $owner_uid;
7587 $article = format_article($link, $id, false, true);
7588 $_SESSION["uid"] = "";
7590 print_r($article['content']);
7593 print "Article not found.";
7599 $feed = db_escape_string($_REQUEST["id"]);
7600 $key = db_escape_string($_REQUEST["key"]);
7601 $is_cat = $_REQUEST["is_cat"] != false;
7602 $limit = (int)db_escape_string($_REQUEST["limit"]);
7604 $search = db_escape_string($_REQUEST["q"]);
7605 $match_on = db_escape_string($_REQUEST["m"]);
7606 $search_mode = db_escape_string($_REQUEST["smode"]);
7607 $view_mode = db_escape_string($_REQUEST["view-mode"]);
7609 if (SINGLE_USER_MODE
) {
7610 authenticate_user($link, "admin", null);
7616 $result = db_query($link, "SELECT owner_uid FROM
7617 ttrss_access_keys WHERE access_key = '$key' AND feed_id = '$feed'");
7619 if (db_num_rows($result) == 1)
7620 $owner_id = db_fetch_result($result, 0, "owner_uid");
7624 $_SESSION['uid'] = $owner_id;
7626 generate_syndicated_feed($link, 0, $feed, $is_cat, $limit,
7627 $search, $search_mode, $match_on, $view_mode);
7629 header('HTTP/1.1 403 Forbidden');
7634 case "globalUpdateFeeds":
7635 // Update all feeds needing a update.
7636 update_daemon_common($link, 0, true, true);
7637 break; // globalUpdateFeeds
7641 header("Content-Type: text/plain");
7642 print json_encode(array("error" => array("code" => 7)));