3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 function get_translations() {
13 "auto" => "Detect automatically",
15 "fr_FR" => "Français",
17 "zh_CN" => "Simplified Chinese");
22 if (ENABLE_TRANSLATIONS
== true) {
23 require_once "accept-to-gettext.php";
24 require_once "gettext/gettext.inc";
26 function startup_gettext() {
28 # Get locale from Accept-Language header
29 $lang = al2gt(array_keys(get_translations()), "text/html");
31 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
32 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
35 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
36 $lang = $_COOKIE["ttrss_lang"];
40 _setlocale(LC_MESSAGES
, $lang);
41 _bindtextdomain("messages", "locale");
42 _textdomain("messages");
43 _bind_textdomain_codeset("messages", "UTF-8");
53 function startup_gettext() {
59 require_once 'db-prefs.php';
60 require_once 'compat.php';
61 require_once 'errors.php';
62 require_once 'version.php';
64 require_once 'phpmailer/class.phpmailer.php';
66 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
67 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
69 if (ENABLE_SIMPLEPIE
) {
70 require_once "simplepie/simplepie.inc";
72 require_once "magpierss/rss_fetch.inc";
73 require_once 'magpierss/rss_utils.inc';
76 include_once "tw/tw-config.php";
77 include_once "tw/tw.php";
78 include_once TW_SETUP
. "paranoya.php";
80 $tw_parser = new twParser();
82 function _debug($msg) {
83 $ts = strftime("%H:%M:%S", time());
87 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
91 if (DB_TYPE
== "pgsql") {
92 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
93 marked = false AND feed_id = '$feed_id' AND
94 (SELECT date_entered FROM ttrss_entries WHERE
95 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
97 $pg_version = get_pgsql_version($link);
99 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
101 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
102 ttrss_entries.id = ref_id AND
104 feed_id = '$feed_id' AND
105 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
109 $result = db_query($link, "DELETE FROM ttrss_user_entries
111 WHERE ttrss_entries.id = ref_id AND
113 feed_id = '$feed_id' AND
114 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
117 $rows = pg_affected_rows($result);
121 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
122 marked = false AND feed_id = '$feed_id' AND
123 (SELECT date_entered FROM ttrss_entries WHERE
124 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
126 $result = db_query($link, "DELETE FROM ttrss_user_entries
127 USING ttrss_user_entries, ttrss_entries
128 WHERE ttrss_entries.id = ref_id AND
130 feed_id = '$feed_id' AND
131 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
133 $rows = mysql_affected_rows($link);
138 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
142 function global_purge_old_posts($link, $do_output = false, $limit = false) {
144 $random_qpart = sql_random_function();
147 $limit_qpart = "LIMIT $limit";
152 $result = db_query($link,
153 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
154 ORDER BY $random_qpart $limit_qpart");
156 while ($line = db_fetch_assoc($result)) {
158 $feed_id = $line["id"];
159 $purge_interval = $line["purge_interval"];
160 $owner_uid = $line["owner_uid"];
162 if ($purge_interval == 0) {
164 $tmp_result = db_query($link,
165 "SELECT value FROM ttrss_user_prefs WHERE
166 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
168 if (db_num_rows($tmp_result) != 0) {
169 $purge_interval = db_fetch_result($tmp_result, 0, "value");
174 // print "Feed $feed_id: purge interval = $purge_interval\n";
177 if ($purge_interval > 0) {
178 purge_feed($link, $feed_id, $purge_interval, $do_output);
182 // purge orphaned posts in main content table
183 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
184 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
187 $rows = db_affected_rows($link, $result);
188 _debug("Purged $rows orphaned posts.");
193 function purge_old_posts($link) {
195 $user_id = $_SESSION["uid"];
197 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
198 WHERE owner_uid = '$user_id'");
200 while ($line = db_fetch_assoc($result)) {
202 $feed_id = $line["id"];
203 $purge_interval = $line["purge_interval"];
205 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
207 if ($purge_interval > 0) {
208 purge_feed($link, $feed_id, $purge_interval);
212 // purge orphaned posts in main content table
213 db_query($link, "DELETE FROM ttrss_entries WHERE
214 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
217 function get_feed_update_interval($link, $feed_id) {
218 $result = db_query($link, "SELECT owner_uid, update_interval FROM
219 ttrss_feeds WHERE id = '$feed_id'");
221 if (db_num_rows($result) == 1) {
222 $update_interval = db_fetch_result($result, 0, "update_interval");
223 $owner_uid = db_fetch_result($result, 0, "owner_uid");
225 if ($update_interval != 0) {
226 return $update_interval;
228 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
236 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
238 if (WEB_DEMO_MODE
) return;
241 $user_id = $_SESSION["uid"];
242 purge_old_posts($link);
245 // db_query($link, "BEGIN");
247 if (MAX_UPDATE_TIME
> 0) {
248 if (DB_TYPE
== "mysql") {
251 $q_order = "RANDOM()";
254 $q_order = "last_updated DESC";
257 $result = db_query($link, "SELECT feed_url,id,
258 SUBSTRING(last_updated,1,19) AS last_updated,
259 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
264 while ($line = db_fetch_assoc($result)) {
265 $upd_intl = $line["update_interval"];
267 if (!$upd_intl ||
$upd_intl == 0) {
268 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
272 // Updates for this feed are disabled
276 if ($fetch ||
(!$line["last_updated"] ||
277 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
279 // print "<!-- feed: ".$line["feed_url"]." -->";
281 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
283 $upd_elapsed = time() - $upd_start;
285 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
291 // db_query($link, "COMMIT");
295 function fetch_file_contents($url) {
296 if (USE_CURL_FOR_ICONS
) {
297 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
299 $ch = curl_init($url);
300 $fp = fopen($tmpfile, "w");
303 curl_setopt($ch, CURLOPT_FILE
, $fp);
304 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
305 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
311 $contents = file_get_contents($tmpfile);
317 return file_get_contents($url);
322 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
323 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
325 function get_favicon_url($url) {
327 if ($html = @fetch_file_contents
($url)) {
329 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
330 // Attempt to grab a favicon link from their webpage url
331 $linkUrl = html_entity_decode($matches[1]);
333 if (substr($linkUrl, 0, 1) == '/') {
334 $urlParts = parse_url($url);
335 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
336 } else if (substr($linkUrl, 0, 7) == 'http://') {
337 $faviconURL = $linkUrl;
338 } else if (substr($url, -1, 1) == '/') {
339 $faviconURL = $url.$linkUrl;
341 $faviconURL = $url.'/'.$linkUrl;
345 // If unsuccessful, attempt to "guess" the favicon location
346 $urlParts = parse_url($url);
347 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
351 // Run a test to see if what we have attempted to get actually exists.
352 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
359 function url_validate($link) {
361 $url_parts = @parse_url
($link);
363 if ( empty( $url_parts["host"] ) )
366 if ( !empty( $url_parts["path"] ) ) {
367 $documentpath = $url_parts["path"];
372 if ( !empty( $url_parts["query"] ) )
373 $documentpath .= "?" . $url_parts["query"];
375 $host = $url_parts["host"];
376 $port = $url_parts["port"];
381 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
386 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
388 $http_response = fgets( $socket, 22 );
390 $responses = "/(200 OK)|(30[0-9] Moved)/";
391 if ( preg_match($responses, $http_response) ) {
400 function check_feed_favicon($site_url, $feed, $link) {
401 $favicon_url = get_favicon_url($site_url);
403 # print "FAVICON [$site_url]: $favicon_url\n";
407 $icon_file = ICONS_DIR
. "/$feed.ico";
409 if ($favicon_url && !file_exists($icon_file)) {
410 $contents = fetch_file_contents($favicon_url);
412 $fp = fopen($icon_file, "w");
415 fwrite($fp, $contents);
417 chmod($icon_file, 0644);
421 error_reporting(DEFAULT_ERROR_LEVEL
);
425 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
427 if (!$_GET["daemon"] && !$ignore_daemon) {
431 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
432 _debug("update_rss_feed: start");
435 $result = db_query($link, "SELECT id,update_interval,auth_login,auth_pass,cache_images
436 FROM ttrss_feeds WHERE id = '$feed'");
438 if (db_num_rows($result) == 0) {
439 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
440 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND");
445 $auth_login = db_fetch_result($result, 0, "auth_login");
446 $auth_pass = db_fetch_result($result, 0, "auth_pass");
448 if (!ENABLE_SIMPLEPIE
) {
449 $auth_login = urlencode($auth_login);
450 $auth_pass = urlencode($auth_pass);
453 $update_interval = db_fetch_result($result, 0, "update_interval");
454 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
456 if ($update_interval < 0) { return; }
458 $feed = db_escape_string($feed);
460 $fetch_url = $feed_url;
462 if ($auth_login && $auth_pass) {
463 $url_parts = array();
464 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
466 if ($url_parts[1] && $url_parts[2]) {
467 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
472 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
473 _debug("update_rss_feed: fetching [$fetch_url]...");
476 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
480 if (!ENABLE_SIMPLEPIE
) {
481 $rss = fetch_rss($fetch_url);
483 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
484 mkdir(SIMPLEPIE_CACHE_DIR
);
487 $rss = new SimplePie();
488 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
489 $rss->set_timeout(MAGPIE_FETCH_TIME_OUT
);
490 $rss->set_feed_url($fetch_url);
491 $rss->set_output_encoding('UTF-8');
493 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
494 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
495 _debug("enabling image cache");
498 $rss->set_image_handler('./image.php', 'i');
501 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
502 _debug("feed update interval (sec): " .
503 get_feed_update_interval($link, $feed)*60);
506 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
507 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
508 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
516 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
517 _debug("update_rss_feed: fetch done, parsing...");
519 error_reporting (DEFAULT_ERROR_LEVEL
);
522 $feed = db_escape_string($feed);
524 if (ENABLE_SIMPLEPIE
) {
525 $fetch_ok = !$rss->error();
532 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
533 _debug("update_rss_feed: processing feed data...");
536 // db_query($link, "BEGIN");
538 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
539 FROM ttrss_feeds WHERE id = '$feed'");
541 $registered_title = db_fetch_result($result, 0, "title");
542 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
543 $orig_site_url = db_fetch_result($result, 0, "site_url");
545 $owner_uid = db_fetch_result($result, 0, "owner_uid");
547 if (ENABLE_SIMPLEPIE
) {
548 $site_url = $rss->get_link();
550 $site_url = $rss->channel
["link"];
553 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
554 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
555 _debug("update_rss_feed: checking favicon...");
558 check_feed_favicon($site_url, $feed, $link);
561 if (!$registered_title ||
$registered_title == "[Unknown]") {
563 if (ENABLE_SIMPLEPIE
) {
564 $feed_title = db_escape_string($rss->get_title());
566 $feed_title = db_escape_string($rss->channel
["title"]);
569 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
570 _debug("update_rss_feed: registering title: $feed_title");
573 db_query($link, "UPDATE ttrss_feeds SET
574 title = '$feed_title' WHERE id = '$feed'");
577 // weird, weird Magpie
578 if (!ENABLE_SIMPLEPIE
) {
579 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
582 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
583 db_query($link, "UPDATE ttrss_feeds SET
584 site_url = '$site_url' WHERE id = '$feed'");
587 // print "I: " . $rss->channel["image"]["url"];
589 if (!ENABLE_SIMPLEPIE
) {
590 $icon_url = $rss->image
["url"];
592 $icon_url = $rss->get_image_url();
595 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
596 $icon_url = db_escape_string($icon_url);
597 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
600 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
601 _debug("update_rss_feed: loading filters...");
606 $result = db_query($link, "SELECT reg_exp,
607 ttrss_filter_types.name AS name,
608 ttrss_filter_actions.name AS action,
611 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
613 owner_uid = $owner_uid AND
614 ttrss_filter_types.id = filter_type AND
615 ttrss_filter_actions.id = action_id AND
616 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
618 while ($line = db_fetch_assoc($result)) {
619 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
621 $filter["reg_exp"] = $line["reg_exp"];
622 $filter["action"] = $line["action"];
623 $filter["action_param"] = $line["action_param"];
624 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
626 array_push($filters[$line["name"]], $filter);
629 if (ENABLE_SIMPLEPIE
) {
630 $iterator = $rss->get_items();
632 $iterator = $rss->items
;
633 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
634 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
637 if (!is_array($iterator)) {
638 /* db_query($link, "UPDATE ttrss_feeds
639 SET last_error = 'Parse error: can\'t find any articles.'
640 WHERE id = '$feed'"); */
642 // clear any errors and mark feed as updated if fetched okay
643 // even if it's blank
645 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
646 _debug("update_rss_feed: entry iterator is not an array, no articles?");
649 db_query($link, "UPDATE ttrss_feeds
650 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
652 return; // no articles
655 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
656 _debug("update_rss_feed: processing articles...");
659 foreach ($iterator as $item) {
661 if (ENABLE_SIMPLEPIE
) {
662 $entry_guid = $item->get_id();
663 if (!$entry_guid) $entry_guid = $item->get_link();
664 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
668 $entry_guid = $item["id"];
670 if (!$entry_guid) $entry_guid = $item["guid"];
671 if (!$entry_guid) $entry_guid = $item["link"];
672 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
675 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
676 _debug("update_rss_feed: guid $entry_guid");
679 if (!$entry_guid) continue;
681 $entry_timestamp = "";
683 if (ENABLE_SIMPLEPIE
) {
684 $entry_timestamp = strtotime($item->get_date());
686 $rss_2_date = $item['pubdate'];
687 $rss_1_date = $item['dc']['date'];
688 $atom_date = $item['issued'];
689 if (!$atom_date) $atom_date = $item['updated'];
691 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
692 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
693 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
696 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
697 _debug("update_rss_feed: date $entry_timestamp");
700 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
701 $entry_timestamp = time();
702 $no_orig_date = 'true';
704 $no_orig_date = 'false';
707 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
709 if (ENABLE_SIMPLEPIE
) {
710 $entry_title = $item->get_title();
712 $entry_title = trim(strip_tags($item["title"]));
715 if (ENABLE_SIMPLEPIE
) {
716 $entry_link = $item->get_link();
718 // strange Magpie workaround
719 $entry_link = $item["link_"];
720 if (!$entry_link) $entry_link = $item["link"];
723 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
724 _debug("update_rss_feed: title $entry_title");
727 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
729 $entry_link = strip_tags($entry_link);
731 if (ENABLE_SIMPLEPIE
) {
732 $entry_content = $item->get_description();
734 $entry_content = $item["content:escaped"];
736 if (!$entry_content) $entry_content = $item["content:encoded"];
737 if (!$entry_content) $entry_content = $item["content"];
738 if (!$entry_content) $entry_content = $item["atom_content"];
739 if (!$entry_content) $entry_content = $item["summary"];
740 if (!$entry_content) $entry_content = $item["description"];
743 if (is_array($entry_content)) {
744 $entry_content = $entry_content["encoded"];
745 if (!$entry_content) $entry_content = $entry_content["escaped"];
750 // print_r(htmlspecialchars($entry_content));
753 $entry_content_unescaped = $entry_content;
755 if (ENABLE_SIMPLEPIE
) {
756 $entry_comments = strip_tags($item->data
["comments"]);
757 if ($item->get_author()) {
758 $entry_author_item = $item->get_author();
759 $entry_author = $entry_author_item->get_name();
762 $entry_comments = strip_tags($item["comments"]);
764 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
766 if ($item['author']) {
768 if (is_array($item['author'])) {
770 if (!$entry_author) {
771 $entry_author = db_escape_string(strip_tags($item['author']['name']));
774 if (!$entry_author) {
775 $entry_author = db_escape_string(strip_tags($item['author']['email']));
779 if (!$entry_author) {
780 $entry_author = db_escape_string(strip_tags($item['author']));
785 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
787 $entry_guid = db_escape_string(strip_tags($entry_guid));
789 $result = db_query($link, "SELECT id FROM ttrss_entries
790 WHERE guid = '$entry_guid'");
792 $entry_content = db_escape_string($entry_content);
794 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
796 $entry_title = db_escape_string($entry_title);
797 $entry_link = db_escape_string($entry_link);
798 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
799 $entry_author = mb_substr($entry_author, 0, 250);
801 if (ENABLE_SIMPLEPIE
) {
802 $num_comments = 0; #FIXME#
804 $num_comments = db_escape_string($item["slash"]["comments"]);
807 if (!$num_comments) $num_comments = 0;
809 // parse <category> entries into tags
811 if (ENABLE_SIMPLEPIE
) {
813 $additional_tags = array();
814 $additional_tags_src = $item->get_categories();
816 if (is_array($additional_tags_src)) {
817 foreach ($additional_tags_src as $tobj) {
818 array_push($additional_tags, $tobj->get_term());
822 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
823 _debug("update_rss_feed: category tags:");
824 print_r($additional_tags);
829 $t_ctr = $item['category#'];
831 $additional_tags = false;
834 $additional_tags = false;
835 } else if ($t_ctr == 1) {
836 $additional_tags = array($item['category']);
838 $additional_tags = array();
839 for ($i = 0; $i <= $t_ctr; $i++
) {
840 if ($item["category#$i"]) {
841 array_push($additional_tags, $item["category#$i"]);
846 // parse <dc:subject> elements
848 $t_ctr = $item['dc']['subject#'];
851 $additional_tags = array($item['dc']['subject']);
852 } else if ($t_ctr > 1) {
853 $additional_tags = array();
854 for ($i = 0; $i <= $t_ctr; $i++
) {
855 if ($item['dc']["subject#$i"]) {
856 array_push($additional_tags, $item['dc']["subject#$i"]);
864 // $entry_content = sanitize_rss($entry_content);
866 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
867 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
870 db_query($link, "BEGIN");
872 if (db_num_rows($result) == 0) {
874 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
875 _debug("update_rss_feed: base guid not found");
878 // base post entry does not exist, create it
880 $result = db_query($link,
881 "INSERT INTO ttrss_entries
897 '$entry_timestamp_fmt',
906 // we keep encountering the entry in feeds, so we need to
907 // update date_entered column so that we don't get horrible
908 // dupes when the entry gets purged and reinserted again e.g.
909 // in the case of SLOW SLOW OMG SLOW updating feeds
911 $base_entry_id = db_fetch_result($result, 0, "id");
913 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
914 WHERE id = '$base_entry_id'");
917 // now it should exist, if not - bad luck then
919 $result = db_query($link, "SELECT
920 id,content_hash,no_orig_date,title,
921 substring(date_entered,1,19) as date_entered,
922 substring(updated,1,19) as updated,
926 WHERE guid = '$entry_guid'");
928 if (db_num_rows($result) == 1) {
930 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
931 _debug("update_rss_feed: base guid found, checking for user record");
934 // this will be used below in update handler
935 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
936 $orig_title = db_fetch_result($result, 0, "title");
937 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
938 $orig_date_entered = strtotime(db_fetch_result($result,
941 $ref_id = db_fetch_result($result, 0, "id");
943 // check for user post link to main table
945 // do we allow duplicate posts with same GUID in different feeds?
946 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
947 $dupcheck_qpart = "AND feed_id = '$feed'";
949 $dupcheck_qpart = "";
952 // error_reporting(0);
954 $article_filters = get_article_filters($filters, $entry_title,
955 $entry_content, $entry_link);
957 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
958 _debug("update_rss_feed: article filters: ");
959 if (count($article_filters) != 0) {
960 print_r($article_filters);
964 if (find_article_filter($article_filters, "filter")) {
968 // error_reporting (DEFAULT_ERROR_LEVEL);
970 $result = db_query($link,
971 "SELECT ref_id FROM ttrss_user_entries WHERE
972 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
975 // okay it doesn't exist - create user entry
976 if (db_num_rows($result) == 0) {
978 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
979 _debug("update_rss_feed: user record not found, creating...");
982 if (!find_article_filter($article_filters, 'catchup')) {
984 $last_read_qpart = 'NULL';
987 $last_read_qpart = 'NOW()';
990 if (find_article_filter($article_filters, 'mark')) {
996 if (find_article_filter($article_filters, 'publish')) {
999 $published = 'false';
1002 $result = db_query($link,
1003 "INSERT INTO ttrss_user_entries
1004 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
1005 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1006 $last_read_qpart, $marked, $published)");
1009 $post_needs_update = false;
1011 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1012 ($content_hash != $orig_content_hash)) {
1013 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1014 $post_needs_update = true;
1017 if (db_escape_string($orig_title) != $entry_title) {
1018 $post_needs_update = true;
1021 if ($orig_num_comments != $num_comments) {
1022 $post_needs_update = true;
1025 // this doesn't seem to be very reliable
1027 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1028 // $post_needs_update = true;
1031 // if post needs update, update it and mark all user entries
1032 // linking to this post as updated
1033 if ($post_needs_update) {
1035 if (defined('DAEMON_EXTENDED_DEBUG')) {
1036 _debug("update_rss_feed: post $entry_guid needs update...");
1039 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1041 db_query($link, "UPDATE ttrss_entries
1042 SET title = '$entry_title', content = '$entry_content',
1043 content_hash = '$content_hash',
1044 num_comments = '$num_comments'
1045 WHERE id = '$ref_id'");
1047 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1048 db_query($link, "UPDATE ttrss_user_entries
1049 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1051 db_query($link, "UPDATE ttrss_user_entries
1052 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1058 db_query($link, "COMMIT");
1060 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1061 _debug("update_rss_feed: looking for tags...");
1065 // <a href="..." rel="tag">Xorg</a>, //
1069 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1070 $entry_content_unescaped, $entry_tags);
1072 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1073 print_r($entry_tags);
1074 print "<br/></p>"; */
1076 $entry_tags = $entry_tags[1];
1078 # check for manual tags
1080 $tag_filter = find_article_filter($article_filters, "tag");
1084 $manual_tags = trim_array(split(",", $tag_filter[1]));
1086 foreach ($manual_tags as $tag) {
1087 if (tag_is_valid($tag)) {
1088 array_push($entry_tags, $tag);
1093 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1094 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1096 if ($additional_tags && is_array($additional_tags)) {
1097 foreach ($additional_tags as $tag) {
1098 if (tag_is_valid($tag) &&
1099 array_search($tag, $boring_tags) === FALSE) {
1100 array_push($entry_tags, $tag);
1105 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1107 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1108 print_r($entry_tags);
1111 if (count($entry_tags) > 0) {
1113 db_query($link, "BEGIN");
1115 $result = db_query($link, "SELECT id,int_id
1116 FROM ttrss_entries,ttrss_user_entries
1117 WHERE guid = '$entry_guid'
1118 AND feed_id = '$feed' AND ref_id = id
1119 AND owner_uid = '$owner_uid'");
1121 if (db_num_rows($result) == 1) {
1123 $entry_id = db_fetch_result($result, 0, "id");
1124 $entry_int_id = db_fetch_result($result, 0, "int_id");
1126 foreach ($entry_tags as $tag) {
1128 $tag = sanitize_tag($tag);
1129 $tag = db_escape_string($tag);
1131 if (!tag_is_valid($tag)) continue;
1133 $result = db_query($link, "SELECT id FROM ttrss_tags
1134 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1135 owner_uid = '$owner_uid' LIMIT 1");
1137 // print db_fetch_result($result, 0, "id");
1139 if ($result && db_num_rows($result) == 0) {
1141 db_query($link, "INSERT INTO ttrss_tags
1142 (owner_uid,tag_name,post_int_id)
1143 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1147 db_query($link, "COMMIT");
1150 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1151 _debug("update_rss_feed: article processed");
1155 db_query($link, "UPDATE ttrss_feeds
1156 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1158 // db_query($link, "COMMIT");
1162 if (ENABLE_SIMPLEPIE
) {
1163 $error_msg = mb_substr($rss->error(), 0, 250);
1165 $error_msg = mb_substr(magpie_error(), 0, 250);
1168 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1169 _debug("update_rss_feed: error fetching feed: $error_msg");
1172 $error_msg = db_escape_string($error_msg);
1175 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1176 last_updated = NOW() WHERE id = '$feed'");
1179 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1180 _debug("update_rss_feed: done");
1185 function print_select($id, $default, $values, $attributes = "") {
1186 print "<select name=\"$id\" id=\"$id\" $attributes>";
1187 foreach ($values as $v) {
1193 print "<option$sel>$v</option>";
1198 function print_select_hash($id, $default, $values, $attributes = "") {
1199 print "<select name=\"$id\" id='$id' $attributes>";
1200 foreach (array_keys($values) as $v) {
1206 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1212 function get_article_filters($filters, $title, $content, $link) {
1215 if ($filters["title"]) {
1216 foreach ($filters["title"] as $filter) {
1217 $reg_exp = $filter["reg_exp"];
1218 $inverse = $filter["inverse"];
1219 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1220 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1222 array_push($matches, array($filter["action"], $filter["action_param"]));
1227 if ($filters["content"]) {
1228 foreach ($filters["content"] as $filter) {
1229 $reg_exp = $filter["reg_exp"];
1230 $inverse = $filter["inverse"];
1232 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1233 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1235 array_push($matches, array($filter["action"], $filter["action_param"]));
1240 if ($filters["both"]) {
1241 foreach ($filters["both"] as $filter) {
1242 $reg_exp = $filter["reg_exp"];
1243 $inverse = $filter["inverse"];
1246 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1247 array_push($matches, array($filter["action"], $filter["action_param"]));
1250 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1251 array_push($matches, array($filter["action"], $filter["action_param"]));
1257 if ($filters["link"]) {
1258 $reg_exp = $filter["reg_exp"];
1259 foreach ($filters["link"] as $filter) {
1260 $reg_exp = $filter["reg_exp"];
1261 $inverse = $filter["inverse"];
1263 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1264 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1266 array_push($matches, array($filter["action"], $filter["action_param"]));
1274 function find_article_filter($filters, $filter_name) {
1275 foreach ($filters as $f) {
1276 if ($f[0] == $filter_name) {
1283 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1284 $rtl_content = false, $last_updated = false, $last_error = false) {
1286 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1287 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1289 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1293 $rtl_tag = "dir=\"rtl\"";
1295 $rtl_tag = "dir=\"ltr\"";
1298 $error_notify_msg = "";
1301 $link_title = "Error: $last_error ($last_updated)";
1302 $error_notify_msg = "(Error)";
1303 } else if ($last_updated) {
1304 $link_title = "Updated: $last_updated";
1307 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1308 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1310 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1311 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1315 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1320 $fctr_class = "class=\"invisible\"";
1323 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1324 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1326 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1327 print "<div class=\"feedExtInfo\">
1328 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1335 function getmicrotime() {
1336 list($usec, $sec) = explode(" ",microtime());
1337 return ((float)$usec +
(float)$sec);
1340 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1341 foreach ($values as $v) {
1348 if ($v == $true_is) {
1349 $sel .= " value=\"1\"";
1351 $sel .= " value=\"0\"";
1354 print "<input class=\"noborder\"
1355 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1360 function initialize_user_prefs($link, $uid) {
1362 $uid = db_escape_string($uid);
1364 db_query($link, "BEGIN");
1366 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1368 $u_result = db_query($link, "SELECT pref_name
1369 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1371 $active_prefs = array();
1373 while ($line = db_fetch_assoc($u_result)) {
1374 array_push($active_prefs, $line["pref_name"]);
1377 while ($line = db_fetch_assoc($result)) {
1378 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1379 // print "adding " . $line["pref_name"] . "<br>";
1381 db_query($link, "INSERT INTO ttrss_user_prefs
1382 (owner_uid,pref_name,value) VALUES
1383 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1388 db_query($link, "COMMIT");
1392 function lookup_user_id($link, $user) {
1394 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1397 if (db_num_rows($result) == 1) {
1398 return db_fetch_result($result, 0, "id");
1404 function http_authenticate_user($link) {
1406 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1408 if (!$_SERVER["PHP_AUTH_USER"]) {
1410 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1411 header('HTTP/1.0 401 Unauthorized');
1415 $auth_result = authenticate_user($link,
1416 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1418 if (!$auth_result) {
1419 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1420 header('HTTP/1.0 401 Unauthorized');
1428 function authenticate_user($link, $login, $password, $force_auth = false) {
1430 if (!SINGLE_USER_MODE
) {
1432 $pwd_hash1 = encrypt_password($password);
1433 $pwd_hash2 = encrypt_password($password, $login);
1435 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1436 $query = "SELECT id,login,access_level
1437 FROM ttrss_users WHERE
1440 $query = "SELECT id,login,access_level,pwd_hash
1441 FROM ttrss_users WHERE
1442 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1443 pwd_hash = '$pwd_hash2')";
1446 $result = db_query($link, $query);
1448 if (db_num_rows($result) == 1) {
1449 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1450 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1451 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1453 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1456 $user_theme = get_user_theme_path($link);
1458 $_SESSION["theme"] = $user_theme;
1459 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1460 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1462 initialize_user_prefs($link, $_SESSION["uid"]);
1471 $_SESSION["uid"] = 1;
1472 $_SESSION["name"] = "admin";
1474 $user_theme = get_user_theme_path($link);
1476 $_SESSION["theme"] = $user_theme;
1477 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1479 initialize_user_prefs($link, $_SESSION["uid"]);
1485 function make_password($length = 8) {
1488 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1492 while ($i < $length) {
1493 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1495 if (!strstr($password, $char)) {
1503 // this is called after user is created to initialize default feeds, labels
1506 // user preferences are checked on every login, not here
1508 function initialize_user($link, $uid) {
1510 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1511 values ('$uid','unread = true', 'Unread articles')");
1513 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1514 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1516 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1517 values ('$uid', 'Tiny Tiny RSS: New Releases',
1518 'http://tt-rss.spb.ru/releases.rss')");
1520 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1521 values ('$uid', 'Tiny Tiny RSS: Forum',
1522 'http://tt-rss.spb.ru/forum/rss.php')");
1525 function logout_user() {
1527 if (isset($_COOKIE[session_name()])) {
1528 setcookie(session_name(), '', time()-42000, '/');
1532 function get_script_urlpath() {
1533 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1536 function validate_session($link) {
1537 if (SINGLE_USER_MODE
) {
1541 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1542 if ($_SESSION["ip_address"]) {
1543 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1544 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1550 if ($_SESSION["uid"]) {
1552 $result = db_query($link,
1553 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1555 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1557 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1562 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1564 //print_r($_SESSION);
1566 if (time() > $_SESSION["cookie_lifetime"]) {
1574 function login_sequence($link, $mobile = false) {
1575 if (!SINGLE_USER_MODE
) {
1577 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1578 $swu = db_escape_string($_REQUEST["swu"]);
1580 $_SESSION["prefs_cache"] = false;
1581 return authenticate_user($link, $swu, null, true);
1585 $login_action = $_POST["login_action"];
1587 # try to authenticate user if called from login form
1588 if ($login_action == "do_login") {
1589 $login = $_POST["login"];
1590 $password = $_POST["password"];
1591 $remember_me = $_POST["remember_me"];
1593 if (authenticate_user($link, $login, $password)) {
1594 $_POST["password"] = "";
1596 $_SESSION["language"] = $_POST["language"];
1598 header("Location: " . $_SERVER["REQUEST_URI"]);
1603 $_SESSION["login_error_msg"] = "Incorrect username or password";
1607 // print session_id();
1608 // print_r($_SESSION);
1610 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1611 render_login_form($link, $mobile);
1614 /* bump login timestamp */
1615 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1618 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1619 setcookie("ttrss_lang", $_SESSION["language"],
1620 time() + SESSION_COOKIE_LIFETIME
);
1625 return authenticate_user($link, "admin", null);
1629 function truncate_string($str, $max_len) {
1630 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1631 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1637 function get_user_theme_path($link) {
1638 $result = db_query($link, "SELECT theme_path
1640 ttrss_themes,ttrss_users
1641 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1642 if (db_num_rows($result) != 0) {
1643 return db_fetch_result($result, 0, "theme_path");
1649 function smart_date_time($timestamp) {
1650 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1651 return date("G:i", $timestamp);
1652 } else if (date("Y", $timestamp) == date("Y")) {
1653 return date("M d, G:i", $timestamp);
1655 return date("Y/m/d, G:i", $timestamp);
1659 function smart_date($timestamp) {
1660 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1662 } else if (date("Y", $timestamp) == date("Y")) {
1663 return date("D m", $timestamp);
1665 return date("Y/m/d", $timestamp);
1669 function sql_bool_to_string($s) {
1670 if ($s == "t" ||
$s == "1") {
1677 function sql_bool_to_bool($s) {
1678 if ($s == "t" ||
$s == "1") {
1686 function toggleEvenOdd($a) {
1693 function sanity_check($link) {
1698 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1699 $schema_version = db_fetch_result($result, 0, "schema_version");
1701 if ($schema_version != SCHEMA_VERSION
) {
1705 if (DB_TYPE
== "mysql") {
1706 $result = db_query($link, "SELECT true", false);
1707 if (db_num_rows($result) != 1) {
1712 error_reporting (DEFAULT_ERROR_LEVEL
);
1714 if ($error_code != 0) {
1715 print_error_xml($error_code);
1722 function file_is_locked($filename) {
1723 if (function_exists('flock')) {
1725 $fp = fopen($filename, "r");
1726 error_reporting(DEFAULT_ERROR_LEVEL
);
1728 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1729 flock($fp, LOCK_UN
);
1740 function make_lockfile($filename) {
1741 $fp = fopen($filename, "w");
1743 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1750 function make_stampfile($filename) {
1751 $fp = fopen($filename, "w");
1753 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1754 fwrite($fp, time() . "\n");
1755 flock($fp, LOCK_UN
);
1763 function read_stampfile($filename) {
1766 $fp = fopen($filename, "r");
1767 error_reporting (DEFAULT_ERROR_LEVEL
);
1769 if (flock($fp, LOCK_EX
)) {
1770 $stamp = fgets($fp);
1771 flock($fp, LOCK_UN
);
1779 function sql_random_function() {
1780 if (DB_TYPE
== "mysql") {
1787 function catchup_feed($link, $feed, $cat_view) {
1789 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1794 $cat_qpart = "cat_id = '$feed'";
1796 $cat_qpart = "cat_id IS NULL";
1799 $tmp_result = db_query($link, "SELECT id
1800 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1803 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1805 $tmp_feed = $tmp_line["id"];
1807 db_query($link, "UPDATE ttrss_user_entries
1808 SET unread = false,last_read = NOW()
1809 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1812 } else if ($feed > 0) {
1814 $tmp_result = db_query($link, "SELECT id
1815 FROM ttrss_feeds WHERE parent_feed = '$feed'
1816 ORDER BY cat_id,title");
1818 $parent_ids = array();
1820 if (db_num_rows($tmp_result) > 0) {
1821 while ($p = db_fetch_assoc($tmp_result)) {
1822 array_push($parent_ids, "feed_id = " . $p["id"]);
1825 $children_qpart = implode(" OR ", $parent_ids);
1827 db_query($link, "UPDATE ttrss_user_entries
1828 SET unread = false,last_read = NOW()
1829 WHERE (feed_id = '$feed' OR $children_qpart)
1830 AND owner_uid = " . $_SESSION["uid"]);
1833 db_query($link, "UPDATE ttrss_user_entries
1834 SET unread = false,last_read = NOW()
1835 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1838 } else if ($feed < 0 && $feed > -10) { // special, like starred
1841 db_query($link, "UPDATE ttrss_user_entries
1842 SET unread = false,last_read = NOW()
1843 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1847 db_query($link, "UPDATE ttrss_user_entries
1848 SET unread = false,last_read = NOW()
1849 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
1854 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1856 if (DB_TYPE
== "pgsql") {
1857 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1859 $match_part = "date_entered > DATE_SUB(NOW(),
1860 INTERVAL $intl HOUR) ";
1863 $result = db_query($link, "SELECT id FROM ttrss_entries,
1864 ttrss_user_entries WHERE $match_part AND
1866 ttrss_user_entries.ref_id = ttrss_entries.id AND
1867 owner_uid = ".$_SESSION["uid"]);
1869 $affected_ids = array();
1871 while ($line = db_fetch_assoc($result)) {
1872 array_push($affected_ids, $line["id"]);
1875 catchupArticlesById($link, $affected_ids, 0);
1878 } else if ($feed < -10) { // label
1880 // TODO make this more efficient
1882 $label_id = -$feed - 11;
1884 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1885 WHERE id = '$label_id'");
1888 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1890 db_query($link, "BEGIN");
1892 $tmp2_result = db_query($link,
1896 ttrss_user_entries,ttrss_entries,ttrss_feeds
1898 ref_id = ttrss_entries.id AND
1899 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1901 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1903 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1904 db_query($link, "UPDATE
1907 unread = false, last_read = NOW()
1909 int_id = " . $tmp_line["int_id"]);
1912 db_query($link, "COMMIT");
1914 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1915 SET unread = false,last_read = NOW()
1918 AND owner_uid = ".$_SESSION["uid"]); */
1922 db_query($link, "BEGIN");
1924 $tag_name = db_escape_string($feed);
1926 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1927 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1929 while ($line = db_fetch_assoc($result)) {
1930 db_query($link, "UPDATE ttrss_user_entries SET
1931 unread = false, last_read = NOW()
1932 WHERE int_id = " . $line["post_int_id"]);
1934 db_query($link, "COMMIT");
1938 function update_generic_feed($link, $feed, $cat_view) {
1942 $cat_qpart = "cat_id = '$feed'";
1944 $cat_qpart = "cat_id IS NULL";
1947 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
1948 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1950 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1951 $feed_url = $tmp_line["feed_url"];
1952 $feed_id = $tmp_line["id"];
1953 update_rss_feed($link, $feed_url, $feed_id, ENABLE_UPDATE_DAEMON
);
1957 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1958 WHERE id = '$feed'");
1959 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1960 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1964 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1965 /* getLabelCounters($link);
1966 getFeedCounters($link);
1967 getTagCounters($link);
1968 getGlobalCounters($link);
1969 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1970 getCategoryCounters($link);
1973 if (!$omode) $omode = "flc";
1975 getGlobalCounters($link);
1977 if (strchr($omode, "l")) getLabelCounters($link);
1978 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
1979 if (strchr($omode, "t")) getTagCounters($link);
1980 if (strchr($omode, "c")) {
1981 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1982 getCategoryCounters($link);
1987 function getCategoryCounters($link) {
1988 # two special categories are -1 and -2 (all virtuals; all labels)
1990 $ctr = getCategoryUnread($link, -1);
1992 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
1994 $ctr = getCategoryUnread($link, -2);
1996 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
1998 $age_qpart = getMaxAgeSubquery();
2000 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
2001 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2002 AND id = ref_id AND $age_qpart
2003 AND unread = true)) AS unread FROM ttrss_feeds
2005 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2007 while ($line = db_fetch_assoc($result)) {
2008 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2009 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2010 $line["unread"]."\"/>";
2014 function getCategoryUnread($link, $cat) {
2019 $cat_query = "cat_id = '$cat'";
2021 $cat_query = "cat_id IS NULL";
2024 $age_qpart = getMaxAgeSubquery();
2026 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2028 AND owner_uid = " . $_SESSION["uid"]);
2030 $cat_feeds = array();
2031 while ($line = db_fetch_assoc($result)) {
2032 array_push($cat_feeds, "feed_id = " . $line["id"]);
2035 if (count($cat_feeds) == 0) return 0;
2037 $match_part = implode(" OR ", $cat_feeds);
2039 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2040 FROM ttrss_user_entries,ttrss_entries
2041 WHERE unread = true AND ($match_part) AND id = ref_id
2042 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2046 # this needs to be rewritten
2047 while ($line = db_fetch_assoc($result)) {
2048 $unread +
= $line["unread"];
2052 } else if ($cat == -1) {
2053 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2054 } else if ($cat == -2) {
2056 $rv = getLabelCounters($link, false, true);
2059 foreach (array_keys($rv) as $k) {
2061 $ctr +
= $rv[$k]["counter"];
2069 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2070 if (DB_TYPE
== "pgsql") {
2071 return "ttrss_entries.date_entered >
2072 NOW() - INTERVAL '$days days'";
2074 return "ttrss_entries.date_entered >
2075 DATE_SUB(NOW(), INTERVAL $days DAY)";
2079 function getFeedUnread($link, $feed, $is_cat = false) {
2080 $n_feed = sprintf("%d", $feed);
2082 $age_qpart = getMaxAgeSubquery();
2085 return getCategoryUnread($link, $n_feed);
2086 } else if ($n_feed == -1) {
2087 $match_part = "marked = true";
2088 } else if ($n_feed == -2) {
2089 $match_part = "published = true";
2090 } else if ($n_feed == -3) {
2091 $match_part = "unread = true";
2093 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2095 if (DB_TYPE
== "pgsql") {
2096 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2098 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2101 } else if ($n_feed > 0) {
2103 $result = db_query($link, "SELECT id FROM ttrss_feeds
2104 WHERE parent_feed = '$n_feed'
2106 AND owner_uid = " . $_SESSION["uid"]);
2108 if (db_num_rows($result) > 0) {
2110 $linked_feeds = array();
2111 while ($line = db_fetch_assoc($result)) {
2112 array_push($linked_feeds, "feed_id = " . $line["id"]);
2115 array_push($linked_feeds, "feed_id = $n_feed");
2117 $match_part = implode(" OR ", $linked_feeds);
2119 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2120 FROM ttrss_user_entries,ttrss_entries
2121 WHERE unread = true AND
2122 ttrss_user_entries.ref_id = ttrss_entries.id AND
2125 owner_uid = " . $_SESSION["uid"]);
2129 # this needs to be rewritten
2130 while ($line = db_fetch_assoc($result)) {
2131 $unread +
= $line["unread"];
2137 $match_part = "feed_id = '$n_feed'";
2139 } else if ($feed < -10) {
2141 $label_id = -$feed - 11;
2143 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2144 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2146 $match_part = db_fetch_result($result, 0, "sql_exp");
2151 $result = db_query($link, "SELECT count(int_id) AS unread
2152 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2153 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2154 ttrss_user_entries.ref_id = ttrss_entries.id AND
2155 ttrss_feeds.hidden = false AND
2157 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2161 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2162 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2163 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2164 AND unread = true AND $age_qpart AND
2165 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2168 $unread = db_fetch_result($result, 0, "unread");
2173 /* FIXME this needs reworking */
2175 function getGlobalUnread($link, $user_id = false) {
2178 $user_id = $_SESSION["uid"];
2181 $age_qpart = getMaxAgeSubquery();
2183 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2184 WHERE unread = true AND
2185 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2186 ttrss_user_entries.ref_id = ttrss_entries.id AND
2189 ttrss_user_entries.owner_uid = '$user_id'");
2190 $c_id = db_fetch_result($result, 0, "c_id");
2194 function getGlobalCounters($link, $global_unread = -1) {
2195 if ($global_unread == -1) {
2196 $global_unread = getGlobalUnread($link);
2198 print "<counter type=\"global\" id='global-unread'
2199 counter='$global_unread'/>";
2201 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2202 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2204 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2206 print "<counter type=\"global\" id='subscribed-feeds'
2207 counter='$subscribed_feeds'/>";
2211 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2214 if (!$_SESSION["tctr_last_value"]) {
2215 $_SESSION["tctr_last_value"] = array();
2219 $old_counters = $_SESSION["tctr_last_value"];
2221 $tctrs_modified = false;
2223 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2224 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2225 ttrss_user_entries.ref_id = ttrss_entries.id AND
2226 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2227 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2229 select tag_name,0 as count FROM ttrss_tags
2230 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2232 $age_qpart = getMaxAgeSubquery();
2234 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2235 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2236 AND ref_id = id AND $age_qpart
2237 AND unread = true)) AS count FROM ttrss_tags
2238 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2239 ORDER BY count DESC LIMIT 55");
2243 while ($line = db_fetch_assoc($result)) {
2244 $tags[$line["tag_name"]] +
= $line["count"];
2247 foreach (array_keys($tags) as $tag) {
2248 $unread = $tags[$tag];
2250 $tag = htmlspecialchars($tag);
2252 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2253 $old_counters[$tag] = $unread;
2254 $tctrs_modified = true;
2255 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2260 if ($smart_mode && $tctrs_modified) {
2261 $_SESSION["tctr_last_value"] = $old_counters;
2266 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2268 $age_qpart = getMaxAgeSubquery();
2271 if (!$_SESSION["lctr_last_value"]) {
2272 $_SESSION["lctr_last_value"] = array();
2278 $old_counters = $_SESSION["lctr_last_value"];
2279 $lctrs_modified = false;
2281 $count = getFeedUnread($link, -1);
2284 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2286 $ret_arr["-1"]["counter"] = $count;
2287 $ret_arr["-1"]["description"] = __("Starred articles");
2290 $count = getFeedUnread($link, -2);
2293 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2295 $ret_arr["-2"]["counter"] = $count;
2296 $ret_arr["-2"]["description"] = __("Published articles");
2299 $count = getFeedUnread($link, -3);
2302 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2304 $ret_arr["-3"]["counter"] = $count;
2305 $ret_arr["-3"]["description"] = __("Fresh articles");
2309 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2310 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2312 while ($line = db_fetch_assoc($result)) {
2314 $id = -$line["id"] - 11;
2316 $label_name = $line["description"];
2318 error_reporting (0);
2320 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2321 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2322 ttrss_feeds.hidden = false AND
2324 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2325 ttrss_user_entries.ref_id = ttrss_entries.id AND
2326 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2328 $count = db_fetch_result($tmp_result, 0, "count");
2330 if (!$smart_mode ||
$old_counters[$id] != $count) {
2331 $old_counters[$id] = $count;
2332 $lctrs_modified = true;
2334 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2336 $ret_arr[$id]["counter"] = $count;
2337 $ret_arr[$id]["description"] = $label_name;
2341 error_reporting (DEFAULT_ERROR_LEVEL
);
2344 if ($smart_mode && $lctrs_modified) {
2345 $_SESSION["lctr_last_value"] = $old_counters;
2351 /* function getFeedCounter($link, $id) {
2353 $result = db_query($link, "SELECT
2354 count(id) as count,last_error
2355 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2356 WHERE feed_id = '$id' AND unread = true
2357 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2358 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2360 $count = db_fetch_result($result, 0, "count");
2361 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2363 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2366 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2368 $age_qpart = getMaxAgeSubquery();
2371 if (!$_SESSION["fctr_last_value"]) {
2372 $_SESSION["fctr_last_value"] = array();
2376 $old_counters = $_SESSION["fctr_last_value"];
2378 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2379 SUBSTRING(last_updated,1,19) AS last_updated,
2381 FROM ttrss_entries,ttrss_user_entries
2382 WHERE feed_id = ttrss_feeds.id AND
2383 ttrss_user_entries.ref_id = ttrss_entries.id
2384 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2385 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2386 AND parent_feed IS NULL"); */
2388 $query = "SELECT ttrss_feeds.id,
2390 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2392 COUNT(ttrss_entries.id) AS count
2394 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2395 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2396 AND ttrss_user_entries.unread = true)
2397 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2399 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2400 AND parent_feed IS NULL
2401 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2403 $result = db_query($link, $query);
2404 $fctrs_modified = false;
2406 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2408 while ($line = db_fetch_assoc($result)) {
2411 $count = $line["count"];
2412 $last_error = htmlspecialchars($line["last_error"]);
2414 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2415 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2417 $last_updated = date($short_date, strtotime($line["last_updated"]));
2420 $last_updated = htmlspecialchars($last_updated);
2422 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2424 $tmp_result = db_query($link,
2425 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2426 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2427 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2428 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2429 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2431 if (db_num_rows($tmp_result) > 0) {
2432 while ($l = db_fetch_assoc($tmp_result)) {
2433 $count +
= $l["unread"];
2437 if (!$smart_mode ||
$old_counters[$id] != $count) {
2438 $old_counters[$id] = $count;
2439 $fctrs_modified = true;
2442 $error_part = "error=\"$last_error\"";
2448 $has_img_part = "hi=\"$has_img\"";
2453 if ($active_feed && $id == $active_feed) {
2454 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2456 $has_title_part = "";
2459 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2463 if ($smart_mode && $fctrs_modified) {
2464 $_SESSION["fctr_last_value"] = $old_counters;
2468 function get_script_dt_add() {
2469 if (strpos(VERSION
, ".99") === false) {
2476 function get_pgsql_version($link) {
2477 $result = db_query($link, "SELECT version() AS version");
2478 $version = split(" ", db_fetch_result($result, 0, "version"));
2482 function print_error_xml($code, $add_msg = "") {
2485 $error_msg = $ERRORS[$code];
2488 $error_msg = "$error_msg; $add_msg";
2491 print "<rpc-reply>";
2492 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2493 print "</rpc-reply>";
2496 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2497 $auth_login = '', $auth_pass = '') {
2499 # check for feed:http://url
2500 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2502 # check for feed://URL
2503 if (strpos($feed_link, "//") === 0) {
2504 $feed_link = "http:$feed_link";
2507 if ($feed_link == "") return;
2509 if ($cat_id == "0" ||
!$cat_id) {
2510 $cat_qpart = "NULL";
2512 $cat_qpart = "'$cat_id'";
2515 $result = db_query($link,
2516 "SELECT id FROM ttrss_feeds
2517 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2519 if (db_num_rows($result) == 0) {
2521 $result = db_query($link,
2522 "INSERT INTO ttrss_feeds
2523 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2524 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2525 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2527 $result = db_query($link,
2528 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2529 AND owner_uid = " . $_SESSION["uid"]);
2531 $feed_id = db_fetch_result($result, 0, "id");
2534 update_rss_feed($link, $feed_link, $feed_id, true);
2543 function print_feed_select($link, $id, $default_id = "",
2544 $attributes = "", $include_all_feeds = true) {
2546 print "<select id=\"$id\" name=\"$id\" $attributes>";
2547 if ($include_all_feeds) {
2548 print "<option value=\"0\">".__('All feeds')."</option>";
2551 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2552 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2554 if (db_num_rows($result) > 0 && $include_all_feeds) {
2555 print "<option disabled>--------</option>";
2558 while ($line = db_fetch_assoc($result)) {
2559 if ($line["id"] == $default_id) {
2560 $is_selected = "selected";
2564 printf("<option $is_selected value='%d'>%s</option>",
2565 $line["id"], htmlspecialchars($line["title"]));
2571 function print_feed_cat_select($link, $id, $default_id = "",
2572 $attributes = "", $include_all_cats = true) {
2574 print "<select id=\"$id\" name=\"$id\" $attributes>";
2576 if ($include_all_cats) {
2577 print "<option value=\"0\">".__('Uncategorized')."</option>";
2580 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2581 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2583 if (db_num_rows($result) > 0 && $include_all_cats) {
2584 print "<option disabled>--------</option>";
2587 while ($line = db_fetch_assoc($result)) {
2588 if ($line["id"] == $default_id) {
2589 $is_selected = "selected";
2593 printf("<option $is_selected value='%d'>%s</option>",
2594 $line["id"], htmlspecialchars($line["title"]));
2600 function checkbox_to_sql_bool($val) {
2601 return ($val == "on") ?
"true" : "false";
2604 function getFeedCatTitle($link, $id) {
2606 return __("Special");
2607 } else if ($id < -10) {
2608 return __("Labels");
2609 } else if ($id > 0) {
2610 $result = db_query($link, "SELECT ttrss_feed_categories.title
2611 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2612 cat_id = ttrss_feed_categories.id");
2613 if (db_num_rows($result) == 1) {
2614 return db_fetch_result($result, 0, "title");
2616 return __("Uncategorized");
2619 return "getFeedCatTitle($id) failed";
2624 function getFeedTitle($link, $id) {
2626 return __("Starred articles");
2627 } else if ($id == -2) {
2628 return __("Published articles");
2629 } else if ($id == -3) {
2630 return __("Fresh articles");
2631 } else if ($id < -10) {
2632 $label_id = -10 - $id;
2633 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2634 if (db_num_rows($result) == 1) {
2635 return db_fetch_result($result, 0, "description");
2637 return "Unknown label ($label_id)";
2640 } else if ($id > 0) {
2641 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2642 if (db_num_rows($result) == 1) {
2643 return db_fetch_result($result, 0, "title");
2645 return "Unknown feed ($id)";
2648 return "getFeedTitle($id) failed";
2653 function get_session_cookie_name() {
2654 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2657 function print_init_params($link) {
2658 print "<init-params>";
2659 if ($_SESSION["stored-params"]) {
2660 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2662 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2663 print "<param key=\"$key\" value=\"$value\"/>";
2668 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2669 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2670 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2672 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2673 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2675 print "<param key=\"hide_read_feeds\" value=\"" .
2676 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2678 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2679 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2681 print "<param key=\"confirm_feed_catchup\" value=\"" .
2682 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2684 print "<param key=\"cdm_auto_catchup\" value=\"" .
2685 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2687 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2689 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2691 print "<param key=\"default_view_mode\" value=\"" .
2692 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2694 print "<param key=\"default_view_limit\" value=\"" .
2695 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2697 print "<param key=\"prefs_active_tab\" value=\"" .
2698 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2700 print "<param key=\"infobox_disable_overlay\" value=\"" .
2701 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2703 print "<param key=\"icons_location\" value=\"" .
2706 print "</init-params>";
2709 function print_runtime_info($link) {
2710 print "<runtime-info>";
2711 if (ENABLE_UPDATE_DAEMON
) {
2712 print "<param key=\"daemon_is_running\" value=\"".
2713 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2715 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2717 $stamp = (int)read_stampfile("update_daemon.stamp");
2719 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2722 $stamp_delta = time() - $stamp;
2724 if ($stamp_delta > 1800) {
2728 $_SESSION["daemon_stamp_check"] = time();
2731 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2733 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2735 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2740 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2742 if ($_SESSION["last_version_check"] +
7200 < time()) {
2743 $new_version_details = check_for_update($link);
2745 print "<param key=\"new_version_available\" value=\"".
2746 sprintf("%d", $new_version_details != ""). "\"/>";
2748 $_SESSION["last_version_check"] = time();
2752 // print "<param key=\"new_version_available\" value=\"1\"/>";
2754 print "</runtime-info>";
2757 function getSearchSql($search, $match_on) {
2759 $search_query_part = "";
2761 $keywords = split(" ", $search);
2762 $query_keywords = array();
2764 if ($match_on == "both") {
2766 foreach ($keywords as $k) {
2767 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2768 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2771 $search_query_part = implode("AND", $query_keywords) . " AND ";
2773 } else if ($match_on == "title") {
2775 foreach ($keywords as $k) {
2776 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2779 $search_query_part = implode("AND", $query_keywords) . " AND ";
2781 } else if ($match_on == "content") {
2783 foreach ($keywords as $k) {
2784 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2788 $search_query_part = implode("AND", $query_keywords);
2790 return $search_query_part;
2793 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
2795 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2799 $search_query_part = getSearchSql($search, $match_on);
2800 $search_query_part .= " AND ";
2803 $search_query_part = "";
2806 $view_query_part = "";
2808 if ($view_mode == "adaptive") {
2810 $view_query_part = " ";
2811 } else if ($feed != -1) {
2812 $unread = getFeedUnread($link, $feed, $cat_view);
2814 $view_query_part = " unread = true AND ";
2819 if ($view_mode == "marked") {
2820 $view_query_part = " marked = true AND ";
2823 if ($view_mode == "unread") {
2824 $view_query_part = " unread = true AND ";
2828 $limit_query_part = "LIMIT " . $limit;
2831 $vfeed_query_part = "";
2833 // override query strategy and enable feed display when searching globally
2834 if ($search && $search_mode == "all_feeds") {
2835 $query_strategy_part = "ttrss_entries.id > 0";
2836 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2837 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2838 $query_strategy_part = "ttrss_entries.id > 0";
2839 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2840 id = feed_id) as feed_title,";
2841 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2843 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2845 $tmp_result = false;
2848 $tmp_result = db_query($link, "SELECT id
2849 FROM ttrss_feeds WHERE cat_id = '$feed'");
2851 $tmp_result = db_query($link, "SELECT id
2852 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2853 WHERE id = '$feed') AND id != '$feed'");
2856 $cat_siblings = array();
2858 if (db_num_rows($tmp_result) > 0) {
2859 while ($p = db_fetch_assoc($tmp_result)) {
2860 array_push($cat_siblings, "feed_id = " . $p["id"]);
2863 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2864 $feed, implode(" OR ", $cat_siblings));
2867 $query_strategy_part = "ttrss_entries.id > 0";
2870 } else if ($feed >= 0) {
2875 $query_strategy_part = "cat_id = '$feed'";
2877 $query_strategy_part = "cat_id IS NULL";
2880 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2883 $tmp_result = db_query($link, "SELECT id
2884 FROM ttrss_feeds WHERE parent_feed = '$feed'
2885 ORDER BY cat_id,title");
2887 $parent_ids = array();
2889 if (db_num_rows($tmp_result) > 0) {
2890 while ($p = db_fetch_assoc($tmp_result)) {
2891 array_push($parent_ids, "feed_id = " . $p["id"]);
2894 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2895 $feed, implode(" OR ", $parent_ids));
2897 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2899 $query_strategy_part = "feed_id = '$feed'";
2902 } else if ($feed == -1) { // starred virtual feed
2903 $query_strategy_part = "marked = true";
2904 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2905 } else if ($feed == -2) { // published virtual feed
2906 $query_strategy_part = "published = true";
2907 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2908 } else if ($feed == -3) { // fresh virtual feed
2909 $query_strategy_part = "unread = true";
2911 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2913 if (DB_TYPE
== "pgsql") {
2914 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2916 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2919 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2920 } else if ($feed <= -10) { // labels
2921 $label_id = -$feed - 11;
2923 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2924 WHERE id = '$label_id'");
2926 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2928 if (!$query_strategy_part) {
2932 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2934 $query_strategy_part = "id > 0"; // dumb
2937 if (get_pref($link, 'REVERSE_HEADLINES')) {
2938 $order_by = "updated";
2940 $order_by = "updated DESC";
2943 if ($override_order) {
2944 $order_by = $override_order;
2949 if ($search && $search_mode == "all_feeds") {
2950 $feed_title = __("Search results")." ($search)";
2951 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2952 $feed_title = __("Search results")." ($search, $feed)";
2953 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2954 $feed_title = $feed;
2955 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2960 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2961 WHERE id = '$feed' AND owner_uid = $owner_uid");
2962 $feed_title = db_fetch_result($result, 0, "title");
2964 $feed_title = __("Uncategorized");
2968 $feed_title = __("Searched for")." $search ($feed_title)";
2973 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2974 WHERE id = '$feed' AND owner_uid = $owner_uid");
2976 $feed_title = db_fetch_result($result, 0, "title");
2977 $feed_site_url = db_fetch_result($result, 0, "site_url");
2978 $last_error = db_fetch_result($result, 0, "last_error");
2981 $feed_title = __("Searched for") . " $search ($feed_title)";
2985 } else if ($feed == -1) {
2986 $feed_title = __("Starred articles");
2987 } else if ($feed == -2) {
2988 $feed_title = __("Published articles");
2989 } else if ($feed == -3) {
2990 $feed_title = __("Fresh articles");
2991 } else if ($feed < -10) {
2992 $label_id = -$feed - 11;
2993 $result = db_query($link, "SELECT description FROM ttrss_labels
2994 WHERE id = '$label_id'");
2995 $feed_title = db_fetch_result($result, 0, "description");
2998 $feed_title = __("Searched for") . " $search ($feed_title)";
3004 if ($feed < -10) error_reporting (0);
3006 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3009 $feed_kind = "Feeds";
3011 $feed_kind = "Labels";
3014 $content_query_part = "content as content_preview,";
3016 if ($limit_query_part) {
3017 $offset_query_part = "OFFSET $offset";
3022 ttrss_entries.id,ttrss_entries.title,
3024 unread,feed_id,marked,published,link,last_read,
3025 SUBSTRING(last_read,1,19) as last_read_noms,
3028 SUBSTRING(updated,1,19) as updated_noms,
3031 ttrss_entries,ttrss_user_entries,ttrss_feeds
3033 ttrss_feeds.hidden = false AND
3034 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3035 ttrss_user_entries.ref_id = ttrss_entries.id AND
3036 ttrss_user_entries.owner_uid = '$owner_uid' AND
3039 $query_strategy_part ORDER BY $order_by
3040 $limit_query_part $offset_query_part";
3042 $result = db_query($link, $query);
3044 if ($_GET["debug"]) print $query;
3049 $feed_kind = "Tags";
3051 $result = db_query($link, "SELECT
3053 ttrss_entries.id as id,title,
3056 marked,link,last_read,
3057 SUBSTRING(last_read,1,19) as last_read_noms,
3060 SUBSTRING(updated,1,19) as updated_noms
3062 ttrss_entries,ttrss_user_entries,ttrss_tags
3064 ref_id = ttrss_entries.id AND
3065 ttrss_user_entries.owner_uid = '$owner_uid' AND
3066 post_int_id = int_id AND tag_name = '$feed' AND
3069 $query_strategy_part ORDER BY $order_by
3070 $limit_query_part");
3073 return array($result, $feed_title, $feed_site_url, $last_error);
3077 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3078 $search, $search_mode, $match_on) {
3080 $qfh_ret = queryFeedHeadlines($link, $feed,
3081 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3084 $result = $qfh_ret[0];
3085 $feed_title = htmlspecialchars($qfh_ret[1]);
3086 $feed_site_url = $qfh_ret[2];
3087 $last_error = $qfh_ret[3];
3089 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3091 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3092 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3093 <rss version=\"2.0\">
3095 <title>$feed_title</title>
3096 <link>$feed_site_url</link>
3097 <description>Feed generated by Tiny Tiny RSS</description>";
3099 while ($line = db_fetch_assoc($result)) {
3101 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3102 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3104 $tags = get_article_tags($link, $line["id"], $owner_uid);
3106 foreach ($tags as $tag) {
3107 print "<category>" . htmlspecialchars($tag) . "</category>";
3110 $rfc822_date = date('r', strtotime($line["updated"]));
3112 print "<pubDate>$rfc822_date</pubDate>";
3115 htmlspecialchars($line["title"]) . "</title>";
3117 print "<description><![CDATA[" .
3118 $line["content_preview"] . "]]></description>";
3123 print "</channel></rss>";
3127 function getCategoryTitle($link, $cat_id) {
3129 if ($cat_id == -1) {
3130 return __("Special");
3131 } else if ($cat_id == -2) {
3132 return __("Labels");
3135 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3138 if (db_num_rows($result) == 1) {
3139 return db_fetch_result($result, 0, "title");
3141 return "Uncategorized";
3146 // http://ru2.php.net/strip-tags
3148 function strip_tags_long($textstring, $allowed){
3149 while($textstring != strip_tags($textstring, $allowed))
3151 while (strlen($textstring) != 0)
3153 if (strlen($textstring) > 1024) {
3156 $otherlen = strlen($textstring);
3158 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3159 $safetext .= $temptext;
3160 $textstring = substr_replace($textstring,'',0,$otherlen);
3162 $textstring = $safetext;
3168 function sanitize_rss($link, $str, $force_strip_tags = false) {
3171 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3173 global $tw_paranoya_setup;
3175 $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
3177 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3178 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3184 function send_headlines_digests($link, $limit = 100) {
3186 if (!DIGEST_ENABLE
) return false;
3188 $user_limit = DIGEST_EMAIL_LIMIT
;
3191 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3193 if (DB_TYPE
== "pgsql") {
3194 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3195 } else if (DB_TYPE
== "mysql") {
3196 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3199 $result = db_query($link, "SELECT id,email FROM ttrss_users
3200 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3202 while ($line = db_fetch_assoc($result)) {
3204 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3205 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3207 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3209 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3210 $digest = $tuple[0];
3211 $headlines_count = $tuple[1];
3212 $affected_ids = $tuple[2];
3214 if ($headlines_count > 0) {
3216 if (!DIGEST_SMTP_HOST
) {
3218 $rc = mail($line["login"] . " <" . $line["email"] . ">",
3219 "[tt-rss] New headlines for last 24 hours", $digest,
3220 "From: " . DIGEST_FROM_NAME
. " <" . DIGEST_FROM_ADDRESS
. ">\n".
3221 "Content-Type: text/plain; charset=\"utf-8\"\n".
3222 "Content-Transfer-Encoding: 8bit\n");
3226 $mail = new PHPMailer();
3228 $mail->PluginDir
= "phpmailer/";
3229 $mail->SetLanguage("en", "phpmailer/language/");
3231 $mail->CharSet
= "UTF-8";
3233 $mail->From
= DIGEST_FROM_ADDRESS
;
3234 $mail->FromName
= DIGEST_FROM_NAME
;
3235 $mail->AddAddress($line["email"], $line["login"]);
3236 $mail->Host
= DIGEST_SMTP_HOST
;
3237 $mail->Mailer
= "smtp";
3239 $mail->Username
= DIGEST_SMTP_LOGIN
;
3240 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3242 $mail->Subject
= "[tt-rss] New headlines for last 24 hours";
3243 $mail->Body
= $digest;
3245 $rc = $mail->Send();
3247 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3254 print "Marking affected articles as read...\n";
3255 catchupArticlesById($link, $affected_ids, 0);
3258 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3259 WHERE id = " . $line["id"]);
3261 print "No headlines\n";
3266 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
3270 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3271 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
3272 $tmp .= "=======================================================\n\n";
3274 $affected_ids = array();
3276 if (DB_TYPE
== "pgsql") {
3277 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3278 } else if (DB_TYPE
== "mysql") {
3279 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3282 $result = db_query($link, "SELECT ttrss_entries.title,
3283 ttrss_feeds.title AS feed_title,
3285 ttrss_user_entries.ref_id,
3287 SUBSTRING(last_updated,1,19) AS last_updated
3289 ttrss_user_entries,ttrss_entries,ttrss_feeds
3291 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3292 AND include_in_digest = true
3295 AND ttrss_user_entries.owner_uid = $user_id
3296 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
3299 $cur_feed_title = "";
3301 $headlines_count = db_num_rows($result);
3303 while ($line = db_fetch_assoc($result)) {
3305 array_push($affected_ids, $line["ref_id"]);
3307 $updated = smart_date_time(strtotime($line["last_updated"]));
3308 $feed_title = $line["feed_title"];
3310 if ($cur_feed_title != $feed_title) {
3311 $cur_feed_title = $feed_title;
3313 $tmp .= "$feed_title\n\n";
3316 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
3317 $tmp .= " " . trim($line["link"]) . "\n";
3322 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
3323 DIGEST_HOSTNAME
. "\n".
3324 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
3327 return array($tmp, $headlines_count, $affected_ids);
3330 function check_for_update($link, $brief_fmt = true) {
3331 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3333 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3338 if (ENABLE_SIMPLEPIE
) {
3339 $rss = new SimplePie();
3340 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3341 $rss->set_timeout(MAGPIE_FETCH_TIME_OUT
);
3342 $rss->set_feed_url($fetch_url);
3343 $rss->set_output_encoding('UTF-8');
3346 $rss = fetch_rss($releases_feed);
3348 error_reporting (DEFAULT_ERROR_LEVEL
);
3352 if (ENABLE_SIMPLEPIE
) {
3353 $items = $rss->get_items();
3355 $items = $rss->items
;
3357 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3358 if (!$items ||
!is_array($items)) $items = $rss;
3361 if (!is_array($items) ||
count($items) == 0) {
3365 $latest_item = $items[0];
3367 if (ENABLE_SIMPLEPIE
) {
3368 $last_title = $latest_item->get_title();
3370 $last_title = $latest_item["title"];
3373 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3375 if (ENABLE_SIMPLEPIE
) {
3376 $release_url = sanitize_rss($link, $latest_item->get_link());
3377 $content = sanitize_rss($link, $latest_item->get_description());
3379 $release_url = sanitize_rss($link, $latest_item["link"]);
3380 $content = sanitize_rss($link, $latest_item["description"]);
3383 if (version_compare(VERSION
, $latest_version) == -1) {
3385 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3386 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3387 <div id=\"milestoneDetails\">$content</div>");
3389 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3390 <div class='milestoneDetails'>$content</div>
3391 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3392 download and update information.";
3399 function markArticlesById($link, $ids, $cmode) {
3403 foreach ($ids as $id) {
3404 array_push($tmp_ids, "ref_id = '$id'");
3407 $ids_qpart = join(" OR ", $tmp_ids);
3410 db_query($link, "UPDATE ttrss_user_entries SET
3411 marked = false,last_read = NOW()
3412 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3413 } else if ($cmode == 1) {
3414 db_query($link, "UPDATE ttrss_user_entries SET
3416 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3418 db_query($link, "UPDATE ttrss_user_entries SET
3419 marked = NOT marked,last_read = NOW()
3420 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3424 function publishArticlesById($link, $ids, $cmode) {
3428 foreach ($ids as $id) {
3429 array_push($tmp_ids, "ref_id = '$id'");
3432 $ids_qpart = join(" OR ", $tmp_ids);
3435 db_query($link, "UPDATE ttrss_user_entries SET
3436 published = false,last_read = NOW()
3437 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3438 } else if ($cmode == 1) {
3439 db_query($link, "UPDATE ttrss_user_entries SET
3441 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3443 db_query($link, "UPDATE ttrss_user_entries SET
3444 published = NOT published,last_read = NOW()
3445 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3449 function catchupArticlesById($link, $ids, $cmode) {
3453 foreach ($ids as $id) {
3454 array_push($tmp_ids, "ref_id = '$id'");
3457 $ids_qpart = join(" OR ", $tmp_ids);
3460 db_query($link, "UPDATE ttrss_user_entries SET
3461 unread = false,last_read = NOW()
3462 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3463 } else if ($cmode == 1) {
3464 db_query($link, "UPDATE ttrss_user_entries SET
3466 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3468 db_query($link, "UPDATE ttrss_user_entries SET
3469 unread = NOT unread,last_read = NOW()
3470 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3474 function catchupArticleById($link, $id, $cmode) {
3477 db_query($link, "UPDATE ttrss_user_entries SET
3478 unread = false,last_read = NOW()
3479 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3480 } else if ($cmode == 1) {
3481 db_query($link, "UPDATE ttrss_user_entries SET
3483 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3485 db_query($link, "UPDATE ttrss_user_entries SET
3486 unread = NOT unread,last_read = NOW()
3487 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3491 function make_guid_from_title($title) {
3492 return preg_replace("/[ \"\',.:;]/", "-",
3493 mb_strtolower(strip_tags($title), 'utf-8'));
3496 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3497 $bottom = false, $rtl_content = false, $feed_id = 0,
3498 $is_cat = false, $search = false, $match_on = false,
3499 $search_mode = false, $offset = 0, $limit = 0) {
3501 $user_page_offset = $offset +
1;
3504 $class = "headlinesSubToolbar";
3505 $tid = "headlineActionsTop";
3507 $class = "headlinesSubToolbar";
3508 $tid = "headlineActionsBottom";
3511 print "<table class=\"$class\" id=\"$tid\"
3512 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3520 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3521 $page_next_link = "javascript:viewFeedGoPage(1)";
3522 $page_first_link = "javascript:viewFeedGoPage(0)";
3524 $catchup_page_link = "javascript:catchupPage()";
3525 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3526 $catchup_sel_link = "javascript:catchupSelection()";
3528 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3530 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3531 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3532 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3534 $tog_unread_link = "javascript:selectionToggleUnread()";
3535 $tog_marked_link = "javascript:selectionToggleMarked()";
3536 $tog_published_link = "javascript:selectionTogglePublished()";
3540 $sel_all_link = "javascript:cdmSelectArticles('all')";
3541 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3542 $sel_none_link = "javascript:cdmSelectArticles('none')";
3544 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3545 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3546 $tog_published_link = "javascript:selectionTogglePublished(true)";
3550 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3552 print "<td class=\"headlineActions$rtl_cpart\">
3553 <ul class=\"headlineDropdownMenu\">
3556 <a href=\"$sel_all_link\">".__('All')."</a>,
3557 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3558 <a href=\"$sel_none_link\">".__('None')."</a></li>
3559 <li class=\"vsep\"> </li>
3560 <li class=\"top\">".__('Toggle')."<ul>
3561 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3562 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3563 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3565 <li class=\"vsep\"> </li>
3566 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
3567 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3568 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->
3569 <li><span class=\"insensitive\">--------</span></li>
3570 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3571 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3572 <li><span class=\"insensitive\">--------</span></li>
3573 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3576 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3578 if ($limit != 0 && !$search && $enable_pagination) {
3580 <li class=\"vsep\"> </li>
3581 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3582 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3583 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3587 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3589 <li class=\"vsep\"> </li>
3591 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3592 '$match_on', '$feed_id', '$is_cat');\">
3593 ".__('Convert to label')."</a></td>";
3599 // old style subtoolbar:
3601 print "<td class=\"headlineActions$rtl_cpart\">".
3603 <a href=\"$sel_all_link\">".__('All')."</a>,
3604 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3605 <a href=\"$sel_none_link\">".__('None')."</a>
3607 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3608 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3610 __('Mark as read:')."
3611 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3612 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3614 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3617 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3618 '$match_on', '$feed_id', '$is_cat');\">
3619 ".__('Convert to label')."</a>";
3626 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3627 print "<td class=\"headlineActions$rtl_cpart\">
3628 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3629 '$match_on', '$feed_id', '$is_cat');\">
3630 ".__('Convert to Label')."</a></td>";
3633 print "<td class=\"headlineTitle$rtl_cpart\">";
3635 if ($feed_site_url) {
3637 $target = "target=\"_new\"";
3639 print "<a $target href=\"$feed_site_url\">".
3640 truncate_string($feed_title,30)."</a>";
3646 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3649 if ($user_page_offset > 1) {
3650 print " [$user_page_offset] ";
3656 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3657 <img class=\"noborder\"
3658 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3663 print "</tr></table>";
3667 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3669 $tmp_category = getCategoryTitle($link, $cat_id);
3670 $cat_unread = getCategoryUnread($link, $cat_id);
3673 $holder_style = "display:none;";
3680 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3682 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3683 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3686 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3688 print "<span id=\"FCAP-$cat_id\">";
3691 print " <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3692 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
3702 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3705 function outputFeedList($link, $tags = false) {
3707 print "<ul class=\"feedList\" id=\"feedList\">";
3709 $owner_uid = $_SESSION["uid"];
3713 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3715 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
3718 $cat_hidden = false;
3721 # print "<li class=\"feedCat\">".__('Special')."</li>";
3722 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3723 # print "<li class=\"feedCat\">".
3724 # "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
3725 # __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
3727 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
3728 # <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
3730 # $cat_unread = getCategoryUnread($link, -1);
3731 # $tmp_category = __("Special");
3732 # $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3734 printCategoryHeader($link, -1, $cat_hidden, false);
3737 $num_starred = getFeedUnread($link, -1);
3738 $num_published = getFeedUnread($link, -2);
3739 $num_fresh = getFeedUnread($link, -3);
3743 if ($num_fresh > 0) $class .= "Unread";
3745 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
3746 "images/fresh.png", $link);
3750 if ($num_starred > 0) $class .= "Unread";
3752 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
3755 $mark_img_ext = "gif";
3757 $mark_img_ext = "png";
3760 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
3761 "images/mark_set.$mark_img_ext", $link);
3765 if ($num_published > 0) $class .= "Unread";
3767 printFeedEntry(-2, $class, __("Published articles"), $num_published,
3768 "images/pub_set.gif", $link);
3770 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3776 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
3778 $result = db_query($link, "SELECT id,sql_exp,description FROM
3779 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3781 if (db_num_rows($result) > 0) {
3782 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3784 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
3787 $cat_hidden = false;
3790 printCategoryHeader($link, -2, $cat_hidden, false);
3792 # print "<li class=\"feedCat\">".
3793 # "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
3794 # __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
3796 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
3798 print "<li><hr></li>";
3802 while ($line = db_fetch_assoc($result)) {
3804 error_reporting (0);
3806 $label_id = -$line['id'] - 11;
3807 $count = getFeedUnread($link, $label_id);
3815 error_reporting (DEFAULT_ERROR_LEVEL
);
3817 printFeedEntry($label_id,
3818 $class, $line["description"],
3819 $count, "images/label.png", $link);
3823 if (db_num_rows($result) > 0) {
3824 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3831 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3832 print "<li><hr></li>";
3835 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3836 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3837 $order_by_qpart = "category,unread DESC,title";
3839 $order_by_qpart = "category,title";
3842 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3843 $order_by_qpart = "unread DESC,title";
3845 $order_by_qpart = "title";
3849 $age_qpart = getMaxAgeSubquery();
3851 $result = db_query($link, "SELECT ttrss_feeds.*,
3852 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3853 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3854 WHERE feed_id = ttrss_feeds.id AND unread = true
3856 AND ttrss_user_entries.ref_id = ttrss_entries.id
3857 AND owner_uid = '$owner_uid') as unread,
3859 ttrss_feed_categories.title AS category,
3860 ttrss_feed_categories.collapsed
3861 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
3862 ON (ttrss_feed_categories.id = cat_id)
3864 ttrss_feeds.hidden = false AND
3865 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3866 ORDER BY $order_by_qpart");
3868 $actid = $_GET["actid"];
3878 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3880 while ($line = db_fetch_assoc($result)) {
3882 $feed = trim($line["title"]);
3884 if (!$feed) $feed = "[Untitled]";
3886 $feed_id = $line["id"];
3888 $subop = $_GET["subop"];
3890 $unread = $line["unread"];
3892 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3893 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3895 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3898 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3901 $rtl_tag = "dir=\"RTL\"";
3906 $tmp_result = db_query($link,
3907 "SELECT id,COUNT(unread) AS unread
3908 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
3909 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
3910 WHERE parent_feed = '$feed_id' AND unread = true
3911 GROUP BY ttrss_feeds.id");
3913 if (db_num_rows($tmp_result) > 0) {
3914 while ($l = db_fetch_assoc($tmp_result)) {
3915 $unread +
= $l["unread"];
3919 $cat_id = $line["cat_id"];
3921 $tmp_category = $line["category"];
3923 if (!$tmp_category) {
3924 $tmp_category = __("Uncategorized");
3927 // $class = ($lnum % 2) ? "even" : "odd";
3929 if ($line["last_error"]) {
3935 if ($unread > 0) $class .= "Unread";
3937 if ($actid == $feed_id) {
3938 $class .= "Selected";
3941 $total_unread +
= $unread;
3943 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3949 $category = $tmp_category;
3951 $collapsed = $line["collapsed"];
3953 // workaround for NULL category
3954 if ($category == __("Uncategorized")) {
3955 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3960 if ($collapsed == "t" ||
$collapsed == "1") {
3961 $holder_class = "feedCatHolder";
3962 $holder_style = "display:none;";
3965 $holder_class = "feedCatHolder";
3970 $cat_id = sprintf("%d", $cat_id);
3972 $cat_unread = getCategoryUnread($link, $cat_id);
3974 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3976 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3977 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3978 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3979 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3980 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3983 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3986 printFeedEntry($feed_id, $class, $feed, $unread,
3987 ICONS_DIR
."/$feed_id.ico", $link, $rtl_content,
3988 $last_updated, $line["last_error"]);
3993 if (db_num_rows($result) == 0) {
3994 print "<li>".__('No feeds to display.')."</li>";
4001 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4002 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4003 post_int_id = ttrss_user_entries.int_id AND
4004 unread = true AND ref_id = ttrss_entries.id
4005 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4007 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4008 ORDER BY tag_name"); */
4010 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4011 print "<li class=\"feedCat\">".__('Tags')."</li>";
4012 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4015 $age_qpart = getMaxAgeSubquery();
4017 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4018 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4019 AND ref_id = id AND $age_qpart
4020 AND unread = true)) AS count FROM ttrss_tags
4021 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4022 ORDER BY count DESC LIMIT 50");
4026 while ($line = db_fetch_assoc($result)) {
4027 $tags[$line["tag_name"]] +
= $line["count"];
4030 foreach (array_keys($tags) as $tag) {
4032 $unread = $tags[$tag];
4040 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4044 if (db_num_rows($result) == 0) {
4045 print "<li>No tags to display.</li>";
4048 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4058 function get_article_tags($link, $id, $owner_uid = 0) {
4060 $a_id = db_escape_string($id);
4062 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4064 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4065 owner_uid as owner FROM
4066 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4067 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4071 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4072 array_push($tags, $tmp_line["tag_name"]);
4078 function trim_value(&$value) {
4079 $value = trim($value);
4082 function trim_array($array) {
4084 array_walk($tmp, 'trim_value');
4088 function tag_is_valid($tag) {
4089 if ($tag == '') return false;
4090 if (preg_match("/^[0-9]*$/", $tag)) return false;
4092 $tag = iconv("utf-8", "utf-8", $tag);
4093 if (!$tag) return false;
4098 function render_login_form($link, $mobile = false) {
4100 require_once "login_form.php";
4102 require_once "mobile/login_form.php";
4106 // from http://developer.apple.com/internet/safari/faq.html
4107 function no_cache_incantation() {
4108 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4109 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4110 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4111 header("Cache-Control: post-check=0, pre-check=0", false);
4112 header("Pragma: no-cache"); // HTTP/1.0
4115 function format_warning($msg, $id = "") {
4116 return "<div class=\"warning\" id=\"$id\">
4117 <img src=\"images/sign_excl.gif\">$msg</div>";
4120 function format_notice($msg) {
4121 return "<div class=\"notice\">
4122 <img src=\"images/sign_info.gif\">$msg</div>";
4125 function format_error($msg) {
4126 return "<div class=\"error\">
4127 <img src=\"images/sign_excl.gif\">$msg</div>";
4130 function print_notice($msg) {
4131 return print format_notice($msg);
4134 function print_warning($msg) {
4135 return print format_warning($msg);
4138 function print_error($msg) {
4139 return print format_error($msg);
4143 function T_sprintf() {
4144 $args = func_get_args();
4145 return vsprintf(__(array_shift($args)), $args);
4148 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4150 /* we can figure out feed_id from article id anyway, why do we
4151 * pass feed_id here? */
4153 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4154 WHERE ref_id = '$id'");
4156 $feed_id = db_fetch_result($result, 0, "feed_id");
4158 print "<article id='$id'><![CDATA[";
4160 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4161 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4163 if (db_num_rows($result) == 1) {
4164 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4166 $rtl_content = false;
4170 $rtl_tag = "dir=\"RTL\"";
4177 if ($mark_as_read) {
4178 $result = db_query($link, "UPDATE ttrss_user_entries
4179 SET unread = false,last_read = NOW()
4180 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4183 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4184 SUBSTRING(updated,1,16) as updated,
4185 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4188 FROM ttrss_entries,ttrss_user_entries
4189 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4195 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4196 $link_target = "target=\"_new\"";
4199 $line = db_fetch_assoc($result);
4201 if ($line["icon_url"]) {
4202 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4204 $feed_icon = " ";
4207 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4208 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4210 $entry_comments = "";
4213 $num_comments = $line["num_comments"];
4214 $entry_comments = "";
4216 if ($num_comments > 0) {
4217 if ($line["comments"]) {
4218 $comments_url = $line["comments"];
4220 $comments_url = $line["link"];
4222 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4224 if ($line["comments"] && $line["link"] != $line["comments"]) {
4225 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4229 print "<div class=\"postReply\">";
4231 print "<div class=\"postHeader\">";
4233 $entry_author = $line["author"];
4235 if ($entry_author) {
4236 $entry_author = __(" - by ") . $entry_author;
4239 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4240 strtotime($line["updated"]));
4242 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4244 if ($line["link"]) {
4245 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4246 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4248 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4251 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4252 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4253 ORDER BY tag_name"); */
4255 $tags = get_article_tags($link, $id);
4262 foreach ($tags as $tag) {
4264 $tag_escaped = str_replace("'", "\\'", $tag);
4266 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4268 if ($num_tags == 6) {
4271 } else if ($num_tags < 6) {
4272 $tags_str .= $tag_str;
4274 $f_tags_str .= $tag_str;
4277 $tags_str = preg_replace("/, $/", "", $tags_str);
4278 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4280 $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4281 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4283 if (!$entry_comments) $entry_comments = " "; # placeholder
4285 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4287 print "<div style='float : right'>
4288 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4290 <a title=\"Edit tags for this article\"
4291 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4292 <div clear='both'>$entry_comments</div>";
4296 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4297 print "<div class=\"postContent\">";
4299 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4301 $line["content"] = sanitize_rss($link, $line["content"]);
4303 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4304 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4307 print $line["content"] . "</div>";
4313 print "]]></article>";
4317 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4318 $next_unread_feed, $offset) {
4320 $timing_info = getmicrotime();
4322 $topmost_article_ids = array();
4328 if ($subop == "undefined") $subop = "";
4330 if ($subop == "CatchupSelected") {
4331 $ids = split(",", db_escape_string($_GET["ids"]));
4332 $cmode = sprintf("%d", $_GET["cmode"]);
4334 catchupArticlesById($link, $ids, $cmode);
4337 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4338 update_generic_feed($link, $feed, $cat_view);
4341 if ($subop == "MarkAllRead") {
4342 catchup_feed($link, $feed, $cat_view);
4344 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4345 if ($next_unread_feed) {
4346 $feed = $next_unread_feed;
4352 $result = db_query($link,
4353 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4355 if (db_num_rows($result) == 0) {
4356 print "<div align='center'>".__('Feed not found.')."</div>";
4361 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4363 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4364 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4366 if (db_num_rows($result) == 1) {
4367 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4369 $rtl_content = false;
4373 $rtl_tag = "dir=\"RTL\"";
4379 $rtl_content = false;
4382 $script_dt_add = get_script_dt_add();
4384 /// START /////////////////////////////////////////////////////////////////////////////////
4386 $search = db_escape_string($_GET["query"]);
4387 $search_mode = db_escape_string($_GET["search_mode"]);
4388 $match_on = db_escape_string($_GET["match_on"]);
4394 $real_offset = $offset * $limit;
4396 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4398 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4399 $search, $search_mode, $match_on, false, $real_offset);
4401 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4403 $result = $qfh_ret[0];
4404 $feed_title = $qfh_ret[1];
4405 $feed_site_url = $qfh_ret[2];
4406 $last_error = $qfh_ret[3];
4409 $feed_site_url = article_publish_url($link);
4412 /// STOP //////////////////////////////////////////////////////////////////////////////////
4415 print "<div id=\"headlinesContainer\" $rtl_tag>";
4418 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4422 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4423 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4426 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4429 $headlines_count = db_num_rows($result);
4431 if (db_num_rows($result) > 0) {
4433 # print "\{$offset}";
4435 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4436 print "<table class=\"headlinesList\" id=\"headlinesList\"
4437 cellspacing=\"0\">";
4440 $lnum = $limit*$offset;
4442 error_reporting (DEFAULT_ERROR_LEVEL
);
4446 while ($line = db_fetch_assoc($result)) {
4448 $class = ($lnum %
2) ?
"even" : "odd";
4451 $feed_id = $line["feed_id"];
4453 if (count($topmost_article_ids) < 5) {
4454 array_push($topmost_article_ids, $id);
4457 if ($line["last_read"] == "" &&
4458 ($line["unread"] != "t" && $line["unread"] != "1")) {
4460 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4463 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4467 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4475 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4478 $mark_img_ext = "gif";
4480 $mark_img_ext = "png";
4483 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4484 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4486 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4488 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4490 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4493 if ($line["published"] == "t" ||
$line["published"] == "1") {
4494 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4496 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4498 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4500 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4503 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4504 # $line["title"] . "</a>";
4506 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4507 $line["title"] . "</a>";
4509 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4510 # $line["title"] . "</a>";
4512 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4513 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4515 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4516 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4519 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4520 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4524 $entry_author = $line["author"];
4526 if ($entry_author) {
4527 $entry_author = " - by $entry_author";
4530 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4532 print "<tr class='$class' id='RROW-$id'>";
4534 print "<td class='hlUpdPic'>$update_pic</td>";
4536 print "<td class='hlSelectRow'>
4537 <input type=\"checkbox\" onclick=\"tSR(this)\"
4541 print "<td class='hlMarkedPic'>$marked_pic</td>";
4542 print "<td class='hlMarkedPic'>$published_pic</td>";
4544 # if ($line["feed_title"]) {
4545 # print "<td class='hlContent'>$content_link</td>";
4546 # print "<td class='hlFeed'>
4547 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4548 # truncate_string($line["feed_title"],30)."</a> </td>";
4551 print "<td class='hlContent' valign='middle'>";
4553 print "<a href=\"javascript:view($id,$feed_id);\">" .
4556 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4557 if ($content_preview) {
4558 print "<span class=\"contentPreview\"> - $content_preview</span>";
4564 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4565 # $line["feed_title"]."</a>
4567 if ($line["feed_title"]) {
4568 print "<span class=\"hlFeed\">
4569 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4570 $line["feed_title"]."</a>)
4579 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
4586 $add_class = "Unread";
4591 print "<div class=\"cdmArticle$add_class\"
4592 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4593 onmouseout='cdmMouseOut(this)'>";
4595 print "<div class=\"cdmHeader\">";
4597 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4599 print "<a class=\"title\"
4600 onclick=\"javascript:toggleUnread($id, 0)\"
4601 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4603 print $entry_author;
4605 if ($line["feed_title"]) {
4606 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4611 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4612 $line["content_preview"] = preg_replace("/href=/i",
4613 "target=\"_new\" href=", $line["content_preview"]);
4616 print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
4618 print "<div class=\"cdmFooter\"><span class='s0'>";
4620 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
4622 print __("Select:").
4623 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
4624 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
4626 print "</span><span class='s1'>$marked_pic</span> ";
4627 print "<span class='s1'>$published_pic</span> ";
4629 $tags = get_article_tags($link, $id);
4632 $full_tags_str = "";
4635 foreach ($tags as $tag) {
4637 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
4638 if ($num_tags < 5) {
4639 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
4640 } else if ($num_tags == 5) {
4645 $tags_str = preg_replace("/, $/", "", $tags_str);
4646 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
4648 $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
4650 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4653 if ($tags_str == "") $tags_str = "no tags";
4655 // print "<img src='images/tag.png' class='markedPic'>";
4657 print "<span class='s1'>
4658 <img class='tagsPic' src='images/tag.png' alt='Tags'
4659 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
4660 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
4664 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
4665 href=\"javascript:toggleUnread($id)\">
4676 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4680 // print_headline_subtoolbar($link,
4681 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
4685 if (!$offset) print "<div class='whiteBox'>".__('No articles found.')."</div>";
4693 return array($topmost_article_ids, $headlines_count);
4696 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
4698 function printTagCloud($link) {
4700 /* get first ref_id to count from */
4706 if (DB_TYPE == "pgsql") {
4707 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
4708 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
4709 AND date_entered > NOW() - INTERVAL '30 days'";
4711 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
4712 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
4713 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
4716 $result = db_query($link, $query);
4717 $first_id = db_fetch_result($result, 0, "id"); */
4719 //AND post_int_id >= '$first_id'
4720 $query = "SELECT tag_name, COUNT(post_int_id) AS count
4721 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
4722 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
4724 $result = db_query($link, $query);
4728 while ($line = db_fetch_assoc($result)) {
4729 $tags[$line["tag_name"]] = $line["count"];
4734 $max_size = 32; // max font size in pixels
4735 $min_size = 11; // min font size in pixels
4737 // largest and smallest array values
4738 $max_qty = max(array_values($tags));
4739 $min_qty = min(array_values($tags));
4741 // find the range of values
4742 $spread = $max_qty - $min_qty;
4743 if ($spread == 0) { // we don't want to divide by zero
4747 // set the font-size increment
4748 $step = ($max_size - $min_size) / ($spread);
4750 // loop through the tag array
4751 foreach ($tags as $key => $value) {
4752 // calculate font-size
4753 // find the $value in excess of $min_qty
4754 // multiply by the font-size increment ($size)
4755 // and add the $min_size set above
4756 $size = round($min_size +
(($value - $min_qty) * $step));
4758 $key_escaped = str_replace("'", "\\'", $key);
4760 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
4761 $size . "px\" title=\"$value articles tagged with " .
4762 $key . '">' . $key . '</a> ';
4766 function print_checkpoint($n, $s) {
4767 $ts = getmicrotime();
4768 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
4772 function sanitize_tag($tag) {
4775 $tag = mb_strtolower($tag, 'utf-8');
4777 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
4779 // $tag = str_replace('"', "", $tag);
4780 // $tag = str_replace("+", " ", $tag);
4781 $tag = str_replace("technorati tag: ", "", $tag);
4786 function generate_publish_key() {
4787 return sha1(uniqid(rand(), true));
4790 function article_publish_url($link) {
4792 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
4794 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
4799 function clear_feed_articles($link, $id) {
4800 $result = db_query($link, "DELETE FROM ttrss_user_entries
4801 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
4803 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
4804 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
4807 function add_feed_url() {
4808 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
4809 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
4813 function encrypt_password($pass, $login = '') {
4815 return "SHA1X:" . sha1("$login:$pass");
4817 return "SHA1:" . sha1($pass);