3 date_default_timezone_set('UTC');
4 if (defined('E_DEPRECATED')) {
5 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
7 error_reporting(E_ALL
& ~E_NOTICE
);
10 require_once 'config.php';
12 if (DB_TYPE
== "pgsql") {
13 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
18 define('THEME_VERSION_REQUIRED', 1.1);
21 * Return available translations names.
24 * @return array A array of available translations.
26 function get_translations() {
28 "auto" => "Detect automatically",
33 "fr_FR" => "Français",
34 "hu_HU" => "Magyar (Hungarian)",
35 "it_IT" => "Italiano",
36 "ja_JP" => "日本語 (Japanese)",
37 "nb_NO" => "Norwegian bokmål",
39 "pt_BR" => "Portuguese/Brazil",
40 "zh_CN" => "Simplified Chinese");
45 require_once "lib/accept-to-gettext.php";
46 require_once "lib/gettext/gettext.inc";
48 function startup_gettext() {
50 # Get locale from Accept-Language header
51 $lang = al2gt(array_keys(get_translations()), "text/html");
53 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
54 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
57 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
58 $lang = $_COOKIE["ttrss_lang"];
61 /* In login action of mobile version */
62 if ($_POST["language"] && defined('MOBILE_VERSION')) {
63 $lang = $_POST["language"];
64 $_COOKIE["ttrss_lang"] = $lang;
68 if (defined('LC_MESSAGES')) {
69 _setlocale(LC_MESSAGES
, $lang);
70 } else if (defined('LC_ALL')) {
71 _setlocale(LC_ALL
, $lang);
74 if (defined('MOBILE_VERSION')) {
75 _bindtextdomain("messages", "../locale");
77 _bindtextdomain("messages", "locale");
80 _textdomain("messages");
81 _bind_textdomain_codeset("messages", "UTF-8");
87 if (defined('MEMCACHE_SERVER')) {
88 $memcache = new Memcache
;
89 $memcache->connect(MEMCACHE_SERVER
, 11211);
92 require_once 'db-prefs.php';
93 require_once 'errors.php';
94 require_once 'version.php';
96 require_once 'lib/phpmailer/class.phpmailer.php';
97 require_once 'lib/sphinxapi.php';
98 require_once 'lib/tmhoauth/tmhOAuth.php';
100 //define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
101 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
104 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
106 ini_set('user_agent', SELF_USER_AGENT
);
108 require_once "lib/simplepie/simplepie.inc";
109 require_once "lib/magpierss/rss_fetch.inc";
110 require_once 'lib/magpierss/rss_utils.inc';
111 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
112 require_once 'lib/pubsubhubbub/publisher.php';
113 require_once 'lib/pubsubhubbub/subscriber.php';
115 $config = HTMLPurifier_Config
::createDefault();
117 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
119 $config->set('HTML.SafeObject', true);
120 @$config->set('HTML', 'Allowed', $allowed);
121 $config->set('Output.FlashCompat', true);
122 $config->set('Attr.EnableID', true);
123 if (!defined('MOBILE_VERSION')) {
124 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
126 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
129 $purifier = new HTMLPurifier($config);
132 $utc_tz = new DateTimeZone('UTC');
133 $schema_version = false;
136 * Print a timestamped debug message.
138 * @param string $msg The debug message.
141 function _debug($msg) {
142 $ts = strftime("%H:%M:%S", time());
143 if (function_exists('posix_getpid')) {
144 $ts = "$ts/" . posix_getpid();
146 print "[$ts] $msg\n";
150 * Purge a feed old posts.
152 * @param mixed $link A database connection.
153 * @param mixed $feed_id The id of the purged feed.
154 * @param mixed $purge_interval Olderness of purged posts.
155 * @param boolean $debug Set to True to enable the debug. False by default.
159 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
161 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
165 $result = db_query($link,
166 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
170 if (db_num_rows($result) == 1) {
171 $owner_uid = db_fetch_result($result, 0, "owner_uid");
174 if ($purge_interval == -1 ||
!$purge_interval) {
176 ccache_update($link, $feed_id, $owner_uid);
181 if (!$owner_uid) return;
183 if (FORCE_ARTICLE_PURGE
== 0) {
184 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
187 $purge_unread = true;
188 $purge_interval = FORCE_ARTICLE_PURGE
;
191 if (!$purge_unread) $query_limit = " unread = false AND ";
193 if (DB_TYPE
== "pgsql") {
194 $pg_version = get_pgsql_version($link);
196 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
198 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
199 ttrss_entries.id = ref_id AND
201 feed_id = '$feed_id' AND
203 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
207 $result = db_query($link, "DELETE FROM ttrss_user_entries
209 WHERE ttrss_entries.id = ref_id AND
211 feed_id = '$feed_id' AND
213 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
216 $rows = pg_affected_rows($result);
220 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
221 marked = false AND feed_id = '$feed_id' AND
222 (SELECT date_updated FROM ttrss_entries WHERE
223 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
225 $result = db_query($link, "DELETE FROM ttrss_user_entries
226 USING ttrss_user_entries, ttrss_entries
227 WHERE ttrss_entries.id = ref_id AND
229 feed_id = '$feed_id' AND
231 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
233 $rows = mysql_affected_rows($link);
237 ccache_update($link, $feed_id, $owner_uid);
240 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
242 } // function purge_feed
245 * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
247 * @param mixed $link A database connection
248 * @param boolean $do_output Set to true to enable printed output, false by default.
249 * @param integer $limit The maximal number of removed posts.
253 /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
255 $random_qpart = sql_random_function();
258 $limit_qpart = "LIMIT $limit";
263 $result = db_query($link,
264 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
265 ORDER BY $random_qpart $limit_qpart");
267 while ($line = db_fetch_assoc($result)) {
269 $feed_id = $line["id"];
270 $purge_interval = $line["purge_interval"];
271 $owner_uid = $line["owner_uid"];
273 if ($purge_interval == 0) {
275 $tmp_result = db_query($link,
276 "SELECT value FROM ttrss_user_prefs WHERE
277 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
279 if (db_num_rows($tmp_result) != 0) {
280 $purge_interval = db_fetch_result($tmp_result, 0, "value");
285 // print "Feed $feed_id: purge interval = $purge_interval\n";
288 if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
289 purge_feed($link, $feed_id, $purge_interval, $do_output);
293 purge_orphans($link, $do_output);
295 } // function global_purge_old_posts */
297 function feed_purge_interval($link, $feed_id) {
299 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
300 WHERE id = '$feed_id'");
302 if (db_num_rows($result) == 1) {
303 $purge_interval = db_fetch_result($result, 0, "purge_interval");
304 $owner_uid = db_fetch_result($result, 0, "owner_uid");
306 if ($purge_interval == 0) $purge_interval = get_pref($link,
307 'PURGE_OLD_DAYS', $owner_uid);
309 return $purge_interval;
316 function purge_old_posts($link) {
318 $user_id = $_SESSION["uid"];
320 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
321 WHERE owner_uid = '$user_id'");
323 while ($line = db_fetch_assoc($result)) {
325 $feed_id = $line["id"];
326 $purge_interval = $line["purge_interval"];
328 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
330 if ($purge_interval > 0) {
331 purge_feed($link, $feed_id, $purge_interval);
335 purge_orphans($link);
338 function purge_orphans($link, $do_output = false) {
340 // purge orphaned posts in main content table
341 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
342 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
345 $rows = db_affected_rows($link, $result);
346 _debug("Purged $rows orphaned posts.");
350 function get_feed_update_interval($link, $feed_id) {
351 $result = db_query($link, "SELECT owner_uid, update_interval FROM
352 ttrss_feeds WHERE id = '$feed_id'");
354 if (db_num_rows($result) == 1) {
355 $update_interval = db_fetch_result($result, 0, "update_interval");
356 $owner_uid = db_fetch_result($result, 0, "owner_uid");
358 if ($update_interval != 0) {
359 return $update_interval;
361 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
369 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
370 $login = urlencode($login);
371 $pass = urlencode($pass);
373 if (function_exists('curl_init') && !ini_get("open_basedir")) {
374 $ch = curl_init($url);
376 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
377 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
378 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
379 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
380 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
381 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
382 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
383 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
384 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
387 curl_setopt($ch, CURLOPT_POST
, true);
388 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
392 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
394 $contents = @curl_exec
($ch);
395 if ($contents === false) {
400 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
401 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
404 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
410 if ($login && $pass ){
411 $url_parts = array();
413 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
415 if ($url_parts[1] && $url_parts[2]) {
416 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
420 return @file_get_contents
($url);
426 * Try to determine the favicon URL for a feed.
427 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
428 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
430 * @param string $url A feed or page URL
432 * @return mixed The favicon URL, or false if none was found.
434 function get_favicon_url($url) {
436 $favicon_url = false;
438 if ($html = @fetch_file_contents
($url)) {
440 libxml_use_internal_errors(true);
442 $doc = new DOMDocument();
443 $doc->loadHTML($html);
444 $xpath = new DOMXPath($doc);
446 $base = $xpath->query('/html/head/base');
447 foreach ($base as $b) {
448 $url = $b->getAttribute("href");
452 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
453 if (count($entries) > 0) {
454 foreach ($entries as $entry) {
455 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
462 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
465 } // function get_favicon_url
467 function check_feed_favicon($site_url, $feed, $link) {
468 $favicon_url = get_favicon_url($site_url);
470 # print "FAVICON [$site_url]: $favicon_url\n";
472 $icon_file = ICONS_DIR
. "/$feed.ico";
474 if ($favicon_url && !file_exists($icon_file)) {
475 $contents = fetch_file_contents($favicon_url, "image");
477 $fp = fopen($icon_file, "w");
480 fwrite($fp, $contents);
482 chmod($icon_file, 0644);
488 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
492 /* Update all feeds with the same URL to utilize memcache */
495 $result = db_query($link, "SELECT f1.id
496 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
497 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
499 while ($line = db_fetch_assoc($result)) {
500 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
503 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
507 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
508 $override_url = false) {
512 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') ||
$_REQUEST['xdebug'];
514 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
518 if ($debug_enabled) {
519 _debug("update_rss_feed: start");
522 if (!$ignore_daemon) {
524 if (DB_TYPE
== "pgsql") {
525 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
527 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
530 $result = db_query($link, "SELECT id,update_interval,auth_login,
531 auth_pass,cache_images,update_method
532 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
536 $result = db_query($link, "SELECT id,update_interval,auth_login,
537 feed_url,auth_pass,cache_images,update_method,last_updated,
538 mark_unread_on_update, owner_uid, update_on_checksum_change,
540 FROM ttrss_feeds WHERE id = '$feed'");
544 if (db_num_rows($result) == 0) {
545 if ($debug_enabled) {
546 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
551 $update_method = db_fetch_result($result, 0, "update_method");
552 $last_updated = db_fetch_result($result, 0, "last_updated");
553 $owner_uid = db_fetch_result($result, 0, "owner_uid");
554 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
555 0, "mark_unread_on_update"));
556 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
557 0, "update_on_checksum_change"));
558 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
560 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
561 WHERE id = '$feed'");
563 $auth_login = db_fetch_result($result, 0, "auth_login");
564 $auth_pass = db_fetch_result($result, 0, "auth_pass");
566 if ($update_method == 0)
567 $update_method = DEFAULT_UPDATE_METHOD +
1;
573 if ($update_method == 2)
574 $use_simplepie = true;
576 $use_simplepie = false;
578 if ($debug_enabled) {
579 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
582 if ($update_method == 1) {
583 $auth_login = urlencode($auth_login);
584 $auth_pass = urlencode($auth_pass);
587 $update_interval = db_fetch_result($result, 0, "update_interval");
588 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
589 $fetch_url = db_fetch_result($result, 0, "feed_url");
591 if ($update_interval < 0) { return false; }
593 $feed = db_escape_string($feed);
595 if ($auth_login && $auth_pass ){
596 $url_parts = array();
597 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
599 if ($url_parts[1] && $url_parts[2]) {
600 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
606 $fetch_url = $override_url;
608 if ($debug_enabled) {
609 _debug("update_rss_feed: fetching [$fetch_url]...");
612 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
614 if ($memcache && $obj = $memcache->get($obj_id)) {
616 if ($debug_enabled) {
617 _debug("update_rss_feed: data found in memcache.");
624 if ($update_method == 3) {
625 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
626 } else if ($update_method == 1) {
628 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
629 define('MAGPIE_CACHE_ON', !$no_cache);
630 define('MAGPIE_FETCH_TIME_OUT', 60);
631 define('MAGPIE_CACHE_DIR', CACHE_DIR
. "/magpie");
633 $rss = @fetch_rss
($fetch_url);
635 $simplepie_cache_dir = CACHE_DIR
. "/simplepie";
637 if (!is_dir($simplepie_cache_dir)) {
638 mkdir($simplepie_cache_dir);
641 $rss = new SimplePie();
642 $rss->set_useragent(SELF_USER_AGENT
);
643 # $rss->set_timeout(10);
644 $rss->set_feed_url($fetch_url);
645 $rss->set_output_encoding('UTF-8');
647 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
649 if ($debug_enabled) {
650 _debug("enabling image cache");
653 $rss->set_image_handler("image.php", 'i');
656 if ($debug_enabled) {
657 _debug("feed update interval (sec): " .
658 get_feed_update_interval($link, $feed)*60);
661 $rss->enable_cache(!$no_cache);
664 $rss->set_cache_location($simplepie_cache_dir);
665 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
671 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
676 if ($debug_enabled) {
677 _debug("update_rss_feed: fetch done, parsing...");
680 $feed = db_escape_string($feed);
682 if ($update_method == 2) {
683 $fetch_ok = !$rss->error();
690 if ($debug_enabled) {
691 _debug("update_rss_feed: processing feed data...");
694 // db_query($link, "BEGIN");
696 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
697 FROM ttrss_feeds WHERE id = '$feed'");
699 $registered_title = db_fetch_result($result, 0, "title");
700 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
701 $orig_site_url = db_fetch_result($result, 0, "site_url");
703 $owner_uid = db_fetch_result($result, 0, "owner_uid");
705 if ($use_simplepie) {
706 $site_url = $rss->get_link();
708 $site_url = $rss->channel
["link"];
711 $site_url = rewrite_relative_url($fetch_url, $site_url);
713 if ($debug_enabled) {
714 _debug("update_rss_feed: checking favicon...");
717 check_feed_favicon($site_url, $feed, $link);
719 if (!$registered_title ||
$registered_title == "[Unknown]") {
721 if ($use_simplepie) {
722 $feed_title = db_escape_string($rss->get_title());
724 $feed_title = db_escape_string($rss->channel
["title"]);
727 if ($debug_enabled) {
728 _debug("update_rss_feed: registering title: $feed_title");
731 db_query($link, "UPDATE ttrss_feeds SET
732 title = '$feed_title' WHERE id = '$feed'");
735 // weird, weird Magpie
736 if (!$use_simplepie) {
737 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
740 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
741 db_query($link, "UPDATE ttrss_feeds SET
742 site_url = '$site_url' WHERE id = '$feed'");
745 // print "I: " . $rss->channel["image"]["url"];
747 if (!$use_simplepie) {
748 $icon_url = db_escape_string($rss->image
["url"]);
750 $icon_url = db_escape_string($rss->get_image_url());
753 $icon_url = substr($icon_url, 0, 250);
755 if ($icon_url && $orig_icon_url != $icon_url) {
756 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
759 if ($debug_enabled) {
760 _debug("update_rss_feed: loading filters...");
763 $filters = load_filters($link, $feed, $owner_uid);
765 // if ($debug_enabled) {
766 // print_r($filters);
769 if ($use_simplepie) {
770 $iterator = $rss->get_items();
772 $iterator = $rss->items
;
773 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
774 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
777 if (!is_array($iterator)) {
778 /* db_query($link, "UPDATE ttrss_feeds
779 SET last_error = 'Parse error: can\'t find any articles.'
780 WHERE id = '$feed'"); */
782 // clear any errors and mark feed as updated if fetched okay
783 // even if it's blank
785 if ($debug_enabled) {
786 _debug("update_rss_feed: entry iterator is not an array, no articles?");
789 db_query($link, "UPDATE ttrss_feeds
790 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
792 return; // no articles
795 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED
) {
797 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
799 $feed_hub_url = false;
800 if ($use_simplepie) {
801 $links = $rss->get_links('hub');
803 if ($links && is_array($links)) {
804 foreach ($links as $l) {
811 $atom = $rss->channel
['atom'];
814 if ($atom['link@rel'] == 'hub') {
815 $feed_hub_url = $atom['link@href'];
818 if (!$feed_hub_url && $atom['link#'] > 1) {
819 for ($i = 2; $i <= $atom['link#']; $i++
) {
820 if ($atom["link#$i@rel"] == 'hub') {
821 $feed_hub_url = $atom["link#$i@href"];
827 $feed_hub_url = $rss->channel
['link_hub'];
831 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
833 if ($feed_hub_url && function_exists('curl_init') &&
834 !ini_get("open_basedir")) {
836 $callback_url = get_self_url_prefix() .
837 "/backend.php?op=pubsub&id=$feed";
839 $s = new Subscriber($feed_hub_url, $callback_url);
841 $rc = $s->subscribe($fetch_url);
844 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
846 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
847 WHERE id = '$feed'");
851 if ($debug_enabled) {
852 _debug("update_rss_feed: processing articles...");
855 foreach ($iterator as $item) {
857 if ($_REQUEST['xdebug'] == 2) {
861 if ($use_simplepie) {
862 $entry_guid = $item->get_id();
863 if (!$entry_guid) $entry_guid = $item->get_link();
864 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
868 $entry_guid = $item["id"];
870 if (!$entry_guid) $entry_guid = $item["guid"];
871 if (!$entry_guid) $entry_guid = $item["about"];
872 if (!$entry_guid) $entry_guid = $item["link"];
873 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
876 if ($debug_enabled) {
877 _debug("update_rss_feed: guid $entry_guid");
880 if (!$entry_guid) continue;
882 $entry_timestamp = "";
884 if ($use_simplepie) {
885 $entry_timestamp = strtotime($item->get_date());
887 $rss_2_date = $item['pubdate'];
888 $rss_1_date = $item['dc']['date'];
889 $atom_date = $item['issued'];
890 if (!$atom_date) $atom_date = $item['updated'];
892 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
893 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
894 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
898 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
899 $entry_timestamp = time();
900 $no_orig_date = 'true';
902 $no_orig_date = 'false';
905 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
907 if ($debug_enabled) {
908 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
911 if ($use_simplepie) {
912 $entry_title = $item->get_title();
914 $entry_title = trim(strip_tags($item["title"]));
917 if ($use_simplepie) {
918 $entry_link = $item->get_link();
920 // strange Magpie workaround
921 $entry_link = $item["link_"];
922 if (!$entry_link) $entry_link = $item["link"];
925 $entry_link = rewrite_relative_url($site_url, $entry_link);
927 if ($debug_enabled) {
928 _debug("update_rss_feed: title $entry_title");
929 _debug("update_rss_feed: link $entry_link");
932 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
934 $entry_link = strip_tags($entry_link);
936 if ($use_simplepie) {
937 $entry_content = $item->get_content();
938 if (!$entry_content) $entry_content = $item->get_description();
940 $entry_content = $item["content:escaped"];
942 if (!$entry_content) $entry_content = $item["content:encoded"];
943 if (!$entry_content) $entry_content = $item["content"]["encoded"];
944 if (!$entry_content) $entry_content = $item["content"];
946 // Magpie bugs are getting ridiculous
947 if (trim($entry_content) == "Array") $entry_content = false;
949 if (!$entry_content) $entry_content = $item["atom_content"];
950 if (!$entry_content) $entry_content = $item["summary"];
952 if (!$entry_content ||
953 strlen($entry_content) < strlen($item["description"])) {
954 $entry_content = $item["description"];
958 if (is_array($entry_content)) {
959 $entry_content = $entry_content["encoded"];
960 if (!$entry_content) $entry_content = $entry_content["escaped"];
964 if ($_REQUEST["xdebug"] == 2) {
965 print "update_rss_feed: content: ";
966 print_r(htmlspecialchars($entry_content));
969 $entry_content_unescaped = $entry_content;
971 if ($use_simplepie) {
972 $entry_comments = strip_tags($item->data
["comments"]);
973 if ($item->get_author()) {
974 $entry_author_item = $item->get_author();
975 $entry_author = $entry_author_item->get_name();
976 if (!$entry_author) $entry_author = $entry_author_item->get_email();
978 $entry_author = db_escape_string($entry_author);
981 $entry_comments = strip_tags($item["comments"]);
983 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
985 if ($item['author']) {
987 if (is_array($item['author'])) {
989 if (!$entry_author) {
990 $entry_author = db_escape_string(strip_tags($item['author']['name']));
993 if (!$entry_author) {
994 $entry_author = db_escape_string(strip_tags($item['author']['email']));
998 if (!$entry_author) {
999 $entry_author = db_escape_string(strip_tags($item['author']));
1004 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
1006 $entry_guid = db_escape_string(strip_tags($entry_guid));
1007 $entry_guid = mb_substr($entry_guid, 0, 250);
1009 $result = db_query($link, "SELECT id FROM ttrss_entries
1010 WHERE guid = '$entry_guid'");
1012 $entry_content = db_escape_string($entry_content, false);
1014 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
1016 $entry_title = db_escape_string($entry_title);
1017 $entry_link = db_escape_string($entry_link);
1018 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
1019 $entry_author = mb_substr($entry_author, 0, 250);
1021 if ($use_simplepie) {
1022 $num_comments = 0; #FIXME#
1024 $num_comments = db_escape_string($item["slash"]["comments"]);
1027 if (!$num_comments) $num_comments = 0;
1029 if ($debug_enabled) {
1030 _debug("update_rss_feed: looking for tags [1]...");
1033 // parse <category> entries into tags
1035 $additional_tags = array();
1037 if ($use_simplepie) {
1039 $additional_tags_src = $item->get_categories();
1041 if (is_array($additional_tags_src)) {
1042 foreach ($additional_tags_src as $tobj) {
1043 array_push($additional_tags, $tobj->get_term());
1047 if ($debug_enabled) {
1048 _debug("update_rss_feed: category tags:");
1049 print_r($additional_tags);
1054 $t_ctr = $item['category#'];
1057 $additional_tags = array();
1058 } else if ($t_ctr > 0) {
1059 $additional_tags = array($item['category']);
1061 if ($item['category@term']) {
1062 array_push($additional_tags, $item['category@term']);
1065 for ($i = 0; $i <= $t_ctr; $i++
) {
1066 if ($item["category#$i"]) {
1067 array_push($additional_tags, $item["category#$i"]);
1070 if ($item["category#$i@term"]) {
1071 array_push($additional_tags, $item["category#$i@term"]);
1076 // parse <dc:subject> elements
1078 $t_ctr = $item['dc']['subject#'];
1081 array_push($additional_tags, $item['dc']['subject']);
1083 for ($i = 0; $i <= $t_ctr; $i++
) {
1084 if ($item['dc']["subject#$i"]) {
1085 array_push($additional_tags, $item['dc']["subject#$i"]);
1091 if ($debug_enabled) {
1092 _debug("update_rss_feed: looking for tags [2]...");
1096 // <a href="..." rel="tag">Xorg</a>, //
1100 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1101 $entry_content_unescaped, $entry_tags);
1103 $entry_tags = $entry_tags[1];
1105 $entry_tags = array_merge($entry_tags, $additional_tags);
1106 $entry_tags = array_unique($entry_tags);
1108 for ($i = 0; $i < count($entry_tags); $i++
)
1109 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
1111 if ($debug_enabled) {
1112 _debug("update_rss_feed: unfiltered tags found:");
1113 print_r($entry_tags);
1118 $entry_content = sanitize_article_content($entry_content);
1119 $entry_title = sanitize_article_content($entry_title);
1121 if ($debug_enabled) {
1122 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1125 db_query($link, "BEGIN");
1127 if (db_num_rows($result) == 0) {
1129 if ($debug_enabled) {
1130 _debug("update_rss_feed: base guid not found");
1133 // base post entry does not exist, create it
1135 $result = db_query($link,
1136 "INSERT INTO ttrss_entries
1153 '$entry_timestamp_fmt',
1163 // we keep encountering the entry in feeds, so we need to
1164 // update date_updated column so that we don't get horrible
1165 // dupes when the entry gets purged and reinserted again e.g.
1166 // in the case of SLOW SLOW OMG SLOW updating feeds
1168 $base_entry_id = db_fetch_result($result, 0, "id");
1170 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1171 WHERE id = '$base_entry_id'");
1174 // now it should exist, if not - bad luck then
1176 $result = db_query($link, "SELECT
1177 id,content_hash,no_orig_date,title,
1178 ".SUBSTRING_FOR_DATE
."(date_updated,1,19) as date_updated,
1179 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated,
1183 WHERE guid = '$entry_guid'");
1188 if (db_num_rows($result) == 1) {
1190 if ($debug_enabled) {
1191 _debug("update_rss_feed: base guid found, checking for user record");
1194 // this will be used below in update handler
1195 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1196 $orig_title = db_fetch_result($result, 0, "title");
1197 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1198 $orig_date_updated = strtotime(db_fetch_result($result,
1199 0, "date_updated"));
1201 $ref_id = db_fetch_result($result, 0, "id");
1202 $entry_ref_id = $ref_id;
1204 // check for user post link to main table
1206 // do we allow duplicate posts with same GUID in different feeds?
1207 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1208 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1210 $dupcheck_qpart = "";
1213 /* Collect article tags here so we could filter by them: */
1215 $article_filters = get_article_filters($filters, $entry_title,
1216 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1219 if ($debug_enabled) {
1220 _debug("update_rss_feed: article filters: ");
1221 if (count($article_filters) != 0) {
1222 print_r($article_filters);
1226 if (find_article_filter($article_filters, "filter")) {
1227 db_query($link, "COMMIT"); // close transaction in progress
1231 $score = calculate_article_score($article_filters);
1233 if ($debug_enabled) {
1234 _debug("update_rss_feed: initial score: $score");
1237 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1238 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1241 // if ($_REQUEST["xdebug"]) print "$query\n";
1243 $result = db_query($link, $query);
1245 // okay it doesn't exist - create user entry
1246 if (db_num_rows($result) == 0) {
1248 if ($debug_enabled) {
1249 _debug("update_rss_feed: user record not found, creating...");
1252 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1254 $last_read_qpart = 'NULL';
1257 $last_read_qpart = 'NOW()';
1260 if (find_article_filter($article_filters, 'mark') ||
$score > 1000) {
1266 if (find_article_filter($article_filters, 'publish')) {
1267 $published = 'true';
1269 $published = 'false';
1272 $result = db_query($link,
1273 "INSERT INTO ttrss_user_entries
1274 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1275 published, score, tag_cache, label_cache)
1276 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1277 $last_read_qpart, $marked, $published, '$score', '', '')");
1279 if (PUBSUBHUBBUB_HUB
&& $published == 'true') {
1280 $rss_link = get_self_url_prefix() .
1281 "/backend.php?op=rss&id=-2&key=" .
1282 get_feed_access_key($link, -2, false, $owner_uid);
1284 $p = new Publisher(PUBSUBHUBBUB_HUB
);
1286 $pubsub_result = $p->publish_update($rss_link);
1289 $result = db_query($link,
1290 "SELECT int_id FROM ttrss_user_entries WHERE
1291 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1292 feed_id = '$feed' LIMIT 1");
1294 if (db_num_rows($result) == 1) {
1295 $entry_int_id = db_fetch_result($result, 0, "int_id");
1298 if ($debug_enabled) {
1299 _debug("update_rss_feed: user record FOUND");
1302 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1303 $entry_int_id = db_fetch_result($result, 0, "int_id");
1306 if ($debug_enabled) {
1307 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1310 $post_needs_update = false;
1311 $update_insignificant = false;
1313 if ($orig_num_comments != $num_comments) {
1314 $post_needs_update = true;
1315 $update_insignificant = true;
1318 if ($content_hash != $orig_content_hash) {
1319 $post_needs_update = true;
1320 $update_insignificant = false;
1323 if (db_escape_string($orig_title) != $entry_title) {
1324 $post_needs_update = true;
1325 $update_insignificant = false;
1328 // if post needs update, update it and mark all user entries
1329 // linking to this post as updated
1330 if ($post_needs_update) {
1332 if (defined('DAEMON_EXTENDED_DEBUG')) {
1333 _debug("update_rss_feed: post $entry_guid needs update...");
1336 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1338 db_query($link, "UPDATE ttrss_entries
1339 SET title = '$entry_title', content = '$entry_content',
1340 content_hash = '$content_hash',
1341 updated = '$entry_timestamp_fmt',
1342 num_comments = '$num_comments'
1343 WHERE id = '$ref_id'");
1345 if (!$update_insignificant) {
1346 if ($mark_unread_on_update) {
1347 db_query($link, "UPDATE ttrss_user_entries
1348 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1349 } else if ($update_on_checksum_change) {
1350 db_query($link, "UPDATE ttrss_user_entries
1351 SET last_read = null WHERE ref_id = '$ref_id'
1352 AND unread = false");
1358 db_query($link, "COMMIT");
1360 if ($debug_enabled) {
1361 _debug("update_rss_feed: assigning labels...");
1364 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1367 if ($debug_enabled) {
1368 _debug("update_rss_feed: looking for enclosures...");
1373 $enclosures = array();
1375 if ($use_simplepie) {
1376 $encs = $item->get_enclosures();
1378 if (is_array($encs)) {
1379 foreach ($encs as $e) {
1381 $e->link
, $e->type
, $e->length
);
1383 array_push($enclosures, $e_item);
1390 $e_ctr = $item['enclosure#'];
1393 $e_item = array($item['enclosure@url'],
1394 $item['enclosure@type'],
1395 $item['enclosure@length']);
1397 array_push($enclosures, $e_item);
1399 for ($i = 0; $i <= $e_ctr; $i++
) {
1401 if ($item["enclosure#$i@url"]) {
1402 $e_item = array($item["enclosure#$i@url"],
1403 $item["enclosure#$i@type"],
1404 $item["enclosure#$i@length"]);
1405 array_push($enclosures, $e_item);
1411 // can there be many of those? yes -fox
1413 $m_ctr = $item['media']['content#'];
1416 $e_item = array($item['media']['content@url'],
1417 $item['media']['content@medium'],
1418 $item['media']['content@length']);
1420 array_push($enclosures, $e_item);
1422 for ($i = 0; $i <= $m_ctr; $i++
) {
1424 if ($item["media"]["content#$i@url"]) {
1425 $e_item = array($item["media"]["content#$i@url"],
1426 $item["media"]["content#$i@medium"],
1427 $item["media"]["content#$i@length"]);
1428 array_push($enclosures, $e_item);
1436 if ($debug_enabled) {
1437 _debug("update_rss_feed: article enclosures:");
1438 print_r($enclosures);
1441 db_query($link, "BEGIN");
1443 foreach ($enclosures as $enc) {
1444 $enc_url = db_escape_string($enc[0]);
1445 $enc_type = db_escape_string($enc[1]);
1446 $enc_dur = db_escape_string($enc[2]);
1448 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1449 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1451 if (db_num_rows($result) == 0) {
1452 db_query($link, "INSERT INTO ttrss_enclosures
1453 (content_url, content_type, title, duration, post_id) VALUES
1454 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1458 db_query($link, "COMMIT");
1460 // check for manual tags (we have to do it here since they're loaded from filters)
1462 foreach ($article_filters as $f) {
1463 if ($f[0] == "tag") {
1465 $manual_tags = trim_array(explode(",", $f[1]));
1467 foreach ($manual_tags as $tag) {
1468 if (tag_is_valid($tag)) {
1469 array_push($entry_tags, $tag);
1477 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1478 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1480 $filtered_tags = array();
1481 $tags_to_cache = array();
1483 if ($entry_tags && is_array($entry_tags)) {
1484 foreach ($entry_tags as $tag) {
1485 if (array_search($tag, $boring_tags) === false) {
1486 array_push($filtered_tags, $tag);
1491 $filtered_tags = array_unique($filtered_tags);
1493 if ($debug_enabled) {
1494 _debug("update_rss_feed: filtered article tags:");
1495 print_r($filtered_tags);
1498 // Save article tags in the database
1500 if (count($filtered_tags) > 0) {
1502 db_query($link, "BEGIN");
1504 foreach ($filtered_tags as $tag) {
1506 $tag = sanitize_tag($tag);
1507 $tag = db_escape_string($tag);
1509 if (!tag_is_valid($tag)) continue;
1511 $result = db_query($link, "SELECT id FROM ttrss_tags
1512 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1513 owner_uid = '$owner_uid' LIMIT 1");
1515 if ($result && db_num_rows($result) == 0) {
1517 db_query($link, "INSERT INTO ttrss_tags
1518 (owner_uid,tag_name,post_int_id)
1519 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1522 array_push($tags_to_cache, $tag);
1525 /* update the cache */
1527 $tags_to_cache = array_unique($tags_to_cache);
1529 $tags_str = db_escape_string(join(",", $tags_to_cache));
1531 db_query($link, "UPDATE ttrss_user_entries
1532 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1533 AND owner_uid = $owner_uid");
1535 db_query($link, "COMMIT");
1538 if ($debug_enabled) {
1539 _debug("update_rss_feed: article processed");
1543 if (!$last_updated) {
1544 if ($debug_enabled) {
1545 _debug("update_rss_feed: new feed, catching it up...");
1547 catchup_feed($link, $feed, false, $owner_uid);
1550 if ($debug_enabled) {
1551 _debug("purging feed...");
1554 purge_feed($link, $feed, 0, $debug_enabled);
1556 db_query($link, "UPDATE ttrss_feeds
1557 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1559 // db_query($link, "COMMIT");
1563 if ($use_simplepie) {
1564 $error_msg = mb_substr($rss->error(), 0, 250);
1566 $error_msg = mb_substr(magpie_error(), 0, 250);
1569 if ($debug_enabled) {
1570 _debug("update_rss_feed: error fetching feed: $error_msg");
1573 $error_msg = db_escape_string($error_msg);
1576 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1577 last_updated = NOW() WHERE id = '$feed'");
1580 if ($use_simplepie) {
1584 if ($debug_enabled) {
1585 _debug("update_rss_feed: done");
1590 function print_select($id, $default, $values, $attributes = "") {
1591 print "<select name=\"$id\" id=\"$id\" $attributes>";
1592 foreach ($values as $v) {
1594 $sel = "selected=\"1\"";
1598 print "<option value=\"$v\" $sel>$v</option>";
1603 function print_select_hash($id, $default, $values, $attributes = "") {
1604 print "<select name=\"$id\" id='$id' $attributes>";
1605 foreach (array_keys($values) as $v) {
1607 $sel = 'selected="selected"';
1611 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1617 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1620 if ($filters["title"]) {
1621 foreach ($filters["title"] as $filter) {
1622 $reg_exp = $filter["reg_exp"];
1623 $inverse = $filter["inverse"];
1624 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
1625 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
1627 array_push($matches, array($filter["action"], $filter["action_param"]));
1632 if ($filters["content"]) {
1633 foreach ($filters["content"] as $filter) {
1634 $reg_exp = $filter["reg_exp"];
1635 $inverse = $filter["inverse"];
1637 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
1638 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
1640 array_push($matches, array($filter["action"], $filter["action_param"]));
1645 if ($filters["both"]) {
1646 foreach ($filters["both"] as $filter) {
1647 $reg_exp = $filter["reg_exp"];
1648 $inverse = $filter["inverse"];
1651 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1652 array_push($matches, array($filter["action"], $filter["action_param"]));
1655 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1656 array_push($matches, array($filter["action"], $filter["action_param"]));
1662 if ($filters["link"]) {
1663 $reg_exp = $filter["reg_exp"];
1664 foreach ($filters["link"] as $filter) {
1665 $reg_exp = $filter["reg_exp"];
1666 $inverse = $filter["inverse"];
1668 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
1669 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
1671 array_push($matches, array($filter["action"], $filter["action_param"]));
1676 if ($filters["date"]) {
1677 $reg_exp = $filter["reg_exp"];
1678 foreach ($filters["date"] as $filter) {
1679 $date_modifier = $filter["filter_param"];
1680 $inverse = $filter["inverse"];
1681 $check_timestamp = strtotime($filter["reg_exp"]);
1683 # no-op when timestamp doesn't parse to prevent misfires
1685 if ($check_timestamp) {
1688 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1689 $date_modifier == "after" && $timestamp > $check_timestamp) {
1693 if ($inverse) $match_ok = !$match_ok;
1696 array_push($matches, array($filter["action"], $filter["action_param"]));
1702 if ($filters["author"]) {
1703 foreach ($filters["author"] as $filter) {
1704 $reg_exp = $filter["reg_exp"];
1705 $inverse = $filter["inverse"];
1706 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
1707 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
1709 array_push($matches, array($filter["action"], $filter["action_param"]));
1714 if ($filters["tag"]) {
1716 $tag_string = join(",", $tags);
1718 foreach ($filters["tag"] as $filter) {
1719 $reg_exp = $filter["reg_exp"];
1720 $inverse = $filter["inverse"];
1722 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
1723 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
1725 array_push($matches, array($filter["action"], $filter["action_param"]));
1734 function find_article_filter($filters, $filter_name) {
1735 foreach ($filters as $f) {
1736 if ($f[0] == $filter_name) {
1743 function calculate_article_score($filters) {
1746 foreach ($filters as $f) {
1747 if ($f[0] == "score") {
1754 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1755 foreach ($filters as $f) {
1756 if ($f[0] == "label") {
1757 label_add_article($link, $id, $f[1], $owner_uid);
1762 function getmicrotime() {
1763 list($usec, $sec) = explode(" ",microtime());
1764 return ((float)$usec +
(float)$sec);
1767 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1768 foreach ($values as $v) {
1775 if ($v == $true_is) {
1776 $sel .= " value=\"1\"";
1778 $sel .= " value=\"0\"";
1781 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
1782 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1787 function initialize_user_prefs($link, $uid, $profile = false) {
1789 $uid = db_escape_string($uid);
1793 $profile_qpart = "AND profile IS NULL";
1795 $profile_qpart = "AND profile = '$profile'";
1798 if (get_schema_version($link) < 63) $profile_qpart = "";
1800 db_query($link, "BEGIN");
1802 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1804 $u_result = db_query($link, "SELECT pref_name
1805 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1807 $active_prefs = array();
1809 while ($line = db_fetch_assoc($u_result)) {
1810 array_push($active_prefs, $line["pref_name"]);
1813 while ($line = db_fetch_assoc($result)) {
1814 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1815 // print "adding " . $line["pref_name"] . "<br>";
1817 if (get_schema_version($link) < 63) {
1818 db_query($link, "INSERT INTO ttrss_user_prefs
1819 (owner_uid,pref_name,value) VALUES
1820 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1823 db_query($link, "INSERT INTO ttrss_user_prefs
1824 (owner_uid,pref_name,value, profile) VALUES
1825 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1831 db_query($link, "COMMIT");
1835 function lookup_user_id($link, $user) {
1837 $result = db_query($link, "SELECT id FROM ttrss_users WHERE login = '$user'");
1839 if (db_num_rows($result) == 1) {
1840 return db_fetch_result($result, 0, "id");
1846 /* function http_authenticate_user($link) {
1847 if (!$_SERVER["PHP_AUTH_USER"]) {
1849 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1850 header('HTTP/1.0 401 Unauthorized');
1854 $auth_result = authenticate_user($link,
1855 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1857 if (!$auth_result) {
1858 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1859 header('HTTP/1.0 401 Unauthorized');
1867 function get_ssl_certificate_id() {
1868 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1869 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1870 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1871 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1872 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1877 function get_login_by_ssl_certificate($link) {
1879 $cert_serial = db_escape_string(get_ssl_certificate_id());
1882 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1883 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1884 owner_uid = ttrss_users.id");
1886 if (db_num_rows($result) != 0) {
1887 return db_escape_string(db_fetch_result($result, 0, "login"));
1894 function get_remote_user($link) {
1896 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
1897 return db_escape_string($_SERVER["REMOTE_USER"]);
1900 return db_escape_string(get_login_by_ssl_certificate($link));
1903 function get_remote_fakepass($link) {
1904 if (get_remote_user($link))
1910 function authenticate_user($link, $login, $password, $force_auth = false) {
1912 if (!SINGLE_USER_MODE
) {
1914 $pwd_hash1 = encrypt_password($password);
1915 $pwd_hash2 = encrypt_password($password, $login);
1916 $login = db_escape_string($login);
1918 $remote_user = get_remote_user($link);
1920 if ($remote_user && $remote_user == $login && $login != "admin") {
1922 $login = $remote_user;
1924 $query = "SELECT id,login,access_level,pwd_hash
1925 FROM ttrss_users WHERE
1928 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1929 && $_SERVER["REMOTE_USER"]) {
1930 $result = db_query($link, $query);
1933 if (db_num_rows($result) == 0) {
1934 $query2 = "INSERT INTO ttrss_users
1935 (login,access_level,last_login,created)
1936 VALUES ('$login', 0, null, NOW())";
1937 db_query($link, $query2);
1942 $query = "SELECT id,login,access_level,pwd_hash
1943 FROM ttrss_users WHERE
1944 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1945 pwd_hash = '$pwd_hash2')";
1948 $result = db_query($link, $query);
1950 if (db_num_rows($result) == 1) {
1951 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1952 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1953 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1955 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1959 // LemonLDAP can send user informations via HTTP HEADER
1960 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
1962 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1964 $fullname = db_escape_string($fullname);
1965 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1969 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1971 $email = db_escape_string($email);
1972 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1977 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1978 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1980 $_SESSION["last_version_check"] = time();
1982 initialize_user_prefs($link, $_SESSION["uid"]);
1991 $_SESSION["uid"] = 1;
1992 $_SESSION["name"] = "admin";
1994 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1996 initialize_user_prefs($link, $_SESSION["uid"]);
2002 function make_password($length = 8) {
2005 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
2009 while ($i < $length) {
2010 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
2012 if (!strstr($password, $char)) {
2020 // this is called after user is created to initialize default feeds, labels
2023 // user preferences are checked on every login, not here
2025 function initialize_user($link, $uid) {
2027 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2028 values ('$uid', 'Tiny Tiny RSS: New Releases',
2029 'http://tt-rss.org/releases.rss')");
2031 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2032 values ('$uid', 'Tiny Tiny RSS: Forum',
2033 'http://tt-rss.org/forum/rss.php')");
2036 function logout_user() {
2038 if (isset($_COOKIE[session_name()])) {
2039 setcookie(session_name(), '', time()-42000, '/');
2043 function get_script_urlpath() {
2044 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
2047 function validate_session($link) {
2048 if (SINGLE_USER_MODE
) return true;
2050 $check_ip = $_SESSION['ip_address'];
2052 switch (SESSION_CHECK_ADDRESS
) {
2057 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2060 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
2061 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
2065 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
2066 $_SESSION["login_error_msg"] =
2067 __("Session failed to validate (incorrect IP)");
2071 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
2074 if ($_SESSION["uid"]) {
2076 $result = db_query($link,
2077 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
2079 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
2081 if ($pwd_hash != $_SESSION["pwd_hash"]) {
2086 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
2088 //print_r($_SESSION);
2090 if (time() > $_SESSION["cookie_lifetime"]) {
2098 function login_sequence($link, $mobile = false) {
2099 if (!SINGLE_USER_MODE
) {
2101 $login_action = $_POST["login_action"];
2103 # try to authenticate user if called from login form
2104 if ($login_action == "do_login") {
2105 $login = $_POST["login"];
2106 $password = $_POST["password"];
2107 $remember_me = $_POST["remember_me"];
2109 if (authenticate_user($link, $login, $password)) {
2110 $_POST["password"] = "";
2112 $_SESSION["language"] = $_POST["language"];
2113 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2114 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
2116 if ($_POST["profile"]) {
2118 $profile = db_escape_string($_POST["profile"]);
2120 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2121 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2123 if (db_num_rows($result) != 0) {
2124 $_SESSION["profile"] = $profile;
2125 $_SESSION["prefs_cache"] = array();
2129 if ($_REQUEST['return']) {
2130 header("Location: " . $_REQUEST['return']);
2132 header("Location: " . $_SERVER["REQUEST_URI"]);
2139 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2143 if (!$_SESSION["uid"] ||
!validate_session($link)) {
2145 if (get_remote_user($link) && AUTO_LOGIN
) {
2146 authenticate_user($link, get_remote_user($link), null);
2147 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2149 render_login_form($link, $mobile);
2150 //header("Location: login.php");
2154 /* bump login timestamp */
2155 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2158 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
2159 setcookie("ttrss_lang", $_SESSION["language"],
2160 time() + SESSION_COOKIE_LIFETIME
);
2163 // try to remove possible duplicates from feed counter cache
2164 // ccache_cleanup($link, $_SESSION["uid"]);
2168 return authenticate_user($link, "admin", null);
2172 function truncate_string($str, $max_len, $suffix = '…') {
2173 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2174 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2180 function theme_image($link, $filename) {
2182 $theme_path = get_user_theme_path($link);
2184 if ($theme_path && is_file($theme_path.$filename)) {
2185 return $theme_path.$filename;
2194 function get_user_theme($link) {
2196 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2197 $theme_name = get_pref($link, "_THEME_ID");
2198 if (is_dir("themes/$theme_name")) {
2209 function get_user_theme_path($link) {
2212 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2213 $theme_name = get_pref($link, "_THEME_ID");
2215 if ($theme_name && is_dir("themes/$theme_name")) {
2216 $theme_path = "themes/$theme_name/";
2225 if (is_file("$theme_path/theme.ini")) {
2226 $ini = parse_ini_file("$theme_path/theme.ini", true);
2227 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
2235 function get_user_theme_options($link) {
2236 $t = get_user_theme_path($link);
2239 if (is_file("$t/theme.ini")) {
2240 $ini = parse_ini_file("$t/theme.ini", true);
2241 if ($ini['theme']['version']) {
2242 return $ini['theme']['options'];
2249 function print_theme_includes($link) {
2251 $t = get_user_theme_path($link);
2255 print "<link rel=\"stylesheet\" type=\"text/css\"
2256 href=\"$t/theme.css?$time \">";
2257 if (file_exists("$t/theme.js")) {
2258 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2264 function get_all_themes() {
2265 $themes = glob("themes/*");
2271 foreach ($themes as $t) {
2272 if (is_file("$t/theme.ini")) {
2273 $ini = parse_ini_file("$t/theme.ini", true);
2274 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
2275 !$ini['theme']['disabled']) {
2277 $entry["path"] = $t;
2278 $entry["base"] = basename($t);
2279 $entry["name"] = $ini['theme']['name'];
2280 $entry["version"] = $ini['theme']['version'];
2281 $entry["author"] = $ini['theme']['author'];
2282 $entry["options"] = $ini['theme']['options'];
2283 array_push($rv, $entry);
2291 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2294 $source_tz = new DateTimeZone($source_tz);
2295 } catch (Exception
$e) {
2296 $source_tz = new DateTimeZone('UTC');
2300 $dest_tz = new DateTimeZone($dest_tz);
2301 } catch (Exception
$e) {
2302 $dest_tz = new DateTimeZone('UTC');
2305 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2306 return $dt->format('U') +
$dest_tz->getOffset($dt);
2309 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2310 $no_smart_dt = false) {
2312 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2313 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2318 # We store date in UTC internally
2319 $dt = new DateTime($timestamp, $utc_tz);
2321 if ($tz_offset == -1) {
2323 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2326 $user_tz = new DateTimeZone($user_tz_string);
2327 } catch (Exception
$e) {
2331 $tz_offset = $user_tz->getOffset($dt);
2334 $user_timestamp = $dt->format('U') +
$tz_offset;
2336 if (!$no_smart_dt) {
2337 return smart_date_time($link, $user_timestamp,
2338 $tz_offset, $owner_uid);
2341 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2343 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2345 return date($format, $user_timestamp);
2349 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2350 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2352 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
2353 return date("G:i", $timestamp);
2354 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
2355 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2356 return date($format, $timestamp);
2358 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2359 return date($format, $timestamp);
2363 function smart_date($timestamp) {
2364 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2366 } else if (date("Y", $timestamp) == date("Y")) {
2367 return date("D m", $timestamp);
2369 return date("Y/m/d", $timestamp);
2373 function sql_bool_to_string($s) {
2374 if ($s == "t" ||
$s == "1") {
2381 function sql_bool_to_bool($s) {
2382 if ($s == "t" ||
$s == "1" ||
$s == "true") {
2389 function bool_to_sql_bool($s) {
2397 function toggleEvenOdd($a) {
2404 // Session caching removed due to causing wrong redirects to upgrade
2405 // script when get_schema_version() is called on an obsolete session
2406 // created on a previous schema version.
2407 function get_schema_version($link, $nocache = false) {
2408 global $schema_version;
2410 if (!$schema_version) {
2411 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2412 $version = db_fetch_result($result, 0, "schema_version");
2413 $schema_version = $version;
2416 return $schema_version;
2420 function sanity_check($link) {
2425 $schema_version = get_schema_version($link, true);
2427 if ($schema_version != SCHEMA_VERSION
) {
2431 if (DB_TYPE
== "mysql") {
2432 $result = db_query($link, "SELECT true", false);
2433 if (db_num_rows($result) != 1) {
2438 if (db_escape_string("testTEST") != "testTEST") {
2442 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2445 function file_is_locked($filename) {
2446 if (function_exists('flock')) {
2447 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
2449 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2450 flock($fp, LOCK_UN
);
2460 return true; // consider the file always locked and skip the test
2463 function make_lockfile($filename) {
2464 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2466 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2467 if (function_exists('posix_getpid')) {
2468 fwrite($fp, posix_getpid() . "\n");
2476 function make_stampfile($filename) {
2477 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
2479 if (flock($fp, LOCK_EX | LOCK_NB
)) {
2480 fwrite($fp, time() . "\n");
2481 flock($fp, LOCK_UN
);
2489 function sql_random_function() {
2490 if (DB_TYPE
== "mysql") {
2497 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2499 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2501 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2503 if (is_numeric($feed)) {
2509 $cat_qpart = "cat_id = '$feed'";
2511 $cat_qpart = "cat_id IS NULL";
2514 $tmp_result = db_query($link, "SELECT id
2515 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2517 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2519 $tmp_feed = $tmp_line["id"];
2521 db_query($link, "UPDATE ttrss_user_entries
2522 SET unread = false,last_read = NOW()
2523 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2525 } else if ($feed == -2) {
2527 db_query($link, "UPDATE ttrss_user_entries
2528 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2529 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2530 AND unread = true AND owner_uid = $owner_uid");
2533 } else if ($feed > 0) {
2535 db_query($link, "UPDATE ttrss_user_entries
2536 SET unread = false,last_read = NOW()
2537 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2539 } else if ($feed < 0 && $feed > -10) { // special, like starred
2542 db_query($link, "UPDATE ttrss_user_entries
2543 SET unread = false,last_read = NOW()
2544 WHERE marked = true AND owner_uid = $owner_uid");
2548 db_query($link, "UPDATE ttrss_user_entries
2549 SET unread = false,last_read = NOW()
2550 WHERE published = true AND owner_uid = $owner_uid");
2555 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2557 if (DB_TYPE
== "pgsql") {
2558 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2560 $match_part = "updated > DATE_SUB(NOW(),
2561 INTERVAL $intl HOUR) ";
2564 $result = db_query($link, "SELECT id FROM ttrss_entries,
2565 ttrss_user_entries WHERE $match_part AND
2567 ttrss_user_entries.ref_id = ttrss_entries.id AND
2568 owner_uid = $owner_uid");
2570 $affected_ids = array();
2572 while ($line = db_fetch_assoc($result)) {
2573 array_push($affected_ids, $line["id"]);
2576 catchupArticlesById($link, $affected_ids, 0);
2580 db_query($link, "UPDATE ttrss_user_entries
2581 SET unread = false,last_read = NOW()
2582 WHERE owner_uid = $owner_uid");
2585 } else if ($feed < -10) { // label
2587 $label_id = -$feed - 11;
2589 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2590 SET unread = false, last_read = NOW()
2591 WHERE label_id = '$label_id' AND unread = true
2592 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2596 ccache_update($link, $feed, $owner_uid, $cat_view);
2599 db_query($link, "BEGIN");
2601 $tag_name = db_escape_string($feed);
2603 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2604 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2606 while ($line = db_fetch_assoc($result)) {
2607 db_query($link, "UPDATE ttrss_user_entries SET
2608 unread = false, last_read = NOW()
2609 WHERE int_id = " . $line["post_int_id"]);
2611 db_query($link, "COMMIT");
2615 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2617 if (!$omode) $omode = "flc";
2619 $data = getGlobalCounters($link);
2621 $data = array_merge($data, getVirtCounters($link));
2623 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2624 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2625 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2626 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
2631 function getCategoryCounters($link) {
2634 /* Labels category */
2636 $cv = array("id" => -2, "kind" => "cat",
2637 "counter" => getCategoryUnread($link, -2));
2639 array_push($ret_arr, $cv);
2641 $age_qpart = getMaxAgeSubquery();
2643 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2644 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2645 WHERE ttrss_cat_counters_cache.feed_id = id AND
2646 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2648 while ($line = db_fetch_assoc($result)) {
2649 $line["cat_id"] = (int) $line["cat_id"];
2651 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2652 "counter" => $line["unread"]);
2654 array_push($ret_arr, $cv);
2657 /* Special case: NULL category doesn't actually exist in the DB */
2659 $cv = array("id" => 0, "kind" => "cat",
2660 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2662 array_push($ret_arr, $cv);
2667 function getCategoryUnread($link, $cat, $owner_uid = false) {
2669 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2674 $cat_query = "cat_id = '$cat'";
2676 $cat_query = "cat_id IS NULL";
2679 $age_qpart = getMaxAgeSubquery();
2681 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2682 AND owner_uid = " . $owner_uid);
2684 $cat_feeds = array();
2685 while ($line = db_fetch_assoc($result)) {
2686 array_push($cat_feeds, "feed_id = " . $line["id"]);
2689 if (count($cat_feeds) == 0) return 0;
2691 $match_part = implode(" OR ", $cat_feeds);
2693 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2694 FROM ttrss_user_entries,ttrss_entries
2695 WHERE unread = true AND ($match_part) AND id = ref_id
2696 AND $age_qpart AND owner_uid = " . $owner_uid);
2700 # this needs to be rewritten
2701 while ($line = db_fetch_assoc($result)) {
2702 $unread +
= $line["unread"];
2706 } else if ($cat == -1) {
2707 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
2708 } else if ($cat == -2) {
2710 $result = db_query($link, "
2711 SELECT COUNT(unread) AS unread FROM
2712 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2713 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2714 ttrss_labels2.owner_uid = '$owner_uid'
2715 AND unread = true AND feed_id = ttrss_feeds.id
2716 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2718 $unread = db_fetch_result($result, 0, "unread");
2725 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2726 if (DB_TYPE
== "pgsql") {
2727 return "ttrss_entries.date_updated >
2728 NOW() - INTERVAL '$days days'";
2730 return "ttrss_entries.date_updated >
2731 DATE_SUB(NOW(), INTERVAL $days DAY)";
2735 function getFeedUnread($link, $feed, $is_cat = false) {
2736 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2739 function getLabelUnread($link, $label_id, $owner_uid = false) {
2740 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2742 $result = db_query($link, "
2743 SELECT COUNT(unread) AS unread FROM
2744 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2745 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2746 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2747 AND unread = true AND feed_id = ttrss_feeds.id
2748 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2750 if (db_num_rows($result) != 0) {
2751 return db_fetch_result($result, 0, "unread");
2757 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2758 $owner_uid = false) {
2760 $n_feed = (int) $feed;
2762 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2765 $unread_qpart = "unread = true";
2767 $unread_qpart = "true";
2770 $age_qpart = getMaxAgeSubquery();
2773 return getCategoryUnread($link, $n_feed, $owner_uid);
2774 } if ($feed != "0" && $n_feed == 0) {
2776 $feed = db_escape_string($feed);
2778 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2779 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2780 AND ref_id = id AND $age_qpart
2781 AND $unread_qpart)) AS count FROM ttrss_tags
2782 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2783 return db_fetch_result($result, 0, "count");
2785 } else if ($n_feed == -1) {
2786 $match_part = "marked = true";
2787 } else if ($n_feed == -2) {
2788 $match_part = "published = true";
2789 } else if ($n_feed == -3) {
2790 $match_part = "unread = true AND score >= 0";
2792 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2794 if (DB_TYPE
== "pgsql") {
2795 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2797 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2799 } else if ($n_feed == -4) {
2800 $match_part = "true";
2801 } else if ($n_feed >= 0) {
2804 $match_part = "feed_id = '$n_feed'";
2806 $match_part = "feed_id IS NULL";
2809 } else if ($feed < -10) {
2811 $label_id = -$feed - 11;
2813 return getLabelUnread($link, $label_id, $owner_uid);
2820 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2821 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2823 $from_qpart = "ttrss_user_entries,ttrss_entries";
2827 $query = "SELECT count(int_id) AS unread
2828 FROM $from_qpart WHERE
2829 ttrss_user_entries.ref_id = ttrss_entries.id AND
2832 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2834 $result = db_query($link, $query);
2838 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2839 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2840 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2841 AND $unread_qpart AND $age_qpart AND
2842 ttrss_tags.owner_uid = " . $owner_uid);
2845 $unread = db_fetch_result($result, 0, "unread");
2850 function getGlobalUnread($link, $user_id = false) {
2853 $user_id = $_SESSION["uid"];
2856 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2857 WHERE owner_uid = '$user_id' AND feed_id > 0");
2859 $c_id = db_fetch_result($result, 0, "c_id");
2864 function getGlobalCounters($link, $global_unread = -1) {
2867 if ($global_unread == -1) {
2868 $global_unread = getGlobalUnread($link);
2871 $cv = array("id" => "global-unread",
2872 "counter" => $global_unread);
2874 array_push($ret_arr, $cv);
2876 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2877 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2879 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2881 $cv = array("id" => "subscribed-feeds",
2882 "counter" => $subscribed_feeds);
2884 array_push($ret_arr, $cv);
2889 function getSubscribedFeeds($link) {
2890 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2891 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2893 return db_fetch_result($result, 0, "fn");
2896 function getTagCounters($link) {
2900 $age_qpart = getMaxAgeSubquery();
2902 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2903 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2904 AND ref_id = id AND $age_qpart
2905 AND unread = true)) AS count FROM ttrss_tags
2906 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2907 ORDER BY count DESC LIMIT 55");
2911 while ($line = db_fetch_assoc($result)) {
2912 $tags[$line["tag_name"]] +
= $line["count"];
2915 foreach (array_keys($tags) as $tag) {
2916 $unread = $tags[$tag];
2917 $tag = htmlspecialchars($tag);
2919 $cv = array("id" => $tag,
2921 "counter" => $unread);
2923 array_push($ret_arr, $cv);
2929 function getVirtCounters($link) {
2933 for ($i = 0; $i >= -4; $i--) {
2935 $count = getFeedUnread($link, $i);
2937 $cv = array("id" => $i,
2938 "counter" => $count);
2940 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2941 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2943 array_push($ret_arr, $cv);
2949 function getLabelCounters($link, $descriptions = false) {
2953 $age_qpart = getMaxAgeSubquery();
2955 $owner_uid = $_SESSION["uid"];
2957 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2958 WHERE owner_uid = '$owner_uid'");
2960 while ($line = db_fetch_assoc($result)) {
2962 $id = -$line["id"] - 11;
2964 $label_name = $line["caption"];
2965 $count = getFeedUnread($link, $id);
2967 $cv = array("id" => $id,
2968 "counter" => $count);
2971 $cv["description"] = $label_name;
2973 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2974 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2976 array_push($ret_arr, $cv);
2982 function getFeedCounters($link, $active_feed = false) {
2986 $age_qpart = getMaxAgeSubquery();
2988 $query = "SELECT ttrss_feeds.id,
2990 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
2991 last_error, value AS count
2992 FROM ttrss_feeds, ttrss_counters_cache
2993 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2994 AND ttrss_counters_cache.feed_id = id";
2996 $result = db_query($link, $query);
2997 $fctrs_modified = false;
2999 while ($line = db_fetch_assoc($result)) {
3002 $count = $line["count"];
3003 $last_error = htmlspecialchars($line["last_error"]);
3005 $last_updated = make_local_datetime($link, $line['last_updated'], false);
3007 $has_img = feed_has_icon($id);
3009 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
3012 $cv = array("id" => $id,
3013 "updated" => $last_updated,
3014 "counter" => $count,
3015 "has_img" => (int) $has_img);
3018 $cv["error"] = $last_error;
3020 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
3021 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
3023 if ($active_feed && $id == $active_feed)
3024 $cv["title"] = truncate_string($line["title"], 30);
3026 array_push($ret_arr, $cv);
3033 function get_pgsql_version($link) {
3034 $result = db_query($link, "SELECT version() AS version");
3035 $version = explode(" ", db_fetch_result($result, 0, "version"));
3040 * Subscribes the user to the given feed
3042 * @param resource $link Database connection
3043 * @param string $url Feed URL to subscribe to
3044 * @param integer $cat_id Category ID the feed shall be added to
3045 * @param string $auth_login (optional) Feed username
3046 * @param string $auth_pass (optional) Feed password
3048 * @return integer Status code:
3049 * 0 - OK, Feed already exists
3050 * 1 - OK, Feed added
3052 * 3 - URL content is HTML, no feeds available
3053 * 4 - URL content is HTML which contains multiple feeds.
3054 * Here you should call extractfeedurls in rpc-backend
3055 * to get all possible feeds.
3056 * 5 - Couldn't download the URL content.
3058 function subscribe_to_feed($link, $url, $cat_id = 0,
3059 $auth_login = '', $auth_pass = '') {
3061 $url = fix_url($url);
3063 if (!$url ||
!validate_feed_url($url)) return 2;
3067 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
3068 WHERE id = ".$_SESSION['uid']);
3070 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
3072 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
3073 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
3075 if (url_is_html($url, $auth_login, $auth_pass)) {
3076 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
3077 if (count($feedUrls) == 0) {
3079 } else if (count($feedUrls) > 1) {
3082 //use feed url as new URL
3083 $url = key($feedUrls);
3087 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
3092 if ($cat_id == "0" ||
!$cat_id) {
3093 $cat_qpart = "NULL";
3095 $cat_qpart = "'$cat_id'";
3098 $result = db_query($link,
3099 "SELECT id FROM ttrss_feeds
3100 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
3102 if (db_num_rows($result) == 0) {
3103 $result = db_query($link,
3104 "INSERT INTO ttrss_feeds
3105 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
3106 VALUES ('".$_SESSION["uid"]."', '$url',
3107 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
3109 $result = db_query($link,
3110 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
3111 AND owner_uid = " . $_SESSION["uid"]);
3113 $feed_id = db_fetch_result($result, 0, "id");
3116 update_rss_feed($link, $feed_id, true);
3125 function print_feed_select($link, $id, $default_id = "",
3126 $attributes = "", $include_all_feeds = true) {
3128 print "<select id=\"$id\" name=\"$id\" $attributes>";
3129 if ($include_all_feeds) {
3130 print "<option value=\"0\">".__('All feeds')."</option>";
3133 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
3134 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3136 if (db_num_rows($result) > 0 && $include_all_feeds) {
3137 print "<option disabled>--------</option>";
3140 while ($line = db_fetch_assoc($result)) {
3141 if ($line["id"] == $default_id) {
3142 $is_selected = "selected=\"1\"";
3147 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3149 printf("<option $is_selected value='%d'>%s</option>",
3150 $line["id"], $title);
3156 function print_feed_cat_select($link, $id, $default_id = "",
3157 $attributes = "", $include_all_cats = true) {
3159 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3161 if ($include_all_cats) {
3162 print "<option value=\"0\">".__('Uncategorized')."</option>";
3165 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3166 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3168 if (db_num_rows($result) > 0 && $include_all_cats) {
3169 print "<option disabled=\"1\">--------</option>";
3172 while ($line = db_fetch_assoc($result)) {
3173 if ($line["id"] == $default_id) {
3174 $is_selected = "selected=\"1\"";
3180 printf("<option $is_selected value='%d'>%s</option>",
3181 $line["id"], htmlspecialchars($line["title"]));
3184 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3189 function checkbox_to_sql_bool($val) {
3190 return ($val == "on") ?
"true" : "false";
3193 function getFeedCatTitle($link, $id) {
3195 return __("Special");
3196 } else if ($id < -10) {
3197 return __("Labels");
3198 } else if ($id > 0) {
3199 $result = db_query($link, "SELECT ttrss_feed_categories.title
3200 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3201 cat_id = ttrss_feed_categories.id");
3202 if (db_num_rows($result) == 1) {
3203 return db_fetch_result($result, 0, "title");
3205 return __("Uncategorized");
3208 return "getFeedCatTitle($id) failed";
3213 function getFeedIcon($id) {
3216 return "images/archive.png";
3219 return "images/mark_set.png";
3222 return "images/pub_set.png";
3225 return "images/fresh.png";
3228 return "images/tag.png";
3232 return "images/label.png";
3234 if (file_exists(ICONS_DIR
. "/$id.ico"))
3235 return ICONS_URL
. "/$id.ico";
3241 function getFeedTitle($link, $id) {
3243 return __("Starred articles");
3244 } else if ($id == -2) {
3245 return __("Published articles");
3246 } else if ($id == -3) {
3247 return __("Fresh articles");
3248 } else if ($id == -4) {
3249 return __("All articles");
3250 } else if ($id === 0 ||
$id === "0") {
3251 return __("Archived articles");
3252 } else if ($id < -10) {
3253 $label_id = -$id - 11;
3254 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3255 if (db_num_rows($result) == 1) {
3256 return db_fetch_result($result, 0, "caption");
3258 return "Unknown label ($label_id)";
3261 } else if (is_numeric($id) && $id > 0) {
3262 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3263 if (db_num_rows($result) == 1) {
3264 return db_fetch_result($result, 0, "title");
3266 return "Unknown feed ($id)";
3273 function get_session_cookie_name() {
3274 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
3277 function make_init_params($link) {
3280 $params["theme"] = get_user_theme($link);
3281 $params["theme_options"] = get_user_theme_options($link);
3283 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3284 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3285 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3286 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3288 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3289 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3290 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3291 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3293 $params[strtolower($param)] = (int) get_pref($link, $param);
3296 $params["icons_url"] = ICONS_URL
;
3297 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
3298 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3299 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3300 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3301 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3303 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3304 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3306 $max_feed_id = db_fetch_result($result, 0, "mid");
3307 $num_feeds = db_fetch_result($result, 0, "nf");
3309 $params["max_feed_id"] = (int) $max_feed_id;
3310 $params["num_feeds"] = (int) $num_feeds;
3312 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3317 function print_runtime_info($link) {
3318 print "<runtime-info><![CDATA[";
3319 print json_encode(make_runtime_info($link));
3320 print "]]></runtime-info>";
3323 function make_runtime_info($link) {
3326 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3327 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3329 $max_feed_id = db_fetch_result($result, 0, "mid");
3330 $num_feeds = db_fetch_result($result, 0, "nf");
3332 $data["max_feed_id"] = (int) $max_feed_id;
3333 $data["num_feeds"] = (int) $num_feeds;
3335 $data['last_article_id'] = getLastArticleId($link);
3336 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3338 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
3340 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3342 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3344 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
3347 $stamp_delta = time() - $stamp;
3349 if ($stamp_delta > 1800) {
3353 $_SESSION["daemon_stamp_check"] = time();
3356 $data['daemon_stamp_ok'] = $stamp_check;
3358 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3360 $data['daemon_stamp'] = $stamp_fmt;
3365 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
3366 $new_version_details = @check_for_update
($link);
3368 $data['new_version_available'] = (int) ($new_version_details != false);
3370 $_SESSION["last_version_check"] = time();
3376 function search_to_sql($link, $search, $match_on) {
3378 $search_query_part = "";
3380 $keywords = explode(" ", $search);
3381 $query_keywords = array();
3383 foreach ($keywords as $k) {
3384 if (strpos($k, "-") === 0) {
3391 $commandpair = explode(":", mb_strtolower($k), 2);
3393 if ($commandpair[0] == "note" && $commandpair[1]) {
3395 if ($commandpair[1] == "true")
3396 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3398 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3400 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3402 if ($commandpair[1] == "true")
3403 array_push($query_keywords, "($not (marked = true))");
3405 array_push($query_keywords, "($not (marked = false))");
3407 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3409 if ($commandpair[1] == "true")
3410 array_push($query_keywords, "($not (published = true))");
3412 array_push($query_keywords, "($not (published = false))");
3414 } else if (strpos($k, "@") === 0) {
3416 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3417 $orig_ts = strtotime(substr($k, 1));
3418 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3420 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3422 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
3423 } else if ($match_on == "both") {
3424 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3425 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3426 } else if ($match_on == "title") {
3427 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3428 } else if ($match_on == "content") {
3429 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3433 $search_query_part = implode("AND", $query_keywords);
3435 return $search_query_part;
3439 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) {
3441 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3443 $ext_tables_part = "";
3447 if (SPHINX_ENABLED
) {
3448 $ids = join(",", @sphinx_search
($search, 0, 500));
3451 $search_query_part = "ref_id IN ($ids) AND ";
3453 $search_query_part = "ref_id = -1 AND ";
3456 $search_query_part = search_to_sql($link, $search, $match_on);
3457 $search_query_part .= " AND ";
3461 $search_query_part = "";
3465 $filter_query_part = filter_to_sql($filter);
3467 $filter_query_part = "";
3471 $since_id_part = "ttrss_entries.id > $since_id AND ";
3473 $since_id_part = "";
3476 $view_query_part = "";
3478 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
3480 $view_query_part = " ";
3481 } else if ($feed != -1) {
3482 $unread = getFeedUnread($link, $feed, $cat_view);
3484 $view_query_part = " unread = true AND ";
3489 if ($view_mode == "marked") {
3490 $view_query_part = " marked = true AND ";
3493 if ($view_mode == "published") {
3494 $view_query_part = " published = true AND ";
3497 if ($view_mode == "unread") {
3498 $view_query_part = " unread = true AND ";
3501 if ($view_mode == "updated") {
3502 $view_query_part = " (last_read is null and unread = false) AND ";
3506 $limit_query_part = "LIMIT " . $limit;
3509 $vfeed_query_part = "";
3511 // override query strategy and enable feed display when searching globally
3512 if ($search && $search_mode == "all_feeds") {
3513 $query_strategy_part = "ttrss_entries.id > 0";
3514 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3516 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3517 $query_strategy_part = "ttrss_entries.id > 0";
3518 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3519 id = feed_id) as feed_title,";
3520 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3522 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3524 $tmp_result = false;
3527 $tmp_result = db_query($link, "SELECT id
3528 FROM ttrss_feeds WHERE cat_id = '$feed'");
3530 $tmp_result = db_query($link, "SELECT id
3531 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3532 WHERE id = '$feed') AND id != '$feed'");
3535 $cat_siblings = array();
3537 if (db_num_rows($tmp_result) > 0) {
3538 while ($p = db_fetch_assoc($tmp_result)) {
3539 array_push($cat_siblings, "feed_id = " . $p["id"]);
3542 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3543 $feed, implode(" OR ", $cat_siblings));
3546 $query_strategy_part = "ttrss_entries.id > 0";
3549 } else if ($feed > 0) {
3554 $query_strategy_part = "cat_id = '$feed'";
3556 $query_strategy_part = "cat_id IS NULL";
3559 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3562 $query_strategy_part = "feed_id = '$feed'";
3564 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3565 $query_strategy_part = "feed_id IS NULL";
3566 } else if ($feed == 0 && $cat_view) { // uncategorized
3567 $query_strategy_part = "cat_id IS NULL";
3568 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3569 } else if ($feed == -1) { // starred virtual feed
3570 $query_strategy_part = "marked = true";
3571 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3572 } else if ($feed == -2) { // published virtual feed OR labels category
3575 $query_strategy_part = "published = true";
3576 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3578 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3580 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3582 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3583 ttrss_user_labels2.article_id = ref_id";
3587 } else if ($feed == -3) { // fresh virtual feed
3588 $query_strategy_part = "unread = true AND score >= 0";
3590 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3592 if (DB_TYPE
== "pgsql") {
3593 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3595 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3598 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3599 } else if ($feed == -4) { // all articles virtual feed
3600 $query_strategy_part = "true";
3601 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3602 } else if ($feed <= -10) { // labels
3603 $label_id = -$feed - 11;
3605 $query_strategy_part = "label_id = '$label_id' AND
3606 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3607 ttrss_user_labels2.article_id = ref_id";
3609 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3610 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3613 $query_strategy_part = "id > 0"; // dumb
3616 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3617 $date_sort_field = "updated";
3619 $date_sort_field = "date_entered";
3622 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3623 $order_by = "$date_sort_field";
3625 $order_by = "$date_sort_field DESC";
3628 if ($view_mode != "noscores") {
3629 $order_by = "score DESC, $order_by";
3632 if ($override_order) {
3633 $order_by = $override_order;
3639 $feed_title = "Search results";
3642 $feed_title = getCategoryTitle($link, $feed);
3644 if (is_numeric($feed) && $feed > 0) {
3645 $result = db_query($link, "SELECT title,site_url,last_error
3646 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3648 $feed_title = db_fetch_result($result, 0, "title");
3649 $feed_site_url = db_fetch_result($result, 0, "site_url");
3650 $last_error = db_fetch_result($result, 0, "last_error");
3652 $feed_title = getFeedTitle($link, $feed);
3657 $content_query_part = "content as content_preview,";
3659 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3662 $feed_kind = "Feeds";
3664 $feed_kind = "Labels";
3667 if ($limit_query_part) {
3668 $offset_query_part = "OFFSET $offset";
3671 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3672 if (!$override_order) {
3673 $order_by = "ttrss_feeds.title, $order_by";
3678 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3679 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3682 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3683 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3686 $query = "SELECT DISTINCT
3689 ttrss_entries.id,ttrss_entries.title,
3692 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3693 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
3696 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
3702 ttrss_user_entries.ref_id = ttrss_entries.id AND
3703 ttrss_user_entries.owner_uid = '$owner_uid' AND
3708 $query_strategy_part ORDER BY $order_by
3709 $limit_query_part $offset_query_part";
3711 if ($_REQUEST["debug"]) print $query;
3713 $result = db_query($link, $query);
3718 $select_qpart = "SELECT DISTINCT " .
3722 "ttrss_entries.id as id," .
3731 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
3734 $content_query_part .
3735 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
3738 $feed_kind = "Tags";
3739 $all_tags = explode(",", $feed);
3740 if ($search_mode == 'any') {
3741 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3742 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3743 $where_qpart = " WHERE " .
3744 "ref_id = ttrss_entries.id AND " .
3745 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3746 "post_int_id = int_id AND $tag_sql AND " .
3748 $search_query_part .
3749 $query_strategy_part . " ORDER BY $order_by " .
3754 $sub_selects = array();
3755 $sub_ands = array();
3756 foreach ($all_tags as $term) {
3757 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");
3764 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3769 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3770 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3771 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3772 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3774 // error_log("TAG SQL: " . $tag_sql);
3775 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3777 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3778 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
3781 return array($result, $feed_title, $feed_site_url, $last_error);
3785 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3786 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3788 require_once "lib/MiniTemplator.class.php";
3790 $note_style = "background-color : #fff7d5;
3791 border-width : 1px; ".
3792 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3793 "margin-bottom : 1em; color : #9a8c59;";
3795 if (!$limit) $limit = 30;
3797 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3798 $date_sort_field = "updated";
3800 $date_sort_field = "date_entered";
3803 $qfh_ret = queryFeedHeadlines($link, $feed,
3804 $limit, $view_mode, $is_cat, $search, $search_mode,
3805 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3807 $result = $qfh_ret[0];
3808 $feed_title = htmlspecialchars($qfh_ret[1]);
3809 $feed_site_url = $qfh_ret[2];
3810 $last_error = $qfh_ret[3];
3812 $feed_self_url = get_self_url_prefix() .
3813 "/backend.php?op=rss&id=-2&key=" .
3814 get_feed_access_key($link, -2, false);
3816 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3818 $tpl = new MiniTemplator
;
3820 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3822 $tpl->setVariable('FEED_TITLE', $feed_title);
3823 $tpl->setVariable('VERSION', VERSION
);
3824 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3826 if (PUBSUBHUBBUB_HUB
&& $feed == -2) {
3827 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB
));
3828 $tpl->addBlock('feed_hub');
3831 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3833 while ($line = db_fetch_assoc($result)) {
3834 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3835 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3836 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3837 $tpl->setVariable('ARTICLE_EXCERPT',
3838 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3840 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3842 if ($line['note']) {
3843 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
3847 $tpl->setVariable('ARTICLE_CONTENT', $content);
3849 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3850 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3852 $tags = get_article_tags($link, $line["id"], $owner_uid);
3854 foreach ($tags as $tag) {
3855 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3856 $tpl->addBlock('category');
3859 $enclosures = get_article_enclosures($link, $line["id"]);
3861 foreach ($enclosures as $e) {
3862 $type = htmlspecialchars($e['content_type']);
3863 $url = htmlspecialchars($e['content_url']);
3864 $length = $e['duration'];
3866 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3867 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3868 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3870 $tpl->addBlock('enclosure');
3873 $tpl->addBlock('entry');
3878 $tpl->addBlock('feed');
3879 $tpl->generateOutputToString($tmp);
3884 function getCategoryTitle($link, $cat_id) {
3886 if ($cat_id == -1) {
3887 return __("Special");
3888 } else if ($cat_id == -2) {
3889 return __("Labels");
3892 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3895 if (db_num_rows($result) == 1) {
3896 return db_fetch_result($result, 0, "title");
3898 return "Uncategorized";
3903 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3906 if (!$owner) $owner = $_SESSION["uid"];
3908 $res = trim($str); if (!$res) return '';
3910 // if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3911 $res = $purifier->purify($res);
3914 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3915 $res = preg_replace('/<img[^>]+>/is', '', $res);
3918 if (strpos($res, "href=") === false)
3919 $res = rewrite_urls($res);
3921 $charset_hack = '<head>
3922 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3925 $res = trim($res); if (!$res) return '';
3927 libxml_use_internal_errors(true);
3929 $doc = new DOMDocument();
3930 $doc->loadHTML($charset_hack . $res);
3931 $xpath = new DOMXPath($doc);
3933 $entries = $xpath->query('(//a[@href]|//img[@src])');
3936 foreach ($entries as $entry) {
3940 if ($entry->hasAttribute('href'))
3941 $entry->setAttribute('href',
3942 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3944 if ($entry->hasAttribute('src'))
3945 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3946 $entry->setAttribute('src',
3947 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3950 if (strtolower($entry->nodeName
) == "a") {
3951 $entry->setAttribute("target", "_blank");
3954 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
3955 $br = $doc->createElement("br");
3957 if ($entry->parentNode
->nextSibling
) {
3958 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
3965 $node = $doc->getElementsByTagName('body')->item(0);
3967 return $doc->saveXML($node);
3971 * Send by mail a digest of last articles.
3973 * @param mixed $link The database connection.
3974 * @param integer $limit The maximum number of articles by digest.
3975 * @return boolean Return false if digests are not enabled.
3977 function send_headlines_digests($link, $limit = 100) {
3979 if (!DIGEST_ENABLE
) return false;
3981 $user_limit = DIGEST_EMAIL_LIMIT
;
3984 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3986 if (DB_TYPE
== "pgsql") {
3987 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3988 } else if (DB_TYPE
== "mysql") {
3989 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3992 $result = db_query($link, "SELECT id,email FROM ttrss_users
3993 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3995 while ($line = db_fetch_assoc($result)) {
3997 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3998 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
4000 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
4002 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
4003 $digest = $tuple[0];
4004 $headlines_count = $tuple[1];
4005 $affected_ids = $tuple[2];
4006 $digest_text = $tuple[3];
4008 if ($headlines_count > 0) {
4010 $mail = new PHPMailer();
4012 $mail->PluginDir
= "lib/phpmailer/";
4013 $mail->SetLanguage("en", "lib/phpmailer/language/");
4015 $mail->CharSet
= "UTF-8";
4017 $mail->From
= DIGEST_FROM_ADDRESS
;
4018 $mail->FromName
= DIGEST_FROM_NAME
;
4019 $mail->AddAddress($line["email"], $line["login"]);
4021 if (DIGEST_SMTP_HOST
) {
4022 $mail->Host
= DIGEST_SMTP_HOST
;
4023 $mail->Mailer
= "smtp";
4024 $mail->SMTPAuth
= DIGEST_SMTP_LOGIN
!= '';
4025 $mail->Username
= DIGEST_SMTP_LOGIN
;
4026 $mail->Password
= DIGEST_SMTP_PASSWORD
;
4029 $mail->IsHTML(true);
4030 $mail->Subject
= DIGEST_SUBJECT
;
4031 $mail->Body
= $digest;
4032 $mail->AltBody
= $digest_text;
4034 $rc = $mail->Send();
4036 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
4040 if ($rc && $do_catchup) {
4041 print "Marking affected articles as read...\n";
4042 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
4045 print "No headlines\n";
4048 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
4049 WHERE id = " . $line["id"]);
4053 print "All done.\n";
4057 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
4059 require_once "lib/MiniTemplator.class.php";
4061 $tpl = new MiniTemplator
;
4062 $tpl_t = new MiniTemplator
;
4064 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
4065 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
4067 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
4068 $tpl->setVariable('CUR_TIME', date('G:i'));
4070 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
4071 $tpl_t->setVariable('CUR_TIME', date('G:i'));
4073 $affected_ids = array();
4075 if (DB_TYPE
== "pgsql") {
4076 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
4077 } else if (DB_TYPE
== "mysql") {
4078 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
4081 $result = db_query($link, "SELECT ttrss_entries.title,
4082 ttrss_feeds.title AS feed_title,
4084 ttrss_user_entries.ref_id,
4086 SUBSTRING(content, 1, 120) AS excerpt,
4087 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4089 ttrss_user_entries,ttrss_entries,ttrss_feeds
4091 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
4092 AND include_in_digest = true
4094 AND ttrss_user_entries.owner_uid = $user_id
4096 ORDER BY ttrss_feeds.title, date_updated DESC
4099 $cur_feed_title = "";
4101 $headlines_count = db_num_rows($result);
4103 $headlines = array();
4105 while ($line = db_fetch_assoc($result)) {
4106 array_push($headlines, $line);
4109 for ($i = 0; $i < sizeof($headlines); $i++
) {
4111 $line = $headlines[$i];
4113 array_push($affected_ids, $line["ref_id"]);
4115 $updated = make_local_datetime($link, $line['last_updated'], false,
4118 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
4119 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
4120 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
4121 $tpl->setVariable('ARTICLE_UPDATED', $updated);
4122 $tpl->setVariable('ARTICLE_EXCERPT',
4123 truncate_string(strip_tags($line["excerpt"]), 100));
4125 $tpl->addBlock('article');
4127 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
4128 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4129 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4130 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4131 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4132 // truncate_string(strip_tags($line["excerpt"]), 100));
4134 $tpl_t->addBlock('article');
4136 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
4137 $tpl->addBlock('feed');
4138 $tpl_t->addBlock('feed');
4143 $tpl->addBlock('digest');
4144 $tpl->generateOutputToString($tmp);
4146 $tpl_t->addBlock('digest');
4147 $tpl_t->generateOutputToString($tmp_t);
4149 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4152 function check_for_update($link) {
4153 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
4154 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
4156 $version_data = @fetch_file_contents
($version_url);
4158 if ($version_data) {
4159 $version_data = json_decode($version_data, true);
4160 if ($version_data && $version_data['version']) {
4162 if (version_compare(VERSION
, $version_data['version']) == -1) {
4163 return $version_data;
4171 function markArticlesById($link, $ids, $cmode) {
4175 foreach ($ids as $id) {
4176 array_push($tmp_ids, "ref_id = '$id'");
4179 $ids_qpart = join(" OR ", $tmp_ids);
4182 db_query($link, "UPDATE ttrss_user_entries SET
4183 marked = false,last_read = NOW()
4184 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4185 } else if ($cmode == 1) {
4186 db_query($link, "UPDATE ttrss_user_entries SET
4188 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4190 db_query($link, "UPDATE ttrss_user_entries SET
4191 marked = NOT marked,last_read = NOW()
4192 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4196 function publishArticlesById($link, $ids, $cmode) {
4200 foreach ($ids as $id) {
4201 array_push($tmp_ids, "ref_id = '$id'");
4204 $ids_qpart = join(" OR ", $tmp_ids);
4207 db_query($link, "UPDATE ttrss_user_entries SET
4208 published = false,last_read = NOW()
4209 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4210 } else if ($cmode == 1) {
4211 db_query($link, "UPDATE ttrss_user_entries SET
4213 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4215 db_query($link, "UPDATE ttrss_user_entries SET
4216 published = NOT published,last_read = NOW()
4217 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4220 if (PUBSUBHUBBUB_HUB
) {
4221 $rss_link = get_self_url_prefix() .
4222 "/backend.php?op=rss&id=-2&key=" .
4223 get_feed_access_key($link, -2, false);
4225 $p = new Publisher(PUBSUBHUBBUB_HUB
);
4227 $pubsub_result = $p->publish_update($rss_link);
4231 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4233 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4234 if (count($ids) == 0) return;
4238 foreach ($ids as $id) {
4239 array_push($tmp_ids, "ref_id = '$id'");
4242 $ids_qpart = join(" OR ", $tmp_ids);
4245 db_query($link, "UPDATE ttrss_user_entries SET
4246 unread = false,last_read = NOW()
4247 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4248 } else if ($cmode == 1) {
4249 db_query($link, "UPDATE ttrss_user_entries SET
4251 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4253 db_query($link, "UPDATE ttrss_user_entries SET
4254 unread = NOT unread,last_read = NOW()
4255 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4260 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4261 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4263 while ($line = db_fetch_assoc($result)) {
4264 ccache_update($link, $line["feed_id"], $owner_uid);
4268 function catchupArticleById($link, $id, $cmode) {
4271 db_query($link, "UPDATE ttrss_user_entries SET
4272 unread = false,last_read = NOW()
4273 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4274 } else if ($cmode == 1) {
4275 db_query($link, "UPDATE ttrss_user_entries SET
4277 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4279 db_query($link, "UPDATE ttrss_user_entries SET
4280 unread = NOT unread,last_read = NOW()
4281 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4284 $feed_id = getArticleFeed($link, $id);
4285 ccache_update($link, $feed_id, $_SESSION["uid"]);
4288 function make_guid_from_title($title) {
4289 return preg_replace("/[ \"\',.:;]/", "-",
4290 mb_strtolower(strip_tags($title), 'utf-8'));
4293 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4294 $feed_id, $is_cat, $search, $match_on,
4295 $search_mode, $view_mode, $error) {
4297 $page_prev_link = "viewFeedGoPage(-1)";
4298 $page_next_link = "viewFeedGoPage(1)";
4299 $page_first_link = "viewFeedGoPage(0)";
4301 $catchup_page_link = "catchupPage()";
4302 $catchup_feed_link = "catchupCurrentFeed()";
4303 $catchup_sel_link = "catchupSelection()";
4305 $archive_sel_link = "archiveSelection()";
4306 $delete_sel_link = "deleteSelection()";
4308 $sel_all_link = "selectArticles('all')";
4309 $sel_unread_link = "selectArticles('unread')";
4310 $sel_none_link = "selectArticles('none')";
4311 $sel_inv_link = "selectArticles('invert')";
4313 $tog_unread_link = "selectionToggleUnread()";
4314 $tog_marked_link = "selectionToggleMarked()";
4315 $tog_published_link = "selectionTogglePublished()";
4317 $reply = "<div id=\"subtoolbar_main\">";
4319 $reply .= __('Select:')."
4320 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4321 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4322 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4323 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4327 $reply .= "<select dojoType=\"dijit.form.Select\"
4328 onchange=\"headlineActionsChange(this)\">";
4329 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4331 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4333 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4334 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4335 <option value=\"$tog_published_link\">".__('Published')."</option>";
4337 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4339 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4341 if ($feed_id != "0") {
4342 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4344 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4345 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4349 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4352 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4355 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4360 $rss_link = htmlspecialchars(get_self_url_prefix() .
4361 "/backend.php?op=rss&id=$feed_id$cat_q$search_q");
4363 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4365 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4367 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4369 $reply .= "</select>";
4373 $reply .= "<div id=\"subtoolbar_ftitle\">";
4375 if ($feed_site_url) {
4376 $target = "target=\"_blank\"";
4377 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4378 truncate_string($feed_title,30)."</a>";
4381 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4385 if ($feed_id < -10) {
4386 $label_id = -11-$feed_id;
4388 $result = db_query($link, "SELECT fg_color, bg_color
4389 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4392 if (db_num_rows($result) != 0) {
4393 $fg_color = db_fetch_result($result, 0, "fg_color");
4394 $bg_color = db_fetch_result($result, 0, "bg_color");
4396 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
4397 $reply .= $feed_title;
4398 $reply .= "</span>";
4400 $reply .= $feed_title;
4404 $reply .= $feed_title;
4410 title=\"".__("View as RSS feed")."\"
4411 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4412 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4419 function outputFeedList($link, $special = true) {
4421 $feedlist = array();
4423 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4425 $feedlist['identifier'] = 'id';
4426 $feedlist['label'] = 'name';
4427 $feedlist['items'] = array();
4429 $owner_uid = $_SESSION["uid"];
4436 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4437 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4439 $cat['items'] = array();
4442 foreach (array(-4, -3, -1, -2, 0) as $i) {
4443 array_push($cat['items'], feedlist_init_feed($link, $i));
4447 array_push($feedlist['items'], $cat);
4449 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4452 $result = db_query($link, "SELECT * FROM
4453 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4455 if (db_num_rows($result) > 0) {
4457 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4458 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4459 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4461 $cat['items'] = array();
4464 while ($line = db_fetch_assoc($result)) {
4466 $label_id = -$line['id'] - 11;
4467 $count = getFeedUnread($link, $label_id);
4469 $feed = feedlist_init_feed($link, $label_id, false, $count);
4471 $feed['fg_color'] = $line['fg_color'];
4472 $feed['bg_color'] = $line['bg_color'];
4474 array_push($cat['items'], $feed);
4478 array_push($feedlist['items'], $cat);
4480 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4485 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4486 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4487 $order_by_qpart = "order_id,category,unread DESC,title";
4489 $order_by_qpart = "order_id,category,title";
4492 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4493 $order_by_qpart = "unread DESC,title";
4495 $order_by_qpart = "title";
4502 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4503 ttrss_feeds.order_id,title";
4505 $order_by_qpart = "title";
4507 $age_qpart = getMaxAgeSubquery();
4509 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4510 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated_noms,
4512 ttrss_feed_categories.title AS category,
4513 ttrss_feed_categories.collapsed,
4515 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4516 ON (ttrss_feed_categories.id = cat_id)
4517 LEFT JOIN ttrss_counters_cache
4519 (ttrss_feeds.id = feed_id)
4521 ttrss_feeds.owner_uid = '$owner_uid'
4522 ORDER BY $order_by_qpart";
4524 $result = db_query($link, $query);
4526 $actid = $_REQUEST["actid"];
4528 if (db_num_rows($result) > 0) {
4533 $cat['items'] = array();
4537 while ($line = db_fetch_assoc($result)) {
4539 $feed = htmlspecialchars(trim($line["title"]));
4541 if (!$feed) $feed = "[Untitled]";
4543 $feed_id = $line["id"];
4544 $unread = $line["unread"];
4546 $cat_id = $line["cat_id"];
4547 $tmp_category = $line["category"];
4548 if (!$tmp_category) $tmp_category = __("Uncategorized");
4550 if ($category != $tmp_category && $enable_cats) {
4552 $category = $tmp_category;
4554 $collapsed = sql_bool_to_bool($line["collapsed"]);
4556 // workaround for NULL category
4557 if ($category == __("Uncategorized")) {
4558 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4561 if ($cat) array_push($feedlist['items'], $cat);
4563 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4566 $updated = make_local_datetime($link, $line["updated_noms"], false);
4568 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4569 $feed, $unread, $line['last_error'], $updated));
4573 array_push($feedlist['items'], $cat);
4575 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4583 function get_article_tags($link, $id, $owner_uid = 0) {
4587 $a_id = db_escape_string($id);
4589 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4591 $query = "SELECT DISTINCT tag_name,
4592 owner_uid as owner FROM
4593 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4594 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4596 $obj_id = md5("TAGS:$owner_uid:$id");
4599 if ($memcache && $obj = $memcache->get($obj_id)) {
4602 /* check cache first */
4604 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4605 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4607 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4610 $tags = explode(",", $tag_cache);
4613 /* do it the hard way */
4615 $tmp_result = db_query($link, $query);
4617 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4618 array_push($tags, $tmp_line["tag_name"]);
4621 /* update the cache */
4623 $tags_str = db_escape_string(join(",", $tags));
4625 db_query($link, "UPDATE ttrss_user_entries
4626 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4627 AND owner_uid = " . $_SESSION["uid"]);
4630 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4636 function trim_value(&$value) {
4637 $value = trim($value);
4640 function trim_array($array) {
4642 array_walk($tmp, 'trim_value');
4646 function tag_is_valid($tag) {
4647 if ($tag == '') return false;
4648 if (preg_match("/^[0-9]*$/", $tag)) return false;
4649 if (mb_strlen($tag) > 250) return false;
4651 if (function_exists('iconv')) {
4652 $tag = iconv("utf-8", "utf-8", $tag);
4655 if (!$tag) return false;
4660 function render_login_form($link, $mobile = 0) {
4663 require_once "login_form.php";
4666 require_once "mobile/login_form.php";
4669 require_once "mobile/classic/login_form.php";
4673 // from http://developer.apple.com/internet/safari/faq.html
4674 function no_cache_incantation() {
4675 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4676 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4677 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4678 header("Cache-Control: post-check=0, pre-check=0", false);
4679 header("Pragma: no-cache"); // HTTP/1.0
4682 function format_warning($msg, $id = "") {
4684 return "<div class=\"warning\" id=\"$id\">
4685 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4688 function format_notice($msg, $id = "") {
4690 return "<div class=\"notice\" id=\"$id\">
4691 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4694 function format_error($msg, $id = "") {
4696 return "<div class=\"error\" id=\"$id\">
4697 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4700 function print_notice($msg) {
4701 return print format_notice($msg);
4704 function print_warning($msg) {
4705 return print format_warning($msg);
4708 function print_error($msg) {
4709 return print format_error($msg);
4713 function T_sprintf() {
4714 $args = func_get_args();
4715 return vsprintf(__(array_shift($args)), $args);
4718 function format_inline_player($link, $url, $ctype) {
4722 if (strpos($ctype, "audio/") === 0) {
4724 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4725 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4726 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4728 $id = 'AUDIO-' . uniqid();
4730 $entry .= "<audio id=\"$id\"\">
4731 <source src=\"$url\"></source>
4734 $entry .= "<span onclick=\"player(this)\"
4735 title=\"".__("Click to play")."\" status=\"0\"
4736 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4740 $entry .= "<object type=\"application/x-shockwave-flash\"
4741 data=\"lib/button/musicplayer.swf?song_url=$url\"
4742 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4743 <param name=\"movie\"
4744 value=\"lib/button/musicplayer.swf?song_url=$url\" />
4749 $filename = substr($url, strrpos($url, "/")+
1);
4751 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4752 $filename . " (" . $ctype . ")" . "</a>";
4757 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
4763 /* we can figure out feed_id from article id anyway, why do we
4764 * pass feed_id here? let's ignore the argument :( */
4766 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4767 WHERE ref_id = '$id'");
4769 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4771 $rv['feed_id'] = $feed_id;
4773 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4775 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4776 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4778 if (db_num_rows($result) == 1) {
4779 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4780 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4782 $rtl_content = false;
4783 $always_display_enclosures = false;
4787 $rtl_tag = "dir=\"RTL\"";
4794 if ($mark_as_read) {
4795 $result = db_query($link, "UPDATE ttrss_user_entries
4796 SET unread = false,last_read = NOW()
4797 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4799 ccache_update($link, $feed_id, $_SESSION["uid"]);
4802 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4803 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
4804 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4805 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4810 FROM ttrss_entries,ttrss_user_entries
4811 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4815 $line = db_fetch_assoc($result);
4817 if ($line["icon_url"]) {
4818 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4820 $feed_icon = " ";
4823 $feed_site_url = $line['site_url'];
4825 $num_comments = $line["num_comments"];
4826 $entry_comments = "";
4828 if ($num_comments > 0) {
4829 if ($line["comments"]) {
4830 $comments_url = $line["comments"];
4832 $comments_url = $line["link"];
4834 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4836 if ($line["comments"] && $line["link"] != $line["comments"]) {
4837 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4842 header("Content-Type: text/html");
4843 $rv['content'] .= "<html><head>
4844 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4845 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4846 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4850 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4851 truncate_string(strip_tags($line['title']), 15) . "</div>";
4853 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4855 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4856 class=\"postHeader\" id=\"POSTHDR-$id\">";
4858 $entry_author = $line["author"];
4860 if ($entry_author) {
4861 $entry_author = __(" - ") . $entry_author;
4864 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4867 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4869 if ($line["link"]) {
4870 $rv['content'] .= "<div clear='both'><a target='_blank'
4871 title=\"".htmlspecialchars($line['title'])."\"
4873 $line["link"] . "\">" .
4874 truncate_string($line["title"], 100) .
4875 "<span class='author'>$entry_author</span></a></div>";
4877 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4880 $tags = get_article_tags($link, $id);
4881 $tags_str = format_tags_string($tags, $id);
4882 $tags_str_full = join(", ", $tags);
4884 if (!$tags_str_full) $tags_str_full = __("no tags");
4886 if (!$entry_comments) $entry_comments = " "; # placeholder
4888 $rv['content'] .= "<div style='float : right'>
4889 <img src='".theme_image($link, 'images/tag.png')."'
4890 class='tagsPic' alt='Tags' title='Tags'> ";
4893 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4894 <a title=\"".__('Edit tags for this article')."\"
4895 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4897 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4898 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4899 position=\"below\">$tags_str_full</div>";
4901 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4902 class='tagsPic' style=\"cursor : pointer\"
4903 onclick=\"postOpenInNewTab(event, $id)\"
4904 alt='Zoom' title='".__('Open article in new tab')."'>";
4906 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4908 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4909 class='tagsPic' style=\"cursor : pointer\"
4910 onclick=\"editArticleNote($id)\"
4911 alt='PubNote' title='".__('Edit article note')."'>";
4913 if (DIGEST_ENABLE
) {
4914 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4915 class='tagsPic' style=\"cursor : pointer\"
4916 onclick=\"emailArticle($id)\"
4917 alt='Zoom' title='".__('Forward by email')."'>";
4920 if (ENABLE_TWEET_BUTTON
) {
4921 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4922 class='tagsPic' style=\"cursor : pointer\"
4923 onclick=\"tweetArticle($id)\"
4924 alt='Zoom' title='".__('Share on Twitter')."'>";
4927 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4928 class='tagsPic' style=\"cursor : pointer\"
4929 onclick=\"closeArticlePanel($id)\"
4930 alt='Zoom' title='".__('Close this panel')."'>";
4933 $tags_str = strip_tags($tags_str);
4934 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4936 $rv['content'] .= "</div>";
4937 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4939 if ($line["orig_feed_id"]) {
4941 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4942 WHERE id = ".$line["orig_feed_id"]);
4944 if (db_num_rows($tmp_result) != 0) {
4946 $rv['content'] .= "<div clear='both'>";
4947 $rv['content'] .= __("Originally from:");
4949 $rv['content'] .= " ";
4951 $tmp_line = db_fetch_assoc($tmp_result);
4953 $rv['content'] .= "<a target='_blank'
4954 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4955 $tmp_line['title'] . "</a>";
4957 $rv['content'] .= " ";
4959 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4960 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4962 $rv['content'] .= "</div>";
4966 $rv['content'] .= "</div>";
4968 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4969 if ($line['note']) {
4970 $rv['content'] .= format_article_note($id, $line['note']);
4972 $rv['content'] .= "</div>";
4974 $rv['content'] .= "<div class=\"postIcon\">" .
4975 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4976 href=\"".htmlspecialchars($feed_site_url)."\">".
4977 $feed_icon . "</a></div>";
4979 $rv['content'] .= "<div class=\"postContent\">";
4981 $article_content = sanitize_rss($link, $line["content"], false, false,
4984 $rv['content'] .= $article_content;
4986 $rv['content'] .= format_article_enclosures($link, $id,
4987 $always_display_enclosures, $article_content);
4989 $rv['content'] .= "</div>";
4991 $rv['content'] .= "</div>";
4997 <div style=\"text-align : center\">
4998 <button onclick=\"return window.close()\">".
4999 __("Close this window")."</button></div>";
5000 $rv['content'] .= "</body></html>";
5007 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
5008 $next_unread_feed, $offset, $vgr_last_feed = false,
5009 $override_order = false) {
5011 $disable_cache = false;
5015 $timing_info = getmicrotime();
5017 $topmost_article_ids = array();
5019 if (!$offset) $offset = 0;
5020 if ($subop == "undefined") $subop = "";
5022 $subop_split = explode(":", $subop);
5024 /* if ($subop == "CatchupSelected") {
5025 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
5026 $cmode = sprintf("%d", $_REQUEST["cmode"]);
5028 catchupArticlesById($link, $ids, $cmode);
5031 if ($subop == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
5032 update_rss_feed($link, $feed, true);
5035 if ($subop == "MarkAllRead") {
5036 catchup_feed($link, $feed, $cat_view);
5038 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
5039 if ($next_unread_feed) {
5040 $feed = $next_unread_feed;
5045 if ($subop_split[0] == "MarkAllReadGR") {
5046 catchup_feed($link, $subop_split[1], false);
5049 // FIXME: might break tag display?
5051 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
5052 $result = db_query($link,
5053 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
5055 if (db_num_rows($result) == 0) {
5056 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
5060 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
5062 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
5063 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
5065 if (db_num_rows($result) == 1) {
5066 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
5068 $rtl_content = false;
5072 $rtl_tag = "dir=\"RTL\"";
5078 $rtl_content = false;
5081 @$search = db_escape_string($_REQUEST["query"]);
5084 $disable_cache = true;
5087 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
5088 @$match_on = db_escape_string($_REQUEST["match_on"]);
5094 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5096 // error_log("format_headlines_list: [" . $feed . "] subop [" . $subop . "]");
5097 if( $search_mode == '' && $subop != '' ){
5098 $search_mode = $subop;
5100 // error_log("search_mode: " . $search_mode);
5101 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
5102 $search, $search_mode, $match_on, $override_order, $offset);
5104 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5106 $result = $qfh_ret[0];
5107 $feed_title = $qfh_ret[1];
5108 $feed_site_url = $qfh_ret[2];
5109 $last_error = $qfh_ret[3];
5111 $vgroup_last_feed = $vgr_last_feed;
5115 if (db_num_rows($result) > 0) {
5116 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
5118 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5123 $headlines_count = db_num_rows($result);
5125 if (db_num_rows($result) > 0) {
5130 $cur_feed_title = '';
5132 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5134 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5136 while ($line = db_fetch_assoc($result)) {
5138 $class = ($lnum %
2) ?
"even" : "odd";
5141 $feed_id = $line["feed_id"];
5143 $labels = get_article_labels($link, $id);
5145 $labels_str = "<span id=\"HLLCTR-$id\">";
5146 $labels_str .= format_article_labels($labels, $id);
5147 $labels_str .= "</span>";
5149 if (count($topmost_article_ids) < 3) {
5150 array_push($topmost_article_ids, $id);
5153 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5155 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5156 theme_image($link, 'images/updated.png')."\"
5159 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5163 if (sql_bool_to_bool($line["unread"]) &&
5164 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5166 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5167 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5170 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
5171 $class .= " Unread";
5178 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
5179 $marked_pic = "<img id=\"FMPIC-$id\"
5180 src=\"".theme_image($link, 'images/mark_set.png')."\"
5181 class=\"markedPic\" alt=\"Unstar article\"
5182 onclick='javascript:tMark($id)'>";
5184 $marked_pic = "<img id=\"FMPIC-$id\"
5185 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5186 class=\"markedPic\" alt=\"Star article\"
5187 onclick='javascript:tMark($id)'>";
5190 if ($line["published"] == "t" ||
$line["published"] == "1") {
5191 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5192 'images/pub_set.png')."\"
5194 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5196 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5197 'images/pub_unset.png')."\"
5199 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5202 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5203 # $line["title"] . "</a>";
5205 # $content_link = "<a
5206 # href=\"" . htmlspecialchars($line["link"]) . "\"
5207 # onclick=\"view($id,$feed_id);\">" .
5208 # $line["title"] . "</a>";
5210 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5211 # $line["title"] . "</a>";
5213 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5215 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5216 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5220 $score = $line["score"];
5222 $score_pic = theme_image($link,
5223 "images/" . get_score_pic($score));
5225 /* $score_title = __("(Click to change)");
5226 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5227 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5229 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5234 } else if ($score < -100) {
5240 $entry_author = $line["author"];
5242 if ($entry_author) {
5243 $entry_author = " - $entry_author";
5246 $has_feed_icon = feed_has_icon($feed_id);
5248 if ($has_feed_icon) {
5249 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5251 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5254 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5256 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5257 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5259 $cur_feed_title = $line["feed_title"];
5260 $vgroup_last_feed = $feed_id;
5262 $cur_feed_title = htmlspecialchars($cur_feed_title);
5264 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5266 $reply['content'] .= "<div class='cdmFeedTitle'>".
5267 "<div style=\"float : right\">$feed_icon_img</div>".
5268 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5269 $line["feed_title"]."</a> $vf_catchup_link</div>";
5274 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5275 onmouseout='postMouseOut($id)'";
5277 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5279 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5281 $reply['content'] .= "<div class='hlLeft'>";
5283 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5286 $reply['content'] .= "$marked_pic";
5287 $reply['content'] .= "$published_pic";
5289 $reply['content'] .= "</div>";
5291 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5292 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5293 $reply['content'] .= "<a id=\"RTITLE-$id\"
5294 href=\"" . htmlspecialchars($line["link"]) . "\"
5298 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5299 if ($content_preview) {
5300 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5304 $reply['content'] .= "</a></span>";
5306 $reply['content'] .= $labels_str;
5308 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5309 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5310 if (@$line["feed_title"]) {
5311 $reply['content'] .= "<span class=\"hlFeed\">
5312 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5313 $line["feed_title"]."</a>)
5318 $reply['content'] .= "</div>";
5320 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5321 $reply['content'] .= "<div class=\"hlRight\">";
5323 $reply['content'] .= $score_pic;
5325 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5327 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5328 style=\"cursor : pointer\"
5329 title=\"".htmlspecialchars($line['feed_title'])."\">
5330 $feed_icon_img<span>";
5333 $reply['content'] .= "</div>";
5334 $reply['content'] .= "</div>";
5338 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5339 if ($feed_id != $vgroup_last_feed) {
5341 $cur_feed_title = $line["feed_title"];
5342 $vgroup_last_feed = $feed_id;
5344 $cur_feed_title = htmlspecialchars($cur_feed_title);
5346 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5348 $has_feed_icon = feed_has_icon($feed_id);
5350 if ($has_feed_icon) {
5351 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL
."/$feed_id.ico\" alt=\"\">";
5353 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5356 $reply['content'] .= "<div class='cdmFeedTitle'>".
5357 "<div style=\"float : right\">$feed_icon_img</div>".
5358 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5359 $line["feed_title"]."</a> $vf_catchup_link</div>";
5363 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5365 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5366 onmouseout='postMouseOut($id)'";
5368 $reply['content'] .= "<div class=\"$class\"
5369 id=\"RROW-$id\" $mouseover_attrs'>";
5371 $reply['content'] .= "<div class=\"cdmHeader\">";
5373 $reply['content'] .= "<div style='float : right'>";
5374 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5375 $reply['content'] .= "$score_pic";
5377 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5378 $reply['content'] .= "<span style=\"cursor : pointer\"
5379 title=\"".htmlspecialchars($line["feed_title"])."\"
5380 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5382 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5384 $reply['content'] .= "</div>";
5386 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5387 'RROW-$id')\" id=\"RCHK-$id\"/>";
5389 $reply['content'] .= "$marked_pic";
5390 $reply['content'] .= "$published_pic";
5392 $reply['content'] .= "<span id=\"RTITLE-$id\"
5393 onclick=\"return cdmClicked(event, $id);\"
5394 class=\"titleWrap$hlc_suffix\">
5396 title=\"".htmlspecialchars($line['title'])."\"
5397 target=\"_blank\" href=\"".
5398 htmlspecialchars($line["link"])."\">".
5399 truncate_string($line["title"], 100) .
5400 " $entry_author</a>";
5402 $reply['content'] .= $labels_str;
5404 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5405 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5406 if (@$line["feed_title"]) {
5407 $reply['content'] .= "<span class=\"hlFeed\">
5408 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5409 $line["feed_title"]."</a>)
5415 $content_hidden = "style=\"display : none\"";
5417 $excerpt_hidden = "style=\"display : none\"";
5419 $reply['content'] .= "<span $excerpt_hidden
5420 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5422 $reply['content'] .= "</span>";
5424 $reply['content'] .= "</div>";
5426 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5427 onclick=\"return cdmClicked(event, $id);\"
5430 $reply['content'] .= "<div class=\"cdmContentInner\">";
5432 if ($line["orig_feed_id"]) {
5434 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5435 WHERE id = ".$line["orig_feed_id"]);
5437 if (db_num_rows($tmp_result) != 0) {
5439 $reply['content'] .= "<div clear='both'>";
5440 $reply['content'] .= __("Originally from:");
5442 $reply['content'] .= " ";
5444 $tmp_line = db_fetch_assoc($tmp_result);
5446 $reply['content'] .= "<a target='_blank'
5447 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5448 $tmp_line['title'] . "</a>";
5450 $reply['content'] .= " ";
5452 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5453 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5455 $reply['content'] .= "</div>";
5459 // FIXME: make this less of a hack
5461 $feed_site_url = false;
5463 if ($line["feed_id"]) {
5464 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5465 WHERE id = " . $line["feed_id"]);
5467 if (db_num_rows($tmp_result) == 1) {
5468 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5473 $article_content = sanitize_rss($link, $line["content_preview"],
5474 false, false, $feed_site_url);
5476 if (!$article_content) $article_content = " ";
5478 $article_content = '';
5481 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5482 if ($line['note']) {
5483 $reply['content'] .= format_article_note($id, $line['note']);
5485 $reply['content'] .= "</div>";
5487 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5489 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5490 ttrss_feeds WHERE id = ".
5491 (($line['feed_id'] == null) ?
$line['orig_feed_id'] :
5492 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5494 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5495 0, "always_display_enclosures"));
5497 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5500 $reply['content'] .= "</div>";
5502 $reply['content'] .= "<div class=\"cdmFooter\">";
5504 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5506 $reply['content'] .= "<img src='".theme_image($link,
5507 'images/tag.png')."' alt='Tags' title='Tags'>
5508 <span id=\"ATSTR-$id\">$tags_str</span>
5509 <a title=\"".__('Edit tags for this article')."\"
5510 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5512 $reply['content'] .= "<div style=\"float : right\">";
5514 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5515 onclick=\"zoomToArticle(event, $id)\"
5516 style=\"cursor : pointer\"
5518 title='".__('Open article in new tab')."'>";
5520 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5522 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5523 style=\"cursor : pointer\" style=\"cursor : pointer\"
5524 onclick=\"editArticleNote($id)\"
5525 alt='PubNote' title='".__('Edit article note')."'>";
5527 if (DIGEST_ENABLE
) {
5528 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5529 style=\"cursor : pointer\"
5530 onclick=\"emailArticle($id)\"
5531 alt='Zoom' title='".__('Forward by email')."'>";
5534 if (ENABLE_TWEET_BUTTON
) {
5535 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5536 class='tagsPic' style=\"cursor : pointer\"
5537 onclick=\"tweetArticle($id)\"
5538 alt='Zoom' title='".__('Share on Twitter')."'>";
5541 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5542 style=\"cursor : pointer\" style=\"cursor : pointer\"
5543 onclick=\"dismissArticle($id)\"
5544 alt='Dismiss' title='".__('Dismiss article')."'>";
5546 $reply['content'] .= "</div>";
5547 $reply['content'] .= "</div>";
5549 $reply['content'] .= "</div>";
5551 $reply['content'] .= "</div>";
5558 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5563 switch ($view_mode) {
5565 $message = __("No unread articles found to display.");
5568 $message = __("No updated articles found to display.");
5571 $message = __("No starred articles found to display.");
5575 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5577 $message = __("No articles found to display.");
5581 if (!$offset && $message) {
5582 $reply['content'] .= "<div class='whiteBox'>$message";
5584 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5586 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5587 WHERE owner_uid = " . $_SESSION['uid']);
5589 $last_updated = db_fetch_result($result, 0, "last_updated");
5590 $last_updated = make_local_datetime($link, $last_updated, false);
5592 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5594 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5595 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5597 $num_errors = db_fetch_result($result, 0, "num_errors");
5599 if ($num_errors > 0) {
5600 $reply['content'] .= "<br/>";
5601 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5602 __('Some feeds have update errors (click for details)')."</a>";
5604 $reply['content'] .= "</span></p></div>";
5608 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5610 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5611 $vgroup_last_feed, $reply);
5614 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5616 function printTagCloud($link) {
5618 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5619 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5620 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5622 $result = db_query($link, $query);
5626 while ($line = db_fetch_assoc($result)) {
5627 $tags[$line["tag_name"]] = $line["count"];
5630 if( count($tags) == 0 ){ return; }
5634 $max_size = 32; // max font size in pixels
5635 $min_size = 11; // min font size in pixels
5637 // largest and smallest array values
5638 $max_qty = max(array_values($tags));
5639 $min_qty = min(array_values($tags));
5641 // find the range of values
5642 $spread = $max_qty - $min_qty;
5643 if ($spread == 0) { // we don't want to divide by zero
5647 // set the font-size increment
5648 $step = ($max_size - $min_size) / ($spread);
5650 // loop through the tag array
5651 foreach ($tags as $key => $value) {
5652 // calculate font-size
5653 // find the $value in excess of $min_qty
5654 // multiply by the font-size increment ($size)
5655 // and add the $min_size set above
5656 $size = round($min_size +
(($value - $min_qty) * $step));
5658 $key_escaped = str_replace("'", "\\'", $key);
5660 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5661 $size . "px\" title=\"$value articles tagged with " .
5662 $key . '">' . $key . '</a> ';
5666 function print_checkpoint($n, $s) {
5667 $ts = getmicrotime();
5668 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5672 function sanitize_tag($tag) {
5675 $tag = mb_strtolower($tag, 'utf-8');
5677 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5679 // $tag = str_replace('"', "", $tag);
5680 // $tag = str_replace("+", " ", $tag);
5681 $tag = str_replace("technorati tag: ", "", $tag);
5686 function get_self_url_prefix() {
5687 return SELF_URL_PATH
;
5690 function opml_publish_url($link){
5692 $url_path = get_self_url_prefix();
5693 $url_path .= "/opml.php?op=publish&key=" .
5694 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5700 * Purge a feed contents, marked articles excepted.
5702 * @param mixed $link The database connection.
5703 * @param integer $id The id of the feed to purge.
5706 function clear_feed_articles($link, $id) {
5709 $result = db_query($link, "DELETE FROM ttrss_user_entries
5710 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5712 $result = db_query($link, "DELETE FROM ttrss_user_entries
5713 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5716 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5717 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5719 ccache_update($link, $id, $_SESSION['uid']);
5720 } // function clear_feed_articles
5723 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5725 * @return string The Mozilla Firefox feed adding URL.
5727 function add_feed_url() {
5728 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5730 $url_path = get_self_url_prefix() .
5731 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5733 } // function add_feed_url
5736 * Encrypt a password in SHA1.
5738 * @param string $pass The password to encrypt.
5739 * @param string $login A optionnal login.
5740 * @return string The encrypted password.
5742 function encrypt_password($pass, $login = '') {
5744 return "SHA1X:" . sha1("$login:$pass");
5746 return "SHA1:" . sha1($pass);
5748 } // function encrypt_password
5751 * Update a feed batch.
5752 * Used by daemons to update n feeds by run.
5753 * Only update feed needing a update, and not being processed
5754 * by another process.
5756 * @param mixed $link Database link
5757 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5758 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5759 * @param boolean $debug Set to false to disable debug output. Default to true.
5762 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5763 // Process all other feeds using last_updated and interval parameters
5765 // Test if the user has loggued in recently. If not, it does not update its feeds.
5766 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5767 if (DB_TYPE
== "pgsql") {
5768 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5770 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5773 $login_thresh_qpart = "";
5776 // Test if the feed need a update (update interval exceded).
5777 if (DB_TYPE
== "pgsql") {
5778 $update_limit_qpart = "AND ((
5779 ttrss_feeds.update_interval = 0
5780 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5782 ttrss_feeds.update_interval > 0
5783 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5784 ) OR ttrss_feeds.last_updated IS NULL)";
5786 $update_limit_qpart = "AND ((
5787 ttrss_feeds.update_interval = 0
5788 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5790 ttrss_feeds.update_interval > 0
5791 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5792 ) OR ttrss_feeds.last_updated IS NULL)";
5795 // Test if feed is currently being updated by another process.
5796 if (DB_TYPE
== "pgsql") {
5797 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5799 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5802 // Test if there is a limit to number of updated feeds
5804 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5806 $random_qpart = sql_random_function();
5808 // We search for feed needing update.
5809 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5810 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
5811 ttrss_feeds.update_interval
5813 ttrss_feeds, ttrss_users, ttrss_user_prefs
5815 ttrss_feeds.owner_uid = ttrss_users.id
5816 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5817 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5818 $login_thresh_qpart $update_limit_qpart
5819 $updstart_thresh_qpart
5820 ORDER BY $random_qpart $query_limit");
5822 $user_prefs_cache = array();
5824 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5826 // Here is a little cache magic in order to minimize risk of double feed updates.
5827 $feeds_to_update = array();
5828 while ($line = db_fetch_assoc($result)) {
5829 $feeds_to_update[$line['id']] = $line;
5832 // We update the feed last update started date before anything else.
5833 // There is no lag due to feed contents downloads
5834 // It prevent an other process to update the same feed.
5835 $feed_ids = array_keys($feeds_to_update);
5837 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5838 WHERE id IN (%s)", implode(',', $feed_ids)));
5841 // For each feed, we call the feed update function.
5842 while ($line = array_pop($feeds_to_update)) {
5844 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5846 update_rss_feed($link, $line["id"], true);
5848 sleep(1); // prevent flood (FIXME make this an option?)
5851 // Send feed digests by email if needed.
5852 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5854 } // function update_daemon_common
5856 function sanitize_article_content($text) {
5857 # we don't support CDATA sections in articles, they break our own escaping
5858 $text = preg_replace("/\[\[CDATA/", "", $text);
5859 $text = preg_replace("/\]\]\>/", "", $text);
5863 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5868 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5870 if ($memcache && $obj = $memcache->get($obj_id)) {
5876 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5878 $result = db_query($link, "SELECT reg_exp,
5879 ttrss_filter_types.name AS name,
5880 ttrss_filter_actions.name AS action,
5884 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5887 owner_uid = $owner_uid AND
5888 ttrss_filter_types.id = filter_type AND
5889 ttrss_filter_actions.id = action_id AND
5890 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5892 while ($line = db_fetch_assoc($result)) {
5893 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5894 $filter["reg_exp"] = $line["reg_exp"];
5895 $filter["action"] = $line["action"];
5896 $filter["action_param"] = $line["action_param"];
5897 $filter["filter_param"] = $line["filter_param"];
5898 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5900 array_push($filters[$line["name"]], $filter);
5903 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5909 function get_score_pic($score) {
5911 return "score_high.png";
5912 } else if ($score > 0) {
5913 return "score_half_high.png";
5914 } else if ($score < -100) {
5915 return "score_low.png";
5916 } else if ($score < 0) {
5917 return "score_half_low.png";
5919 return "score_neutral.png";
5923 function rounded_table_start($classname, $header = " ") {
5924 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5925 print "<tr><td class='c1'> </td><td class='top'>$header</td><td class='c2'> </td></tr>";
5926 print "<tr><td class='left'> </td><td class='content'>";
5929 function rounded_table_end($footer = " ") {
5930 print "</td><td class='right'> </td></tr>";
5931 print "<tr><td class='c4'> </td><td class='bottom'>$footer</td><td class='c3'> </td></tr>";
5935 function feed_has_icon($id) {
5936 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
5939 function init_connection($link) {
5940 if (DB_TYPE
== "pgsql") {
5941 pg_query($link, "set client_encoding = 'UTF-8'");
5942 pg_set_client_encoding("UNICODE");
5943 pg_query($link, "set datestyle = 'ISO, european'");
5944 pg_query($link, "set TIME ZONE 0");
5946 db_query($link, "SET time_zone = '+0:0'");
5948 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
5949 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
5950 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5955 function update_feedbrowser_cache($link) {
5957 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
5958 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5959 WHERE tf.feed_url = ttrss_feeds.feed_url
5960 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
5961 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
5963 db_query($link, "BEGIN");
5965 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5969 while ($line = db_fetch_assoc($result)) {
5970 $subscribers = db_escape_string($line["subscribers"]);
5971 $feed_url = db_escape_string($line["feed_url"]);
5972 $title = db_escape_string($line["title"]);
5973 $site_url = db_escape_string($line["site_url"]);
5975 $tmp_result = db_query($link, "SELECT subscribers FROM
5976 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5978 if (db_num_rows($tmp_result) == 0) {
5980 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5981 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5982 '$site_url', '$title', '$subscribers')");
5990 db_query($link, "COMMIT");
5996 function ccache_zero($link, $feed_id, $owner_uid) {
5997 db_query($link, "UPDATE ttrss_counters_cache SET
5998 value = 0, updated = NOW() WHERE
5999 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6002 function ccache_zero_all($link, $owner_uid) {
6003 db_query($link, "UPDATE ttrss_counters_cache SET
6004 value = 0 WHERE owner_uid = '$owner_uid'");
6006 db_query($link, "UPDATE ttrss_cat_counters_cache SET
6007 value = 0 WHERE owner_uid = '$owner_uid'");
6010 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
6013 $table = "ttrss_counters_cache";
6015 $table = "ttrss_cat_counters_cache";
6018 db_query($link, "DELETE FROM $table WHERE
6019 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6023 function ccache_update_all($link, $owner_uid) {
6025 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
6027 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
6028 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6030 while ($line = db_fetch_assoc($result)) {
6031 ccache_update($link, $line["feed_id"], $owner_uid, true);
6034 /* We have to manually include category 0 */
6036 ccache_update($link, 0, $owner_uid, true);
6039 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
6040 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6042 while ($line = db_fetch_assoc($result)) {
6043 print ccache_update($link, $line["feed_id"], $owner_uid);
6050 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
6051 $no_update = false) {
6053 if (!is_numeric($feed_id)) return;
6056 $table = "ttrss_counters_cache";
6058 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
6059 WHERE id = '$feed_id'");
6060 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6063 $table = "ttrss_cat_counters_cache";
6066 if (DB_TYPE
== "pgsql") {
6067 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
6068 } else if (DB_TYPE
== "mysql") {
6069 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
6072 $result = db_query($link, "SELECT value FROM $table
6073 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
6076 if (db_num_rows($result) == 1) {
6077 return db_fetch_result($result, 0, "value");
6082 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
6088 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6089 $update_pcat = true) {
6091 if (!is_numeric($feed_id)) return;
6093 if (!$is_cat && $feed_id > 0) {
6094 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
6095 WHERE id = '$feed_id'");
6096 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6099 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6101 /* When updating a label, all we need to do is recalculate feed counters
6102 * because labels are not cached */
6105 ccache_update_all($link, $owner_uid);
6110 $table = "ttrss_counters_cache";
6112 $table = "ttrss_cat_counters_cache";
6115 if ($is_cat && $feed_id >= 0) {
6116 if ($feed_id != 0) {
6117 $cat_qpart = "cat_id = '$feed_id'";
6119 $cat_qpart = "cat_id IS NULL";
6122 /* Recalculate counters for child feeds */
6124 $result = db_query($link, "SELECT id FROM ttrss_feeds
6125 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6127 while ($line = db_fetch_assoc($result)) {
6128 ccache_update($link, $line["id"], $owner_uid, false, false);
6131 $result = db_query($link, "SELECT SUM(value) AS sv
6132 FROM ttrss_counters_cache, ttrss_feeds
6133 WHERE id = feed_id AND $cat_qpart AND
6134 ttrss_feeds.owner_uid = '$owner_uid'");
6136 $unread = (int) db_fetch_result($result, 0, "sv");
6139 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6142 db_query($link, "BEGIN");
6144 $result = db_query($link, "SELECT feed_id FROM $table
6145 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6147 if (db_num_rows($result) == 1) {
6148 db_query($link, "UPDATE $table SET
6149 value = '$unread', updated = NOW() WHERE
6150 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6153 db_query($link, "INSERT INTO $table
6154 (feed_id, value, owner_uid, updated)
6156 ($feed_id, $unread, $owner_uid, NOW())");
6159 db_query($link, "COMMIT");
6161 if ($feed_id > 0 && $prev_unread != $unread) {
6165 /* Update parent category */
6169 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6170 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6172 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6174 ccache_update($link, $cat_id, $owner_uid, true);
6178 } else if ($feed_id < 0) {
6179 ccache_update_all($link, $owner_uid);
6185 function ccache_cleanup($link, $owner_uid) {
6187 if (DB_TYPE
== "pgsql") {
6188 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6189 (SELECT count(*) FROM ttrss_counters_cache AS c2
6190 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6191 AND owner_uid = '$owner_uid'");
6193 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6194 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6195 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6196 AND owner_uid = '$owner_uid'");
6198 db_query($link, "DELETE c1 FROM
6199 ttrss_counters_cache AS c1,
6200 ttrss_counters_cache AS c2
6202 c1.owner_uid = '$owner_uid' AND
6203 c1.owner_uid = c2.owner_uid AND
6204 c1.feed_id = c2.feed_id");
6206 db_query($link, "DELETE c1 FROM
6207 ttrss_cat_counters_cache AS c1,
6208 ttrss_cat_counters_cache AS c2
6210 c1.owner_uid = '$owner_uid' AND
6211 c1.owner_uid = c2.owner_uid AND
6212 c1.feed_id = c2.feed_id");
6217 function label_find_id($link, $label, $owner_uid) {
6218 $result = db_query($link,
6219 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6220 AND owner_uid = '$owner_uid' LIMIT 1");
6222 if (db_num_rows($result) == 1) {
6223 return db_fetch_result($result, 0, "id");
6229 function get_article_labels($link, $id) {
6232 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6236 if ($memcache && $obj = $memcache->get($obj_id)) {
6240 $result = db_query($link, "SELECT label_cache FROM
6241 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6244 $label_cache = db_fetch_result($result, 0, "label_cache");
6248 $label_cache = json_decode($label_cache, true);
6250 if ($label_cache["no-labels"] == 1)
6253 return $label_cache;
6256 $result = db_query($link,
6257 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6258 FROM ttrss_labels2, ttrss_user_labels2
6260 AND article_id = '$id'
6261 AND owner_uid = ".$_SESSION["uid"] . "
6264 while ($line = db_fetch_assoc($result)) {
6265 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6267 array_push($rv, $rk);
6269 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6272 label_update_cache($link, $id, $rv);
6274 label_update_cache($link, $id, array("no-labels" => 1));
6281 function label_find_caption($link, $label, $owner_uid) {
6282 $result = db_query($link,
6283 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6284 AND owner_uid = '$owner_uid' LIMIT 1");
6286 if (db_num_rows($result) == 1) {
6287 return db_fetch_result($result, 0, "caption");
6293 function label_update_cache($link, $id, $labels = false, $force = false) {
6296 label_clear_cache($link, $id);
6299 $labels = get_article_labels($link, $id);
6301 $labels = db_escape_string(json_encode($labels));
6303 db_query($link, "UPDATE ttrss_user_entries SET
6304 label_cache = '$labels' WHERE ref_id = '$id'");
6308 function label_clear_cache($link, $id) {
6310 db_query($link, "UPDATE ttrss_user_entries SET
6311 label_cache = '' WHERE ref_id = '$id'");
6315 function label_remove_article($link, $id, $label, $owner_uid) {
6317 $label_id = label_find_id($link, $label, $owner_uid);
6319 if (!$label_id) return;
6321 $result = db_query($link,
6322 "DELETE FROM ttrss_user_labels2
6324 label_id = '$label_id' AND
6325 article_id = '$id'");
6327 label_clear_cache($link, $id);
6330 function label_add_article($link, $id, $label, $owner_uid) {
6335 $obj_id = md5("LABELS:$id:$owner_uid");
6336 $memcache->delete($obj_id);
6339 $label_id = label_find_id($link, $label, $owner_uid);
6341 if (!$label_id) return;
6343 $result = db_query($link,
6345 article_id FROM ttrss_labels2, ttrss_user_labels2
6348 label_id = '$label_id' AND
6349 article_id = '$id' AND owner_uid = '$owner_uid'
6352 if (db_num_rows($result) == 0) {
6353 db_query($link, "INSERT INTO ttrss_user_labels2
6354 (label_id, article_id) VALUES ('$label_id', '$id')");
6357 label_clear_cache($link, $id);
6361 function label_remove($link, $id, $owner_uid) {
6364 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6367 $obj_id = md5("LABELS:$id:$owner_uid");
6368 $memcache->delete($obj_id);
6371 db_query($link, "BEGIN");
6373 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6376 $caption = db_fetch_result($result, 0, "caption");
6378 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6379 AND owner_uid = " . $owner_uid);
6381 if (db_affected_rows($link, $result) != 0 && $caption) {
6383 /* Remove access key for the label */
6385 $ext_id = -11 - $id;
6387 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6388 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6390 /* Disable filters that reference label being removed */
6392 db_query($link, "UPDATE ttrss_filters SET
6393 enabled = false WHERE action_param = '$caption'
6395 AND owner_uid = " . $owner_uid);
6397 /* Remove cached data */
6399 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6400 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6404 db_query($link, "COMMIT");
6407 function label_create($link, $caption) {
6409 db_query($link, "BEGIN");
6413 $result = db_query($link, "SELECT id FROM ttrss_labels2
6414 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6416 if (db_num_rows($result) == 0) {
6417 $result = db_query($link,
6418 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6419 VALUES ('$caption', '".$_SESSION["uid"]."')");
6421 $result = db_affected_rows($link, $result) != 0;
6424 db_query($link, "COMMIT");
6429 function print_labels_headlines_dropdown($link, $feed_id) {
6430 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6432 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6433 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6435 while ($line = db_fetch_assoc($result)) {
6437 $label_id = $line["id"];
6438 $label_caption = $line["caption"];
6441 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6442 print "<option id=\"LHDL-$id\"
6443 value=\"selectionRemoveLabel($label_id)\">".
6444 __('Remove:') . " $label_caption</option>";
6446 print "<option id=\"LHDL-$id\"
6447 value=\"selectionAssignLabel($label_id)\">".
6448 __('Assign:') . " $label_caption</option>";
6453 function format_tags_string($tags, $id) {
6456 $tags_nolinks_str = "";
6462 $formatted_tags = array();
6464 foreach ($tags as $tag) {
6466 $tag_escaped = str_replace("'", "\\'", $tag);
6468 if (mb_strlen($tag) > 30) {
6469 $tag = truncate_string($tag, 30);
6472 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6474 array_push($formatted_tags, $tag_str);
6476 $tmp_tags_str = implode(", ", $formatted_tags);
6478 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
6483 $tags_str = implode(", ", $formatted_tags);
6485 if ($num_tags < count($tags)) {
6486 $tags_str .= ", …";
6489 if ($num_tags == 0) {
6490 $tags_str = __("no tags");
6497 function format_article_labels($labels, $id) {
6501 foreach ($labels as $l) {
6502 $labels_str .= sprintf("<span class='hlLabelRef'
6503 style='color : %s; background-color : %s'>%s</span>",
6504 $l[2], $l[3], $l[1]);
6511 function format_article_note($id, $note) {
6513 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6514 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6515 __('(edit note)')."</div>$note</div>";
6520 function toggle_collapse_cat($link, $cat_id, $mode) {
6522 $mode = bool_to_sql_bool($mode);
6524 db_query($link, "UPDATE ttrss_feed_categories SET
6525 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6532 $pref_name = '_COLLAPSED_SPECIAL';
6535 $pref_name = '_COLLAPSED_LABELS';
6538 $pref_name = '_COLLAPSED_UNCAT';
6544 set_pref($link, $pref_name, 'true');
6546 set_pref($link, $pref_name, 'false');
6552 function remove_feed($link, $id, $owner_uid) {
6556 /* save starred articles in Archived feed */
6558 db_query($link, "BEGIN");
6560 /* prepare feed if necessary */
6562 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6565 if (db_num_rows($result) == 0) {
6566 db_query($link, "INSERT INTO ttrss_archived_feeds
6567 (id, owner_uid, title, feed_url, site_url)
6568 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6572 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6573 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6574 marked = true AND owner_uid = $owner_uid");
6576 /* Remove access key for the feed */
6578 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6579 feed_id = '$id' AND owner_uid = $owner_uid");
6581 /* remove the feed */
6583 db_query($link, "DELETE FROM ttrss_feeds
6584 WHERE id = '$id' AND owner_uid = $owner_uid");
6586 db_query($link, "COMMIT");
6588 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6589 unlink(ICONS_DIR . "/$id.ico");
6592 ccache_remove($link, $id, $owner_uid);
6595 label_remove($link, -11-$id, $owner_uid);
6596 ccache_remove($link, -11-$id, $owner_uid);
6600 function add_feed_category($link, $feed_cat) {
6602 if (!$feed_cat) return false;
6604 db_query($link, "BEGIN");
6606 $result = db_query($link,
6607 "SELECT id FROM ttrss_feed_categories
6608 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6610 if (db_num_rows($result) == 0) {
6612 $result = db_query($link,
6613 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6614 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6616 db_query($link, "COMMIT");
6624 function remove_feed_category($link, $id, $owner_uid) {
6626 db_query($link, "DELETE FROM ttrss_feed_categories
6627 WHERE id = '$id' AND owner_uid = $owner_uid");
6629 ccache_remove($link, $id, $owner_uid, true);
6632 function archive_article($link, $id, $owner_uid) {
6633 db_query($link, "BEGIN");
6635 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6636 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6638 if (db_num_rows($result) != 0) {
6640 /* prepare the archived table */
6642 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6645 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6646 WHERE id = '$feed_id'");
6648 if (db_num_rows($result) == 0) {
6649 db_query($link, "INSERT INTO ttrss_archived_feeds
6650 (id, owner_uid, title, feed_url, site_url)
6651 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6652 WHERE id = '$feed_id'");
6655 db_query($link, "UPDATE ttrss_user_entries
6656 SET orig_feed_id = feed_id, feed_id = NULL
6657 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6661 db_query($link, "COMMIT");
6664 function getArticleFeed($link, $id) {
6665 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6666 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6668 if (db_num_rows($result) != 0) {
6669 return db_fetch_result($result, 0, "feed_id");
6675 function make_url_from_parts($parts) {
6676 $url = $parts['scheme'] . '://' . $parts['host'];
6678 if ($parts['path']) $url .= $parts['path'];
6679 if ($parts['query']) $url .= '?' . $parts['query'];
6685 * Fixes incomplete URLs by prepending "http://".
6686 * Also replaces feed:// with http://, and
6687 * prepends a trailing slash if the url is a domain name only.
6689 * @param string $url Possibly incomplete URL
6691 * @return string Fixed URL.
6693 function fix_url($url) {
6694 if (strpos($url, '://') === false) {
6695 $url = 'http://' . $url;
6696 } else if (substr($url, 0, 5) == 'feed:') {
6697 $url = 'http:' . substr($url, 5);
6700 //prepend slash if the URL has no slash in it
6701 // "http://www.example" -> "http://www.example/"
6702 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
6706 if ($url != "http:///")
6712 function validate_feed_url($url) {
6713 $parts = parse_url($url);
6715 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
6719 function get_article_enclosures($link, $id) {
6723 $query = "SELECT * FROM ttrss_enclosures
6724 WHERE post_id = '$id' AND content_url != ''";
6726 $obj_id = md5("ENCLOSURES:$id");
6730 if ($memcache && $obj = $memcache->get($obj_id)) {
6733 $result = db_query($link, $query);
6735 if (db_num_rows($result) > 0) {
6736 while ($line = db_fetch_assoc($result)) {
6737 array_push($rv, $line);
6739 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6746 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6752 if ($cat_id == -4 ||
$cat_id == -2) {
6753 $counters = getLabelCounters($link, true);
6755 foreach (array_values($counters) as $cv) {
6757 $unread = $cv["counter"];
6759 if ($unread ||
!$unread_only) {
6763 "title" => $cv["description"],
6764 "unread" => $cv["counter"],
6768 array_push($feeds, $row);
6775 if ($cat_id == -4 ||
$cat_id == -1) {
6776 foreach (array(-1, -2, -3, -4, 0) as $i) {
6777 $unread = getFeedUnread($link, $i);
6779 if ($unread ||
!$unread_only) {
6780 $title = getFeedTitle($link, $i);
6785 "unread" => $unread,
6788 array_push($feeds, $row);
6797 $limit_qpart = "LIMIT $limit OFFSET $offset";
6802 if ($cat_id == -4 ||
$cat_id == -3) {
6803 $result = db_query($link, "SELECT
6804 id, feed_url, cat_id, title, ".
6805 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6806 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6807 " ORDER BY cat_id, title " . $limit_qpart);
6811 $cat_qpart = "cat_id = '$cat_id'";
6813 $cat_qpart = "cat_id IS NULL";
6815 $result = db_query($link, "SELECT
6816 id, feed_url, cat_id, title, ".
6817 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
6818 FROM ttrss_feeds WHERE
6819 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6820 " ORDER BY cat_id, title " . $limit_qpart);
6823 while ($line = db_fetch_assoc($result)) {
6825 $unread = getFeedUnread($link, $line["id"]);
6827 $has_icon = feed_has_icon($line['id']);
6829 if ($unread ||
!$unread_only) {
6832 "feed_url" => $line["feed_url"],
6833 "title" => $line["title"],
6834 "id" => (int)$line["id"],
6835 "unread" => (int)$unread,
6836 "has_icon" => $has_icon,
6837 "cat_id" => (int)$line["cat_id"],
6838 "last_updated" => strtotime($line["last_updated"])
6841 array_push($feeds, $row);
6848 function api_get_headlines($link, $feed_id, $limit, $offset,
6849 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6850 $include_attachments, $since_id) {
6852 /* do not rely on params below */
6854 $search = db_escape_string($_REQUEST["search"]);
6855 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6856 $match_on = db_escape_string($_REQUEST["match_on"]);
6858 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6859 $view_mode, $is_cat, $search, $search_mode, $match_on,
6860 $order, $offset, 0, false, $since_id);
6862 $result = $qfh_ret[0];
6863 $feed_title = $qfh_ret[1];
6865 $headlines = array();
6867 while ($line = db_fetch_assoc($result)) {
6868 $is_updated = ($line["last_read"] == "" &&
6869 ($line["unread"] != "t" && $line["unread"] != "1"));
6871 $headline_row = array(
6872 "id" => (int)$line["id"],
6873 "unread" => sql_bool_to_bool($line["unread"]),
6874 "marked" => sql_bool_to_bool($line["marked"]),
6875 "published" => sql_bool_to_bool($line["published"]),
6876 "updated" => strtotime($line["updated"]),
6877 "is_updated" => $is_updated,
6878 "title" => $line["title"],
6879 "link" => $line["link"],
6880 "feed_id" => $line["feed_id"],
6881 "tags" => get_article_tags($link, $line["id"]),
6884 if ($include_attachments)
6885 $headline_row['attachments'] = get_article_enclosures($link,
6888 if ($show_excerpt) {
6889 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6890 $headline_row["excerpt"] = $excerpt;
6893 if ($show_content) {
6894 $headline_row["content"] = $line["content_preview"];
6897 array_push($headlines, $headline_row);
6903 function generate_error_feed($link, $error) {
6906 $reply['headlines']['id'] = -6;
6907 $reply['headlines']['is_cat'] = false;
6909 $reply['headlines']['toolbar'] = '';
6910 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6912 $reply['headlines-info'] = array("count" => 0,
6913 "vgroup_last_feed" => '',
6915 "disable_cache" => true);
6921 function generate_dashboard_feed($link) {
6924 $reply['headlines']['id'] = -5;
6925 $reply['headlines']['is_cat'] = false;
6927 $reply['headlines']['toolbar'] = '';
6928 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6930 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6932 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6933 WHERE owner_uid = " . $_SESSION['uid']);
6935 $last_updated = db_fetch_result($result, 0, "last_updated");
6936 $last_updated = make_local_datetime($link, $last_updated, false);
6938 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6940 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6941 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6943 $num_errors = db_fetch_result($result, 0, "num_errors");
6945 if ($num_errors > 0) {
6946 $reply['headlines']['content'] .= "<br/>";
6947 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6948 __('Some feeds have update errors (click for details)')."</a>";
6950 $reply['headlines']['content'] .= "</span></p>";
6952 $reply['headlines-info'] = array("count" => 0,
6953 "vgroup_last_feed" => '',
6955 "disable_cache" => true);
6960 function save_email_address($link, $email) {
6961 // FIXME: implement persistent storage of emails
6963 if (!$_SESSION['stored_emails'])
6964 $_SESSION['stored_emails'] = array();
6966 if (!in_array($email, $_SESSION['stored_emails']))
6967 array_push($_SESSION['stored_emails'], $email);
6970 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6971 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6973 $sql_is_cat = bool_to_sql_bool($is_cat);
6975 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6976 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6977 AND owner_uid = " . $owner_uid);
6979 if (db_num_rows($result) == 1) {
6980 $key = db_escape_string(sha1(uniqid(rand(), true)));
6982 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6983 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6984 AND owner_uid = " . $owner_uid);
6989 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6993 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6995 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6997 $sql_is_cat = bool_to_sql_bool($is_cat);
6999 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
7000 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
7001 AND owner_uid = " . $owner_uid);
7003 if (db_num_rows($result) == 1) {
7004 return db_fetch_result($result, 0, "access_key");
7006 $key = db_escape_string(sha1(uniqid(rand(), true)));
7008 $result = db_query($link, "INSERT INTO ttrss_access_keys
7009 (access_key, feed_id, is_cat, owner_uid)
7010 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
7018 * Extracts RSS/Atom feed URLs from the given HTML URL.
7020 * @param string $url HTML page URL
7022 * @return array Array of feeds. Key is the full URL, value the title
7024 function get_feeds_from_html($url, $login = false, $pass = false)
7026 $url = fix_url($url);
7027 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
7029 libxml_use_internal_errors(true);
7031 $content = @fetch_file_contents
($url, false, $login, $pass);
7033 $doc = new DOMDocument();
7034 $doc->loadHTML($content);
7035 $xpath = new DOMXPath($doc);
7036 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
7037 $feedUrls = array();
7038 foreach ($entries as $entry) {
7039 if ($entry->hasAttribute('href')) {
7040 $title = $entry->getAttribute('title');
7042 $title = $entry->getAttribute('type');
7044 $feedUrl = rewrite_relative_url(
7045 $baseUrl, $entry->getAttribute('href')
7047 $feedUrls[$feedUrl] = $title;
7054 * Checks if the content behind the given URL is a HTML file
7056 * @param string $url URL to check
7058 * @return boolean True if the URL contains HTML content
7060 function url_is_html($url, $login = false, $pass = false) {
7061 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
7063 if (stripos($content, '<html>') === false
7064 && stripos($content, '<html ') === false
7072 function print_label_select($link, $name, $value, $attributes = "") {
7074 $result = db_query($link, "SELECT caption FROM ttrss_labels2
7075 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
7077 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
7078 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
7080 while ($line = db_fetch_assoc($result)) {
7082 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
7084 print "<option value=\"".htmlspecialchars($line["caption"])."\"
7085 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
7089 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
7096 function format_article_enclosures($link, $id, $always_display_enclosures,
7099 $result = get_article_enclosures($link, $id);
7102 if (count($result) > 0) {
7104 $entries_html = array();
7107 foreach ($result as $line) {
7109 $url = $line["content_url"];
7110 $ctype = $line["content_type"];
7112 if (!$ctype) $ctype = __("unknown type");
7114 # $filename = substr($url, strrpos($url, "/")+1);
7116 $entry = format_inline_player($link, $url, $ctype);
7118 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
7119 # $filename . " (" . $ctype . ")" . "</a>";
7121 array_push($entries_html, $entry);
7125 $entry["type"] = $ctype;
7126 $entry["filename"] = $filename;
7127 $entry["url"] = $url;
7129 array_push($entries, $entry);
7132 $rv .= "<div class=\"postEnclosures\">";
7134 if (!get_pref($link, "STRIP_IMAGES")) {
7135 if ($always_display_enclosures ||
7136 !preg_match("/<img/i", $article_content)) {
7138 foreach ($entries as $entry) {
7140 if (preg_match("/image/", $entry["type"]) ||
7141 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
7144 alt=\"".htmlspecialchars($entry["filename"])."\"
7145 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7151 if (count($entries) == 1) {
7152 $rv .= __("Attachment:") . " ";
7154 $rv .= __("Attachments:") . " ";
7157 $rv .= join(", ", $entries_html);
7165 function getLastArticleId($link) {
7166 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7167 WHERE owner_uid = " . $_SESSION["uid"]);
7169 if (db_num_rows($result) == 1) {
7170 return db_fetch_result($result, 0, "id");
7176 function build_url($parts) {
7177 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7181 * Converts a (possibly) relative URL to a absolute one.
7183 * @param string $url Base URL (i.e. from where the document is)
7184 * @param string $rel_url Possibly relative URL in the document
7186 * @return string Absolute URL
7188 function rewrite_relative_url($url, $rel_url) {
7189 if (strpos($rel_url, "://") !== false) {
7191 } else if (strpos($rel_url, "/") === 0)
7193 $parts = parse_url($url);
7194 $parts['path'] = $rel_url;
7196 return build_url($parts);
7199 $parts = parse_url($url);
7200 if (!isset($parts['path'])) {
7201 $parts['path'] = '/';
7203 $dir = $parts['path'];
7204 if (substr($dir, -1) !== '/') {
7205 $dir = dirname($parts['path']);
7206 $dir !== '/' && $dir .= '/';
7208 $parts['path'] = $dir . $rel_url;
7210 return build_url($parts);
7214 function sphinx_search($query, $offset = 0, $limit = 30) {
7215 $sphinxClient = new SphinxClient();
7217 $sphinxClient->SetServer('localhost', 9312);
7218 $sphinxClient->SetConnectTimeout(1);
7220 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7221 'feed_title' => 20));
7223 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
7224 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
7225 $sphinxClient->SetLimits($offset, $limit, 1000);
7226 $sphinxClient->SetArrayResult(false);
7227 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7229 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
7233 if (is_array($result['matches'])) {
7234 foreach (array_keys($result['matches']) as $int_id) {
7235 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7236 array_push($ids, $ref_id);
7243 function cleanup_tags($link, $days = 14, $limit = 1000) {
7245 if (DB_TYPE
== "pgsql") {
7246 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7247 } else if (DB_TYPE
== "mysql") {
7248 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7253 while ($limit > 0) {
7256 $query = "SELECT ttrss_tags.id AS id
7257 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7258 WHERE post_int_id = int_id AND $interval_query AND
7259 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7261 $result = db_query($link, $query);
7265 while ($line = db_fetch_assoc($result)) {
7266 array_push($ids, $line['id']);
7269 if (count($ids) > 0) {
7270 $ids = join(",", $ids);
7273 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7274 $tags_deleted +
= db_affected_rows($link, $tmp_result);
7279 $limit -= $limit_part;
7284 return $tags_deleted;
7287 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7289 $cat_id = (int) $cat_id;
7292 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7293 } else if ($cat_id == 0 ||
$cat_id == -2) {
7294 $cat_unread = getCategoryUnread($link, $cat_id);
7297 $obj['id'] = 'CAT:' . $cat_id;
7298 $obj['items'] = array();
7299 $obj['name'] = getCategoryTitle($link, $cat_id);
7300 $obj['type'] = 'feed';
7301 $obj['unread'] = (int) $cat_unread;
7302 $obj['hidden'] = $hidden;
7303 $obj['bare_id'] = $cat_id;
7308 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7310 $feed_id = (int) $feed_id;
7313 $title = getFeedTitle($link, $feed_id, false);
7315 if ($unread === false)
7316 $unread = getFeedUnread($link, $feed_id, false);
7318 $obj['id'] = 'FEED:' . $feed_id;
7319 $obj['name'] = $title;
7320 $obj['unread'] = (int) $unread;
7321 $obj['type'] = 'feed';
7322 $obj['error'] = $error;
7323 $obj['updated'] = $updated;
7324 $obj['icon'] = getFeedIcon($feed_id);
7325 $obj['bare_id'] = $feed_id;
7331 function fetch_twitter_rss($link, $url, $owner_uid) {
7332 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7333 WHERE id = $owner_uid");
7335 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7336 $url_escaped = db_escape_string($url);
7338 if ($access_token) {
7340 $tmhOAuth = new tmhOAuth(array(
7341 'consumer_key' => CONSUMER_KEY
,
7342 'consumer_secret' => CONSUMER_SECRET
,
7343 'user_token' => $access_token['oauth_token'],
7344 'user_secret' => $access_token['oauth_token_secret'],
7347 $code = $tmhOAuth->request('GET', $url);
7351 $content = $tmhOAuth->response
['response'];
7353 define('MAGPIE_CACHE_ON', false);
7355 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING
,
7356 MAGPIE_INPUT_ENCODING
, MAGPIE_DETECT_ENCODING
);
7362 db_query($link, "UPDATE ttrss_feeds
7363 SET last_error = 'OAuth authorization failed ($code).'
7364 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7369 db_query($link, "UPDATE ttrss_feeds
7370 SET last_error = 'OAuth information not found.'
7371 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7377 function print_user_stylesheet($link) {
7378 $value = get_pref($link, 'USER_STYLESHEET');
7381 print "<style type=\"text/css\">";
7382 print str_replace("<br/>", "\n", $value);
7388 function rewrite_urls($line) {
7393 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7394 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7399 function filter_to_sql($filter) {
7402 if (DB_TYPE
== "pgsql")
7405 $reg_qpart = "REGEXP";
7407 switch ($filter["type"]) {
7409 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7410 $filter['reg_exp'] . "')";
7413 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7414 $filter['reg_exp'] . "')";
7417 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7418 $filter['reg_exp'] . "') OR LOWER(" .
7419 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7422 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7423 $filter['reg_exp'] . "')";
7426 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7427 $filter['reg_exp'] . "')";
7431 if ($filter["filter_param"] == "before")
7436 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7437 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7440 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7441 $filter['reg_exp'] . "')";
7445 if ($filter["inverse"])
7446 $query = "NOT ($query)";
7449 if (DB_TYPE
== "pgsql") {
7450 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
7452 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
7462 // -1 - never connected
7463 // 0 - no data received
7464 // 1 - data received successfully
7465 // 2 - did not receive valid data
7466 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7468 function get_linked_feeds($link, $instance_id = false) {
7470 $instance_qpart = "id = '$instance_id' AND ";
7472 $instance_qpart = "";
7474 if (DB_TYPE
== "pgsql") {
7475 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
7477 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
7480 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7481 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7483 while ($line = db_fetch_assoc($result)) {
7486 _debug("Updating: " . $line['access_url'] . " ($id)");
7488 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7489 $post_query = 'key=' . $line['access_key'];
7491 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7494 $feeds = json_decode($feeds, true);
7497 if ($feeds['error']) {
7498 $status = $feeds['error']['code'] +
10;
7502 if (count($feeds['feeds']) > 0) {
7504 db_query($link, "DELETE FROM ttrss_linked_feeds
7505 WHERE instance_id = '$id'");
7507 foreach ($feeds['feeds'] as $feed) {
7508 $feed_url = db_escape_string($feed['feed_url']);
7509 $title = db_escape_string($feed['title']);
7510 $subscribers = db_escape_string($feed['subscribers']);
7511 $site_url = db_escape_string($feed['site_url']);
7513 db_query($link, "INSERT INTO ttrss_linked_feeds
7514 (feed_url, site_url, title, subscribers, instance_id, created, updated)
7516 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
7519 // received 0 feeds, this might indicate that
7520 // the instance on the other hand is rebuilding feedbrowser cache
7521 // we will try again later
7523 // TODO: maybe perform expiration based on updated here?
7526 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7536 _debug("Status: $status");
7538 db_query($link, "UPDATE ttrss_linked_instances SET
7539 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");