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 'version.php';
95 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
97 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
98 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
100 ini_set('user_agent', SELF_USER_AGENT
);
102 require_once 'lib/pubsubhubbub/publisher.php';
107 $utc_tz = new DateTimeZone('UTC');
108 $schema_version = false;
111 * Print a timestamped debug message.
113 * @param string $msg The debug message.
116 function _debug($msg) {
117 $ts = strftime("%H:%M:%S", time());
118 if (function_exists('posix_getpid')) {
119 $ts = "$ts/" . posix_getpid();
121 print "[$ts] $msg\n";
125 * Purge a feed old posts.
127 * @param mixed $link A database connection.
128 * @param mixed $feed_id The id of the purged feed.
129 * @param mixed $purge_interval Olderness of purged posts.
130 * @param boolean $debug Set to True to enable the debug. False by default.
134 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
136 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
140 $result = db_query($link,
141 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
145 if (db_num_rows($result) == 1) {
146 $owner_uid = db_fetch_result($result, 0, "owner_uid");
149 if ($purge_interval == -1 ||
!$purge_interval) {
151 ccache_update($link, $feed_id, $owner_uid);
156 if (!$owner_uid) return;
158 if (FORCE_ARTICLE_PURGE
== 0) {
159 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
162 $purge_unread = true;
163 $purge_interval = FORCE_ARTICLE_PURGE
;
166 if (!$purge_unread) $query_limit = " unread = false AND ";
168 if (DB_TYPE
== "pgsql") {
169 $pg_version = get_pgsql_version($link);
171 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
173 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
174 ttrss_entries.id = ref_id AND
176 feed_id = '$feed_id' AND
178 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
182 $result = db_query($link, "DELETE FROM ttrss_user_entries
184 WHERE ttrss_entries.id = ref_id AND
186 feed_id = '$feed_id' AND
188 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
191 $rows = pg_affected_rows($result);
195 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
196 marked = false AND feed_id = '$feed_id' AND
197 (SELECT date_updated FROM ttrss_entries WHERE
198 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
200 $result = db_query($link, "DELETE FROM ttrss_user_entries
201 USING ttrss_user_entries, ttrss_entries
202 WHERE ttrss_entries.id = ref_id AND
204 feed_id = '$feed_id' AND
206 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
208 $rows = mysql_affected_rows($link);
212 ccache_update($link, $feed_id, $owner_uid);
215 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
217 } // function purge_feed
219 function feed_purge_interval($link, $feed_id) {
221 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
222 WHERE id = '$feed_id'");
224 if (db_num_rows($result) == 1) {
225 $purge_interval = db_fetch_result($result, 0, "purge_interval");
226 $owner_uid = db_fetch_result($result, 0, "owner_uid");
228 if ($purge_interval == 0) $purge_interval = get_pref($link,
229 'PURGE_OLD_DAYS', $owner_uid);
231 return $purge_interval;
238 function purge_orphans($link, $do_output = false) {
240 // purge orphaned posts in main content table
241 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
242 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
245 $rows = db_affected_rows($link, $result);
246 _debug("Purged $rows orphaned posts.");
250 function get_feed_update_interval($link, $feed_id) {
251 $result = db_query($link, "SELECT owner_uid, update_interval FROM
252 ttrss_feeds WHERE id = '$feed_id'");
254 if (db_num_rows($result) == 1) {
255 $update_interval = db_fetch_result($result, 0, "update_interval");
256 $owner_uid = db_fetch_result($result, 0, "owner_uid");
258 if ($update_interval != 0) {
259 return $update_interval;
261 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
269 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
270 $login = urlencode($login);
271 $pass = urlencode($pass);
273 if (function_exists('curl_init') && !ini_get("open_basedir")) {
274 $ch = curl_init($url);
276 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
277 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
278 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
279 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
280 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
281 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
282 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
283 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
284 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
285 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
288 curl_setopt($ch, CURLOPT_POST
, true);
289 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
293 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
295 $contents = @curl_exec
($ch);
297 if ($contents === false) {
302 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
303 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
306 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
312 if ($login && $pass ){
313 $url_parts = array();
315 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
317 if ($url_parts[1] && $url_parts[2]) {
318 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
322 return @file_get_contents
($url);
328 * Try to determine the favicon URL for a feed.
329 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
330 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
332 * @param string $url A feed or page URL
334 * @return mixed The favicon URL, or false if none was found.
336 function get_favicon_url($url) {
338 $favicon_url = false;
340 if ($html = @fetch_file_contents
($url)) {
342 libxml_use_internal_errors(true);
344 $doc = new DOMDocument();
345 $doc->loadHTML($html);
346 $xpath = new DOMXPath($doc);
348 $base = $xpath->query('/html/head/base');
349 foreach ($base as $b) {
350 $url = $b->getAttribute("href");
354 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
355 if (count($entries) > 0) {
356 foreach ($entries as $entry) {
357 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
364 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
367 } // function get_favicon_url
369 function check_feed_favicon($site_url, $feed, $link) {
370 # print "FAVICON [$site_url]: $favicon_url\n";
372 $icon_file = ICONS_DIR
. "/$feed.ico";
374 if (!file_exists($icon_file)) {
375 $favicon_url = get_favicon_url($site_url);
378 $contents = fetch_file_contents($favicon_url, "image");
381 $fp = @fopen
($icon_file, "w");
384 fwrite($fp, $contents);
386 chmod($icon_file, 0644);
393 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
397 /* Update all feeds with the same URL to utilize memcache */
400 $result = db_query($link, "SELECT f1.id
401 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
402 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
404 while ($line = db_fetch_assoc($result)) {
405 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
408 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
412 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
413 $override_url = false) {
415 require_once "lib/simplepie/simplepie.inc";
416 require_once "lib/magpierss/rss_fetch.inc";
417 require_once 'lib/magpierss/rss_utils.inc';
421 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
423 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
427 if ($debug_enabled) {
428 _debug("update_rss_feed: start");
431 if (!$ignore_daemon) {
433 if (DB_TYPE
== "pgsql") {
434 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
436 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
439 $result = db_query($link, "SELECT id,update_interval,auth_login,
440 auth_pass,cache_images,update_method
441 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
445 $result = db_query($link, "SELECT id,update_interval,auth_login,
446 feed_url,auth_pass,cache_images,update_method,last_updated,
447 mark_unread_on_update, owner_uid, update_on_checksum_change,
449 FROM ttrss_feeds WHERE id = '$feed'");
453 if (db_num_rows($result) == 0) {
454 if ($debug_enabled) {
455 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
460 $update_method = db_fetch_result($result, 0, "update_method");
461 $last_updated = db_fetch_result($result, 0, "last_updated");
462 $owner_uid = db_fetch_result($result, 0, "owner_uid");
463 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
464 0, "mark_unread_on_update"));
465 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
466 0, "update_on_checksum_change"));
467 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
469 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
470 WHERE id = '$feed'");
472 $auth_login = db_fetch_result($result, 0, "auth_login");
473 $auth_pass = db_fetch_result($result, 0, "auth_pass");
475 if ($update_method == 0)
476 $update_method = DEFAULT_UPDATE_METHOD +
1;
482 if ($update_method == 2)
483 $use_simplepie = true;
485 $use_simplepie = false;
487 if ($debug_enabled) {
488 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
491 if ($update_method == 1) {
492 $auth_login = urlencode($auth_login);
493 $auth_pass = urlencode($auth_pass);
496 $update_interval = db_fetch_result($result, 0, "update_interval");
497 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
498 $fetch_url = db_fetch_result($result, 0, "feed_url");
500 if ($update_interval < 0) { return false; }
502 $feed = db_escape_string($feed);
504 if ($auth_login && $auth_pass ){
505 $url_parts = array();
506 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
508 if ($url_parts[1] && $url_parts[2]) {
509 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
515 $fetch_url = $override_url;
517 if ($debug_enabled) {
518 _debug("update_rss_feed: fetching [$fetch_url]...");
521 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
523 if ($memcache && $obj = $memcache->get($obj_id)) {
525 if ($debug_enabled) {
526 _debug("update_rss_feed: data found in memcache.");
533 if ($update_method == 3) {
534 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
535 } else if ($update_method == 1) {
537 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
538 define('MAGPIE_CACHE_ON', !$no_cache);
539 define('MAGPIE_FETCH_TIME_OUT', 60);
540 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
542 $rss = @fetch_rss
($fetch_url);
544 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
546 if (!is_dir($simplepie_cache_dir)) {
547 mkdir($simplepie_cache_dir);
550 $rss = new SimplePie();
551 $rss->set_useragent(SELF_USER_AGENT
);
552 # $rss->set_timeout(10);
553 $rss->set_feed_url($fetch_url);
554 $rss->set_output_encoding('UTF-8');
555 $rss->force_feed(true);
557 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
559 if ($debug_enabled) {
560 _debug("enabling image cache");
563 $rss->set_image_handler("image.php", 'i');
566 if ($debug_enabled) {
567 _debug("feed update interval (sec): " .
568 get_feed_update_interval($link, $feed)*60);
571 $rss->enable_cache(!$no_cache);
574 $rss->set_cache_location($simplepie_cache_dir);
575 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
581 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
586 if ($debug_enabled) {
587 _debug("update_rss_feed: fetch done, parsing...");
590 $feed = db_escape_string($feed);
592 if ($update_method == 2) {
593 $fetch_ok = !$rss->error();
600 if ($debug_enabled) {
601 _debug("update_rss_feed: processing feed data...");
604 // db_query($link, "BEGIN");
606 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
607 FROM ttrss_feeds WHERE id = '$feed'");
609 $registered_title = db_fetch_result($result, 0, "title");
610 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
611 $orig_site_url = db_fetch_result($result, 0, "site_url");
613 $owner_uid = db_fetch_result($result, 0, "owner_uid");
615 if ($use_simplepie) {
616 $site_url = $rss->get_link();
618 $site_url = $rss->channel
["link"];
621 $site_url = rewrite_relative_url($fetch_url, $site_url);
623 if ($debug_enabled) {
624 _debug("update_rss_feed: checking favicon...");
627 check_feed_favicon($site_url, $feed, $link);
629 if (!$registered_title ||
$registered_title == "[Unknown]") {
631 if ($use_simplepie) {
632 $feed_title = db_escape_string($rss->get_title());
634 $feed_title = db_escape_string($rss->channel
["title"]);
637 if ($debug_enabled) {
638 _debug("update_rss_feed: registering title: $feed_title");
641 db_query($link, "UPDATE ttrss_feeds SET
642 title = '$feed_title' WHERE id = '$feed'");
645 // weird, weird Magpie
646 if (!$use_simplepie) {
647 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
650 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
651 db_query($link, "UPDATE ttrss_feeds SET
652 site_url = '$site_url' WHERE id = '$feed'");
655 // print "I: " . $rss->channel["image"]["url"];
657 if (!$use_simplepie) {
658 $icon_url = db_escape_string($rss->image
["url"]);
660 $icon_url = db_escape_string($rss->get_image_url());
663 $icon_url = substr($icon_url, 0, 250);
665 if ($icon_url && $orig_icon_url != $icon_url) {
666 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
669 if ($debug_enabled) {
670 _debug("update_rss_feed: loading filters...");
673 $filters = load_filters($link, $feed, $owner_uid);
675 // if ($debug_enabled) {
676 // print_r($filters);
679 if ($use_simplepie) {
680 $iterator = $rss->get_items();
682 $iterator = $rss->items
;
683 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
684 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
687 if (!is_array($iterator)) {
688 /* db_query($link, "UPDATE ttrss_feeds
689 SET last_error = 'Parse error: can\'t find any articles.'
690 WHERE id = '$feed'"); */
692 // clear any errors and mark feed as updated if fetched okay
693 // even if it's blank
695 if ($debug_enabled) {
696 _debug("update_rss_feed: entry iterator is not an array, no articles?");
699 db_query($link, "UPDATE ttrss_feeds
700 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
702 return; // no articles
705 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
707 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
709 $feed_hub_url = false;
710 if ($use_simplepie) {
711 $links = $rss->get_links('hub');
713 if ($links && is_array($links)) {
714 foreach ($links as $l) {
721 $atom = $rss->channel
['atom'];
724 if ($atom['link@rel'] == 'hub') {
725 $feed_hub_url = $atom['link@href'];
728 if (!$feed_hub_url && $atom['link#'] > 1) {
729 for ($i = 2; $i <= $atom['link#']; $i++
) {
730 if ($atom["link#$i@rel"] == 'hub') {
731 $feed_hub_url = $atom["link#$i@href"];
737 $feed_hub_url = $rss->channel
['link_hub'];
741 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
743 if ($feed_hub_url && function_exists('curl_init') &&
744 !ini_get("open_basedir")) {
746 require_once 'lib/pubsubhubbub/subscriber.php';
748 $callback_url = get_self_url_prefix() .
749 "/public.php?op=pubsub&id=$feed";
751 $s = new Subscriber($feed_hub_url, $callback_url);
753 $rc = $s->subscribe($fetch_url);
756 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
758 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
759 WHERE id = '$feed'");
763 if ($debug_enabled) {
764 _debug("update_rss_feed: processing articles...");
767 foreach ($iterator as $item) {
769 if ($_REQUEST['xdebug'] == 2) {
773 if ($use_simplepie) {
774 $entry_guid = $item->get_id();
775 if (!$entry_guid) $entry_guid = $item->get_link();
776 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
780 $entry_guid = $item["id"];
782 if (!$entry_guid) $entry_guid = $item["guid"];
783 if (!$entry_guid) $entry_guid = $item["about"];
784 if (!$entry_guid) $entry_guid = $item["link"];
785 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
788 if ($debug_enabled) {
789 _debug("update_rss_feed: guid $entry_guid");
792 if (!$entry_guid) continue;
794 $entry_timestamp = "";
796 if ($use_simplepie) {
797 $entry_timestamp = strtotime($item->get_date());
799 $rss_2_date = $item['pubdate'];
800 $rss_1_date = $item['dc']['date'];
801 $atom_date = $item['issued'];
802 if (!$atom_date) $atom_date = $item['updated'];
804 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
805 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
806 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
810 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
811 $entry_timestamp = time();
812 $no_orig_date = 'true';
814 $no_orig_date = 'false';
817 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
819 if ($debug_enabled) {
820 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
823 if ($use_simplepie) {
824 $entry_title = $item->get_title();
826 $entry_title = trim(strip_tags($item["title"]));
829 if ($use_simplepie) {
830 $entry_link = $item->get_link();
832 // strange Magpie workaround
833 $entry_link = $item["link_"];
834 if (!$entry_link) $entry_link = $item["link"];
837 $entry_link = rewrite_relative_url($site_url, $entry_link);
839 if ($debug_enabled) {
840 _debug("update_rss_feed: title $entry_title");
841 _debug("update_rss_feed: link $entry_link");
844 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
846 $entry_link = strip_tags($entry_link);
848 if ($use_simplepie) {
849 $entry_content = $item->get_content();
850 if (!$entry_content) $entry_content = $item->get_description();
852 $entry_content = $item["content:escaped"];
854 if (!$entry_content) $entry_content = $item["content:encoded"];
855 if (!$entry_content) $entry_content = $item["content"]["encoded"];
856 if (!$entry_content) $entry_content = $item["content"];
858 if (is_array($entry_content)) $entry_content = $entry_content[0];
860 // Magpie bugs are getting ridiculous
861 if (trim($entry_content) == "Array") $entry_content = false;
863 if (!$entry_content) $entry_content = $item["atom_content"];
864 if (!$entry_content) $entry_content = $item["summary"];
866 if (!$entry_content ||
867 strlen($entry_content) < strlen($item["description"])) {
868 $entry_content = $item["description"];
872 if (is_array($entry_content)) {
873 $entry_content = $entry_content["encoded"];
874 if (!$entry_content) $entry_content = $entry_content["escaped"];
878 if ($_REQUEST["xdebug"] == 2) {
879 print "update_rss_feed: content: ";
880 print_r(htmlspecialchars($entry_content));
883 $entry_content_unescaped = $entry_content;
885 if ($use_simplepie) {
886 $entry_comments = strip_tags($item->data
["comments"]);
887 if ($item->get_author()) {
888 $entry_author_item = $item->get_author();
889 $entry_author = $entry_author_item->get_name();
890 if (!$entry_author) $entry_author = $entry_author_item->get_email();
892 $entry_author = db_escape_string($entry_author);
895 $entry_comments = strip_tags($item["comments"]);
897 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
899 if ($item['author']) {
901 if (is_array($item['author'])) {
903 if (!$entry_author) {
904 $entry_author = db_escape_string(strip_tags($item['author']['name']));
907 if (!$entry_author) {
908 $entry_author = db_escape_string(strip_tags($item['author']['email']));
912 if (!$entry_author) {
913 $entry_author = db_escape_string(strip_tags($item['author']));
918 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
920 $entry_guid = db_escape_string(strip_tags($entry_guid));
921 $entry_guid = mb_substr($entry_guid, 0, 250);
923 $result = db_query($link, "SELECT id FROM ttrss_entries
924 WHERE guid = '$entry_guid'");
926 $entry_content = db_escape_string($entry_content, false);
928 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
930 $entry_title = db_escape_string($entry_title);
931 $entry_link = db_escape_string($entry_link);
932 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
933 $entry_author = mb_substr($entry_author, 0, 250);
935 if ($use_simplepie) {
936 $num_comments = 0; #FIXME#
938 $num_comments = db_escape_string($item["slash"]["comments"]);
941 if (!$num_comments) $num_comments = 0;
943 if ($debug_enabled) {
944 _debug("update_rss_feed: looking for tags [1]...");
947 // parse <category> entries into tags
949 $additional_tags = array();
951 if ($use_simplepie) {
953 $additional_tags_src = $item->get_categories();
955 if (is_array($additional_tags_src)) {
956 foreach ($additional_tags_src as $tobj) {
957 array_push($additional_tags, $tobj->get_term());
961 if ($debug_enabled) {
962 _debug("update_rss_feed: category tags:");
963 print_r($additional_tags);
968 $t_ctr = $item['category#'];
971 $additional_tags = array();
972 } else if ($t_ctr > 0) {
973 $additional_tags = array($item['category']);
975 if ($item['category@term']) {
976 array_push($additional_tags, $item['category@term']);
979 for ($i = 0; $i <= $t_ctr; $i++
) {
980 if ($item["category#$i"]) {
981 array_push($additional_tags, $item["category#$i"]);
984 if ($item["category#$i@term"]) {
985 array_push($additional_tags, $item["category#$i@term"]);
990 // parse <dc:subject> elements
992 $t_ctr = $item['dc']['subject#'];
995 array_push($additional_tags, $item['dc']['subject']);
997 for ($i = 0; $i <= $t_ctr; $i++
) {
998 if ($item['dc']["subject#$i"]) {
999 array_push($additional_tags, $item['dc']["subject#$i"]);
1005 if ($debug_enabled) {
1006 _debug("update_rss_feed: looking for tags [2]...");
1010 // <a href="..." rel="tag">Xorg</a>, //
1014 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1015 $entry_content_unescaped, $entry_tags);
1017 $entry_tags = $entry_tags[1];
1019 $entry_tags = array_merge($entry_tags, $additional_tags);
1020 $entry_tags = array_unique($entry_tags);
1022 for ($i = 0; $i < count($entry_tags); $i++
)
1023 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1025 if ($debug_enabled) {
1026 _debug("update_rss_feed: unfiltered tags found:");
1027 print_r($entry_tags);
1032 $entry_content = sanitize_article_content($entry_content);
1033 $entry_title = sanitize_article_content($entry_title);
1035 if ($debug_enabled) {
1036 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1039 db_query($link, "BEGIN");
1041 if (db_num_rows($result) == 0) {
1043 if ($debug_enabled) {
1044 _debug("update_rss_feed: base guid not found");
1047 // base post entry does not exist, create it
1049 $result = db_query($link,
1050 "INSERT INTO ttrss_entries
1067 '$entry_timestamp_fmt',
1077 // we keep encountering the entry in feeds, so we need to
1078 // update date_updated column so that we don't get horrible
1079 // dupes when the entry gets purged and reinserted again e.g.
1080 // in the case of SLOW SLOW OMG SLOW updating feeds
1082 $base_entry_id = db_fetch_result($result, 0, "id");
1084 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1085 WHERE id = '$base_entry_id'");
1088 // now it should exist, if not - bad luck then
1090 $result = db_query($link, "SELECT
1091 id,content_hash,no_orig_date,title,
1092 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1093 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1097 WHERE guid = '$entry_guid'");
1102 if (db_num_rows($result) == 1) {
1104 if ($debug_enabled) {
1105 _debug("update_rss_feed: base guid found, checking for user record");
1108 // this will be used below in update handler
1109 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1110 $orig_title = db_fetch_result($result, 0, "title");
1111 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1112 $orig_date_updated = strtotime(db_fetch_result($result,
1113 0, "date_updated"));
1115 $ref_id = db_fetch_result($result, 0, "id");
1116 $entry_ref_id = $ref_id;
1118 // check for user post link to main table
1120 // do we allow duplicate posts with same GUID in different feeds?
1121 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1122 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1124 $dupcheck_qpart = "";
1127 /* Collect article tags here so we could filter by them: */
1129 $article_filters = get_article_filters($filters, $entry_title,
1130 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1133 if ($debug_enabled) {
1134 _debug("update_rss_feed: article filters: ");
1135 if (count($article_filters) != 0) {
1136 print_r($article_filters);
1140 if (find_article_filter($article_filters, "filter")) {
1141 db_query($link, "COMMIT"); // close transaction in progress
1145 $score = calculate_article_score($article_filters);
1147 if ($debug_enabled) {
1148 _debug("update_rss_feed: initial score: $score");
1151 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1152 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1155 // if ($_REQUEST["xdebug"]) print "$query\n";
1157 $result = db_query($link, $query);
1159 // okay it doesn't exist - create user entry
1160 if (db_num_rows($result) == 0) {
1162 if ($debug_enabled) {
1163 _debug("update_rss_feed: user record not found, creating...");
1166 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1168 $last_read_qpart = 'NULL';
1171 $last_read_qpart = 'NOW()';
1174 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1180 if (find_article_filter($article_filters, 'publish')) {
1181 $published = 'true';
1183 $published = 'false';
1186 $result = db_query($link,
1187 "INSERT INTO ttrss_user_entries
1188 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1189 published, score, tag_cache, label_cache, uuid)
1190 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1191 $last_read_qpart, $marked, $published, '$score', '', '', '')");
1193 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1194 $rss_link = get_self_url_prefix() .
1195 "/public.php?op=rss&id=-2&key=" .
1196 get_feed_access_key($link, -2, false, $owner_uid);
1198 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1200 $pubsub_result = $p->publish_update($rss_link);
1203 $result = db_query($link,
1204 "SELECT int_id FROM ttrss_user_entries WHERE
1205 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1206 feed_id = '$feed' LIMIT 1");
1208 if (db_num_rows($result) == 1) {
1209 $entry_int_id = db_fetch_result($result, 0, "int_id");
1212 if ($debug_enabled) {
1213 _debug("update_rss_feed: user record FOUND");
1216 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1217 $entry_int_id = db_fetch_result($result, 0, "int_id");
1220 if ($debug_enabled) {
1221 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1224 $post_needs_update = false;
1225 $update_insignificant = false;
1227 if ($orig_num_comments != $num_comments) {
1228 $post_needs_update = true;
1229 $update_insignificant = true;
1232 if ($content_hash != $orig_content_hash) {
1233 $post_needs_update = true;
1234 $update_insignificant = false;
1237 if (db_escape_string($orig_title) != $entry_title) {
1238 $post_needs_update = true;
1239 $update_insignificant = false;
1242 // if post needs update, update it and mark all user entries
1243 // linking to this post as updated
1244 if ($post_needs_update) {
1246 if (defined('DAEMON_EXTENDED_DEBUG')) {
1247 _debug("update_rss_feed: post $entry_guid needs update...");
1250 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1252 db_query($link, "UPDATE ttrss_entries
1253 SET title = '$entry_title', content = '$entry_content',
1254 content_hash = '$content_hash',
1255 updated = '$entry_timestamp_fmt',
1256 num_comments = '$num_comments'
1257 WHERE id = '$ref_id'");
1259 if (!$update_insignificant) {
1260 if ($mark_unread_on_update) {
1261 db_query($link, "UPDATE ttrss_user_entries
1262 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1263 } else if ($update_on_checksum_change) {
1264 db_query($link, "UPDATE ttrss_user_entries
1265 SET last_read = null WHERE ref_id = '$ref_id'
1266 AND unread = false");
1272 db_query($link, "COMMIT");
1274 if ($debug_enabled) {
1275 _debug("update_rss_feed: assigning labels...");
1278 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1281 if ($debug_enabled) {
1282 _debug("update_rss_feed: looking for enclosures...");
1287 $enclosures = array();
1289 if ($use_simplepie) {
1290 $encs = $item->get_enclosures();
1292 if (is_array($encs)) {
1293 foreach ($encs as $e) {
1295 $e->link
, $e->type
, $e->length
);
1297 array_push($enclosures, $e_item);
1304 $e_ctr = $item['enclosure#'];
1307 $e_item = array($item['enclosure@url'],
1308 $item['enclosure@type'],
1309 $item['enclosure@length']);
1311 array_push($enclosures, $e_item);
1313 for ($i = 0; $i <= $e_ctr; $i++
) {
1315 if ($item["enclosure#$i@url"]) {
1316 $e_item = array($item["enclosure#$i@url"],
1317 $item["enclosure#$i@type"],
1318 $item["enclosure#$i@length"]);
1319 array_push($enclosures, $e_item);
1325 // can there be many of those? yes -fox
1327 $m_ctr = $item['media']['content#'];
1330 $e_item = array($item['media']['content@url'],
1331 $item['media']['content@medium'],
1332 $item['media']['content@length']);
1334 array_push($enclosures, $e_item);
1336 for ($i = 0; $i <= $m_ctr; $i++
) {
1338 if ($item["media"]["content#$i@url"]) {
1339 $e_item = array($item["media"]["content#$i@url"],
1340 $item["media"]["content#$i@medium"],
1341 $item["media"]["content#$i@length"]);
1342 array_push($enclosures, $e_item);
1350 if ($debug_enabled) {
1351 _debug("update_rss_feed: article enclosures:");
1352 print_r($enclosures);
1355 db_query($link, "BEGIN");
1357 foreach ($enclosures as $enc) {
1358 $enc_url = db_escape_string($enc[0]);
1359 $enc_type = db_escape_string($enc[1]);
1360 $enc_dur = db_escape_string($enc[2]);
1362 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1363 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1365 if (db_num_rows($result) == 0) {
1366 db_query($link, "INSERT INTO ttrss_enclosures
1367 (content_url, content_type, title, duration, post_id) VALUES
1368 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1372 db_query($link, "COMMIT");
1374 // check for manual tags (we have to do it here since they're loaded from filters)
1376 foreach ($article_filters as $f) {
1377 if ($f[0] == "tag") {
1379 $manual_tags = trim_array(explode(",", $f[1]));
1381 foreach ($manual_tags as $tag) {
1382 if (tag_is_valid($tag)) {
1383 array_push($entry_tags, $tag);
1391 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1392 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1394 $filtered_tags = array();
1395 $tags_to_cache = array();
1397 if ($entry_tags && is_array($entry_tags)) {
1398 foreach ($entry_tags as $tag) {
1399 if (array_search($tag, $boring_tags) === false) {
1400 array_push($filtered_tags, $tag);
1405 $filtered_tags = array_unique($filtered_tags);
1407 if ($debug_enabled) {
1408 _debug("update_rss_feed: filtered article tags:");
1409 print_r($filtered_tags);
1412 // Save article tags in the database
1414 if (count($filtered_tags) > 0) {
1416 db_query($link, "BEGIN");
1418 foreach ($filtered_tags as $tag) {
1420 $tag = sanitize_tag($tag);
1421 $tag = db_escape_string($tag);
1423 if (!tag_is_valid($tag)) continue;
1425 $result = db_query($link, "SELECT id FROM ttrss_tags
1426 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1427 owner_uid = '$owner_uid' LIMIT 1");
1429 if ($result && db_num_rows($result) == 0) {
1431 db_query($link, "INSERT INTO ttrss_tags
1432 (owner_uid,tag_name,post_int_id)
1433 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1436 array_push($tags_to_cache, $tag);
1439 /* update the cache */
1441 $tags_to_cache = array_unique($tags_to_cache);
1443 $tags_str = db_escape_string(join(",", $tags_to_cache));
1445 db_query($link, "UPDATE ttrss_user_entries
1446 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1447 AND owner_uid = $owner_uid");
1449 db_query($link, "COMMIT");
1452 if ($debug_enabled) {
1453 _debug("update_rss_feed: article processed");
1457 if (!$last_updated) {
1458 if ($debug_enabled) {
1459 _debug("update_rss_feed: new feed, catching it up...");
1461 catchup_feed($link, $feed, false, $owner_uid);
1464 if ($debug_enabled) {
1465 _debug("purging feed...");
1468 purge_feed($link, $feed, 0, $debug_enabled);
1470 db_query($link, "UPDATE ttrss_feeds
1471 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1473 // db_query($link, "COMMIT");
1477 if ($use_simplepie) {
1478 $error_msg = mb_substr($rss->error(), 0, 250);
1480 $error_msg = mb_substr(magpie_error(), 0, 250);
1483 if ($debug_enabled) {
1484 _debug("update_rss_feed: error fetching feed: $error_msg");
1487 $error_msg = db_escape_string($error_msg);
1490 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1491 last_updated = NOW() WHERE id = '$feed'");
1494 if ($use_simplepie) {
1498 if ($debug_enabled) {
1499 _debug("update_rss_feed: done");
1504 function print_select($id, $default, $values, $attributes = "") {
1505 print "<select name=\"$id\" id=\"$id\" $attributes>";
1506 foreach ($values as $v) {
1508 $sel = "selected=\"1\"";
1512 print "<option value=\"$v\" $sel>$v</option>";
1517 function print_select_hash($id, $default, $values, $attributes = "") {
1518 print "<select name=\"$id\" id='$id' $attributes>";
1519 foreach (array_keys($values) as $v) {
1521 $sel = 'selected="selected"';
1525 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1531 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1534 if ($filters["title"]) {
1535 foreach ($filters["title"] as $filter) {
1536 $reg_exp = $filter["reg_exp"];
1537 $inverse = $filter["inverse"];
1538 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1539 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1541 array_push($matches, array($filter["action"], $filter["action_param"]));
1546 if ($filters["content"]) {
1547 foreach ($filters["content"] as $filter) {
1548 $reg_exp = $filter["reg_exp"];
1549 $inverse = $filter["inverse"];
1551 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1552 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1554 array_push($matches, array($filter["action"], $filter["action_param"]));
1559 if ($filters["both"]) {
1560 foreach ($filters["both"] as $filter) {
1561 $reg_exp = $filter["reg_exp"];
1562 $inverse = $filter["inverse"];
1565 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1566 array_push($matches, array($filter["action"], $filter["action_param"]));
1569 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1570 array_push($matches, array($filter["action"], $filter["action_param"]));
1576 if ($filters["link"]) {
1577 $reg_exp = $filter["reg_exp"];
1578 foreach ($filters["link"] as $filter) {
1579 $reg_exp = $filter["reg_exp"];
1580 $inverse = $filter["inverse"];
1582 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1583 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1585 array_push($matches, array($filter["action"], $filter["action_param"]));
1590 if ($filters["date"]) {
1591 $reg_exp = $filter["reg_exp"];
1592 foreach ($filters["date"] as $filter) {
1593 $date_modifier = $filter["filter_param"];
1594 $inverse = $filter["inverse"];
1595 $check_timestamp = strtotime($filter["reg_exp"]);
1597 # no-op when timestamp doesn't parse to prevent misfires
1599 if ($check_timestamp) {
1602 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1603 $date_modifier == "after" && $timestamp > $check_timestamp) {
1607 if ($inverse) $match_ok = !$match_ok;
1610 array_push($matches, array($filter["action"], $filter["action_param"]));
1616 if ($filters["author"]) {
1617 foreach ($filters["author"] as $filter) {
1618 $reg_exp = $filter["reg_exp"];
1619 $inverse = $filter["inverse"];
1620 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1621 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1623 array_push($matches, array($filter["action"], $filter["action_param"]));
1628 if ($filters["tag"]) {
1630 $tag_string = join(",", $tags);
1632 foreach ($filters["tag"] as $filter) {
1633 $reg_exp = $filter["reg_exp"];
1634 $inverse = $filter["inverse"];
1636 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1637 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1639 array_push($matches, array($filter["action"], $filter["action_param"]));
1648 function find_article_filter($filters, $filter_name) {
1649 foreach ($filters as $f) {
1650 if ($f[0] == $filter_name) {
1657 function calculate_article_score($filters) {
1660 foreach ($filters as $f) {
1661 if ($f[0] == "score") {
1668 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1669 foreach ($filters as $f) {
1670 if ($f[0] == "label") {
1671 label_add_article($link, $id, $f[1], $owner_uid);
1676 function getmicrotime() {
1677 list($usec, $sec) = explode(" ",microtime());
1678 return ((float)$usec +
(float)$sec);
1681 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1682 foreach ($values as $v) {
1689 if ($v == $true_is) {
1690 $sel .= " value=\"1\"";
1692 $sel .= " value=\"0\"";
1695 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1696 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1701 function initialize_user_prefs($link, $uid, $profile = false) {
1703 $uid = db_escape_string($uid);
1707 $profile_qpart = "AND profile IS NULL";
1709 $profile_qpart = "AND profile = '$profile'";
1712 if (get_schema_version($link) < 63) $profile_qpart = "";
1714 db_query($link, "BEGIN");
1716 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1718 $u_result = db_query($link, "SELECT pref_name
1719 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1721 $active_prefs = array();
1723 while ($line = db_fetch_assoc($u_result)) {
1724 array_push($active_prefs, $line["pref_name"]);
1727 while ($line = db_fetch_assoc($result)) {
1728 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1729 // print "adding " . $line["pref_name"] . "<br>";
1731 if (get_schema_version($link) < 63) {
1732 db_query($link, "INSERT INTO ttrss_user_prefs
1733 (owner_uid,pref_name,value) VALUES
1734 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1737 db_query($link, "INSERT INTO ttrss_user_prefs
1738 (owner_uid,pref_name,value, profile) VALUES
1739 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1745 db_query($link, "COMMIT");
1749 function get_ssl_certificate_id() {
1750 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1751 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1752 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1753 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1754 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1759 function get_login_by_ssl_certificate($link) {
1761 $cert_serial = db_escape_string(get_ssl_certificate_id());
1764 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1765 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1766 owner_uid = ttrss_users.id");
1768 if (db_num_rows($result) != 0) {
1769 return db_escape_string(db_fetch_result($result, 0, "login"));
1776 function get_remote_user($link) {
1778 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
1779 return db_escape_string($_SERVER["REMOTE_USER"]);
1782 return db_escape_string(get_login_by_ssl_certificate($link));
1785 function get_remote_fakepass($link) {
1786 if (get_remote_user($link))
1792 function authenticate_user($link, $login, $password, $force_auth = false) {
1794 if (!SINGLE_USER_MODE
) {
1796 $pwd_hash1 = encrypt_password($password);
1797 $pwd_hash2 = encrypt_password($password, $login);
1798 $login = db_escape_string($login);
1800 $remote_user = get_remote_user($link);
1802 if ($remote_user && $remote_user == $login && $login != "admin") {
1804 $login = $remote_user;
1806 $query = "SELECT id,login,access_level,pwd_hash
1807 FROM ttrss_users WHERE
1810 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1811 && $_SERVER["REMOTE_USER"]) {
1812 $result = db_query($link, $query);
1815 if (db_num_rows($result) == 0) {
1816 $query2 = "INSERT INTO ttrss_users
1817 (login,access_level,last_login,created)
1818 VALUES ('$login', 0, null, NOW())";
1819 db_query($link, $query2);
1824 $query = "SELECT id,login,access_level,pwd_hash
1825 FROM ttrss_users WHERE
1826 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1827 pwd_hash = '$pwd_hash2')";
1830 $result = db_query($link, $query);
1832 if (db_num_rows($result) == 1) {
1833 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1834 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1835 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1837 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1841 // LemonLDAP can send user informations via HTTP HEADER
1842 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
1844 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1846 $fullname = db_escape_string($fullname);
1847 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1851 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1853 $email = db_escape_string($email);
1854 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1859 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1860 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1862 $_SESSION["last_version_check"] = time();
1864 initialize_user_prefs($link, $_SESSION["uid"]);
1873 $_SESSION["uid"] = 1;
1874 $_SESSION["name"] = "admin";
1876 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1878 initialize_user_prefs($link, $_SESSION["uid"]);
1884 function make_password($length = 8) {
1887 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1891 while ($i < $length) {
1892 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1894 if (!strstr($password, $char)) {
1902 // this is called after user is created to initialize default feeds, labels
1905 // user preferences are checked on every login, not here
1907 function initialize_user($link, $uid) {
1909 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1910 values ('$uid', 'Tiny Tiny RSS: New Releases',
1911 'http://tt-rss.org/releases.rss')");
1913 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1914 values ('$uid', 'Tiny Tiny RSS: Forum',
1915 'http://tt-rss.org/forum/rss.php')");
1918 function logout_user() {
1920 if (isset($_COOKIE[session_name()])) {
1921 setcookie(session_name(), '', time()-42000, '/');
1925 function validate_session($link) {
1926 if (SINGLE_USER_MODE
) return true;
1928 $check_ip = $_SESSION['ip_address'];
1930 switch (SESSION_CHECK_ADDRESS
) {
1935 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1938 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1939 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
1943 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
1944 $_SESSION["login_error_msg"] =
1945 __("Session failed to validate (incorrect IP)");
1949 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
1952 if ($_SESSION["uid"]) {
1954 $result = db_query($link,
1955 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1957 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1959 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1964 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1966 //print_r($_SESSION);
1968 if (time() > $_SESSION["cookie_lifetime"]) {
1976 function login_sequence($link, $mobile = false) {
1977 $_SESSION["prefs_cache"] = array();
1979 if (!SINGLE_USER_MODE
) {
1981 $login_action = $_POST["login_action"];
1983 # try to authenticate user if called from login form
1984 if ($login_action == "do_login") {
1985 $login = db_escape_string($_POST["login"]);
1986 $password = $_POST["password"];
1987 $remember_me = $_POST["remember_me"];
1989 if (authenticate_user($link, $login, $password)) {
1990 $_POST["password"] = "";
1992 $_SESSION["language"] = $_POST["language"];
1993 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1994 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1996 if ($_POST["profile"]) {
1998 $profile = db_escape_string($_POST["profile"]);
2000 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2001 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2003 if (db_num_rows($result) != 0) {
2004 $_SESSION["profile"] = $profile;
2005 $_SESSION["prefs_cache"] = array();
2009 if ($_REQUEST['return']) {
2010 header("Location: " . $_REQUEST['return']);
2012 header("Location: " . $_SERVER["REQUEST_URI"]);
2019 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2023 if (!$_SESSION["uid"] ||
!validate_session($link)) {
2025 if (get_remote_user($link) && AUTO_LOGIN
) {
2026 authenticate_user($link, get_remote_user($link), null);
2027 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2029 render_login_form($link, $mobile);
2030 //header("Location: login.php");
2034 /* bump login timestamp */
2035 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2038 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
2039 setcookie("ttrss_lang", $_SESSION["language"],
2040 time() + SESSION_COOKIE_LIFETIME
);
2043 // try to remove possible duplicates from feed counter cache
2044 // ccache_cleanup($link, $_SESSION["uid"]);
2048 return authenticate_user($link, "admin", null);
2052 function truncate_string($str, $max_len, $suffix = '…') {
2053 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2054 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2060 function theme_image($link, $filename) {
2062 $theme_path = get_user_theme_path($link);
2064 if ($theme_path && is_file($theme_path.$filename)) {
2065 return $theme_path.$filename;
2074 function get_user_theme($link) {
2076 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2077 $theme_name = get_pref($link, "_THEME_ID");
2078 if (is_dir("themes/$theme_name")) {
2089 function get_user_theme_path($link) {
2092 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2093 $theme_name = get_pref($link, "_THEME_ID");
2095 if ($theme_name && is_dir("themes/$theme_name")) {
2096 $theme_path = "themes/$theme_name/";
2105 if (is_file("$theme_path/theme.ini")) {
2106 $ini = parse_ini_file("$theme_path/theme.ini", true);
2107 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2115 function get_user_theme_options($link) {
2116 $t = get_user_theme_path($link);
2119 if (is_file("$t/theme.ini")) {
2120 $ini = parse_ini_file("$t/theme.ini", true);
2121 if ($ini['theme']['version']) {
2122 return $ini['theme']['options'];
2129 function print_theme_includes($link) {
2131 $t = get_user_theme_path($link);
2135 print "<link rel=\"stylesheet\" type=\"text/css\"
2136 href=\"$t/theme.css?$time \">";
2137 if (file_exists("$t/theme.js")) {
2138 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2144 function get_all_themes() {
2145 $themes = glob("themes/*");
2151 foreach ($themes as $t) {
2152 if (is_file("$t/theme.ini")) {
2153 $ini = parse_ini_file("$t/theme.ini", true);
2154 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2155 !$ini['theme']['disabled']) {
2157 $entry["path"] = $t;
2158 $entry["base"] = basename($t);
2159 $entry["name"] = $ini['theme']['name'];
2160 $entry["version"] = $ini['theme']['version'];
2161 $entry["author"] = $ini['theme']['author'];
2162 $entry["options"] = $ini['theme']['options'];
2163 array_push($rv, $entry);
2171 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2174 $source_tz = new DateTimeZone($source_tz);
2175 } catch (Exception
$e) {
2176 $source_tz = new DateTimeZone('UTC');
2180 $dest_tz = new DateTimeZone($dest_tz);
2181 } catch (Exception
$e) {
2182 $dest_tz = new DateTimeZone('UTC');
2185 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2186 return $dt->format('U') +
$dest_tz->getOffset($dt);
2189 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2190 $no_smart_dt = false) {
2192 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2193 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2198 # We store date in UTC internally
2199 $dt = new DateTime($timestamp, $utc_tz);
2201 if ($tz_offset == -1) {
2203 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2206 $user_tz = new DateTimeZone($user_tz_string);
2207 } catch (Exception
$e) {
2211 $tz_offset = $user_tz->getOffset($dt);
2214 $user_timestamp = $dt->format('U') +
$tz_offset;
2216 if (!$no_smart_dt) {
2217 return smart_date_time($link, $user_timestamp,
2218 $tz_offset, $owner_uid);
2221 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2223 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2225 return date($format, $user_timestamp);
2229 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2230 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2232 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2233 return date("G:i", $timestamp);
2234 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2235 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2236 return date($format, $timestamp);
2238 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2239 return date($format, $timestamp);
2243 function sql_bool_to_bool($s) {
2244 if ($s == "t" ||
$s == "1" ||
$s == "true") {
2251 function bool_to_sql_bool($s) {
2259 // Session caching removed due to causing wrong redirects to upgrade
2260 // script when get_schema_version() is called on an obsolete session
2261 // created on a previous schema version.
2262 function get_schema_version($link, $nocache = false) {
2263 global $schema_version;
2265 if (!$schema_version) {
2266 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2267 $version = db_fetch_result($result, 0, "schema_version");
2268 $schema_version = $version;
2271 return $schema_version;
2275 function sanity_check($link) {
2276 require_once 'errors.php';
2279 $schema_version = get_schema_version($link, true);
2281 if ($schema_version != SCHEMA_VERSION
) {
2285 if (DB_TYPE
== "mysql") {
2286 $result = db_query($link, "SELECT true", false);
2287 if (db_num_rows($result) != 1) {
2292 if (db_escape_string("testTEST") != "testTEST") {
2296 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2299 function file_is_locked($filename) {
2300 if (function_exists('flock')) {
2301 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2303 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2304 flock($fp, LOCK_UN
);
2314 return true; // consider the file always locked and skip the test
2317 function make_lockfile($filename) {
2318 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2320 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2321 if (function_exists('posix_getpid')) {
2322 fwrite($fp, posix_getpid() . "\n");
2330 function make_stampfile($filename) {
2331 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2333 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2334 fwrite($fp, time() . "\n");
2335 flock($fp, LOCK_UN
);
2343 function sql_random_function() {
2344 if (DB_TYPE
== "mysql") {
2351 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2353 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2355 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2357 if (is_numeric($feed)) {
2363 $cat_qpart = "cat_id = '$feed'";
2365 $cat_qpart = "cat_id IS NULL";
2368 $tmp_result = db_query($link, "SELECT id
2369 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2371 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2373 $tmp_feed = $tmp_line["id"];
2375 db_query($link, "UPDATE ttrss_user_entries
2376 SET unread = false,last_read = NOW()
2377 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2379 } else if ($feed == -2) {
2381 db_query($link, "UPDATE ttrss_user_entries
2382 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2383 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2384 AND unread = true AND owner_uid = $owner_uid");
2387 } else if ($feed > 0) {
2389 db_query($link, "UPDATE ttrss_user_entries
2390 SET unread = false,last_read = NOW()
2391 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2393 } else if ($feed < 0 && $feed > -10) { // special, like starred
2396 db_query($link, "UPDATE ttrss_user_entries
2397 SET unread = false,last_read = NOW()
2398 WHERE marked = true AND owner_uid = $owner_uid");
2402 db_query($link, "UPDATE ttrss_user_entries
2403 SET unread = false,last_read = NOW()
2404 WHERE published = true AND owner_uid = $owner_uid");
2409 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2411 if (DB_TYPE
== "pgsql") {
2412 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2414 $match_part = "updated > DATE_SUB(NOW(),
2415 INTERVAL $intl HOUR) ";
2418 $result = db_query($link, "SELECT id FROM ttrss_entries,
2419 ttrss_user_entries WHERE $match_part AND
2421 ttrss_user_entries.ref_id = ttrss_entries.id AND
2422 owner_uid = $owner_uid");
2424 $affected_ids = array();
2426 while ($line = db_fetch_assoc($result)) {
2427 array_push($affected_ids, $line["id"]);
2430 catchupArticlesById($link, $affected_ids, 0);
2434 db_query($link, "UPDATE ttrss_user_entries
2435 SET unread = false,last_read = NOW()
2436 WHERE owner_uid = $owner_uid");
2439 } else if ($feed < -10) { // label
2441 $label_id = -$feed - 11;
2443 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2444 SET unread = false, last_read = NOW()
2445 WHERE label_id = '$label_id' AND unread = true
2446 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2450 ccache_update($link, $feed, $owner_uid, $cat_view);
2453 db_query($link, "BEGIN");
2455 $tag_name = db_escape_string($feed);
2457 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2458 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2460 while ($line = db_fetch_assoc($result)) {
2461 db_query($link, "UPDATE ttrss_user_entries SET
2462 unread = false, last_read = NOW()
2463 WHERE int_id = " . $line["post_int_id"]);
2465 db_query($link, "COMMIT");
2469 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2471 if (!$omode) $omode = "flc";
2473 $data = getGlobalCounters($link);
2475 $data = array_merge($data, getVirtCounters($link));
2477 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2478 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2479 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2480 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
2485 function getCategoryCounters($link) {
2488 /* Labels category */
2490 $cv = array("id" => -2, "kind" => "cat",
2491 "counter" => getCategoryUnread($link, -2));
2493 array_push($ret_arr, $cv);
2495 $age_qpart = getMaxAgeSubquery();
2497 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2498 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2499 WHERE ttrss_cat_counters_cache.feed_id = id AND
2500 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2502 while ($line = db_fetch_assoc($result)) {
2503 $line["cat_id"] = (int) $line["cat_id"];
2505 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2506 "counter" => $line["unread"]);
2508 array_push($ret_arr, $cv);
2511 /* Special case: NULL category doesn't actually exist in the DB */
2513 $cv = array("id" => 0, "kind" => "cat",
2514 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2516 array_push($ret_arr, $cv);
2521 function getCategoryUnread($link, $cat, $owner_uid = false) {
2523 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2528 $cat_query = "cat_id = '$cat'";
2530 $cat_query = "cat_id IS NULL";
2533 $age_qpart = getMaxAgeSubquery();
2535 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2536 AND owner_uid = " . $owner_uid);
2538 $cat_feeds = array();
2539 while ($line = db_fetch_assoc($result)) {
2540 array_push($cat_feeds, "feed_id = " . $line["id"]);
2543 if (count($cat_feeds) == 0) return 0;
2545 $match_part = implode(" OR ", $cat_feeds);
2547 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2548 FROM ttrss_user_entries,ttrss_entries
2549 WHERE unread = true AND ($match_part) AND id = ref_id
2550 AND $age_qpart AND owner_uid = " . $owner_uid);
2554 # this needs to be rewritten
2555 while ($line = db_fetch_assoc($result)) {
2556 $unread +
= $line["unread"];
2560 } else if ($cat == -1) {
2561 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2562 } else if ($cat == -2) {
2564 $result = db_query($link, "
2565 SELECT COUNT(unread) AS unread FROM
2566 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2567 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2568 ttrss_labels2.owner_uid = '$owner_uid'
2569 AND unread = true AND feed_id = ttrss_feeds.id
2570 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2572 $unread = db_fetch_result($result, 0, "unread");
2579 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2580 if (DB_TYPE
== "pgsql") {
2581 return "ttrss_entries.date_updated >
2582 NOW() - INTERVAL '$days days'";
2584 return "ttrss_entries.date_updated >
2585 DATE_SUB(NOW(), INTERVAL $days DAY)";
2589 function getFeedUnread($link, $feed, $is_cat = false) {
2590 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2593 function getLabelUnread($link, $label_id, $owner_uid = false) {
2594 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2596 $result = db_query($link, "
2597 SELECT COUNT(unread) AS unread FROM
2598 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2599 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2600 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2601 AND unread = true AND feed_id = ttrss_feeds.id
2602 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2604 if (db_num_rows($result) != 0) {
2605 return db_fetch_result($result, 0, "unread");
2611 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2612 $owner_uid = false) {
2614 $n_feed = (int) $feed;
2616 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2619 $unread_qpart = "unread = true";
2621 $unread_qpart = "true";
2624 $age_qpart = getMaxAgeSubquery();
2627 return getCategoryUnread($link, $n_feed, $owner_uid);
2628 } if ($feed != "0" && $n_feed == 0) {
2630 $feed = db_escape_string($feed);
2632 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2633 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2634 AND ref_id = id AND $age_qpart
2635 AND $unread_qpart)) AS count FROM ttrss_tags
2636 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2637 return db_fetch_result($result, 0, "count");
2639 } else if ($n_feed == -1) {
2640 $match_part = "marked = true";
2641 } else if ($n_feed == -2) {
2642 $match_part = "published = true";
2643 } else if ($n_feed == -3) {
2644 $match_part = "unread = true AND score >= 0";
2646 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2648 if (DB_TYPE
== "pgsql") {
2649 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2651 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2653 } else if ($n_feed == -4) {
2654 $match_part = "true";
2655 } else if ($n_feed >= 0) {
2658 $match_part = "feed_id = '$n_feed'";
2660 $match_part = "feed_id IS NULL";
2663 } else if ($feed < -10) {
2665 $label_id = -$feed - 11;
2667 return getLabelUnread($link, $label_id, $owner_uid);
2674 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2675 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2677 $from_qpart = "ttrss_user_entries,ttrss_entries";
2681 $query = "SELECT count(int_id) AS unread
2682 FROM $from_qpart WHERE
2683 ttrss_user_entries.ref_id = ttrss_entries.id AND
2686 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2688 $result = db_query($link, $query);
2692 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2693 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2694 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2695 AND $unread_qpart AND $age_qpart AND
2696 ttrss_tags.owner_uid = " . $owner_uid);
2699 $unread = db_fetch_result($result, 0, "unread");
2704 function getGlobalUnread($link, $user_id = false) {
2707 $user_id = $_SESSION["uid"];
2710 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2711 WHERE owner_uid = '$user_id' AND feed_id > 0");
2713 $c_id = db_fetch_result($result, 0, "c_id");
2718 function getGlobalCounters($link, $global_unread = -1) {
2721 if ($global_unread == -1) {
2722 $global_unread = getGlobalUnread($link);
2725 $cv = array("id" => "global-unread",
2726 "counter" => $global_unread);
2728 array_push($ret_arr, $cv);
2730 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2731 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2733 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2735 $cv = array("id" => "subscribed-feeds",
2736 "counter" => $subscribed_feeds);
2738 array_push($ret_arr, $cv);
2743 function getTagCounters($link) {
2747 $age_qpart = getMaxAgeSubquery();
2749 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2750 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2751 AND ref_id = id AND $age_qpart
2752 AND unread = true)) AS count FROM ttrss_tags
2753 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2754 ORDER BY count DESC LIMIT 55");
2758 while ($line = db_fetch_assoc($result)) {
2759 $tags[$line["tag_name"]] +
= $line["count"];
2762 foreach (array_keys($tags) as $tag) {
2763 $unread = $tags[$tag];
2764 $tag = htmlspecialchars($tag);
2766 $cv = array("id" => $tag,
2768 "counter" => $unread);
2770 array_push($ret_arr, $cv);
2776 function getVirtCounters($link) {
2780 for ($i = 0; $i >= -4; $i--) {
2782 $count = getFeedUnread($link, $i);
2784 $cv = array("id" => $i,
2785 "counter" => $count);
2787 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2788 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2790 array_push($ret_arr, $cv);
2796 function getLabelCounters($link, $descriptions = false) {
2800 $age_qpart = getMaxAgeSubquery();
2802 $owner_uid = $_SESSION["uid"];
2804 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2805 WHERE owner_uid = '$owner_uid'");
2807 while ($line = db_fetch_assoc($result)) {
2809 $id = -$line["id"] - 11;
2811 $label_name = $line["caption"];
2812 $count = getFeedUnread($link, $id);
2814 $cv = array("id" => $id,
2815 "counter" => $count);
2818 $cv["description"] = $label_name;
2820 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2821 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2823 array_push($ret_arr, $cv);
2829 function getFeedCounters($link, $active_feed = false) {
2833 $age_qpart = getMaxAgeSubquery();
2835 $query = "SELECT ttrss_feeds.id,
2837 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2838 last_error, value AS count
2839 FROM ttrss_feeds, ttrss_counters_cache
2840 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2841 AND ttrss_counters_cache.feed_id = id";
2843 $result = db_query($link, $query);
2844 $fctrs_modified = false;
2846 while ($line = db_fetch_assoc($result)) {
2849 $count = $line["count"];
2850 $last_error = htmlspecialchars($line["last_error"]);
2852 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2854 $has_img = feed_has_icon($id);
2856 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2859 $cv = array("id" => $id,
2860 "updated" => $last_updated,
2861 "counter" => $count,
2862 "has_img" => (int) $has_img);
2865 $cv["error"] = $last_error;
2867 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2868 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2870 if ($active_feed && $id == $active_feed)
2871 $cv["title"] = truncate_string($line["title"], 30);
2873 array_push($ret_arr, $cv);
2880 function get_pgsql_version($link) {
2881 $result = db_query($link, "SELECT version() AS version");
2882 $version = explode(" ", db_fetch_result($result, 0, "version"));
2887 * Subscribes the user to the given feed
2889 * @param resource $link Database connection
2890 * @param string $url Feed URL to subscribe to
2891 * @param integer $cat_id Category ID the feed shall be added to
2892 * @param string $auth_login (optional) Feed username
2893 * @param string $auth_pass (optional) Feed password
2895 * @return integer Status code:
2896 * 0 - OK, Feed already exists
2897 * 1 - OK, Feed added
2899 * 3 - URL content is HTML, no feeds available
2900 * 4 - URL content is HTML which contains multiple feeds.
2901 * Here you should call extractfeedurls in rpc-backend
2902 * to get all possible feeds.
2903 * 5 - Couldn't download the URL content.
2905 function subscribe_to_feed($link, $url, $cat_id = 0,
2906 $auth_login = '', $auth_pass = '') {
2908 $url = fix_url($url);
2910 if (!$url ||
!validate_feed_url($url)) return 2;
2914 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
2915 WHERE id = ".$_SESSION['uid']);
2917 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2919 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
2920 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
2922 if (url_is_html($url, $auth_login, $auth_pass)) {
2923 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
2924 if (count($feedUrls) == 0) {
2926 } else if (count($feedUrls) > 1) {
2929 //use feed url as new URL
2930 $url = key($feedUrls);
2934 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
2939 if ($cat_id == "0" ||
!$cat_id) {
2940 $cat_qpart = "NULL";
2942 $cat_qpart = "'$cat_id'";
2945 $result = db_query($link,
2946 "SELECT id FROM ttrss_feeds
2947 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2949 if (db_num_rows($result) == 0) {
2950 $result = db_query($link,
2951 "INSERT INTO ttrss_feeds
2952 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2953 VALUES ('".$_SESSION["uid"]."', '$url',
2954 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
2956 $result = db_query($link,
2957 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
2958 AND owner_uid = " . $_SESSION["uid"]);
2960 $feed_id = db_fetch_result($result, 0, "id");
2963 update_rss_feed($link, $feed_id, true);
2972 function print_feed_select($link, $id, $default_id = "",
2973 $attributes = "", $include_all_feeds = true) {
2975 print "<select id=\"$id\" name=\"$id\" $attributes>";
2976 if ($include_all_feeds) {
2977 print "<option value=\"0\">".__('All feeds')."</option>";
2980 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2981 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2983 if (db_num_rows($result) > 0 && $include_all_feeds) {
2984 print "<option disabled>--------</option>";
2987 while ($line = db_fetch_assoc($result)) {
2988 if ($line["id"] == $default_id) {
2989 $is_selected = "selected=\"1\"";
2994 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2996 printf("<option $is_selected value='%d'>%s</option>",
2997 $line["id"], $title);
3003 function print_feed_cat_select($link, $id, $default_id = "",
3004 $attributes = "", $include_all_cats = true) {
3006 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3008 if ($include_all_cats) {
3009 print "<option value=\"0\">".__('Uncategorized')."</option>";
3012 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3013 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3015 if (db_num_rows($result) > 0 && $include_all_cats) {
3016 print "<option disabled=\"1\">--------</option>";
3019 while ($line = db_fetch_assoc($result)) {
3020 if ($line["id"] == $default_id) {
3021 $is_selected = "selected=\"1\"";
3027 printf("<option $is_selected value='%d'>%s</option>",
3028 $line["id"], htmlspecialchars($line["title"]));
3031 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3036 function checkbox_to_sql_bool($val) {
3037 return ($val == "on") ?
"true" : "false";
3040 function getFeedCatTitle($link, $id) {
3042 return __("Special");
3043 } else if ($id < -10) {
3044 return __("Labels");
3045 } else if ($id > 0) {
3046 $result = db_query($link, "SELECT ttrss_feed_categories.title
3047 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3048 cat_id = ttrss_feed_categories.id");
3049 if (db_num_rows($result) == 1) {
3050 return db_fetch_result($result, 0, "title");
3052 return __("Uncategorized");
3055 return "getFeedCatTitle($id) failed";
3060 function getFeedIcon($id) {
3063 return "images/archive.png";
3066 return "images/mark_set.png";
3069 return "images/pub_set.png";
3072 return "images/fresh.png";
3075 return "images/tag.png";
3079 return "images/label.png";
3081 if (file_exists(ICONS_DIR
. "/$id.ico"))
3082 return ICONS_URL
. "/$id.ico";
3088 function getFeedTitle($link, $id) {
3090 return __("Starred articles");
3091 } else if ($id == -2) {
3092 return __("Published articles");
3093 } else if ($id == -3) {
3094 return __("Fresh articles");
3095 } else if ($id == -4) {
3096 return __("All articles");
3097 } else if ($id === 0 ||
$id === "0") {
3098 return __("Archived articles");
3099 } else if ($id < -10) {
3100 $label_id = -$id - 11;
3101 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3102 if (db_num_rows($result) == 1) {
3103 return db_fetch_result($result, 0, "caption");
3105 return "Unknown label ($label_id)";
3108 } else if (is_numeric($id) && $id > 0) {
3109 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3110 if (db_num_rows($result) == 1) {
3111 return db_fetch_result($result, 0, "title");
3113 return "Unknown feed ($id)";
3120 function make_init_params($link) {
3123 $params["theme"] = get_user_theme($link);
3124 $params["theme_options"] = get_user_theme_options($link);
3126 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3127 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3128 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3129 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3131 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3132 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3133 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3134 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3136 $params[strtolower($param)] = (int) get_pref($link, $param);
3139 $params["icons_url"] = ICONS_URL
;
3140 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3141 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3142 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3143 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3144 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3146 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3147 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3149 $max_feed_id = db_fetch_result($result, 0, "mid");
3150 $num_feeds = db_fetch_result($result, 0, "nf");
3152 $params["max_feed_id"] = (int) $max_feed_id;
3153 $params["num_feeds"] = (int) $num_feeds;
3155 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3160 function make_runtime_info($link) {
3163 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3164 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3166 $max_feed_id = db_fetch_result($result, 0, "mid");
3167 $num_feeds = db_fetch_result($result, 0, "nf");
3169 $data["max_feed_id"] = (int) $max_feed_id;
3170 $data["num_feeds"] = (int) $num_feeds;
3172 $data['last_article_id'] = getLastArticleId($link);
3173 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3175 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
3177 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3179 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3181 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3184 $stamp_delta = time() - $stamp;
3186 if ($stamp_delta > 1800) {
3190 $_SESSION["daemon_stamp_check"] = time();
3193 $data['daemon_stamp_ok'] = $stamp_check;
3195 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3197 $data['daemon_stamp'] = $stamp_fmt;
3202 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3203 $new_version_details = @check_for_update
($link);
3205 $data['new_version_available'] = (int) ($new_version_details != false);
3207 $_SESSION["last_version_check"] = time();
3213 function search_to_sql($link, $search, $match_on) {
3215 $search_query_part = "";
3217 $keywords = explode(" ", $search);
3218 $query_keywords = array();
3220 foreach ($keywords as $k) {
3221 if (strpos($k, "-") === 0) {
3228 $commandpair = explode(":", mb_strtolower($k), 2);
3230 if ($commandpair[0] == "note" && $commandpair[1]) {
3232 if ($commandpair[1] == "true")
3233 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3235 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3237 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3239 if ($commandpair[1] == "true")
3240 array_push($query_keywords, "($not (marked = true))");
3242 array_push($query_keywords, "($not (marked = false))");
3244 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3246 if ($commandpair[1] == "true")
3247 array_push($query_keywords, "($not (published = true))");
3249 array_push($query_keywords, "($not (published = false))");
3251 } else if (strpos($k, "@") === 0) {
3253 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3254 $orig_ts = strtotime(substr($k, 1));
3255 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3257 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3259 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3260 } else if ($match_on == "both") {
3261 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3262 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3263 } else if ($match_on == "title") {
3264 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3265 } else if ($match_on == "content") {
3266 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3270 $search_query_part = implode("AND", $query_keywords);
3272 return $search_query_part;
3276 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) {
3278 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3280 $ext_tables_part = "";
3284 if (SPHINX_ENABLED
) {
3285 $ids = join(",", @sphinx_search
($search, 0, 500));
3288 $search_query_part = "ref_id IN ($ids) AND ";
3290 $search_query_part = "ref_id = -1 AND ";
3293 $search_query_part = search_to_sql($link, $search, $match_on);
3294 $search_query_part .= " AND ";
3298 $search_query_part = "";
3302 $filter_query_part = filter_to_sql($filter);
3304 $filter_query_part = "";
3308 $since_id_part = "ttrss_entries.id > $since_id AND ";
3310 $since_id_part = "";
3313 $view_query_part = "";
3315 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3317 $view_query_part = " ";
3318 } else if ($feed != -1) {
3319 $unread = getFeedUnread($link, $feed, $cat_view);
3321 $view_query_part = " unread = true AND ";
3326 if ($view_mode == "marked") {
3327 $view_query_part = " marked = true AND ";
3330 if ($view_mode == "published") {
3331 $view_query_part = " published = true AND ";
3334 if ($view_mode == "unread") {
3335 $view_query_part = " unread = true AND ";
3338 if ($view_mode == "updated") {
3339 $view_query_part = " (last_read is null and unread = false) AND ";
3343 $limit_query_part = "LIMIT " . $limit;
3346 $vfeed_query_part = "";
3348 // override query strategy and enable feed display when searching globally
3349 if ($search && $search_mode == "all_feeds") {
3350 $query_strategy_part = "ttrss_entries.id > 0";
3351 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3353 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3354 $query_strategy_part = "ttrss_entries.id > 0";
3355 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3356 id = feed_id) as feed_title,";
3357 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3359 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3361 $tmp_result = false;
3364 $tmp_result = db_query($link, "SELECT id
3365 FROM ttrss_feeds WHERE cat_id = '$feed'");
3367 $tmp_result = db_query($link, "SELECT id
3368 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3369 WHERE id = '$feed') AND id != '$feed'");
3372 $cat_siblings = array();
3374 if (db_num_rows($tmp_result) > 0) {
3375 while ($p = db_fetch_assoc($tmp_result)) {
3376 array_push($cat_siblings, "feed_id = " . $p["id"]);
3379 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3380 $feed, implode(" OR ", $cat_siblings));
3383 $query_strategy_part = "ttrss_entries.id > 0";
3386 } else if ($feed > 0) {
3391 $query_strategy_part = "cat_id = '$feed'";
3393 $query_strategy_part = "cat_id IS NULL";
3396 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3399 $query_strategy_part = "feed_id = '$feed'";
3401 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3402 $query_strategy_part = "feed_id IS NULL";
3403 } else if ($feed == 0 && $cat_view) { // uncategorized
3404 $query_strategy_part = "cat_id IS NULL";
3405 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3406 } else if ($feed == -1) { // starred virtual feed
3407 $query_strategy_part = "marked = true";
3408 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3409 } else if ($feed == -2) { // published virtual feed OR labels category
3412 $query_strategy_part = "published = true";
3413 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3415 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3417 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3419 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3420 ttrss_user_labels2.article_id = ref_id";
3424 } else if ($feed == -3) { // fresh virtual feed
3425 $query_strategy_part = "unread = true AND score >= 0";
3427 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3429 if (DB_TYPE
== "pgsql") {
3430 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3432 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3435 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3436 } else if ($feed == -4) { // all articles virtual feed
3437 $query_strategy_part = "true";
3438 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3439 } else if ($feed <= -10) { // labels
3440 $label_id = -$feed - 11;
3442 $query_strategy_part = "label_id = '$label_id' AND
3443 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3444 ttrss_user_labels2.article_id = ref_id";
3446 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3447 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3450 $query_strategy_part = "id > 0"; // dumb
3453 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3454 $date_sort_field = "updated";
3456 $date_sort_field = "date_entered";
3459 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3460 $order_by = "$date_sort_field";
3462 $order_by = "$date_sort_field DESC";
3465 if ($view_mode != "noscores") {
3466 $order_by = "score DESC, $order_by";
3469 if ($override_order) {
3470 $order_by = $override_order;
3476 $feed_title = "Search results";
3479 $feed_title = getCategoryTitle($link, $feed);
3481 if (is_numeric($feed) && $feed > 0) {
3482 $result = db_query($link, "SELECT title,site_url,last_error
3483 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3485 $feed_title = db_fetch_result($result, 0, "title");
3486 $feed_site_url = db_fetch_result($result, 0, "site_url");
3487 $last_error = db_fetch_result($result, 0, "last_error");
3489 $feed_title = getFeedTitle($link, $feed);
3494 $content_query_part = "content as content_preview,";
3496 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3499 $feed_kind = "Feeds";
3501 $feed_kind = "Labels";
3504 if ($limit_query_part) {
3505 $offset_query_part = "OFFSET $offset";
3508 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3509 if (!$override_order) {
3510 $order_by = "ttrss_feeds.title, $order_by";
3515 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3516 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3519 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3520 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3523 $query = "SELECT DISTINCT
3526 ttrss_entries.id,ttrss_entries.title,
3530 always_display_enclosures,
3536 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3537 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3540 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3546 ttrss_user_entries.ref_id = ttrss_entries.id AND
3547 ttrss_user_entries.owner_uid = '$owner_uid' AND
3552 $query_strategy_part ORDER BY $order_by
3553 $limit_query_part $offset_query_part";
3555 if ($_REQUEST["debug"]) print $query;
3557 $result = db_query($link, $query);
3562 $select_qpart = "SELECT DISTINCT " .
3566 "ttrss_entries.id as id," .
3573 "always_display_enclosures, ".
3581 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
3584 $content_query_part .
3585 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
3588 $feed_kind = "Tags";
3589 $all_tags = explode(",", $feed);
3590 if ($search_mode == 'any') {
3591 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3592 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3593 $where_qpart = " WHERE " .
3594 "ref_id = ttrss_entries.id AND " .
3595 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3596 "post_int_id = int_id AND $tag_sql AND " .
3598 $search_query_part .
3599 $query_strategy_part . " ORDER BY $order_by " .
3604 $sub_selects = array();
3605 $sub_ands = array();
3606 foreach ($all_tags as $term) {
3607 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");
3614 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3619 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3620 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3621 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3622 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3624 // error_log("TAG SQL: " . $tag_sql);
3625 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3627 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3628 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
3631 return array($result, $feed_title, $feed_site_url, $last_error);
3635 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3636 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3638 require_once "lib/MiniTemplator.class.php";
3640 $note_style = "background-color : #fff7d5;
3641 border-width : 1px; ".
3642 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3643 "margin-bottom : 1em; color : #9a8c59;";
3645 if (!$limit) $limit = 30;
3647 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3648 $date_sort_field = "updated";
3650 $date_sort_field = "date_entered";
3653 $qfh_ret = queryFeedHeadlines($link, $feed,
3654 $limit, $view_mode, $is_cat, $search, $search_mode,
3655 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3657 $result = $qfh_ret[0];
3658 $feed_title = htmlspecialchars($qfh_ret[1]);
3659 $feed_site_url = $qfh_ret[2];
3660 $last_error = $qfh_ret[3];
3662 $feed_self_url = get_self_url_prefix() .
3663 "/public.php?op=rss&id=-2&key=" .
3664 get_feed_access_key($link, -2, false);
3666 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3668 $tpl = new MiniTemplator
;
3670 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3672 $tpl->setVariable('FEED_TITLE', $feed_title);
3673 $tpl->setVariable('VERSION', VERSION
);
3674 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3676 if (PUBSUBHUBBUB_HUB
&& $feed == -2) {
3677 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB
));
3678 $tpl->addBlock('feed_hub');
3681 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3683 while ($line = db_fetch_assoc($result)) {
3684 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3685 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3686 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3687 $tpl->setVariable('ARTICLE_EXCERPT',
3688 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3690 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3692 if ($line['note']) {
3693 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
3697 $tpl->setVariable('ARTICLE_CONTENT', $content);
3699 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3700 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3702 $tags = get_article_tags($link, $line["id"], $owner_uid);
3704 foreach ($tags as $tag) {
3705 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3706 $tpl->addBlock('category');
3709 $enclosures = get_article_enclosures($link, $line["id"]);
3711 foreach ($enclosures as $e) {
3712 $type = htmlspecialchars($e['content_type']);
3713 $url = htmlspecialchars($e['content_url']);
3714 $length = $e['duration'];
3716 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3717 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3718 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3720 $tpl->addBlock('enclosure');
3723 $tpl->addBlock('entry');
3728 $tpl->addBlock('feed');
3729 $tpl->generateOutputToString($tmp);
3734 function getCategoryTitle($link, $cat_id) {
3736 if ($cat_id == -1) {
3737 return __("Special");
3738 } else if ($cat_id == -2) {
3739 return __("Labels");
3742 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3745 if (db_num_rows($result) == 1) {
3746 return db_fetch_result($result, 0, "title");
3748 return "Uncategorized";
3753 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3756 if (!$owner) $owner = $_SESSION["uid"];
3758 $res = trim($str); if (!$res) return '';
3760 // create global Purifier object if needed
3762 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
3764 $config = HTMLPurifier_Config
::createDefault();
3766 $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";
3768 $config->set('HTML.SafeObject', true);
3769 @$config->set('HTML', 'Allowed', $allowed);
3770 $config->set('Output.FlashCompat', true);
3771 $config->set('Attr.EnableID', true);
3772 if (!defined('MOBILE_VERSION')) {
3773 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
3775 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
3778 $purifier = new HTMLPurifier($config);
3781 $res = $purifier->purify($res);
3783 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3784 $res = preg_replace('/<img[^>]+>/is', '', $res);
3787 if (strpos($res, "href=") === false)
3788 $res = rewrite_urls($res);
3790 $charset_hack = '<head>
3791 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3794 $res = trim($res); if (!$res) return '';
3796 libxml_use_internal_errors(true);
3798 $doc = new DOMDocument();
3799 $doc->loadHTML($charset_hack . $res);
3800 $xpath = new DOMXPath($doc);
3802 $entries = $xpath->query('(//a[@href]|//img[@src])');
3805 foreach ($entries as $entry) {
3809 if ($entry->hasAttribute('href'))
3810 $entry->setAttribute('href',
3811 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3813 if ($entry->hasAttribute('src'))
3814 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3815 $entry->setAttribute('src',
3816 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3819 if (strtolower($entry->nodeName
) == "a") {
3820 $entry->setAttribute("target", "_blank");
3823 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3824 $br = $doc->createElement("br");
3826 if ($entry->parentNode
->nextSibling
) {
3827 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3834 $node = $doc->getElementsByTagName('body')->item(0);
3836 return $doc->saveXML($node);
3840 * Send by mail a digest of last articles.
3842 * @param mixed $link The database connection.
3843 * @param integer $limit The maximum number of articles by digest.
3844 * @return boolean Return false if digests are not enabled.
3846 function send_headlines_digests($link, $limit = 100) {
3848 require_once 'lib/phpmailer/class.phpmailer.php';
3850 if (!DIGEST_ENABLE
) return false;
3852 $user_limit = DIGEST_EMAIL_LIMIT
;
3855 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3857 if (DB_TYPE
== "pgsql") {
3858 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3859 } else if (DB_TYPE
== "mysql") {
3860 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3863 $result = db_query($link, "SELECT id,email FROM ttrss_users
3864 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3866 while ($line = db_fetch_assoc($result)) {
3868 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3869 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3871 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3873 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3874 $digest = $tuple[0];
3875 $headlines_count = $tuple[1];
3876 $affected_ids = $tuple[2];
3877 $digest_text = $tuple[3];
3879 if ($headlines_count > 0) {
3881 $mail = new PHPMailer();
3883 $mail->PluginDir
= "lib/phpmailer/";
3884 $mail->SetLanguage("en", "lib/phpmailer/language/");
3886 $mail->CharSet
= "UTF-8";
3888 $mail->From
= DIGEST_FROM_ADDRESS
;
3889 $mail->FromName
= DIGEST_FROM_NAME
;
3890 $mail->AddAddress($line["email"], $line["login"]);
3892 if (DIGEST_SMTP_HOST
) {
3893 $mail->Host
= DIGEST_SMTP_HOST
;
3894 $mail->Mailer
= "smtp";
3895 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
3896 $mail->Username
= DIGEST_SMTP_LOGIN
;
3897 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3900 $mail->IsHTML(true);
3901 $mail->Subject
= DIGEST_SUBJECT
;
3902 $mail->Body
= $digest;
3903 $mail->AltBody
= $digest_text;
3905 $rc = $mail->Send();
3907 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3911 if ($rc && $do_catchup) {
3912 print "Marking affected articles as read...\n";
3913 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3916 print "No headlines\n";
3919 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3920 WHERE id = " . $line["id"]);
3924 print "All done.\n";
3928 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3930 require_once "lib/MiniTemplator.class.php";
3932 $tpl = new MiniTemplator
;
3933 $tpl_t = new MiniTemplator
;
3935 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3936 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3938 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3939 $tpl->setVariable('CUR_TIME', date('G:i'));
3941 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3942 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3944 $affected_ids = array();
3946 if (DB_TYPE
== "pgsql") {
3947 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3948 } else if (DB_TYPE
== "mysql") {
3949 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3952 $result = db_query($link, "SELECT ttrss_entries.title,
3953 ttrss_feeds.title AS feed_title,
3955 ttrss_user_entries.ref_id,
3957 SUBSTRING(content, 1, 120) AS excerpt,
3958 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
3960 ttrss_user_entries,ttrss_entries,ttrss_feeds
3962 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3963 AND include_in_digest = true
3965 AND ttrss_user_entries.owner_uid = $user_id
3967 ORDER BY ttrss_feeds.title, date_updated DESC
3970 $cur_feed_title = "";
3972 $headlines_count = db_num_rows($result);
3974 $headlines = array();
3976 while ($line = db_fetch_assoc($result)) {
3977 array_push($headlines, $line);
3980 for ($i = 0; $i < sizeof($headlines); $i++
) {
3982 $line = $headlines[$i];
3984 array_push($affected_ids, $line["ref_id"]);
3986 $updated = make_local_datetime($link, $line['last_updated'], false,
3989 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3990 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3991 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3992 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3993 $tpl->setVariable('ARTICLE_EXCERPT',
3994 truncate_string(strip_tags($line["excerpt"]), 100));
3996 $tpl->addBlock('article');
3998 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3999 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4000 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4001 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4002 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4003 // truncate_string(strip_tags($line["excerpt"]), 100));
4005 $tpl_t->addBlock('article');
4007 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
4008 $tpl->addBlock('feed');
4009 $tpl_t->addBlock('feed');
4014 $tpl->addBlock('digest');
4015 $tpl->generateOutputToString($tmp);
4017 $tpl_t->addBlock('digest');
4018 $tpl_t->generateOutputToString($tmp_t);
4020 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4023 function check_for_update($link) {
4024 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
4025 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
4027 $version_data = @fetch_file_contents
($version_url);
4029 if ($version_data) {
4030 $version_data = json_decode($version_data, true);
4031 if ($version_data && $version_data['version']) {
4033 if (version_compare(VERSION
, $version_data['version']) == -1) {
4034 return $version_data;
4042 function markArticlesById($link, $ids, $cmode) {
4046 foreach ($ids as $id) {
4047 array_push($tmp_ids, "ref_id = '$id'");
4050 $ids_qpart = join(" OR ", $tmp_ids);
4053 db_query($link, "UPDATE ttrss_user_entries SET
4054 marked = false,last_read = NOW()
4055 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4056 } else if ($cmode == 1) {
4057 db_query($link, "UPDATE ttrss_user_entries SET
4059 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4061 db_query($link, "UPDATE ttrss_user_entries SET
4062 marked = NOT marked,last_read = NOW()
4063 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4067 function publishArticlesById($link, $ids, $cmode) {
4071 foreach ($ids as $id) {
4072 array_push($tmp_ids, "ref_id = '$id'");
4075 $ids_qpart = join(" OR ", $tmp_ids);
4078 db_query($link, "UPDATE ttrss_user_entries SET
4079 published = false,last_read = NOW()
4080 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4081 } else if ($cmode == 1) {
4082 db_query($link, "UPDATE ttrss_user_entries SET
4084 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4086 db_query($link, "UPDATE ttrss_user_entries SET
4087 published = NOT published,last_read = NOW()
4088 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4091 if (PUBSUBHUBBUB_HUB
) {
4092 $rss_link = get_self_url_prefix() .
4093 "/public.php?op=rss&id=-2&key=" .
4094 get_feed_access_key($link, -2, false);
4096 $p = new Publisher(PUBSUBHUBBUB_HUB
);
4098 $pubsub_result = $p->publish_update($rss_link);
4102 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4104 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4105 if (count($ids) == 0) return;
4109 foreach ($ids as $id) {
4110 array_push($tmp_ids, "ref_id = '$id'");
4113 $ids_qpart = join(" OR ", $tmp_ids);
4116 db_query($link, "UPDATE ttrss_user_entries SET
4117 unread = false,last_read = NOW()
4118 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4119 } else if ($cmode == 1) {
4120 db_query($link, "UPDATE ttrss_user_entries SET
4122 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4124 db_query($link, "UPDATE ttrss_user_entries SET
4125 unread = NOT unread,last_read = NOW()
4126 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4131 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4132 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4134 while ($line = db_fetch_assoc($result)) {
4135 ccache_update($link, $line["feed_id"], $owner_uid);
4139 function catchupArticleById($link, $id, $cmode) {
4142 db_query($link, "UPDATE ttrss_user_entries SET
4143 unread = false,last_read = NOW()
4144 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4145 } else if ($cmode == 1) {
4146 db_query($link, "UPDATE ttrss_user_entries SET
4148 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4150 db_query($link, "UPDATE ttrss_user_entries SET
4151 unread = NOT unread,last_read = NOW()
4152 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4155 $feed_id = getArticleFeed($link, $id);
4156 ccache_update($link, $feed_id, $_SESSION["uid"]);
4159 function make_guid_from_title($title) {
4160 return preg_replace("/[ \"\',.:;]/", "-",
4161 mb_strtolower(strip_tags($title), 'utf-8'));
4164 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4165 $feed_id, $is_cat, $search, $match_on,
4166 $search_mode, $view_mode, $error) {
4168 $page_prev_link = "viewFeedGoPage(-1)";
4169 $page_next_link = "viewFeedGoPage(1)";
4170 $page_first_link = "viewFeedGoPage(0)";
4172 $catchup_page_link = "catchupPage()";
4173 $catchup_feed_link = "catchupCurrentFeed()";
4174 $catchup_sel_link = "catchupSelection()";
4176 $archive_sel_link = "archiveSelection()";
4177 $delete_sel_link = "deleteSelection()";
4179 $sel_all_link = "selectArticles('all')";
4180 $sel_unread_link = "selectArticles('unread')";
4181 $sel_none_link = "selectArticles('none')";
4182 $sel_inv_link = "selectArticles('invert')";
4184 $tog_unread_link = "selectionToggleUnread()";
4185 $tog_marked_link = "selectionToggleMarked()";
4186 $tog_published_link = "selectionTogglePublished()";
4188 $reply = "<div id=\"subtoolbar_main\">";
4190 $reply .= __('Select:')."
4191 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4192 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4193 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4194 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4198 $reply .= "<select dojoType=\"dijit.form.Select\"
4199 onchange=\"headlineActionsChange(this)\">";
4200 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4202 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4204 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4205 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4206 <option value=\"$tog_published_link\">".__('Published')."</option>";
4208 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4210 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4212 if ($feed_id != "0") {
4213 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4215 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4216 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4220 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4223 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4226 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4231 $rss_link = htmlspecialchars(get_self_url_prefix() .
4232 "/public.php?op=rss&id=$feed_id$cat_q$search_q");
4234 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4236 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4238 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4240 $reply .= "</select>";
4244 $reply .= "<div id=\"subtoolbar_ftitle\">";
4246 if ($feed_site_url) {
4247 $target = "target=\"_blank\"";
4248 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4249 truncate_string($feed_title,30)."</a>";
4252 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4256 if ($feed_id < -10) {
4257 $label_id = -11-$feed_id;
4259 $result = db_query($link, "SELECT fg_color, bg_color
4260 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4263 if (db_num_rows($result) != 0) {
4264 $fg_color = db_fetch_result($result, 0, "fg_color");
4265 $bg_color = db_fetch_result($result, 0, "bg_color");
4267 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
4268 $reply .= $feed_title;
4269 $reply .= "</span>";
4271 $reply .= $feed_title;
4275 $reply .= $feed_title;
4281 title=\"".__("View as RSS feed")."\"
4282 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4283 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4290 function outputFeedList($link, $special = true) {
4292 $feedlist = array();
4294 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4296 $feedlist['identifier'] = 'id';
4297 $feedlist['label'] = 'name';
4298 $feedlist['items'] = array();
4300 $owner_uid = $_SESSION["uid"];
4307 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4308 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4310 $cat['items'] = array();
4313 foreach (array(-4, -3, -1, -2, 0) as $i) {
4314 array_push($cat['items'], feedlist_init_feed($link, $i));
4318 array_push($feedlist['items'], $cat);
4320 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4323 $result = db_query($link, "SELECT * FROM
4324 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4326 if (db_num_rows($result) > 0) {
4328 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4329 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4330 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4332 $cat['items'] = array();
4335 while ($line = db_fetch_assoc($result)) {
4337 $label_id = -$line['id'] - 11;
4338 $count = getFeedUnread($link, $label_id);
4340 $feed = feedlist_init_feed($link, $label_id, false, $count);
4342 $feed['fg_color'] = $line['fg_color'];
4343 $feed['bg_color'] = $line['bg_color'];
4345 array_push($cat['items'], $feed);
4349 array_push($feedlist['items'], $cat);
4351 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4356 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4357 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4358 $order_by_qpart = "order_id,category,unread DESC,title";
4360 $order_by_qpart = "order_id,category,title";
4363 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4364 $order_by_qpart = "unread DESC,title";
4366 $order_by_qpart = "title";
4373 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4374 ttrss_feeds.order_id,title";
4376 $order_by_qpart = "title";
4378 $age_qpart = getMaxAgeSubquery();
4380 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4381 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4383 ttrss_feed_categories.title AS category,
4384 ttrss_feed_categories.collapsed,
4386 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4387 ON (ttrss_feed_categories.id = cat_id)
4388 LEFT JOIN ttrss_counters_cache
4390 (ttrss_feeds.id = feed_id)
4392 ttrss_feeds.owner_uid = '$owner_uid'
4393 ORDER BY $order_by_qpart";
4395 $result = db_query($link, $query);
4397 $actid = $_REQUEST["actid"];
4399 if (db_num_rows($result) > 0) {
4404 $cat['items'] = array();
4408 while ($line = db_fetch_assoc($result)) {
4410 $feed = htmlspecialchars(trim($line["title"]));
4412 if (!$feed) $feed = "[Untitled]";
4414 $feed_id = $line["id"];
4415 $unread = $line["unread"];
4417 $cat_id = $line["cat_id"];
4418 $tmp_category = $line["category"];
4419 if (!$tmp_category) $tmp_category = __("Uncategorized");
4421 if ($category != $tmp_category && $enable_cats) {
4423 $category = $tmp_category;
4425 $collapsed = sql_bool_to_bool($line["collapsed"]);
4427 // workaround for NULL category
4428 if ($category == __("Uncategorized")) {
4429 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4432 if ($cat) array_push($feedlist['items'], $cat);
4434 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4437 $updated = make_local_datetime($link, $line["updated_noms"], false);
4439 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4440 $feed, $unread, $line['last_error'], $updated));
4444 array_push($feedlist['items'], $cat);
4446 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4454 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
4458 $a_id = db_escape_string($id);
4460 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4462 $query = "SELECT DISTINCT tag_name,
4463 owner_uid as owner FROM
4464 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4465 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4467 $obj_id = md5("TAGS:$owner_uid:$id");
4470 if ($memcache && $obj = $memcache->get($obj_id)) {
4473 /* check cache first */
4475 if ($tag_cache === false) {
4476 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4477 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4479 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4483 $tags = explode(",", $tag_cache);
4486 /* do it the hard way */
4488 $tmp_result = db_query($link, $query);
4490 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4491 array_push($tags, $tmp_line["tag_name"]);
4494 /* update the cache */
4496 $tags_str = db_escape_string(join(",", $tags));
4498 db_query($link, "UPDATE ttrss_user_entries
4499 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4500 AND owner_uid = " . $_SESSION["uid"]);
4503 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4509 function trim_array($array) {
4511 array_walk($tmp, 'trim');
4515 function tag_is_valid($tag) {
4516 if ($tag == '') return false;
4517 if (preg_match("/^[0-9]*$/", $tag)) return false;
4518 if (mb_strlen($tag) > 250) return false;
4520 if (function_exists('iconv')) {
4521 $tag = iconv("utf-8", "utf-8", $tag);
4524 if (!$tag) return false;
4529 function render_login_form($link, $mobile = 0) {
4532 require_once "login_form.php";
4535 require_once "mobile/login_form.php";
4538 require_once "mobile/classic/login_form.php";
4542 // from http://developer.apple.com/internet/safari/faq.html
4543 function no_cache_incantation() {
4544 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4545 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4546 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4547 header("Cache-Control: post-check=0, pre-check=0", false);
4548 header("Pragma: no-cache"); // HTTP/1.0
4551 function format_warning($msg, $id = "") {
4553 return "<div class=\"warning\" id=\"$id\">
4554 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4557 function format_notice($msg, $id = "") {
4559 return "<div class=\"notice\" id=\"$id\">
4560 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4563 function format_error($msg, $id = "") {
4565 return "<div class=\"error\" id=\"$id\">
4566 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4569 function print_notice($msg) {
4570 return print format_notice($msg);
4573 function print_warning($msg) {
4574 return print format_warning($msg);
4577 function print_error($msg) {
4578 return print format_error($msg);
4582 function T_sprintf() {
4583 $args = func_get_args();
4584 return vsprintf(__(array_shift($args)), $args);
4587 function format_inline_player($link, $url, $ctype) {
4591 if (strpos($ctype, "audio/") === 0) {
4593 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4594 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4595 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4597 $id = 'AUDIO-' . uniqid();
4599 $entry .= "<audio id=\"$id\"\">
4600 <source src=\"$url\"></source>
4603 $entry .= "<span onclick=\"player(this)\"
4604 title=\"".__("Click to play")."\" status=\"0\"
4605 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4609 $entry .= "<object type=\"application/x-shockwave-flash\"
4610 data=\"lib/button/musicplayer.swf?song_url=$url\"
4611 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4612 <param name=\"movie\"
4613 value=\"lib/button/musicplayer.swf?song_url=$url\" />
4618 $filename = substr($url, strrpos($url, "/")+
1);
4620 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4621 $filename . " (" . $ctype . ")" . "</a>";
4626 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
4632 /* we can figure out feed_id from article id anyway, why do we
4633 * pass feed_id here? let's ignore the argument :( */
4635 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4636 WHERE ref_id = '$id'");
4638 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4640 $rv['feed_id'] = $feed_id;
4642 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4644 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4645 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4647 if (db_num_rows($result) == 1) {
4648 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4649 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4651 $rtl_content = false;
4652 $always_display_enclosures = false;
4656 $rtl_tag = "dir=\"RTL\"";
4663 if ($mark_as_read) {
4664 $result = db_query($link, "UPDATE ttrss_user_entries
4665 SET unread = false,last_read = NOW()
4666 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4668 ccache_update($link, $feed_id, $_SESSION["uid"]);
4671 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4672 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4673 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4674 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4680 FROM ttrss_entries,ttrss_user_entries
4681 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4685 $line = db_fetch_assoc($result);
4687 if ($line["icon_url"]) {
4688 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4690 $feed_icon = " ";
4693 $feed_site_url = $line['site_url'];
4695 $num_comments = $line["num_comments"];
4696 $entry_comments = "";
4698 if ($num_comments > 0) {
4699 if ($line["comments"]) {
4700 $comments_url = $line["comments"];
4702 $comments_url = $line["link"];
4704 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4706 if ($line["comments"] && $line["link"] != $line["comments"]) {
4707 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4712 header("Content-Type: text/html");
4713 $rv['content'] .= "<html><head>
4714 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4715 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4716 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4720 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4721 truncate_string(strip_tags($line['title']), 15) . "</div>";
4723 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4725 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4726 class=\"postHeader\" id=\"POSTHDR-$id\">";
4728 $entry_author = $line["author"];
4730 if ($entry_author) {
4731 $entry_author = __(" - ") . $entry_author;
4734 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4737 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4739 if ($line["link"]) {
4740 $rv['content'] .= "<div clear='both'><a target='_blank'
4741 title=\"".htmlspecialchars($line['title'])."\"
4743 $line["link"] . "\">" .
4744 truncate_string($line["title"], 100) .
4745 "<span class='author'>$entry_author</span></a></div>";
4747 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4750 $tag_cache = $line["tag_cache"];
4753 $tags = get_article_tags($link, $id);
4755 $tags = explode(",", $tag_cache);
4757 $tags_str = format_tags_string($tags, $id);
4758 $tags_str_full = join(", ", $tags);
4760 if (!$tags_str_full) $tags_str_full = __("no tags");
4762 if (!$entry_comments) $entry_comments = " "; # placeholder
4764 $rv['content'] .= "<div style='float : right'>
4765 <img src='".theme_image($link, 'images/tag.png')."'
4766 class='tagsPic' alt='Tags' title='Tags'> ";
4769 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4770 <a title=\"".__('Edit tags for this article')."\"
4771 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4773 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4774 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4775 position=\"below\">$tags_str_full</div>";
4777 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4778 class='tagsPic' style=\"cursor : pointer\"
4779 onclick=\"postOpenInNewTab(event, $id)\"
4780 alt='Zoom' title='".__('Open article in new tab')."'>";
4782 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4784 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4785 class='tagsPic' style=\"cursor : pointer\"
4786 onclick=\"editArticleNote($id)\"
4787 alt='PubNote' title='".__('Edit article note')."'>";
4789 if (DIGEST_ENABLE
) {
4790 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4791 class='tagsPic' style=\"cursor : pointer\"
4792 onclick=\"emailArticle($id)\"
4793 alt='Zoom' title='".__('Forward by email')."'>";
4796 if (ENABLE_TWEET_BUTTON
) {
4797 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4798 class='tagsPic' style=\"cursor : pointer\"
4799 onclick=\"tweetArticle($id)\"
4800 alt='Zoom' title='".__('Share on Twitter')."'>";
4803 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
4804 class='tagsPic' style=\"cursor : pointer\"
4805 onclick=\"shareArticle(".$line['int_id'].")\"
4806 alt='Zoom' title='".__('Share by URL')."'>";
4808 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4809 class='tagsPic' style=\"cursor : pointer\"
4810 onclick=\"closeArticlePanel($id)\"
4811 alt='Zoom' title='".__('Close this panel')."'>";
4814 $tags_str = strip_tags($tags_str);
4815 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4817 $rv['content'] .= "</div>";
4818 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4820 if ($line["orig_feed_id"]) {
4822 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4823 WHERE id = ".$line["orig_feed_id"]);
4825 if (db_num_rows($tmp_result) != 0) {
4827 $rv['content'] .= "<div clear='both'>";
4828 $rv['content'] .= __("Originally from:");
4830 $rv['content'] .= " ";
4832 $tmp_line = db_fetch_assoc($tmp_result);
4834 $rv['content'] .= "<a target='_blank'
4835 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4836 $tmp_line['title'] . "</a>";
4838 $rv['content'] .= " ";
4840 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4841 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4843 $rv['content'] .= "</div>";
4847 $rv['content'] .= "</div>";
4849 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4850 if ($line['note']) {
4851 $rv['content'] .= format_article_note($id, $line['note']);
4853 $rv['content'] .= "</div>";
4855 $rv['content'] .= "<div class=\"postIcon\">" .
4856 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4857 href=\"".htmlspecialchars($feed_site_url)."\">".
4858 $feed_icon . "</a></div>";
4860 $rv['content'] .= "<div class=\"postContent\">";
4862 $article_content = sanitize_rss($link, $line["content"], false, false,
4865 $rv['content'] .= $article_content;
4867 $rv['content'] .= format_article_enclosures($link, $id,
4868 $always_display_enclosures, $article_content);
4870 $rv['content'] .= "</div>";
4872 $rv['content'] .= "</div>";
4878 <div style=\"text-align : center\">
4879 <button onclick=\"return window.close()\">".
4880 __("Close this window")."</button></div>";
4881 $rv['content'] .= "</body></html>";
4888 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4889 $next_unread_feed, $offset, $vgr_last_feed = false,
4890 $override_order = false) {
4892 $disable_cache = false;
4896 $timing_info = getmicrotime();
4898 $topmost_article_ids = array();
4900 if (!$offset) $offset = 0;
4901 if ($subop == "undefined") $subop = "";
4903 $subop_split = explode(":", $subop);
4905 /* if ($subop == "CatchupSelected") {
4906 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
4907 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4909 catchupArticlesById($link, $ids, $cmode);
4912 if ($subop == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
4913 update_rss_feed($link, $feed, true);
4916 if ($subop == "MarkAllRead") {
4917 catchup_feed($link, $feed, $cat_view);
4919 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4920 if ($next_unread_feed) {
4921 $feed = $next_unread_feed;
4926 if ($subop_split[0] == "MarkAllReadGR") {
4927 catchup_feed($link, $subop_split[1], false);
4930 // FIXME: might break tag display?
4932 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
4933 $result = db_query($link,
4934 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4936 if (db_num_rows($result) == 0) {
4937 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
4941 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4943 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4944 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4946 if (db_num_rows($result) == 1) {
4947 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4949 $rtl_content = false;
4953 $rtl_tag = "dir=\"RTL\"";
4959 $rtl_content = false;
4962 @$search = db_escape_string($_REQUEST["query"]);
4965 $disable_cache = true;
4968 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4969 @$match_on = db_escape_string($_REQUEST["match_on"]);
4975 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4977 // error_log("format_headlines_list: [" . $feed . "] subop [" . $subop . "]");
4978 if( $search_mode == '' && $subop != '' ){
4979 $search_mode = $subop;
4981 // error_log("search_mode: " . $search_mode);
4982 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4983 $search, $search_mode, $match_on, $override_order, $offset);
4985 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4987 $result = $qfh_ret[0];
4988 $feed_title = $qfh_ret[1];
4989 $feed_site_url = $qfh_ret[2];
4990 $last_error = $qfh_ret[3];
4992 $vgroup_last_feed = $vgr_last_feed;
4996 if (db_num_rows($result) > 0) {
4997 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
4999 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5004 $headlines_count = db_num_rows($result);
5006 if (db_num_rows($result) > 0) {
5011 $cur_feed_title = '';
5013 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5015 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5017 while ($line = db_fetch_assoc($result)) {
5019 $class = ($lnum %
2) ?
"even" : "odd";
5022 $feed_id = $line["feed_id"];
5023 $label_cache = $line["label_cache"];
5027 $label_cache = json_decode($label_cache, true);
5030 if ($label_cache["no-labels"] == 1)
5033 $labels = $label_cache;
5037 if (!is_array($labels)) $labels = get_article_labels($link, $id);
5039 $labels_str = "<span id=\"HLLCTR-$id\">";
5040 $labels_str .= format_article_labels($labels, $id);
5041 $labels_str .= "</span>";
5043 if (count($topmost_article_ids) < 3) {
5044 array_push($topmost_article_ids, $id);
5047 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5049 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5050 theme_image($link, 'images/updated.png')."\"
5053 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5057 if (sql_bool_to_bool($line["unread"]) &&
5058 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5060 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5061 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5064 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5065 $class .= " Unread";
5072 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5073 $marked_pic = "<img id=\"FMPIC-$id\"
5074 src=\"".theme_image($link, 'images/mark_set.png')."\"
5075 class=\"markedPic\" alt=\"Unstar article\"
5076 onclick='javascript:toggleMark($id)'>";
5078 $marked_pic = "<img id=\"FMPIC-$id\"
5079 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5080 class=\"markedPic\" alt=\"Star article\"
5081 onclick='javascript:toggleMark($id)'>";
5084 if ($line["published"] == "t" ||
$line["published"] == "1") {
5085 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5086 'images/pub_set.png')."\"
5088 alt=\"Unpublish article\" onclick='javascript:togglePub($id)'>";
5090 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5091 'images/pub_unset.png')."\"
5093 alt=\"Publish article\" onclick='javascript:togglePub($id)'>";
5096 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5097 # $line["title"] . "</a>";
5099 # $content_link = "<a
5100 # href=\"" . htmlspecialchars($line["link"]) . "\"
5101 # onclick=\"view($id,$feed_id);\">" .
5102 # $line["title"] . "</a>";
5104 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5105 # $line["title"] . "</a>";
5107 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5109 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5110 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5114 $score = $line["score"];
5116 $score_pic = theme_image($link,
5117 "images/" . get_score_pic($score));
5119 /* $score_title = __("(Click to change)");
5120 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5121 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5123 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5128 } else if ($score < -100) {
5134 $entry_author = $line["author"];
5136 if ($entry_author) {
5137 $entry_author = " - $entry_author";
5140 $has_feed_icon = feed_has_icon($feed_id);
5142 if ($has_feed_icon) {
5143 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5145 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5148 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5150 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5151 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5153 $cur_feed_title = $line["feed_title"];
5154 $vgroup_last_feed = $feed_id;
5156 $cur_feed_title = htmlspecialchars($cur_feed_title);
5158 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5160 $reply['content'] .= "<div class='cdmFeedTitle'>".
5161 "<div style=\"float : right\">$feed_icon_img</div>".
5162 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5163 $line["feed_title"]."</a> $vf_catchup_link</div>";
5168 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5169 onmouseout='postMouseOut($id)'";
5171 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5173 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5175 $reply['content'] .= "<div class='hlLeft'>";
5177 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5180 $reply['content'] .= "$marked_pic";
5181 $reply['content'] .= "$published_pic";
5183 $reply['content'] .= "</div>";
5185 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5186 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5187 $reply['content'] .= "<a id=\"RTITLE-$id\"
5188 href=\"" . htmlspecialchars($line["link"]) . "\"
5190 truncate_string($line["title"], 200);
5192 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5193 if ($content_preview) {
5194 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5198 $reply['content'] .= "</a></span>";
5200 $reply['content'] .= $labels_str;
5202 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5203 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5204 if (@$line["feed_title"]) {
5205 $reply['content'] .= "<span class=\"hlFeed\">
5206 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5207 $line["feed_title"]."</a>)
5212 $reply['content'] .= "</div>";
5214 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5215 $reply['content'] .= "<div class=\"hlRight\">";
5217 $reply['content'] .= $score_pic;
5219 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5221 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5222 style=\"cursor : pointer\"
5223 title=\"".htmlspecialchars($line['feed_title'])."\">
5224 $feed_icon_img<span>";
5227 $reply['content'] .= "</div>";
5228 $reply['content'] .= "</div>";
5232 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5233 if ($feed_id != $vgroup_last_feed) {
5235 $cur_feed_title = $line["feed_title"];
5236 $vgroup_last_feed = $feed_id;
5238 $cur_feed_title = htmlspecialchars($cur_feed_title);
5240 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5242 $has_feed_icon = feed_has_icon($feed_id);
5244 if ($has_feed_icon) {
5245 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5247 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5250 $reply['content'] .= "<div class='cdmFeedTitle'>".
5251 "<div style=\"float : right\">$feed_icon_img</div>".
5252 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5253 $line["feed_title"]."</a> $vf_catchup_link</div>";
5257 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5259 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5260 onmouseout='postMouseOut($id)'";
5262 $reply['content'] .= "<div class=\"$class\"
5263 id=\"RROW-$id\" $mouseover_attrs'>";
5265 $reply['content'] .= "<div class=\"cdmHeader\">";
5267 $reply['content'] .= "<div>";
5269 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5270 'RROW-$id')\" id=\"RCHK-$id\"/>";
5272 $reply['content'] .= "$marked_pic";
5273 $reply['content'] .= "$published_pic";
5275 $reply['content'] .= "</div>";
5277 $reply['content'] .= "<span id=\"RTITLE-$id\"
5278 onclick=\"return cdmClicked(event, $id);\"
5279 class=\"titleWrap$hlc_suffix\">
5281 title=\"".htmlspecialchars($line['title'])."\"
5282 target=\"_blank\" href=\"".
5283 htmlspecialchars($line["link"])."\">".
5284 truncate_string($line["title"], 100) .
5285 " $entry_author</a>";
5287 $reply['content'] .= $labels_str;
5289 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5290 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5291 if (@$line["feed_title"]) {
5292 $reply['content'] .= "<span class=\"hlFeed\">
5293 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5294 $line["feed_title"]."</a>)
5300 $content_hidden = "style=\"display : none\"";
5302 $excerpt_hidden = "style=\"display : none\"";
5304 $reply['content'] .= "<span $excerpt_hidden
5305 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5307 $reply['content'] .= "</span>";
5309 $reply['content'] .= "<div>";
5310 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5311 $reply['content'] .= "$score_pic";
5313 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5314 $reply['content'] .= "<span style=\"cursor : pointer\"
5315 title=\"".htmlspecialchars($line["feed_title"])."\"
5316 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5318 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5319 $reply['content'] .= "</div>";
5321 $reply['content'] .= "</div>";
5323 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5324 onclick=\"return cdmClicked(event, $id);\"
5327 $reply['content'] .= "<div class=\"cdmContentInner\">";
5329 if ($line["orig_feed_id"]) {
5331 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5332 WHERE id = ".$line["orig_feed_id"]);
5334 if (db_num_rows($tmp_result) != 0) {
5336 $reply['content'] .= "<div clear='both'>";
5337 $reply['content'] .= __("Originally from:");
5339 $reply['content'] .= " ";
5341 $tmp_line = db_fetch_assoc($tmp_result);
5343 $reply['content'] .= "<a target='_blank'
5344 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5345 $tmp_line['title'] . "</a>";
5347 $reply['content'] .= " ";
5349 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5350 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5352 $reply['content'] .= "</div>";
5356 $feed_site_url = $line["site_url"];
5358 $article_content = sanitize_rss($link, $line["content_preview"],
5359 false, false, $feed_site_url);
5361 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5362 if ($line['note']) {
5363 $reply['content'] .= format_article_note($id, $line['note']);
5365 $reply['content'] .= "</div>";
5367 $reply['content'] .= "<span id=\"CWRAP-$id\">";
5368 $reply['content'] .= $expand_cdm ?
$article_content : '';
5369 $reply['content'] .= "</span>";
5371 /* $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5372 ttrss_feeds WHERE id = ".
5373 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
5374 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5376 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5377 0, "always_display_enclosures")); */
5379 $always_display_enclosures = sql_bool_to_bool($line["always_display_enclosures"]);
5381 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5384 $reply['content'] .= "</div>";
5386 $reply['content'] .= "<div class=\"cdmFooter\">";
5388 $tag_cache = $line["tag_cache"];
5390 $tags_str = format_tags_string(
5391 get_article_tags($link, $id, $_SESSION["uid"], $tag_cache),
5394 $reply['content'] .= "<img src='".theme_image($link,
5395 'images/tag.png')."' alt='Tags' title='Tags'>
5396 <span id=\"ATSTR-$id\">$tags_str</span>
5397 <a title=\"".__('Edit tags for this article')."\"
5398 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5400 $num_comments = $line["num_comments"];
5401 $entry_comments = "";
5403 if ($num_comments > 0) {
5404 if ($line["comments"]) {
5405 $comments_url = $line["comments"];
5407 $comments_url = $line["link"];
5409 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
5411 if ($line["comments"] && $line["link"] != $line["comments"]) {
5412 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
5416 if ($entry_comments) $reply['content'] .= " ($entry_comments)";
5418 $reply['content'] .= "<div style=\"float : right\">";
5420 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5421 onclick=\"zoomToArticle(event, $id)\"
5422 style=\"cursor : pointer\"
5424 title='".__('Open article in new tab')."'>";
5426 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5428 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5429 style=\"cursor : pointer\" style=\"cursor : pointer\"
5430 onclick=\"editArticleNote($id)\"
5431 alt='PubNote' title='".__('Edit article note')."'>";
5433 if (DIGEST_ENABLE
) {
5434 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5435 style=\"cursor : pointer\"
5436 onclick=\"emailArticle($id)\"
5437 alt='Zoom' title='".__('Forward by email')."'>";
5440 if (ENABLE_TWEET_BUTTON
) {
5441 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5442 class='tagsPic' style=\"cursor : pointer\"
5443 onclick=\"tweetArticle($id)\"
5444 alt='Zoom' title='".__('Share on Twitter')."'>";
5447 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
5448 class='tagsPic' style=\"cursor : pointer\"
5449 onclick=\"shareArticle(".$line['int_id'].")\"
5450 alt='Zoom' title='".__('Share by URL')."'>";
5452 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5453 style=\"cursor : pointer\" style=\"cursor : pointer\"
5454 onclick=\"dismissArticle($id)\"
5455 alt='Dismiss' title='".__('Dismiss article')."'>";
5457 $reply['content'] .= "</div>";
5458 $reply['content'] .= "</div>";
5460 $reply['content'] .= "</div>";
5462 $reply['content'] .= "</div>";
5469 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5474 switch ($view_mode) {
5476 $message = __("No unread articles found to display.");
5479 $message = __("No updated articles found to display.");
5482 $message = __("No starred articles found to display.");
5486 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5488 $message = __("No articles found to display.");
5492 if (!$offset && $message) {
5493 $reply['content'] .= "<div class='whiteBox'>$message";
5495 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5497 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5498 WHERE owner_uid = " . $_SESSION['uid']);
5500 $last_updated = db_fetch_result($result, 0, "last_updated");
5501 $last_updated = make_local_datetime($link, $last_updated, false);
5503 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5505 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5506 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5508 $num_errors = db_fetch_result($result, 0, "num_errors");
5510 if ($num_errors > 0) {
5511 $reply['content'] .= "<br/>";
5512 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5513 __('Some feeds have update errors (click for details)')."</a>";
5515 $reply['content'] .= "</span></p></div>";
5519 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5521 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5522 $vgroup_last_feed, $reply);
5525 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5527 function printTagCloud($link) {
5529 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5530 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5531 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5533 $result = db_query($link, $query);
5537 while ($line = db_fetch_assoc($result)) {
5538 $tags[$line["tag_name"]] = $line["count"];
5541 if( count($tags) == 0 ){ return; }
5545 $max_size = 32; // max font size in pixels
5546 $min_size = 11; // min font size in pixels
5548 // largest and smallest array values
5549 $max_qty = max(array_values($tags));
5550 $min_qty = min(array_values($tags));
5552 // find the range of values
5553 $spread = $max_qty - $min_qty;
5554 if ($spread == 0) { // we don't want to divide by zero
5558 // set the font-size increment
5559 $step = ($max_size - $min_size) / ($spread);
5561 // loop through the tag array
5562 foreach ($tags as $key => $value) {
5563 // calculate font-size
5564 // find the $value in excess of $min_qty
5565 // multiply by the font-size increment ($size)
5566 // and add the $min_size set above
5567 $size = round($min_size +
(($value - $min_qty) * $step));
5569 $key_escaped = str_replace("'", "\\'", $key);
5571 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5572 $size . "px\" title=\"$value articles tagged with " .
5573 $key . '">' . $key . '</a> ';
5577 function print_checkpoint($n, $s) {
5578 $ts = getmicrotime();
5579 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5583 function sanitize_tag($tag) {
5586 $tag = mb_strtolower($tag, 'utf-8');
5588 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5590 // $tag = str_replace('"', "", $tag);
5591 // $tag = str_replace("+", " ", $tag);
5592 $tag = str_replace("technorati tag: ", "", $tag);
5597 function get_self_url_prefix() {
5598 return SELF_URL_PATH
;
5601 function opml_publish_url($link){
5603 $url_path = get_self_url_prefix();
5604 $url_path .= "/opml.php?op=publish&key=" .
5605 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5611 * Purge a feed contents, marked articles excepted.
5613 * @param mixed $link The database connection.
5614 * @param integer $id The id of the feed to purge.
5617 function clear_feed_articles($link, $id) {
5620 $result = db_query($link, "DELETE FROM ttrss_user_entries
5621 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5623 $result = db_query($link, "DELETE FROM ttrss_user_entries
5624 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5627 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5628 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5630 ccache_update($link, $id, $_SESSION['uid']);
5631 } // function clear_feed_articles
5634 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5636 * @return string The Mozilla Firefox feed adding URL.
5638 function add_feed_url() {
5639 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5641 $url_path = get_self_url_prefix() .
5642 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5644 } // function add_feed_url
5647 * Encrypt a password in SHA1.
5649 * @param string $pass The password to encrypt.
5650 * @param string $login A optionnal login.
5651 * @return string The encrypted password.
5653 function encrypt_password($pass, $login = '') {
5655 return "SHA1X:" . sha1("$login:$pass");
5657 return "SHA1:" . sha1($pass);
5659 } // function encrypt_password
5662 * Update a feed batch.
5663 * Used by daemons to update n feeds by run.
5664 * Only update feed needing a update, and not being processed
5665 * by another process.
5667 * @param mixed $link Database link
5668 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5669 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5670 * @param boolean $debug Set to false to disable debug output. Default to true.
5673 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5674 // Process all other feeds using last_updated and interval parameters
5676 // Test if the user has loggued in recently. If not, it does not update its feeds.
5677 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5678 if (DB_TYPE
== "pgsql") {
5679 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5681 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5684 $login_thresh_qpart = "";
5687 // Test if the feed need a update (update interval exceded).
5688 if (DB_TYPE
== "pgsql") {
5689 $update_limit_qpart = "AND ((
5690 ttrss_feeds.update_interval = 0
5691 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5693 ttrss_feeds.update_interval > 0
5694 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5695 ) OR ttrss_feeds.last_updated IS NULL)";
5697 $update_limit_qpart = "AND ((
5698 ttrss_feeds.update_interval = 0
5699 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5701 ttrss_feeds.update_interval > 0
5702 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5703 ) OR ttrss_feeds.last_updated IS NULL)";
5706 // Test if feed is currently being updated by another process.
5707 if (DB_TYPE
== "pgsql") {
5708 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
5710 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
5713 // Test if there is a limit to number of updated feeds
5715 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5717 $random_qpart = sql_random_function();
5719 // We search for feed needing update.
5720 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5721 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5722 ttrss_feeds.update_interval
5724 ttrss_feeds, ttrss_users, ttrss_user_prefs
5726 ttrss_feeds.owner_uid = ttrss_users.id
5727 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5728 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5729 $login_thresh_qpart $update_limit_qpart
5730 $updstart_thresh_qpart
5731 ORDER BY $random_qpart $query_limit");
5733 $user_prefs_cache = array();
5735 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5737 // Here is a little cache magic in order to minimize risk of double feed updates.
5738 $feeds_to_update = array();
5739 while ($line = db_fetch_assoc($result)) {
5740 $feeds_to_update[$line['id']] = $line;
5743 // We update the feed last update started date before anything else.
5744 // There is no lag due to feed contents downloads
5745 // It prevent an other process to update the same feed.
5746 $feed_ids = array_keys($feeds_to_update);
5748 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5749 WHERE id IN (%s)", implode(',', $feed_ids)));
5752 // For each feed, we call the feed update function.
5753 while ($line = array_pop($feeds_to_update)) {
5755 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5757 update_rss_feed($link, $line["id"], true);
5759 sleep(1); // prevent flood (FIXME make this an option?)
5762 // Send feed digests by email if needed.
5763 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5765 } // function update_daemon_common
5767 function sanitize_article_content($text) {
5768 # we don't support CDATA sections in articles, they break our own escaping
5769 $text = preg_replace("/\[\[CDATA/", "", $text);
5770 $text = preg_replace("/\]\]\>/", "", $text);
5774 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5779 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5781 if ($memcache && $obj = $memcache->get($obj_id)) {
5787 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5789 $result = db_query($link, "SELECT reg_exp,
5790 ttrss_filter_types.name AS name,
5791 ttrss_filter_actions.name AS action,
5795 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5798 owner_uid = $owner_uid AND
5799 ttrss_filter_types.id = filter_type AND
5800 ttrss_filter_actions.id = action_id AND
5801 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5803 while ($line = db_fetch_assoc($result)) {
5804 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5805 $filter["reg_exp"] = $line["reg_exp"];
5806 $filter["action"] = $line["action"];
5807 $filter["action_param"] = $line["action_param"];
5808 $filter["filter_param"] = $line["filter_param"];
5809 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5811 array_push($filters[$line["name"]], $filter);
5814 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5820 function get_score_pic($score) {
5822 return "score_high.png";
5823 } else if ($score > 0) {
5824 return "score_half_high.png";
5825 } else if ($score < -100) {
5826 return "score_low.png";
5827 } else if ($score < 0) {
5828 return "score_half_low.png";
5830 return "score_neutral.png";
5834 function feed_has_icon($id) {
5835 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5838 function init_connection($link) {
5839 if (DB_TYPE
== "pgsql") {
5840 pg_query($link, "set client_encoding = 'UTF-8'");
5841 pg_set_client_encoding("UNICODE");
5842 pg_query($link, "set datestyle = 'ISO, european'");
5843 pg_query($link, "set TIME ZONE 0");
5845 db_query($link, "SET time_zone = '+0:0'");
5847 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5848 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5849 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5854 function update_feedbrowser_cache($link) {
5856 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
5857 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5858 WHERE tf.feed_url = ttrss_feeds.feed_url
5859 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
5860 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
5862 db_query($link, "BEGIN");
5864 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5868 while ($line = db_fetch_assoc($result)) {
5869 $subscribers = db_escape_string($line["subscribers"]);
5870 $feed_url = db_escape_string($line["feed_url"]);
5871 $title = db_escape_string($line["title"]);
5872 $site_url = db_escape_string($line["site_url"]);
5874 $tmp_result = db_query($link, "SELECT subscribers FROM
5875 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5877 if (db_num_rows($tmp_result) == 0) {
5879 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5880 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5881 '$site_url', '$title', '$subscribers')");
5889 db_query($link, "COMMIT");
5895 /* function ccache_zero($link, $feed_id, $owner_uid) {
5896 db_query($link, "UPDATE ttrss_counters_cache SET
5897 value = 0, updated = NOW() WHERE
5898 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5901 function ccache_zero_all($link, $owner_uid) {
5902 db_query($link, "UPDATE ttrss_counters_cache SET
5903 value = 0 WHERE owner_uid = '$owner_uid'");
5905 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5906 value = 0 WHERE owner_uid = '$owner_uid'");
5909 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5912 $table = "ttrss_counters_cache";
5914 $table = "ttrss_cat_counters_cache";
5917 db_query($link, "DELETE FROM $table WHERE
5918 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5922 function ccache_update_all($link, $owner_uid) {
5924 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5926 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5927 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5929 while ($line = db_fetch_assoc($result)) {
5930 ccache_update($link, $line["feed_id"], $owner_uid, true);
5933 /* We have to manually include category 0 */
5935 ccache_update($link, 0, $owner_uid, true);
5938 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5939 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5941 while ($line = db_fetch_assoc($result)) {
5942 print ccache_update($link, $line["feed_id"], $owner_uid);
5949 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5950 $no_update = false) {
5952 if (!is_numeric($feed_id)) return;
5955 $table = "ttrss_counters_cache";
5957 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5958 WHERE id = '$feed_id'");
5959 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5962 $table = "ttrss_cat_counters_cache";
5965 if (DB_TYPE
== "pgsql") {
5966 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5967 } else if (DB_TYPE
== "mysql") {
5968 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5971 $result = db_query($link, "SELECT value FROM $table
5972 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5975 if (db_num_rows($result) == 1) {
5976 return db_fetch_result($result, 0, "value");
5981 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5987 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5988 $update_pcat = true) {
5990 if (!is_numeric($feed_id)) return;
5992 if (!$is_cat && $feed_id > 0) {
5993 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5994 WHERE id = '$feed_id'");
5995 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5998 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6000 /* When updating a label, all we need to do is recalculate feed counters
6001 * because labels are not cached */
6004 ccache_update_all($link, $owner_uid);
6009 $table = "ttrss_counters_cache";
6011 $table = "ttrss_cat_counters_cache";
6014 if ($is_cat && $feed_id >= 0) {
6015 if ($feed_id != 0) {
6016 $cat_qpart = "cat_id = '$feed_id'";
6018 $cat_qpart = "cat_id IS NULL";
6021 /* Recalculate counters for child feeds */
6023 $result = db_query($link, "SELECT id FROM ttrss_feeds
6024 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6026 while ($line = db_fetch_assoc($result)) {
6027 ccache_update($link, $line["id"], $owner_uid, false, false);
6030 $result = db_query($link, "SELECT SUM(value) AS sv
6031 FROM ttrss_counters_cache, ttrss_feeds
6032 WHERE id = feed_id AND $cat_qpart AND
6033 ttrss_feeds.owner_uid = '$owner_uid'");
6035 $unread = (int) db_fetch_result($result, 0, "sv");
6038 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6041 db_query($link, "BEGIN");
6043 $result = db_query($link, "SELECT feed_id FROM $table
6044 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6046 if (db_num_rows($result) == 1) {
6047 db_query($link, "UPDATE $table SET
6048 value = '$unread', updated = NOW() WHERE
6049 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6052 db_query($link, "INSERT INTO $table
6053 (feed_id, value, owner_uid, updated)
6055 ($feed_id, $unread, $owner_uid, NOW())");
6058 db_query($link, "COMMIT");
6060 if ($feed_id > 0 && $prev_unread != $unread) {
6064 /* Update parent category */
6068 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6069 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6071 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6073 ccache_update($link, $cat_id, $owner_uid, true);
6077 } else if ($feed_id < 0) {
6078 ccache_update_all($link, $owner_uid);
6084 /* function ccache_cleanup($link, $owner_uid) {
6086 if (DB_TYPE == "pgsql") {
6087 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6088 (SELECT count(*) FROM ttrss_counters_cache AS c2
6089 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6090 AND owner_uid = '$owner_uid'");
6092 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6093 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6094 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6095 AND owner_uid = '$owner_uid'");
6097 db_query($link, "DELETE c1 FROM
6098 ttrss_counters_cache AS c1,
6099 ttrss_counters_cache AS c2
6101 c1.owner_uid = '$owner_uid' AND
6102 c1.owner_uid = c2.owner_uid AND
6103 c1.feed_id = c2.feed_id");
6105 db_query($link, "DELETE c1 FROM
6106 ttrss_cat_counters_cache AS c1,
6107 ttrss_cat_counters_cache AS c2
6109 c1.owner_uid = '$owner_uid' AND
6110 c1.owner_uid = c2.owner_uid AND
6111 c1.feed_id = c2.feed_id");
6116 function label_find_id($link, $label, $owner_uid) {
6117 $result = db_query($link,
6118 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6119 AND owner_uid = '$owner_uid' LIMIT 1");
6121 if (db_num_rows($result) == 1) {
6122 return db_fetch_result($result, 0, "id");
6128 function get_article_labels($link, $id) {
6131 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6135 if ($memcache && $obj = $memcache->get($obj_id)) {
6139 $result = db_query($link, "SELECT label_cache FROM
6140 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6143 $label_cache = db_fetch_result($result, 0, "label_cache");
6147 $label_cache = json_decode($label_cache, true);
6149 if ($label_cache["no-labels"] == 1)
6152 return $label_cache;
6155 $result = db_query($link,
6156 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6157 FROM ttrss_labels2, ttrss_user_labels2
6159 AND article_id = '$id'
6160 AND owner_uid = ".$_SESSION["uid"] . "
6163 while ($line = db_fetch_assoc($result)) {
6164 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6166 array_push($rv, $rk);
6168 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6171 label_update_cache($link, $id, $rv);
6173 label_update_cache($link, $id, array("no-labels" => 1));
6180 function label_find_caption($link, $label, $owner_uid) {
6181 $result = db_query($link,
6182 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6183 AND owner_uid = '$owner_uid' LIMIT 1");
6185 if (db_num_rows($result) == 1) {
6186 return db_fetch_result($result, 0, "caption");
6192 function label_update_cache($link, $id, $labels = false, $force = false) {
6195 label_clear_cache($link, $id);
6198 $labels = get_article_labels($link, $id);
6200 $labels = db_escape_string(json_encode($labels));
6202 db_query($link, "UPDATE ttrss_user_entries SET
6203 label_cache = '$labels' WHERE ref_id = '$id'");
6207 function label_clear_cache($link, $id) {
6209 db_query($link, "UPDATE ttrss_user_entries SET
6210 label_cache = '' WHERE ref_id = '$id'");
6214 function label_remove_article($link, $id, $label, $owner_uid) {
6216 $label_id = label_find_id($link, $label, $owner_uid);
6218 if (!$label_id) return;
6220 $result = db_query($link,
6221 "DELETE FROM ttrss_user_labels2
6223 label_id = '$label_id' AND
6224 article_id = '$id'");
6226 label_clear_cache($link, $id);
6229 function label_add_article($link, $id, $label, $owner_uid) {
6234 $obj_id = md5("LABELS:$id:$owner_uid");
6235 $memcache->delete($obj_id);
6238 $label_id = label_find_id($link, $label, $owner_uid);
6240 if (!$label_id) return;
6242 $result = db_query($link,
6244 article_id FROM ttrss_labels2, ttrss_user_labels2
6247 label_id = '$label_id' AND
6248 article_id = '$id' AND owner_uid = '$owner_uid'
6251 if (db_num_rows($result) == 0) {
6252 db_query($link, "INSERT INTO ttrss_user_labels2
6253 (label_id, article_id) VALUES ('$label_id', '$id')");
6256 label_clear_cache($link, $id);
6260 function label_remove($link, $id, $owner_uid) {
6263 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6266 $obj_id = md5("LABELS:$id:$owner_uid");
6267 $memcache->delete($obj_id);
6270 db_query($link, "BEGIN");
6272 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6275 $caption = db_fetch_result($result, 0, "caption");
6277 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6278 AND owner_uid = " . $owner_uid);
6280 if (db_affected_rows($link, $result) != 0 && $caption) {
6282 /* Remove access key for the label */
6284 $ext_id = -11 - $id;
6286 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6287 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6289 /* Disable filters that reference label being removed */
6291 db_query($link, "UPDATE ttrss_filters SET
6292 enabled = false WHERE action_param = '$caption'
6294 AND owner_uid = " . $owner_uid);
6296 /* Remove cached data */
6298 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6299 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6303 db_query($link, "COMMIT");
6306 function label_create($link, $caption) {
6308 db_query($link, "BEGIN");
6312 $result = db_query($link, "SELECT id FROM ttrss_labels2
6313 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6315 if (db_num_rows($result) == 0) {
6316 $result = db_query($link,
6317 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6318 VALUES ('$caption', '".$_SESSION["uid"]."')");
6320 $result = db_affected_rows($link, $result) != 0;
6323 db_query($link, "COMMIT");
6328 function format_tags_string($tags, $id) {
6331 $tags_nolinks_str = "";
6337 $formatted_tags = array();
6339 foreach ($tags as $tag) {
6341 $tag_escaped = str_replace("'", "\\'", $tag);
6343 if (mb_strlen($tag) > 30) {
6344 $tag = truncate_string($tag, 30);
6347 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6349 array_push($formatted_tags, $tag_str);
6351 $tmp_tags_str = implode(", ", $formatted_tags);
6353 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6358 $tags_str = implode(", ", $formatted_tags);
6360 if ($num_tags < count($tags)) {
6361 $tags_str .= ", …";
6364 if ($num_tags == 0) {
6365 $tags_str = __("no tags");
6372 function format_article_labels($labels, $id) {
6376 foreach ($labels as $l) {
6377 $labels_str .= sprintf("<span class='hlLabelRef'
6378 style='color : %s; background-color : %s'>%s</span>",
6379 $l[2], $l[3], $l[1]);
6386 function format_article_note($id, $note) {
6388 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6389 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6390 __('(edit note)')."</div>$note</div>";
6395 function toggle_collapse_cat($link, $cat_id, $mode) {
6397 $mode = bool_to_sql_bool($mode);
6399 db_query($link, "UPDATE ttrss_feed_categories SET
6400 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6407 $pref_name = '_COLLAPSED_SPECIAL';
6410 $pref_name = '_COLLAPSED_LABELS';
6413 $pref_name = '_COLLAPSED_UNCAT';
6419 set_pref($link, $pref_name, 'true');
6421 set_pref($link, $pref_name, 'false');
6427 function remove_feed($link, $id, $owner_uid) {
6431 /* save starred articles in Archived feed */
6433 db_query($link, "BEGIN");
6435 /* prepare feed if necessary */
6437 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6440 if (db_num_rows($result) == 0) {
6441 db_query($link, "INSERT INTO ttrss_archived_feeds
6442 (id, owner_uid, title, feed_url, site_url)
6443 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6447 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6448 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6449 marked = true AND owner_uid = $owner_uid");
6451 /* Remove access key for the feed */
6453 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6454 feed_id = '$id' AND owner_uid = $owner_uid");
6456 /* remove the feed */
6458 db_query($link, "DELETE FROM ttrss_feeds
6459 WHERE id = '$id' AND owner_uid = $owner_uid");
6461 db_query($link, "COMMIT");
6463 if (file_exists(ICONS_DIR
. "/$id.ico")) {
6464 unlink(ICONS_DIR
. "/$id.ico");
6467 ccache_remove($link, $id, $owner_uid);
6470 label_remove($link, -11-$id, $owner_uid);
6471 ccache_remove($link, -11-$id, $owner_uid);
6475 function add_feed_category($link, $feed_cat) {
6477 if (!$feed_cat) return false;
6479 db_query($link, "BEGIN");
6481 $result = db_query($link,
6482 "SELECT id FROM ttrss_feed_categories
6483 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6485 if (db_num_rows($result) == 0) {
6487 $result = db_query($link,
6488 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6489 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6491 db_query($link, "COMMIT");
6499 function remove_feed_category($link, $id, $owner_uid) {
6501 db_query($link, "DELETE FROM ttrss_feed_categories
6502 WHERE id = '$id' AND owner_uid = $owner_uid");
6504 ccache_remove($link, $id, $owner_uid, true);
6507 function archive_article($link, $id, $owner_uid) {
6508 db_query($link, "BEGIN");
6510 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6511 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6513 if (db_num_rows($result) != 0) {
6515 /* prepare the archived table */
6517 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6520 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6521 WHERE id = '$feed_id'");
6523 if (db_num_rows($result) == 0) {
6524 db_query($link, "INSERT INTO ttrss_archived_feeds
6525 (id, owner_uid, title, feed_url, site_url)
6526 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6527 WHERE id = '$feed_id'");
6530 db_query($link, "UPDATE ttrss_user_entries
6531 SET orig_feed_id = feed_id, feed_id = NULL
6532 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6536 db_query($link, "COMMIT");
6539 function getArticleFeed($link, $id) {
6540 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6541 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6543 if (db_num_rows($result) != 0) {
6544 return db_fetch_result($result, 0, "feed_id");
6551 * Fixes incomplete URLs by prepending "http://".
6552 * Also replaces feed:// with http://, and
6553 * prepends a trailing slash if the url is a domain name only.
6555 * @param string $url Possibly incomplete URL
6557 * @return string Fixed URL.
6559 function fix_url($url) {
6560 if (strpos($url, '://') === false) {
6561 $url = 'http://' . $url;
6562 } else if (substr($url, 0, 5) == 'feed:') {
6563 $url = 'http:' . substr($url, 5);
6566 //prepend slash if the URL has no slash in it
6567 // "http://www.example" -> "http://www.example/"
6568 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6572 if ($url != "http:///")
6578 function validate_feed_url($url) {
6579 $parts = parse_url($url);
6581 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6585 function get_article_enclosures($link, $id) {
6589 $query = "SELECT * FROM ttrss_enclosures
6590 WHERE post_id = '$id' AND content_url != ''";
6592 $obj_id = md5("ENCLOSURES:$id");
6596 if ($memcache && $obj = $memcache->get($obj_id)) {
6599 $result = db_query($link, $query);
6601 if (db_num_rows($result) > 0) {
6602 while ($line = db_fetch_assoc($result)) {
6603 array_push($rv, $line);
6605 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6612 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6618 if ($cat_id == -4 ||
$cat_id == -2) {
6619 $counters = getLabelCounters($link, true);
6621 foreach (array_values($counters) as $cv) {
6623 $unread = $cv["counter"];
6625 if ($unread ||
!$unread_only) {
6629 "title" => $cv["description"],
6630 "unread" => $cv["counter"],
6634 array_push($feeds, $row);
6641 if ($cat_id == -4 ||
$cat_id == -1) {
6642 foreach (array(-1, -2, -3, -4, 0) as $i) {
6643 $unread = getFeedUnread($link, $i);
6645 if ($unread ||
!$unread_only) {
6646 $title = getFeedTitle($link, $i);
6651 "unread" => $unread,
6654 array_push($feeds, $row);
6663 $limit_qpart = "LIMIT $limit OFFSET $offset";
6668 if ($cat_id == -4 ||
$cat_id == -3) {
6669 $result = db_query($link, "SELECT
6670 id, feed_url, cat_id, title, ".
6671 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6672 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6673 " ORDER BY cat_id, title " . $limit_qpart);
6677 $cat_qpart = "cat_id = '$cat_id'";
6679 $cat_qpart = "cat_id IS NULL";
6681 $result = db_query($link, "SELECT
6682 id, feed_url, cat_id, title, ".
6683 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6684 FROM ttrss_feeds WHERE
6685 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6686 " ORDER BY cat_id, title " . $limit_qpart);
6689 while ($line = db_fetch_assoc($result)) {
6691 $unread = getFeedUnread($link, $line["id"]);
6693 $has_icon = feed_has_icon($line['id']);
6695 if ($unread ||
!$unread_only) {
6698 "feed_url" => $line["feed_url"],
6699 "title" => $line["title"],
6700 "id" => (int)$line["id"],
6701 "unread" => (int)$unread,
6702 "has_icon" => $has_icon,
6703 "cat_id" => (int)$line["cat_id"],
6704 "last_updated" => strtotime($line["last_updated"])
6707 array_push($feeds, $row);
6714 function api_get_headlines($link, $feed_id, $limit, $offset,
6715 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6716 $include_attachments, $since_id) {
6718 /* do not rely on params below */
6720 $search = db_escape_string($_REQUEST["search"]);
6721 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6722 $match_on = db_escape_string($_REQUEST["match_on"]);
6724 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6725 $view_mode, $is_cat, $search, $search_mode, $match_on,
6726 $order, $offset, 0, false, $since_id);
6728 $result = $qfh_ret[0];
6729 $feed_title = $qfh_ret[1];
6731 $headlines = array();
6733 while ($line = db_fetch_assoc($result)) {
6734 $is_updated = ($line["last_read"] == "" &&
6735 ($line["unread"] != "t" && $line["unread"] != "1"));
6737 $tags = explode(",", $line["tag_cache"]);
6738 $labels = json_decode($line["label_cache"], true);
6740 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
6741 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
6743 $headline_row = array(
6744 "id" => (int)$line["id"],
6745 "unread" => sql_bool_to_bool($line["unread"]),
6746 "marked" => sql_bool_to_bool($line["marked"]),
6747 "published" => sql_bool_to_bool($line["published"]),
6748 "updated" => strtotime($line["updated"]),
6749 "is_updated" => $is_updated,
6750 "title" => $line["title"],
6751 "link" => $line["link"],
6752 "feed_id" => $line["feed_id"],
6756 if ($include_attachments)
6757 $headline_row['attachments'] = get_article_enclosures($link,
6760 if ($show_excerpt) {
6761 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6762 $headline_row["excerpt"] = $excerpt;
6765 if ($show_content) {
6766 $headline_row["content"] = $line["content_preview"];
6769 // unify label output to ease parsing
6770 if ($labels["no-labels"] == 1) $labels = array();
6772 $headline_row["labels"] = $labels;
6774 array_push($headlines, $headline_row);
6780 function generate_error_feed($link, $error) {
6783 $reply['headlines']['id'] = -6;
6784 $reply['headlines']['is_cat'] = false;
6786 $reply['headlines']['toolbar'] = '';
6787 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6789 $reply['headlines-info'] = array("count" => 0,
6790 "vgroup_last_feed" => '',
6792 "disable_cache" => true);
6798 function generate_dashboard_feed($link) {
6801 $reply['headlines']['id'] = -5;
6802 $reply['headlines']['is_cat'] = false;
6804 $reply['headlines']['toolbar'] = '';
6805 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6807 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6809 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6810 WHERE owner_uid = " . $_SESSION['uid']);
6812 $last_updated = db_fetch_result($result, 0, "last_updated");
6813 $last_updated = make_local_datetime($link, $last_updated, false);
6815 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6817 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6818 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6820 $num_errors = db_fetch_result($result, 0, "num_errors");
6822 if ($num_errors > 0) {
6823 $reply['headlines']['content'] .= "<br/>";
6824 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6825 __('Some feeds have update errors (click for details)')."</a>";
6827 $reply['headlines']['content'] .= "</span></p>";
6829 $reply['headlines-info'] = array("count" => 0,
6830 "vgroup_last_feed" => '',
6832 "disable_cache" => true);
6837 function save_email_address($link, $email) {
6838 // FIXME: implement persistent storage of emails
6840 if (!$_SESSION['stored_emails'])
6841 $_SESSION['stored_emails'] = array();
6843 if (!in_array($email, $_SESSION['stored_emails']))
6844 array_push($_SESSION['stored_emails'], $email);
6847 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6848 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6850 $sql_is_cat = bool_to_sql_bool($is_cat);
6852 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6853 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6854 AND owner_uid = " . $owner_uid);
6856 if (db_num_rows($result) == 1) {
6857 $key = db_escape_string(sha1(uniqid(rand(), true)));
6859 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6860 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6861 AND owner_uid = " . $owner_uid);
6866 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6870 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6872 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6874 $sql_is_cat = bool_to_sql_bool($is_cat);
6876 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6877 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6878 AND owner_uid = " . $owner_uid);
6880 if (db_num_rows($result) == 1) {
6881 return db_fetch_result($result, 0, "access_key");
6883 $key = db_escape_string(sha1(uniqid(rand(), true)));
6885 $result = db_query($link, "INSERT INTO ttrss_access_keys
6886 (access_key, feed_id, is_cat, owner_uid)
6887 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6895 * Extracts RSS/Atom feed URLs from the given HTML URL.
6897 * @param string $url HTML page URL
6899 * @return array Array of feeds. Key is the full URL, value the title
6901 function get_feeds_from_html($url, $login = false, $pass = false)
6903 $url = fix_url($url);
6904 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
6906 libxml_use_internal_errors(true);
6908 $content = @fetch_file_contents
($url, false, $login, $pass);
6910 $doc = new DOMDocument();
6911 $doc->loadHTML($content);
6912 $xpath = new DOMXPath($doc);
6913 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6914 $feedUrls = array();
6915 foreach ($entries as $entry) {
6916 if ($entry->hasAttribute('href')) {
6917 $title = $entry->getAttribute('title');
6919 $title = $entry->getAttribute('type');
6921 $feedUrl = rewrite_relative_url(
6922 $baseUrl, $entry->getAttribute('href')
6924 $feedUrls[$feedUrl] = $title;
6931 * Checks if the content behind the given URL is a HTML file
6933 * @param string $url URL to check
6935 * @return boolean True if the URL contains HTML content
6937 function url_is_html($url, $login = false, $pass = false) {
6938 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6940 if (stripos($content, '<html>') === false
6941 && stripos($content, '<html ') === false
6949 function print_label_select($link, $name, $value, $attributes = "") {
6951 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6952 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6954 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6955 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
6957 while ($line = db_fetch_assoc($result)) {
6959 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
6961 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6962 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6966 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6973 function format_article_enclosures($link, $id, $always_display_enclosures,
6976 $result = get_article_enclosures($link, $id);
6979 if (count($result) > 0) {
6981 $entries_html = array();
6984 foreach ($result as $line) {
6986 $url = $line["content_url"];
6987 $ctype = $line["content_type"];
6989 if (!$ctype) $ctype = __("unknown type");
6991 # $filename = substr($url, strrpos($url, "/")+1);
6993 $entry = format_inline_player($link, $url, $ctype);
6995 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6996 # $filename . " (" . $ctype . ")" . "</a>";
6998 array_push($entries_html, $entry);
7002 $entry["type"] = $ctype;
7003 $entry["filename"] = $filename;
7004 $entry["url"] = $url;
7006 array_push($entries, $entry);
7009 $rv .= "<div class=\"postEnclosures\">";
7011 if (!get_pref($link, "STRIP_IMAGES")) {
7012 if ($always_display_enclosures ||
7013 !preg_match("/<img/i", $article_content)) {
7015 foreach ($entries as $entry) {
7017 if (preg_match("/image/", $entry["type"]) ||
7018 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
7021 alt=\"".htmlspecialchars($entry["filename"])."\"
7022 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7028 if (count($entries) == 1) {
7029 $rv .= __("Attachment:") . " ";
7031 $rv .= __("Attachments:") . " ";
7034 $rv .= join(", ", $entries_html);
7042 function getLastArticleId($link) {
7043 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7044 WHERE owner_uid = " . $_SESSION["uid"]);
7046 if (db_num_rows($result) == 1) {
7047 return db_fetch_result($result, 0, "id");
7053 function build_url($parts) {
7054 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7058 * Converts a (possibly) relative URL to a absolute one.
7060 * @param string $url Base URL (i.e. from where the document is)
7061 * @param string $rel_url Possibly relative URL in the document
7063 * @return string Absolute URL
7065 function rewrite_relative_url($url, $rel_url) {
7066 if (strpos($rel_url, "://") !== false) {
7068 } else if (strpos($rel_url, "/") === 0)
7070 $parts = parse_url($url);
7071 $parts['path'] = $rel_url;
7073 return build_url($parts);
7076 $parts = parse_url($url);
7077 if (!isset($parts['path'])) {
7078 $parts['path'] = '/';
7080 $dir = $parts['path'];
7081 if (substr($dir, -1) !== '/') {
7082 $dir = dirname($parts['path']);
7083 $dir !== '/' && $dir .= '/';
7085 $parts['path'] = $dir . $rel_url;
7087 return build_url($parts);
7091 function sphinx_search($query, $offset = 0, $limit = 30) {
7092 require_once 'lib/sphinxapi.php';
7094 $sphinxClient = new SphinxClient();
7096 $sphinxClient->SetServer('localhost', 9312);
7097 $sphinxClient->SetConnectTimeout(1);
7099 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7100 'feed_title' => 20));
7102 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
7103 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
7104 $sphinxClient->SetLimits($offset, $limit, 1000);
7105 $sphinxClient->SetArrayResult(false);
7106 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7108 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
7112 if (is_array($result['matches'])) {
7113 foreach (array_keys($result['matches']) as $int_id) {
7114 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7115 array_push($ids, $ref_id);
7122 function cleanup_tags($link, $days = 14, $limit = 1000) {
7124 if (DB_TYPE
== "pgsql") {
7125 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7126 } else if (DB_TYPE
== "mysql") {
7127 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7132 while ($limit > 0) {
7135 $query = "SELECT ttrss_tags.id AS id
7136 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7137 WHERE post_int_id = int_id AND $interval_query AND
7138 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7140 $result = db_query($link, $query);
7144 while ($line = db_fetch_assoc($result)) {
7145 array_push($ids, $line['id']);
7148 if (count($ids) > 0) {
7149 $ids = join(",", $ids);
7152 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7153 $tags_deleted +
= db_affected_rows($link, $tmp_result);
7158 $limit -= $limit_part;
7163 return $tags_deleted;
7166 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7168 $cat_id = (int) $cat_id;
7171 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7172 } else if ($cat_id == 0 ||
$cat_id == -2) {
7173 $cat_unread = getCategoryUnread($link, $cat_id);
7176 $obj['id'] = 'CAT:' . $cat_id;
7177 $obj['items'] = array();
7178 $obj['name'] = getCategoryTitle($link, $cat_id);
7179 $obj['type'] = 'feed';
7180 $obj['unread'] = (int) $cat_unread;
7181 $obj['hidden'] = $hidden;
7182 $obj['bare_id'] = $cat_id;
7187 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7189 $feed_id = (int) $feed_id;
7192 $title = getFeedTitle($link, $feed_id, false);
7194 if ($unread === false)
7195 $unread = getFeedUnread($link, $feed_id, false);
7197 $obj['id'] = 'FEED:' . $feed_id;
7198 $obj['name'] = $title;
7199 $obj['unread'] = (int) $unread;
7200 $obj['type'] = 'feed';
7201 $obj['error'] = $error;
7202 $obj['updated'] = $updated;
7203 $obj['icon'] = getFeedIcon($feed_id);
7204 $obj['bare_id'] = $feed_id;
7210 function fetch_twitter_rss($link, $url, $owner_uid) {
7212 require_once 'lib/tmhoauth/tmhOAuth.php';
7214 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7215 WHERE id = $owner_uid");
7217 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7218 $url_escaped = db_escape_string($url);
7220 if ($access_token) {
7222 $tmhOAuth = new tmhOAuth(array(
7223 'consumer_key' => CONSUMER_KEY
,
7224 'consumer_secret' => CONSUMER_SECRET
,
7225 'user_token' => $access_token['oauth_token'],
7226 'user_secret' => $access_token['oauth_token_secret'],
7229 $code = $tmhOAuth->request('GET', $url);
7233 $content = $tmhOAuth->response
['response'];
7235 define('MAGPIE_CACHE_ON', false);
7237 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7238 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7244 db_query($link, "UPDATE ttrss_feeds
7245 SET last_error = 'OAuth authorization failed ($code).'
7246 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7251 db_query($link, "UPDATE ttrss_feeds
7252 SET last_error = 'OAuth information not found.'
7253 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7259 function print_user_stylesheet($link) {
7260 $value = get_pref($link, 'USER_STYLESHEET');
7263 print "<style type=\"text/css\">";
7264 print str_replace("<br/>", "\n", $value);
7270 function rewrite_urls($line) {
7275 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7276 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7281 function filter_to_sql($filter) {
7284 if (DB_TYPE
== "pgsql")
7287 $reg_qpart = "REGEXP";
7289 switch ($filter["type"]) {
7291 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7292 $filter['reg_exp'] . "')";
7295 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7296 $filter['reg_exp'] . "')";
7299 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7300 $filter['reg_exp'] . "') OR LOWER(" .
7301 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7304 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7305 $filter['reg_exp'] . "')";
7308 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7309 $filter['reg_exp'] . "')";
7313 if ($filter["filter_param"] == "before")
7318 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7319 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7322 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7323 $filter['reg_exp'] . "')";
7327 if ($filter["inverse"])
7328 $query = "NOT ($query)";
7331 if (DB_TYPE
== "pgsql") {
7332 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
7334 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
7344 // -1 - never connected
7345 // 0 - no data received
7346 // 1 - data received successfully
7347 // 2 - did not receive valid data
7348 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7350 function get_linked_feeds($link, $instance_id = false) {
7352 $instance_qpart = "id = '$instance_id' AND ";
7354 $instance_qpart = "";
7356 if (DB_TYPE
== "pgsql") {
7357 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
7359 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
7362 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7363 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7365 while ($line = db_fetch_assoc($result)) {
7368 _debug("Updating: " . $line['access_url'] . " ($id)");
7370 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
7371 $post_query = 'key=' . $line['access_key'];
7373 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7375 // try doing it the old way
7377 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7378 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7382 $feeds = json_decode($feeds, true);
7385 if ($feeds['error']) {
7386 $status = $feeds['error']['code'] +
10;
7390 if (count($feeds['feeds']) > 0) {
7392 db_query($link, "DELETE FROM ttrss_linked_feeds
7393 WHERE instance_id = '$id'");
7395 foreach ($feeds['feeds'] as $feed) {
7396 $feed_url = db_escape_string($feed['feed_url']);
7397 $title = db_escape_string($feed['title']);
7398 $subscribers = db_escape_string($feed['subscribers']);
7399 $site_url = db_escape_string($feed['site_url']);
7401 db_query($link, "INSERT INTO ttrss_linked_feeds
7402 (feed_url, site_url, title, subscribers, instance_id, created, updated)
7404 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
7407 // received 0 feeds, this might indicate that
7408 // the instance on the other hand is rebuilding feedbrowser cache
7409 // we will try again later
7411 // TODO: maybe perform expiration based on updated here?
7414 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7424 _debug("Status: $status");
7426 db_query($link, "UPDATE ttrss_linked_instances SET
7427 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
7432 function handle_public_request($link, $op) {
7436 $login = db_escape_string($_REQUEST["login"]);
7437 $fresh = $_REQUEST["fresh"] == "1";
7439 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$login'");
7441 if (db_num_rows($result) == 1) {
7442 $uid = db_fetch_result($result, 0, "id");
7444 print getGlobalUnread($link, $uid);
7448 print getFeedArticles($link, -3, false, true, $uid);
7452 print "-1;User not found";
7458 $login = db_escape_string($_REQUEST["login"]);
7459 $password = db_escape_string($_REQUEST["password"]);
7461 if (authenticate_user($link, $login, $password)) {
7462 $result = db_query($link, "SELECT * FROM ttrss_settings_profiles
7463 WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY title");
7465 print "<select style='width: 100%' name='profile'>";
7467 print "<option value='0'>" . __("Default profile") . "</option>";
7469 while ($line = db_fetch_assoc($result)) {
7471 $title = $line["title"];
7473 print "<option value='$id'>$title</option>";
7478 $_SESSION = array();
7480 break; // getprofiles
7483 $mode = db_escape_string($_REQUEST['hub_mode']);
7484 $feed_id = (int) db_escape_string($_REQUEST['id']);
7485 $feed_url = db_escape_string($_REQUEST['hub_topic']);
7487 if (!PUBSUBHUBBUB_ENABLED
) {
7488 header('HTTP/1.0 404 Not Found');
7489 echo "404 Not found";
7493 // TODO: implement hub_verifytoken checking
7495 $result = db_query($link, "SELECT feed_url FROM ttrss_feeds
7496 WHERE id = '$feed_id'");
7498 if (db_num_rows($result) != 0) {
7500 $check_feed_url = db_fetch_result($result, 0, "feed_url");
7502 if ($check_feed_url && ($check_feed_url == $feed_url ||
!$feed_url)) {
7503 if ($mode == "subscribe") {
7505 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 2
7506 WHERE id = '$feed_id'");
7508 print $_REQUEST['hub_challenge'];
7511 } else if ($mode == "unsubscribe") {
7513 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 0
7514 WHERE id = '$feed_id'");
7516 print $_REQUEST['hub_challenge'];
7519 } else if (!$mode) {
7521 // Received update ping, schedule feed update.
7522 //update_rss_feed($link, $feed_id, true, true);
7524 db_query($link, "UPDATE ttrss_feeds SET
7525 last_update_started = '1970-01-01',
7526 last_updated = '1970-01-01' WHERE id = '$feed_id'");
7530 header('HTTP/1.0 404 Not Found');
7531 echo "404 Not found";
7534 header('HTTP/1.0 404 Not Found');
7535 echo "404 Not found";
7542 header("Location: tt-rss.php");
7547 $access_key = db_escape_string($_POST["key"]);
7549 // TODO: rate limit checking using last_connected
7550 $result = db_query($link, "SELECT id FROM ttrss_linked_instances
7551 WHERE access_key = '$access_key'");
7553 if (db_num_rows($result) == 1) {
7555 $instance_id = db_fetch_result($result, 0, "id");
7557 $result = db_query($link, "SELECT feed_url, site_url, title, subscribers
7558 FROM ttrss_feedbrowser_cache ORDER BY subscribers DESC LIMIT 100");
7562 while ($line = db_fetch_assoc($result)) {
7563 array_push($feeds, $line);
7566 db_query($link, "UPDATE ttrss_linked_instances SET
7567 last_status_in = 1 WHERE id = '$instance_id'");
7569 print json_encode(array("feeds" => $feeds));
7571 print json_encode(array("error" => array("code" => 6)));
7576 $uuid = db_escape_string($_REQUEST["key"]);
7578 $result = db_query($link, "SELECT ref_id, owner_uid FROM ttrss_user_entries WHERE
7581 if (db_num_rows($result) != 0) {
7582 header("Content-Type: text/html");
7584 $id = db_fetch_result($result, 0, "ref_id");
7585 $owner_uid = db_fetch_result($result, 0, "owner_uid");
7587 $_SESSION["uid"] = $owner_uid;
7588 $article = format_article($link, $id, false, true);
7589 $_SESSION["uid"] = "";
7591 print_r($article['content']);
7594 print "Article not found.";
7600 $feed = db_escape_string($_REQUEST["id"]);
7601 $key = db_escape_string($_REQUEST["key"]);
7602 $is_cat = $_REQUEST["is_cat"] != false;
7603 $limit = (int)db_escape_string($_REQUEST["limit"]);
7605 $search = db_escape_string($_REQUEST["q"]);
7606 $match_on = db_escape_string($_REQUEST["m"]);
7607 $search_mode = db_escape_string($_REQUEST["smode"]);
7608 $view_mode = db_escape_string($_REQUEST["view-mode"]);
7610 if (SINGLE_USER_MODE
) {
7611 authenticate_user($link, "admin", null);
7617 $result = db_query($link, "SELECT owner_uid FROM
7618 ttrss_access_keys WHERE access_key = '$key' AND feed_id = '$feed'");
7620 if (db_num_rows($result) == 1)
7621 $owner_id = db_fetch_result($result, 0, "owner_uid");
7625 $_SESSION['uid'] = $owner_id;
7627 generate_syndicated_feed($link, 0, $feed, $is_cat, $limit,
7628 $search, $search_mode, $match_on, $view_mode);
7630 header('HTTP/1.1 403 Forbidden');
7635 case "globalUpdateFeeds":
7636 // Update all feeds needing a update.
7637 update_daemon_common($link, 0, true, true);
7638 break; // globalUpdateFeeds
7642 header("Content-Type: text/plain");
7643 print json_encode(array("error" => array("code" => 7)));