]>
git.wh0rd.org - tt-rss.git/blob - functions.php
6376a282c8b3cd2393e02aaf483adec96e9bde67
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 if (ENABLE_TRANSLATIONS
== true) {
12 require_once "accept-to-gettext.php";
13 require_once "gettext/gettext.inc";
15 function startup_gettext() {
17 # Get locale from Accept-Language header
18 $lang = al2gt(array("en_US", "ru_RU"), "text/html");
21 _setlocale(LC_MESSAGES
, $lang);
22 _bindtextdomain("messages", "locale");
23 _textdomain("messages");
24 _bind_textdomain_codeset("messages", "UTF-8");
34 function startup_gettext() {
40 require_once 'db-prefs.php';
41 require_once 'compat.php';
42 require_once 'errors.php';
43 require_once 'version.php';
45 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
46 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
48 require_once "magpierss/rss_fetch.inc";
49 require_once 'magpierss/rss_utils.inc';
51 include_once "tw/tw-config.php";
52 include_once "tw/tw.php";
53 include_once TW_SETUP
. "paranoya.php";
55 $tw_parser = new twParser();
57 function _debug($msg) {
58 $ts = strftime("%H:%M:%S", time());
62 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
66 if (DB_TYPE
== "pgsql") {
67 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
68 marked = false AND feed_id = '$feed_id' AND
69 (SELECT date_entered FROM ttrss_entries WHERE
70 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
72 $pg_version = get_pgsql_version($link);
74 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
76 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
77 ttrss_entries.id = ref_id AND
79 feed_id = '$feed_id' AND
80 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
84 $result = db_query($link, "DELETE FROM ttrss_user_entries
86 WHERE ttrss_entries.id = ref_id AND
88 feed_id = '$feed_id' AND
89 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
92 $rows = pg_affected_rows($result);
96 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
97 marked = false AND feed_id = '$feed_id' AND
98 (SELECT date_entered FROM ttrss_entries WHERE
99 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
101 $result = db_query($link, "DELETE FROM ttrss_user_entries
102 USING ttrss_user_entries, ttrss_entries
103 WHERE ttrss_entries.id = ref_id AND
105 feed_id = '$feed_id' AND
106 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
108 $rows = mysql_affected_rows($link);
113 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
117 function global_purge_old_posts($link, $do_output = false, $limit = false) {
119 $random_qpart = sql_random_function();
122 $limit_qpart = "LIMIT $limit";
127 $result = db_query($link,
128 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
129 ORDER BY $random_qpart $limit_qpart");
131 while ($line = db_fetch_assoc($result)) {
133 $feed_id = $line["id"];
134 $purge_interval = $line["purge_interval"];
135 $owner_uid = $line["owner_uid"];
137 if ($purge_interval == 0) {
139 $tmp_result = db_query($link,
140 "SELECT value FROM ttrss_user_prefs WHERE
141 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
143 if (db_num_rows($tmp_result) != 0) {
144 $purge_interval = db_fetch_result($tmp_result, 0, "value");
149 // print "Feed $feed_id: purge interval = $purge_interval\n";
152 if ($purge_interval > 0) {
153 purge_feed($link, $feed_id, $purge_interval, $do_output);
157 // purge orphaned posts in main content table
158 db_query($link, "DELETE FROM ttrss_entries WHERE
159 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
163 function purge_old_posts($link) {
165 $user_id = $_SESSION["uid"];
167 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
168 WHERE owner_uid = '$user_id'");
170 while ($line = db_fetch_assoc($result)) {
172 $feed_id = $line["id"];
173 $purge_interval = $line["purge_interval"];
175 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
177 if ($purge_interval > 0) {
178 purge_feed($link, $feed_id, $purge_interval);
182 // purge orphaned posts in main content table
183 db_query($link, "DELETE FROM ttrss_entries WHERE
184 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
187 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
189 if (WEB_DEMO_MODE
) return;
192 $user_id = $_SESSION["uid"];
193 purge_old_posts($link);
196 // db_query($link, "BEGIN");
198 if (MAX_UPDATE_TIME
> 0) {
199 if (DB_TYPE
== "mysql") {
202 $q_order = "RANDOM()";
205 $q_order = "last_updated DESC";
208 $result = db_query($link, "SELECT feed_url,id,
209 SUBSTRING(last_updated,1,19) AS last_updated,
210 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
215 while ($line = db_fetch_assoc($result)) {
216 $upd_intl = $line["update_interval"];
218 if (!$upd_intl ||
$upd_intl == 0) {
219 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
223 // Updates for this feed are disabled
227 if ($fetch ||
(!$line["last_updated"] ||
228 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
230 // print "<!-- feed: ".$line["feed_url"]." -->";
232 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
234 $upd_elapsed = time() - $upd_start;
236 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
242 // db_query($link, "COMMIT");
246 function fetch_file_contents($url) {
247 if (USE_CURL_FOR_ICONS
) {
248 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
250 $ch = curl_init($url);
251 $fp = fopen($tmpfile, "w");
254 curl_setopt($ch, CURLOPT_FILE
, $fp);
255 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
256 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
262 $contents = file_get_contents($tmpfile);
268 return file_get_contents($url);
273 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
274 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
276 function get_favicon_url($url) {
278 if ($html = @fetch_file_contents
($url)) {
280 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
281 // Attempt to grab a favicon link from their webpage url
282 $linkUrl = html_entity_decode($matches[1]);
284 if (substr($linkUrl, 0, 1) == '/') {
285 $urlParts = parse_url($url);
286 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
287 } else if (substr($linkUrl, 0, 7) == 'http://') {
288 $faviconURL = $linkUrl;
289 } else if (substr($url, -1, 1) == '/') {
290 $faviconURL = $url.$linkUrl;
292 $faviconURL = $url.'/'.$linkUrl;
296 // If unsuccessful, attempt to "guess" the favicon location
297 $urlParts = parse_url($url);
298 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
302 // Run a test to see if what we have attempted to get actually exists.
303 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
310 function url_validate($link) {
312 $url_parts = @parse_url
($link);
314 if ( empty( $url_parts["host"] ) )
317 if ( !empty( $url_parts["path"] ) ) {
318 $documentpath = $url_parts["path"];
323 if ( !empty( $url_parts["query"] ) )
324 $documentpath .= "?" . $url_parts["query"];
326 $host = $url_parts["host"];
327 $port = $url_parts["port"];
332 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
337 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
339 $http_response = fgets( $socket, 22 );
341 $responses = "/(200 OK)|(30[0-9] Moved)/";
342 if ( preg_match($responses, $http_response) ) {
351 function check_feed_favicon($site_url, $feed, $link) {
352 $favicon_url = get_favicon_url($site_url);
354 # print "FAVICON [$site_url]: $favicon_url\n";
358 $icon_file = ICONS_DIR
. "/$feed.ico";
360 if ($favicon_url && !file_exists($icon_file)) {
361 $contents = fetch_file_contents($favicon_url);
363 $fp = fopen($icon_file, "w");
366 fwrite($fp, $contents);
368 chmod($icon_file, 0644);
372 error_reporting(DEFAULT_ERROR_LEVEL
);
376 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
378 if (DAEMON_REFRESH_ONLY
&& !$_GET["daemon"] && !$ignore_daemon) {
382 if (defined('DAEMON_EXTENDED_DEBUG')) {
383 _debug("update_rss_feed: start");
386 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass
387 FROM ttrss_feeds WHERE id = '$feed'");
389 $auth_login = db_fetch_result($result, 0, "auth_login");
390 $auth_pass = db_fetch_result($result, 0, "auth_pass");
392 $update_interval = db_fetch_result($result, 0, "update_interval");
394 if ($update_interval < 0) { return; }
396 $feed = db_escape_string($feed);
398 $fetch_url = $feed_url;
400 if ($auth_login && $auth_pass) {
401 $url_parts = array();
402 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
404 if ($url_parts[1] && $url_parts[2]) {
405 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
410 if (defined('DAEMON_EXTENDED_DEBUG')) {
411 _debug("update_rss_feed: fetching...");
414 if (!defined('DAEMON_EXTENDED_DEBUG')) {
418 $rss = fetch_rss($fetch_url);
420 if (defined('DAEMON_EXTENDED_DEBUG')) {
421 _debug("update_rss_feed: fetch done, parsing...");
423 error_reporting (DEFAULT_ERROR_LEVEL
);
426 $feed = db_escape_string($feed);
430 if (defined('DAEMON_EXTENDED_DEBUG')) {
431 _debug("update_rss_feed: processing feed data...");
434 // db_query($link, "BEGIN");
436 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
437 FROM ttrss_feeds WHERE id = '$feed'");
439 $registered_title = db_fetch_result($result, 0, "title");
440 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
441 $orig_site_url = db_fetch_result($result, 0, "site_url");
443 $owner_uid = db_fetch_result($result, 0, "owner_uid");
445 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
446 if (defined('DAEMON_EXTENDED_DEBUG')) {
447 _debug("update_rss_feed: checking favicon...");
449 check_feed_favicon($rss->channel
["link"], $feed, $link);
452 if (!$registered_title ||
$registered_title == "[Unknown]") {
454 $feed_title = db_escape_string($rss->channel
["title"]);
456 db_query($link, "UPDATE ttrss_feeds SET
457 title = '$feed_title' WHERE id = '$feed'");
460 $site_url = $rss->channel
["link"];
461 // weird, weird Magpie
462 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
464 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
465 db_query($link, "UPDATE ttrss_feeds SET
466 site_url = '$site_url' WHERE id = '$feed'");
469 // print "I: " . $rss->channel["image"]["url"];
471 $icon_url = $rss->image
["url"];
473 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
474 $icon_url = db_escape_string($icon_url);
475 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
478 if (defined('DAEMON_EXTENDED_DEBUG')) {
479 _debug("update_rss_feed: loading filters...");
484 $result = db_query($link, "SELECT reg_exp,
485 ttrss_filter_types.name AS name,
486 ttrss_filter_actions.name AS action,
489 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
491 owner_uid = $owner_uid AND
492 ttrss_filter_types.id = filter_type AND
493 ttrss_filter_actions.id = action_id AND
494 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
496 while ($line = db_fetch_assoc($result)) {
497 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
499 $filter["reg_exp"] = $line["reg_exp"];
500 $filter["action"] = $line["action"];
501 $filter["action_param"] = $line["action_param"];
502 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
504 array_push($filters[$line["name"]], $filter);
507 $iterator = $rss->items
;
509 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
510 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
512 if (!is_array($iterator)) {
513 /* db_query($link, "UPDATE ttrss_feeds
514 SET last_error = 'Parse error: can\'t find any articles.'
515 WHERE id = '$feed'"); */
517 // clear any errors and mark feed as updated if fetched okay
518 // even if it's blank
520 if (defined('DAEMON_EXTENDED_DEBUG')) {
521 _debug("update_rss_feed: entry iterator is not an array, no articles?");
524 db_query($link, "UPDATE ttrss_feeds
525 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
527 return; // no articles
530 if (defined('DAEMON_EXTENDED_DEBUG')) {
531 _debug("update_rss_feed: processing articles...");
534 foreach ($iterator as $item) {
536 $entry_guid = $item["id"];
538 if (!$entry_guid) $entry_guid = $item["guid"];
539 if (!$entry_guid) $entry_guid = $item["link"];
540 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
542 if (defined('DAEMON_EXTENDED_DEBUG')) {
543 _debug("update_rss_feed: guid $entry_guid");
546 if (!$entry_guid) continue;
548 $entry_timestamp = "";
550 $rss_2_date = $item['pubdate'];
551 $rss_1_date = $item['dc']['date'];
552 $atom_date = $item['issued'];
553 if (!$atom_date) $atom_date = $item['updated'];
555 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
556 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
557 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
559 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
560 $entry_timestamp = time();
561 $no_orig_date = 'true';
563 $no_orig_date = 'false';
566 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
568 $entry_title = trim(strip_tags($item["title"]));
570 // strange Magpie workaround
571 $entry_link = $item["link_"];
572 if (!$entry_link) $entry_link = $item["link"];
574 if (!$entry_title) continue;
575 # if (!$entry_link) continue;
577 $entry_link = strip_tags($entry_link);
579 $entry_content = $item["content:escaped"];
581 if (!$entry_content) $entry_content = $item["content:encoded"];
582 if (!$entry_content) $entry_content = $item["content"];
583 if (!$entry_content) $entry_content = $item["atom_content"];
584 if (!$entry_content) $entry_content = $item["summary"];
585 if (!$entry_content) $entry_content = $item["description"];
587 // if (!$entry_content) continue;
590 if (is_array($entry_content)) {
591 $entry_content = $entry_content["encoded"];
592 if (!$entry_content) $entry_content = $entry_content["escaped"];
596 // print_r(htmlspecialchars($entry_content));
599 $entry_content_unescaped = $entry_content;
601 $entry_comments = strip_tags($item["comments"]);
603 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
605 if ($item['author']) {
607 if (is_array($item['author'])) {
609 if (!$entry_author) {
610 $entry_author = db_escape_string(strip_tags($item['author']['name']));
613 if (!$entry_author) {
614 $entry_author = db_escape_string(strip_tags($item['author']['email']));
618 if (!$entry_author) {
619 $entry_author = db_escape_string(strip_tags($item['author']));
623 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
625 $entry_guid = db_escape_string(strip_tags($entry_guid));
627 $result = db_query($link, "SELECT id FROM ttrss_entries
628 WHERE guid = '$entry_guid'");
630 $entry_content = db_escape_string($entry_content);
632 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
634 $entry_title = db_escape_string($entry_title);
635 $entry_link = db_escape_string($entry_link);
636 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
637 $entry_author = mb_substr($entry_author, 0, 250);
639 $num_comments = db_escape_string($item["slash"]["comments"]);
641 if (!$num_comments) $num_comments = 0;
643 // parse <category> entries into tags
645 $t_ctr = $item['category#'];
647 $additional_tags = false;
650 $additional_tags = false;
651 } else if ($t_ctr == 1) {
652 $additional_tags = array($item['category']);
654 $additional_tags = array();
655 for ($i = 0; $i <= $t_ctr; $i++
) {
656 if ($item["category#$i"]) {
657 array_push($additional_tags, $item["category#$i"]);
662 // parse <dc:subject> elements
664 $t_ctr = $item['dc']['subject#'];
667 $additional_tags = array($item['dc']['subject']);
668 } else if ($t_ctr > 1) {
669 $additional_tags = array();
670 for ($i = 0; $i <= $t_ctr; $i++
) {
671 if ($item['dc']["subject#$i"]) {
672 array_push($additional_tags, $item['dc']["subject#$i"]);
679 // $entry_content = sanitize_rss($entry_content);
681 if (defined('DAEMON_EXTENDED_DEBUG')) {
682 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
685 db_query($link, "BEGIN");
687 if (db_num_rows($result) == 0) {
689 if (defined('DAEMON_EXTENDED_DEBUG')) {
690 _debug("update_rss_feed: base guid not found");
693 // base post entry does not exist, create it
695 $result = db_query($link,
696 "INSERT INTO ttrss_entries
712 '$entry_timestamp_fmt',
721 // we keep encountering the entry in feeds, so we need to
722 // update date_entered column so that we don't get horrible
723 // dupes when the entry gets purged and reinserted again e.g.
724 // in the case of SLOW SLOW OMG SLOW updating feeds
726 $base_entry_id = db_fetch_result($result, 0, "id");
728 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
729 WHERE id = '$base_entry_id'");
732 // now it should exist, if not - bad luck then
734 $result = db_query($link, "SELECT
735 id,content_hash,no_orig_date,title,
736 substring(date_entered,1,19) as date_entered,
737 substring(updated,1,19) as updated,
741 WHERE guid = '$entry_guid'");
743 if (db_num_rows($result) == 1) {
745 if (defined('DAEMON_EXTENDED_DEBUG')) {
746 _debug("update_rss_feed: base guid found, checking for user record");
749 // this will be used below in update handler
750 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
751 $orig_title = db_fetch_result($result, 0, "title");
752 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
753 $orig_date_entered = strtotime(db_fetch_result($result,
756 $ref_id = db_fetch_result($result, 0, "id");
758 // check for user post link to main table
760 // do we allow duplicate posts with same GUID in different feeds?
761 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
762 $dupcheck_qpart = "AND feed_id = '$feed'";
764 $dupcheck_qpart = "";
767 // error_reporting(0);
769 $article_filters = get_article_filters($filters, $entry_title,
770 $entry_content, $entry_link);
772 if (defined('DAEMON_EXTENDED_DEBUG')) {
773 _debug("update_rss_feed: article filters: ");
774 if (count($article_filters) != 0) {
775 print_r($article_filters);
779 if (find_article_filter($article_filters, "filter")) {
783 // error_reporting (DEFAULT_ERROR_LEVEL);
785 $result = db_query($link,
786 "SELECT ref_id FROM ttrss_user_entries WHERE
787 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
790 // okay it doesn't exist - create user entry
791 if (db_num_rows($result) == 0) {
793 if (defined('DAEMON_EXTENDED_DEBUG')) {
794 _debug("update_rss_feed: user record not found, creating...");
797 if (!find_article_filter($article_filters, 'catchup')) {
799 $last_read_qpart = 'NULL';
802 $last_read_qpart = 'NOW()';
805 if (find_article_filter($article_filters, 'mark')) {
811 $result = db_query($link,
812 "INSERT INTO ttrss_user_entries
813 (ref_id, owner_uid, feed_id, unread, last_read, marked)
814 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
815 $last_read_qpart, $marked)");
818 $post_needs_update = false;
820 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
821 ($content_hash != $orig_content_hash)) {
822 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
823 $post_needs_update = true;
826 if (db_escape_string($orig_title) != $entry_title) {
827 $post_needs_update = true;
830 if ($orig_num_comments != $num_comments) {
831 $post_needs_update = true;
834 // this doesn't seem to be very reliable
836 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
837 // $post_needs_update = true;
840 // if post needs update, update it and mark all user entries
841 // linking to this post as updated
842 if ($post_needs_update) {
844 if (defined('DAEMON_EXTENDED_DEBUG')) {
845 _debug("update_rss_feed: post $entry_guid needs update...");
848 // print "<!-- post $orig_title needs update : $post_needs_update -->";
850 db_query($link, "UPDATE ttrss_entries
851 SET title = '$entry_title', content = '$entry_content',
852 content_hash = '$content_hash',
853 num_comments = '$num_comments'
854 WHERE id = '$ref_id'");
856 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
857 db_query($link, "UPDATE ttrss_user_entries
858 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
860 db_query($link, "UPDATE ttrss_user_entries
861 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
867 db_query($link, "COMMIT");
869 if (defined('DAEMON_EXTENDED_DEBUG')) {
870 _debug("update_rss_feed: looking for tags...");
874 // <a href="..." rel="tag">Xorg</a>, //
878 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
879 $entry_content_unescaped, $entry_tags);
881 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
882 print_r($entry_tags);
883 print "<br/></p>"; */
885 $entry_tags = $entry_tags[1];
887 # check for manual tags
889 $tag_filter = find_article_filter($article_filters, "tag");
893 $manual_tags = trim_array(split(",", $tag_filter[1]));
895 foreach ($manual_tags as $tag) {
896 if (tag_is_valid($tag)) {
897 array_push($entry_tags, $tag);
902 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
903 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
905 if ($additional_tags && is_array($additional_tags)) {
906 foreach ($additional_tags as $tag) {
907 if (tag_is_valid($tag) &&
908 array_search($tag, $boring_tags) === FALSE) {
909 array_push($entry_tags, $tag);
914 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
916 if (count($entry_tags) > 0) {
918 db_query($link, "BEGIN");
920 $result = db_query($link, "SELECT id,int_id
921 FROM ttrss_entries,ttrss_user_entries
922 WHERE guid = '$entry_guid'
923 AND feed_id = '$feed' AND ref_id = id
924 AND owner_uid = '$owner_uid'");
926 if (db_num_rows($result) == 1) {
928 $entry_id = db_fetch_result($result, 0, "id");
929 $entry_int_id = db_fetch_result($result, 0, "int_id");
931 foreach ($entry_tags as $tag) {
933 $tag = sanitize_tag($tag);
934 $tag = db_escape_string($tag);
936 if (!tag_is_valid($tag)) continue;
938 $result = db_query($link, "SELECT id FROM ttrss_tags
939 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
940 owner_uid = '$owner_uid' LIMIT 1");
942 // print db_fetch_result($result, 0, "id");
944 if ($result && db_num_rows($result) == 0) {
946 db_query($link, "INSERT INTO ttrss_tags
947 (owner_uid,tag_name,post_int_id)
948 VALUES ('$owner_uid','$tag', '$entry_int_id')");
952 db_query($link, "COMMIT");
956 db_query($link, "UPDATE ttrss_feeds
957 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
959 // db_query($link, "COMMIT");
962 $error_msg = db_escape_string(magpie_error());
964 "UPDATE ttrss_feeds SET last_error = '$error_msg',
965 last_updated = NOW() WHERE id = '$feed'");
968 if (defined('DAEMON_EXTENDED_DEBUG')) {
969 _debug("update_rss_feed: done");
974 function print_select($id, $default, $values, $attributes = "") {
975 print "<select name=\"$id\" id=\"$id\" $attributes>";
976 foreach ($values as $v) {
982 print "<option$sel>$v</option>";
987 function print_select_hash($id, $default, $values, $attributes = "") {
988 print "<select name=\"$id\" id='$id' $attributes>";
989 foreach (array_keys($values) as $v) {
995 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1001 function get_article_filters($filters, $title, $content, $link) {
1004 if ($filters["title"]) {
1005 foreach ($filters["title"] as $filter) {
1006 $reg_exp = $filter["reg_exp"];
1007 $inverse = $filter["inverse"];
1008 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1009 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1011 array_push($matches, array($filter["action"], $filter["action_param"]));
1016 if ($filters["content"]) {
1017 foreach ($filters["content"] as $filter) {
1018 $reg_exp = $filter["reg_exp"];
1019 $inverse = $filter["inverse"];
1021 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1022 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1024 array_push($matches, array($filter["action"], $filter["action_param"]));
1029 if ($filters["both"]) {
1030 foreach ($filters["both"] as $filter) {
1031 $reg_exp = $filter["reg_exp"];
1032 $inverse = $filter["inverse"];
1035 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1036 array_push($matches, array($filter["action"], $filter["action_param"]));
1039 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1040 array_push($matches, array($filter["action"], $filter["action_param"]));
1046 if ($filters["link"]) {
1047 $reg_exp = $filter["reg_exp"];
1048 foreach ($filters["link"] as $filter) {
1049 $reg_exp = $filter["reg_exp"];
1050 $inverse = $filter["inverse"];
1052 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1053 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1055 array_push($matches, array($filter["action"], $filter["action_param"]));
1063 function find_article_filter($filters, $filter_name) {
1064 foreach ($filters as $f) {
1065 if ($f[0] == $filter_name) {
1072 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1073 $rtl_content = false, $last_updated = false, $last_error = false) {
1075 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1076 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1078 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1082 $rtl_tag = "dir=\"rtl\"";
1084 $rtl_tag = "dir=\"ltr\"";
1087 $error_notify_msg = "";
1090 $link_title = "Error: $last_error ($last_updated)";
1091 $error_notify_msg = "(Error)";
1092 } else if ($last_updated) {
1093 $link_title = "Updated: $last_updated";
1096 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1097 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1099 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1100 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1104 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1109 $fctr_class = "class=\"invisible\"";
1112 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1113 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1115 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1116 print "<div class=\"feedExtInfo\">
1117 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1124 function getmicrotime() {
1125 list($usec, $sec) = explode(" ",microtime());
1126 return ((float)$usec +
(float)$sec);
1129 function print_radio($id, $default, $values, $attributes = "") {
1130 foreach ($values as $v) {
1138 $sel .= " value=\"1\"";
1140 $sel .= " value=\"0\"";
1143 print "<input class=\"noborder\"
1144 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1149 function initialize_user_prefs($link, $uid) {
1151 $uid = db_escape_string($uid);
1153 db_query($link, "BEGIN");
1155 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1157 $u_result = db_query($link, "SELECT pref_name
1158 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1160 $active_prefs = array();
1162 while ($line = db_fetch_assoc($u_result)) {
1163 array_push($active_prefs, $line["pref_name"]);
1166 while ($line = db_fetch_assoc($result)) {
1167 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1168 // print "adding " . $line["pref_name"] . "<br>";
1170 db_query($link, "INSERT INTO ttrss_user_prefs
1171 (owner_uid,pref_name,value) VALUES
1172 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1177 db_query($link, "COMMIT");
1181 function lookup_user_id($link, $user) {
1183 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1186 if (db_num_rows($result) == 1) {
1187 return db_fetch_result($result, 0, "id");
1193 function http_authenticate_user($link) {
1195 if (!$_SERVER["PHP_AUTH_USER"]) {
1197 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1198 header('HTTP/1.0 401 Unauthorized');
1202 $auth_result = authenticate_user($link,
1203 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1205 if (!$auth_result) {
1206 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1207 header('HTTP/1.0 401 Unauthorized');
1215 function authenticate_user($link, $login, $password, $force_auth = false) {
1217 if (!SINGLE_USER_MODE
) {
1219 $pwd_hash = 'SHA1:' . sha1($password);
1221 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1222 $query = "SELECT id,login,access_level
1223 FROM ttrss_users WHERE
1226 $query = "SELECT id,login,access_level
1227 FROM ttrss_users WHERE
1228 login = '$login' AND pwd_hash = '$pwd_hash'";
1231 $result = db_query($link, $query);
1233 if (db_num_rows($result) == 1) {
1234 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1235 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1236 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1238 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1241 $user_theme = get_user_theme_path($link);
1243 $_SESSION["theme"] = $user_theme;
1244 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1246 initialize_user_prefs($link, $_SESSION["uid"]);
1255 $_SESSION["uid"] = 1;
1256 $_SESSION["name"] = "admin";
1258 $user_theme = get_user_theme_path($link);
1260 $_SESSION["theme"] = $user_theme;
1261 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1263 initialize_user_prefs($link, $_SESSION["uid"]);
1269 function make_password($length = 8) {
1272 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1276 while ($i < $length) {
1277 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1279 if (!strstr($password, $char)) {
1287 // this is called after user is created to initialize default feeds, labels
1290 // user preferences are checked on every login, not here
1292 function initialize_user($link, $uid) {
1294 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1295 values ('$uid','unread = true', 'Unread articles')");
1297 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1298 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1300 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1301 values ('$uid', 'Tiny Tiny RSS: New Releases',
1302 'http://tt-rss.spb.ru/releases.rss')");
1304 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1305 values ('$uid', 'Tiny Tiny RSS: Forum',
1306 'http://tt-rss.spb.ru/forum/rss.php')");
1309 function logout_user() {
1311 if (isset($_COOKIE[session_name()])) {
1312 setcookie(session_name(), '', time()-42000, '/');
1316 function get_script_urlpath() {
1317 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1320 function validate_session($link) {
1321 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1322 if ($_SESSION["ip_address"]) {
1323 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1324 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1330 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1332 //print_r($_SESSION);
1334 if (time() > $_SESSION["cookie_lifetime"]) {
1342 function login_sequence($link, $mobile = false) {
1343 if (!SINGLE_USER_MODE
) {
1345 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1346 $swu = db_escape_string($_REQUEST["swu"]);
1348 $_SESSION["prefs_cache"] = false;
1349 return authenticate_user($link, $swu, null, true);
1353 $login_action = $_POST["login_action"];
1355 # try to authenticate user if called from login form
1356 if ($login_action == "do_login") {
1357 $login = $_POST["login"];
1358 $password = $_POST["password"];
1359 $remember_me = $_POST["remember_me"];
1361 if (authenticate_user($link, $login, $password)) {
1362 $_POST["password"] = "";
1364 header("Location: " . $_SERVER["REQUEST_URI"]);
1369 $_SESSION["login_error_msg"] = "Incorrect username or password";
1373 // print session_id();
1374 // print_r($_SESSION);
1376 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1377 render_login_form($link, $mobile);
1380 /* bump login timestamp */
1381 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1386 return authenticate_user($link, "admin", null);
1390 function truncate_string($str, $max_len) {
1391 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1392 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1398 function get_user_theme_path($link) {
1399 $result = db_query($link, "SELECT theme_path
1401 ttrss_themes,ttrss_users
1402 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1403 if (db_num_rows($result) != 0) {
1404 return db_fetch_result($result, 0, "theme_path");
1410 function smart_date_time($timestamp) {
1411 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1412 return date("G:i", $timestamp);
1413 } else if (date("Y", $timestamp) == date("Y")) {
1414 return date("M d, G:i", $timestamp);
1416 return date("Y/m/d, G:i", $timestamp);
1420 function smart_date($timestamp) {
1421 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1423 } else if (date("Y", $timestamp) == date("Y")) {
1424 return date("D m", $timestamp);
1426 return date("Y/m/d", $timestamp);
1430 function sql_bool_to_string($s) {
1431 if ($s == "t" ||
$s == "1") {
1438 function sql_bool_to_bool($s) {
1439 if ($s == "t" ||
$s == "1") {
1447 function toggleEvenOdd($a) {
1454 function sanity_check($link) {
1459 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1460 $schema_version = db_fetch_result($result, 0, "schema_version");
1462 if ($schema_version != SCHEMA_VERSION
) {
1466 if (DB_TYPE
== "mysql") {
1467 $result = db_query($link, "SELECT true", false);
1468 if (db_num_rows($result) != 1) {
1473 error_reporting (DEFAULT_ERROR_LEVEL
);
1475 if ($error_code != 0) {
1476 print_error_xml($error_code);
1483 function file_is_locked($filename) {
1485 $fp = fopen($filename, "r");
1486 error_reporting(DEFAULT_ERROR_LEVEL
);
1488 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1489 flock($fp, LOCK_UN
);
1499 function make_lockfile($filename) {
1500 $fp = fopen($filename, "w");
1502 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1509 function make_stampfile($filename) {
1510 $fp = fopen($filename, "w");
1512 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1513 fwrite($fp, time() . "\n");
1514 flock($fp, LOCK_UN
);
1522 function read_stampfile($filename) {
1525 $fp = fopen($filename, "r");
1526 error_reporting (DEFAULT_ERROR_LEVEL
);
1528 if (flock($fp, LOCK_EX
)) {
1529 $stamp = fgets($fp);
1530 flock($fp, LOCK_UN
);
1538 function sql_random_function() {
1539 if (DB_TYPE
== "mysql") {
1546 function catchup_feed($link, $feed, $cat_view) {
1548 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1553 $cat_qpart = "cat_id = '$feed'";
1555 $cat_qpart = "cat_id IS NULL";
1558 $tmp_result = db_query($link, "SELECT id
1559 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1562 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1564 $tmp_feed = $tmp_line["id"];
1566 db_query($link, "UPDATE ttrss_user_entries
1567 SET unread = false,last_read = NOW()
1568 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1571 } else if ($feed > 0) {
1573 $tmp_result = db_query($link, "SELECT id
1574 FROM ttrss_feeds WHERE parent_feed = '$feed'
1575 ORDER BY cat_id,title");
1577 $parent_ids = array();
1579 if (db_num_rows($tmp_result) > 0) {
1580 while ($p = db_fetch_assoc($tmp_result)) {
1581 array_push($parent_ids, "feed_id = " . $p["id"]);
1584 $children_qpart = implode(" OR ", $parent_ids);
1586 db_query($link, "UPDATE ttrss_user_entries
1587 SET unread = false,last_read = NOW()
1588 WHERE (feed_id = '$feed' OR $children_qpart)
1589 AND owner_uid = " . $_SESSION["uid"]);
1592 db_query($link, "UPDATE ttrss_user_entries
1593 SET unread = false,last_read = NOW()
1594 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1597 } else if ($feed < 0 && $feed > -10) { // special, like starred
1600 db_query($link, "UPDATE ttrss_user_entries
1601 SET unread = false,last_read = NOW()
1602 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1605 } else if ($feed < -10) { // label
1607 // TODO make this more efficient
1609 $label_id = -$feed - 11;
1611 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1612 WHERE id = '$label_id'");
1615 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1617 db_query($link, "BEGIN");
1619 $tmp2_result = db_query($link,
1623 ttrss_user_entries,ttrss_entries,ttrss_feeds
1625 ref_id = ttrss_entries.id AND
1626 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1628 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1630 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1631 db_query($link, "UPDATE
1634 unread = false, last_read = NOW()
1636 int_id = " . $tmp_line["int_id"]);
1639 db_query($link, "COMMIT");
1641 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1642 SET unread = false,last_read = NOW()
1645 AND owner_uid = ".$_SESSION["uid"]); */
1649 db_query($link, "BEGIN");
1651 $tag_name = db_escape_string($feed);
1653 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1654 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1656 while ($line = db_fetch_assoc($result)) {
1657 db_query($link, "UPDATE ttrss_user_entries SET
1658 unread = false, last_read = NOW()
1659 WHERE int_id = " . $line["post_int_id"]);
1661 db_query($link, "COMMIT");
1665 function update_generic_feed($link, $feed, $cat_view) {
1669 $cat_qpart = "cat_id = '$feed'";
1671 $cat_qpart = "cat_id IS NULL";
1674 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1675 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1677 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1678 $feed_url = $tmp_line["feed_url"];
1679 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1683 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1684 WHERE id = '$feed'");
1685 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1686 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1690 function getAllCounters($link, $omode = "tflc") {
1691 /* getLabelCounters($link);
1692 getFeedCounters($link);
1693 getTagCounters($link);
1694 getGlobalCounters($link);
1695 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1696 getCategoryCounters($link);
1699 if (!$omode) $omode = "tflc";
1701 getGlobalCounters($link);
1703 if (strchr($omode, "l")) getLabelCounters($link);
1704 if (strchr($omode, "f")) getFeedCounters($link);
1705 if (strchr($omode, "t")) getTagCounters($link);
1706 if (strchr($omode, "c")) {
1707 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1708 getCategoryCounters($link);
1713 function getCategoryCounters($link) {
1714 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1715 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id
1716 AND unread = true)) AS unread FROM ttrss_feeds
1718 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1720 while ($line = db_fetch_assoc($result)) {
1721 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1722 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1723 $line["unread"]."\"/>";
1727 function getCategoryUnread($link, $cat) {
1730 $cat_query = "cat_id = '$cat'";
1732 $cat_query = "cat_id IS NULL";
1735 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1737 AND owner_uid = " . $_SESSION["uid"]);
1739 $cat_feeds = array();
1740 while ($line = db_fetch_assoc($result)) {
1741 array_push($cat_feeds, "feed_id = " . $line["id"]);
1744 if (count($cat_feeds) == 0) return 0;
1746 $match_part = implode(" OR ", $cat_feeds);
1748 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1749 FROM ttrss_user_entries
1750 WHERE unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1754 # this needs to be rewritten
1755 while ($line = db_fetch_assoc($result)) {
1756 $unread +
= $line["unread"];
1763 function getFeedUnread($link, $feed, $is_cat = false) {
1764 $n_feed = sprintf("%d", $feed);
1767 return getCategoryUnread($link, $n_feed);
1768 } else if ($n_feed == -1) {
1769 $match_part = "marked = true";
1770 } else if ($n_feed > 0) {
1772 $result = db_query($link, "SELECT id FROM ttrss_feeds
1773 WHERE parent_feed = '$n_feed'
1775 AND owner_uid = " . $_SESSION["uid"]);
1777 if (db_num_rows($result) > 0) {
1779 $linked_feeds = array();
1780 while ($line = db_fetch_assoc($result)) {
1781 array_push($linked_feeds, "feed_id = " . $line["id"]);
1784 array_push($linked_feeds, "feed_id = $n_feed");
1786 $match_part = implode(" OR ", $linked_feeds);
1788 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1789 FROM ttrss_user_entries
1790 WHERE unread = true AND ($match_part)
1791 AND owner_uid = " . $_SESSION["uid"]);
1795 # this needs to be rewritten
1796 while ($line = db_fetch_assoc($result)) {
1797 $unread +
= $line["unread"];
1803 $match_part = "feed_id = '$n_feed'";
1805 } else if ($feed < -10) {
1807 $label_id = -$feed - 11;
1809 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1810 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1812 $match_part = db_fetch_result($result, 0, "sql_exp");
1817 $result = db_query($link, "SELECT count(int_id) AS unread
1818 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1819 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1820 ttrss_user_entries.ref_id = ttrss_entries.id AND
1821 ttrss_feeds.hidden = false AND
1822 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1826 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1827 FROM ttrss_tags,ttrss_user_entries
1828 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1829 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1832 $unread = db_fetch_result($result, 0, "unread");
1837 /* FIXME this needs reworking */
1839 function getGlobalUnread($link, $user_id = false) {
1842 $user_id = $_SESSION["uid"];
1845 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1846 WHERE unread = true AND
1847 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1848 ttrss_user_entries.ref_id = ttrss_entries.id AND
1850 ttrss_user_entries.owner_uid = '$user_id'");
1851 $c_id = db_fetch_result($result, 0, "c_id");
1855 function getGlobalCounters($link, $global_unread = -1) {
1856 if ($global_unread == -1) {
1857 $global_unread = getGlobalUnread($link);
1859 print "<counter type=\"global\" id='global-unread'
1860 counter='$global_unread'/>";
1862 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1863 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1865 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1867 print "<counter type=\"global\" id='subscribed-feeds'
1868 counter='$subscribed_feeds'/>";
1872 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1875 if (!$_SESSION["tctr_last_value"]) {
1876 $_SESSION["tctr_last_value"] = array();
1880 $old_counters = $_SESSION["tctr_last_value"];
1882 $tctrs_modified = false;
1884 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1885 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1886 ttrss_user_entries.ref_id = ttrss_entries.id AND
1887 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1888 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
1890 select tag_name,0 as count FROM ttrss_tags
1891 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1893 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1894 FROM ttrss_user_entries WHERE int_id = post_int_id
1895 AND unread = true)) AS count FROM ttrss_tags
1896 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1900 while ($line = db_fetch_assoc($result)) {
1901 $tags[$line["tag_name"]] +
= $line["count"];
1904 foreach (array_keys($tags) as $tag) {
1905 $unread = $tags[$tag];
1907 $tag = htmlspecialchars($tag);
1909 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
1910 $old_counters[$tag] = $unread;
1911 $tctrs_modified = true;
1912 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1917 if ($smart_mode && $tctrs_modified) {
1918 $_SESSION["tctr_last_value"] = $old_counters;
1923 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
1926 if (!$_SESSION["lctr_last_value"]) {
1927 $_SESSION["lctr_last_value"] = array();
1933 $old_counters = $_SESSION["lctr_last_value"];
1934 $lctrs_modified = false;
1936 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1937 WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND
1938 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1939 unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1941 $count = db_fetch_result($result, 0, "count");
1944 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1946 $ret_arr["-1"]["counter"] = $count;
1947 $ret_arr["-1"]["description"] = "Starred";
1950 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1951 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1953 while ($line = db_fetch_assoc($result)) {
1955 $id = -$line["id"] - 11;
1957 $label_name = $line["description"];
1959 error_reporting (0);
1961 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1962 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
1963 ttrss_feeds.hidden = false AND
1964 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1965 ttrss_user_entries.ref_id = ttrss_entries.id AND
1966 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1968 $count = db_fetch_result($tmp_result, 0, "count");
1970 if (!$smart_mode ||
$old_counters[$id] != $count) {
1971 $old_counters[$id] = $count;
1972 $lctrs_modified = true;
1974 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1976 $ret_arr[$id]["counter"] = $count;
1977 $ret_arr[$id]["description"] = $label_name;
1981 error_reporting (DEFAULT_ERROR_LEVEL
);
1984 if ($smart_mode && $lctrs_modified) {
1985 $_SESSION["lctr_last_value"] = $old_counters;
1991 /* function getFeedCounter($link, $id) {
1993 $result = db_query($link, "SELECT
1994 count(id) as count,last_error
1995 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1996 WHERE feed_id = '$id' AND unread = true
1997 AND ttrss_user_entries.feed_id = ttrss_feeds.id
1998 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2000 $count = db_fetch_result($result, 0, "count");
2001 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2003 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2006 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2009 if (!$_SESSION["fctr_last_value"]) {
2010 $_SESSION["fctr_last_value"] = array();
2014 $old_counters = $_SESSION["fctr_last_value"];
2016 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2017 SUBSTRING(last_updated,1,19) AS last_updated,
2019 FROM ttrss_entries,ttrss_user_entries
2020 WHERE feed_id = ttrss_feeds.id AND
2021 ttrss_user_entries.ref_id = ttrss_entries.id
2022 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2023 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2024 AND parent_feed IS NULL"); */
2026 $result = db_query($link, "SELECT ttrss_feeds.id,
2027 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2029 COUNT(ttrss_entries.id) AS count
2031 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2032 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2033 AND ttrss_user_entries.unread = true)
2034 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2035 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2036 AND parent_feed IS NULL
2037 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error");
2039 $fctrs_modified = false;
2041 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2043 while ($line = db_fetch_assoc($result)) {
2046 $count = $line["count"];
2047 $last_error = htmlspecialchars($line["last_error"]);
2049 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2050 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2052 $last_updated = date($short_date, strtotime($line["last_updated"]));
2055 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2057 $tmp_result = db_query($link,
2058 "SELECT id,COUNT(unread) AS unread
2059 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2060 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2061 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
2063 if (db_num_rows($tmp_result) > 0) {
2064 while ($l = db_fetch_assoc($tmp_result)) {
2065 $count +
= $l["unread"];
2069 if (!$smart_mode ||
$old_counters[$id] != $count) {
2070 $old_counters[$id] = $count;
2071 $fctrs_modified = true;
2074 $error_part = "error=\"$last_error\"";
2080 $has_img_part = "hi=\"$has_img\"";
2085 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
2089 if ($smart_mode && $fctrs_modified) {
2090 $_SESSION["fctr_last_value"] = $old_counters;
2094 function get_script_dt_add() {
2095 if (strpos(VERSION
, ".99") === false) {
2102 function get_pgsql_version($link) {
2103 $result = db_query($link, "SELECT version() AS version");
2104 $version = split(" ", db_fetch_result($result, 0, "version"));
2108 function print_error_xml($code, $add_msg = "") {
2111 $error_msg = $ERRORS[$code];
2114 $error_msg = "$error_msg; $add_msg";
2117 print "<rpc-reply>";
2118 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2119 print "</rpc-reply>";
2122 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2123 $auth_login = '', $auth_pass = '') {
2125 # check for feed:http://url
2126 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2128 # check for feed://URL
2129 if (strpos($feed_link, "//") === 0) {
2130 $feed_link = "http:$feed_link";
2133 if ($feed_link == "") return;
2135 if ($cat_id == "0" ||
!$cat_id) {
2136 $cat_qpart = "NULL";
2138 $cat_qpart = "'$cat_id'";
2141 $result = db_query($link,
2142 "SELECT id FROM ttrss_feeds
2143 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2145 if (db_num_rows($result) == 0) {
2147 $result = db_query($link,
2148 "INSERT INTO ttrss_feeds
2149 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2150 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2151 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2153 $result = db_query($link,
2154 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2155 AND owner_uid = " . $_SESSION["uid"]);
2157 $feed_id = db_fetch_result($result, 0, "id");
2160 update_rss_feed($link, $feed_link, $feed_id, true);
2169 function print_feed_select($link, $id, $default_id = "",
2170 $attributes = "", $include_all_feeds = true) {
2172 print "<select id=\"$id\" name=\"$id\" $attributes>";
2173 if ($include_all_feeds) {
2174 print "<option value=\"0\">All feeds</option>";
2177 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2178 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2180 if (db_num_rows($result) > 0 && $include_all_feeds) {
2181 print "<option disabled>--------</option>";
2184 while ($line = db_fetch_assoc($result)) {
2185 if ($line["id"] == $default_id) {
2186 $is_selected = "selected";
2190 printf("<option $is_selected value='%d'>%s</option>",
2191 $line["id"], htmlspecialchars($line["title"]));
2197 function print_feed_cat_select($link, $id, $default_id = "",
2198 $attributes = "", $include_all_cats = true) {
2200 print "<select id=\"$id\" name=\"$id\" $attributes>";
2202 if ($include_all_cats) {
2203 print "<option value=\"0\">".__('Uncategorized')."</option>";
2206 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2207 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2209 if (db_num_rows($result) > 0 && $include_all_cats) {
2210 print "<option disabled>--------</option>";
2213 while ($line = db_fetch_assoc($result)) {
2214 if ($line["id"] == $default_id) {
2215 $is_selected = "selected";
2219 printf("<option $is_selected value='%d'>%s</option>",
2220 $line["id"], htmlspecialchars($line["title"]));
2226 function checkbox_to_sql_bool($val) {
2227 return ($val == "on") ?
"true" : "false";
2230 function getFeedCatTitle($link, $id) {
2232 return __("Special");
2233 } else if ($id < -10) {
2234 return __("Labels");
2235 } else if ($id > 0) {
2236 $result = db_query($link, "SELECT ttrss_feed_categories.title
2237 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2238 cat_id = ttrss_feed_categories.id");
2239 if (db_num_rows($result) == 1) {
2240 return db_fetch_result($result, 0, "title");
2242 return __("Uncategorized");
2245 return "getFeedCatTitle($id) failed";
2250 function getFeedTitle($link, $id) {
2252 return __("Starred articles");
2253 } else if ($id < -10) {
2254 $label_id = -10 - $id;
2255 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2256 if (db_num_rows($result) == 1) {
2257 return db_fetch_result($result, 0, "description");
2259 return "Unknown label ($label_id)";
2262 } else if ($id > 0) {
2263 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2264 if (db_num_rows($result) == 1) {
2265 return db_fetch_result($result, 0, "title");
2267 return "Unknown feed ($id)";
2270 return "getFeedTitle($id) failed";
2275 function get_session_cookie_name() {
2276 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2279 function print_init_params($link) {
2280 print "<init-params>";
2281 if ($_SESSION["stored-params"]) {
2282 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2284 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2285 print "<param key=\"$key\" value=\"$value\"/>";
2290 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2291 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2292 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY
. "\"/>";
2294 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2295 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2297 print "<param key=\"hide_read_feeds\" value=\"" .
2298 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2300 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2301 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2303 print "<param key=\"confirm_feed_catchup\" value=\"" .
2304 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2306 print "<param key=\"cdm_auto_catchup\" value=\"" .
2307 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2309 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2311 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2313 print "<param key=\"default_view_mode\" value=\"" .
2314 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2316 print "<param key=\"default_view_limit\" value=\"" .
2317 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2319 print "<param key=\"prefs_active_tab\" value=\"" .
2320 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2322 print "<param key=\"infobox_disable_overlay\" value=\"" .
2323 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2325 print "</init-params>";
2328 function print_runtime_info($link) {
2329 print "<runtime-info>";
2330 if (ENABLE_UPDATE_DAEMON
) {
2331 print "<param key=\"daemon_is_running\" value=\"".
2332 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2334 if ($_SESSION["daemon_stamp_check"] +
0 < time()) {
2336 $stamp = (int)read_stampfile("update_daemon.stamp");
2339 if ($stamp +
86400*3 < time()) {
2340 print "<param key=\"daemon_stamp_ok\" value=\"0\"/>";
2342 print "<param key=\"daemon_stamp_ok\" value=\"1\"/>";
2345 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2347 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2350 $_SESSION["daemon_stamp_check"] = time();
2354 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2356 if ($_SESSION["last_version_check"] +
600 < time()) {
2357 $new_version_details = check_for_update($link);
2359 print "<param key=\"new_version_available\" value=\"".
2360 sprintf("%d", $new_version_details != ""). "\"/>";
2362 $_SESSION["last_version_check"] = time();
2366 print "</runtime-info>";
2369 function getSearchSql($search, $match_on) {
2371 $search_query_part = "";
2373 $keywords = split(" ", $search);
2374 $query_keywords = array();
2376 if ($match_on == "both") {
2378 foreach ($keywords as $k) {
2379 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2380 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2383 $search_query_part = implode("AND", $query_keywords) . " AND ";
2385 } else if ($match_on == "title") {
2387 foreach ($keywords as $k) {
2388 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2391 $search_query_part = implode("AND", $query_keywords) . " AND ";
2393 } else if ($match_on == "content") {
2395 foreach ($keywords as $k) {
2396 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2400 $search_query_part = implode("AND", $query_keywords);
2402 return $search_query_part;
2405 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2409 $search_query_part = getSearchSql($search, $match_on);
2410 $search_query_part .= " AND ";
2413 $search_query_part = "";
2416 $view_query_part = "";
2418 if ($view_mode == "adaptive") {
2420 $view_query_part = " ";
2421 } else if ($feed != -1) {
2422 $unread = getFeedUnread($link, $feed, $cat_view);
2424 $view_query_part = " unread = true AND ";
2429 if ($view_mode == "marked") {
2430 $view_query_part = " marked = true AND ";
2433 if ($view_mode == "unread") {
2434 $view_query_part = " unread = true AND ";
2438 $limit_query_part = "LIMIT " . $limit;
2441 $vfeed_query_part = "";
2443 // override query strategy and enable feed display when searching globally
2444 if ($search && $search_mode == "all_feeds") {
2445 $query_strategy_part = "ttrss_entries.id > 0";
2446 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2447 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2448 $query_strategy_part = "ttrss_entries.id > 0";
2449 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2450 id = feed_id) as feed_title,";
2451 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2453 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2455 $tmp_result = false;
2458 $tmp_result = db_query($link, "SELECT id
2459 FROM ttrss_feeds WHERE cat_id = '$feed'");
2461 $tmp_result = db_query($link, "SELECT id
2462 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2463 WHERE id = '$feed') AND id != '$feed'");
2466 $cat_siblings = array();
2468 if (db_num_rows($tmp_result) > 0) {
2469 while ($p = db_fetch_assoc($tmp_result)) {
2470 array_push($cat_siblings, "feed_id = " . $p["id"]);
2473 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2474 $feed, implode(" OR ", $cat_siblings));
2477 $query_strategy_part = "ttrss_entries.id > 0";
2480 } else if ($feed >= 0) {
2485 $query_strategy_part = "cat_id = '$feed'";
2487 $query_strategy_part = "cat_id IS NULL";
2490 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2493 $tmp_result = db_query($link, "SELECT id
2494 FROM ttrss_feeds WHERE parent_feed = '$feed'
2495 ORDER BY cat_id,title");
2497 $parent_ids = array();
2499 if (db_num_rows($tmp_result) > 0) {
2500 while ($p = db_fetch_assoc($tmp_result)) {
2501 array_push($parent_ids, "feed_id = " . $p["id"]);
2504 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2505 $feed, implode(" OR ", $parent_ids));
2507 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2509 $query_strategy_part = "feed_id = '$feed'";
2512 } else if ($feed == -1) { // starred virtual feed
2513 $query_strategy_part = "marked = true";
2514 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2515 } else if ($feed <= -10) { // labels
2516 $label_id = -$feed - 11;
2518 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2519 WHERE id = '$label_id'");
2521 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2523 if (!$query_strategy_part) {
2527 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2529 $query_strategy_part = "id > 0"; // dumb
2532 if (get_pref($link, 'REVERSE_HEADLINES')) {
2533 $order_by = "updated";
2535 $order_by = "updated DESC";
2538 if ($override_order) {
2539 $order_by = $override_order;
2544 if ($search && $search_mode == "all_feeds") {
2545 $feed_title = __("Search results")." ($search)";
2546 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2547 $feed_title = __("Search results")." ($search, $feed)";
2548 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2549 $feed_title = $feed;
2550 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2555 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2556 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2557 $feed_title = db_fetch_result($result, 0, "title");
2559 $feed_title = __("Uncategorized");
2563 $feed_title = __("Searched for")." $search ($feed_title)";
2568 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2569 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2571 $feed_title = db_fetch_result($result, 0, "title");
2572 $feed_site_url = db_fetch_result($result, 0, "site_url");
2573 $last_error = db_fetch_result($result, 0, "last_error");
2576 $feed_title = __("Searched for") . " $search ($feed_title)";
2580 } else if ($feed == -1) {
2581 $feed_title = __("Starred articles");
2582 } else if ($feed < -10) {
2583 $label_id = -$feed - 11;
2584 $result = db_query($link, "SELECT description FROM ttrss_labels
2585 WHERE id = '$label_id'");
2586 $feed_title = db_fetch_result($result, 0, "description");
2589 $feed_title = __("Searched for") . " $search ($feed_title)";
2595 if ($feed < -10) error_reporting (0);
2597 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2600 $feed_kind = "Feeds";
2602 $feed_kind = "Labels";
2605 $content_query_part = "content as content_preview,";
2607 if ($limit_query_part) {
2608 $offset_query_part = "OFFSET $offset";
2613 ttrss_entries.id,ttrss_entries.title,
2615 unread,feed_id,marked,link,last_read,
2616 SUBSTRING(last_read,1,19) as last_read_noms,
2619 SUBSTRING(updated,1,19) as updated_noms,
2622 ttrss_entries,ttrss_user_entries,ttrss_feeds
2624 ttrss_feeds.hidden = false AND
2625 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2626 ttrss_user_entries.ref_id = ttrss_entries.id AND
2627 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2630 $query_strategy_part ORDER BY $order_by
2631 $limit_query_part $offset_query_part";
2633 $result = db_query($link, $query);
2635 if ($_GET["debug"]) print $query;
2640 $feed_kind = "Tags";
2642 $result = db_query($link, "SELECT
2644 ttrss_entries.id as id,title,
2647 marked,link,last_read,
2648 SUBSTRING(last_read,1,19) as last_read_noms,
2651 SUBSTRING(updated,1,19) as updated_noms
2653 ttrss_entries,ttrss_user_entries,ttrss_tags
2655 ref_id = ttrss_entries.id AND
2656 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2657 post_int_id = int_id AND tag_name = '$feed' AND
2660 $query_strategy_part ORDER BY $order_by
2661 $limit_query_part");
2664 return array($result, $feed_title, $feed_site_url, $last_error);
2668 function generate_syndicated_feed($link, $feed, $is_cat,
2669 $search, $search_mode, $match_on) {
2671 $qfh_ret = queryFeedHeadlines($link, $feed,
2672 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2674 $result = $qfh_ret[0];
2675 $feed_title = htmlspecialchars($qfh_ret[1]);
2676 $feed_site_url = $qfh_ret[2];
2677 $last_error = $qfh_ret[3];
2679 print "<rss version=\"2.0\">
2681 <title>$feed_title</title>
2682 <link>$feed_site_url</link>
2683 <generator>Tiny Tiny RSS v".VERSION
."</generator>";
2685 while ($line = db_fetch_assoc($result)) {
2687 print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2688 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2690 $tags = get_article_tags($link, $line["id"]);
2692 foreach ($tags as $tag) {
2693 print "<category>" . htmlspecialchars($tag) . "</category>";
2696 $rfc822_date = date('r', strtotime($line["updated"]));
2698 print "<pubDate>$rfc822_date</pubDate>";
2701 htmlspecialchars($line["title"]) . "</title>";
2703 print "<description><![CDATA[" .
2704 $line["content_preview"] . "]]></description>";
2709 print "</channel></rss>";
2713 function getCategoryTitle($link, $cat_id) {
2715 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2718 if (db_num_rows($result) == 1) {
2719 return db_fetch_result($result, 0, "title");
2721 return "Uncategorized";
2725 // http://ru2.php.net/strip-tags
2727 function strip_tags_long($textstring, $allowed){
2728 while($textstring != strip_tags($textstring, $allowed))
2730 while (strlen($textstring) != 0)
2732 if (strlen($textstring) > 1024) {
2735 $otherlen = strlen($textstring);
2737 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
2738 $safetext .= $temptext;
2739 $textstring = substr_replace($textstring,'',0,$otherlen);
2741 $textstring = $safetext;
2747 function sanitize_rss($link, $str, $force_strip_tags = false) {
2750 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
2752 global $tw_paranoya_setup;
2754 $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
2756 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
2757 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
2763 function send_headlines_digests($link, $limit = 100) {
2765 if (!DIGEST_ENABLE
) return false;
2767 $user_limit = DIGEST_EMAIL_LIMIT
;
2770 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2772 if (DB_TYPE
== "pgsql") {
2773 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2774 } else if (DB_TYPE
== "mysql") {
2775 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2778 $result = db_query($link, "SELECT id,email FROM ttrss_users
2779 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2781 while ($line = db_fetch_assoc($result)) {
2782 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2783 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2785 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2786 $digest = $tuple[0];
2787 $headlines_count = $tuple[1];
2789 if ($headlines_count > 0) {
2790 $rc = mail($line["login"] . " <" . $line["email"] . ">",
2791 "[tt-rss] New headlines for last 24 hours", $digest,
2792 "From: " . MAIL_FROM
. "\n".
2793 "Content-Type: text/plain; charset=\"utf-8\"\n".
2794 "Content-Transfer-Encoding: 8bit\n");
2796 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2797 WHERE id = " . $line["id"]);
2799 print "No headlines\n";
2804 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2808 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2809 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
2810 $tmp .= "=======================================================\n\n";
2812 if (DB_TYPE
== "pgsql") {
2813 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2814 } else if (DB_TYPE
== "mysql") {
2815 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2818 $result = db_query($link, "SELECT ttrss_entries.title,
2819 ttrss_feeds.title AS feed_title,
2822 SUBSTRING(last_updated,1,19) AS last_updated
2824 ttrss_user_entries,ttrss_entries,ttrss_feeds
2826 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2827 AND include_in_digest = true
2829 AND ttrss_user_entries.owner_uid = $user_id
2830 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2833 $cur_feed_title = "";
2835 $headlines_count = db_num_rows($result);
2837 while ($line = db_fetch_assoc($result)) {
2838 $updated = smart_date_time(strtotime($line["last_updated"]));
2839 $feed_title = $line["feed_title"];
2841 if ($cur_feed_title != $feed_title) {
2842 $cur_feed_title = $feed_title;
2844 $tmp .= "$feed_title\n\n";
2847 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2848 $tmp .= " " . trim($line["link"]) . "\n";
2853 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
2854 DIGEST_HOSTNAME
. "\n".
2855 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2858 return array($tmp, $headlines_count);
2861 function check_for_update($link, $brief_fmt = true) {
2862 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2864 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
2869 $rss = fetch_rss($releases_feed);
2870 error_reporting (DEFAULT_ERROR_LEVEL
);
2874 $items = $rss->items
;
2876 if (!$items ||
!is_array($items)) $items = $rss->entries
;
2877 if (!$items ||
!is_array($items)) $items = $rss;
2879 if (!is_array($items) ||
count($items) == 0) {
2883 $latest_item = $items[0];
2885 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2887 $release_url = sanitize_rss($link, $latest_item["link"]);
2888 $content = sanitize_rss($link, $latest_item["description"]);
2890 if (version_compare(VERSION
, $latest_version) == -1) {
2892 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
2893 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2894 <div id=\"milestoneDetails\">$content</div>");
2896 return "New version of Tiny-Tiny RSS ($latest_version) is available:
2897 <div class='milestoneDetails'>$content</div>
2898 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2899 download and update information.";
2906 function markArticlesById($link, $ids, $cmode) {
2910 foreach ($ids as $id) {
2911 array_push($tmp_ids, "ref_id = '$id'");
2914 $ids_qpart = join(" OR ", $tmp_ids);
2917 db_query($link, "UPDATE ttrss_user_entries SET
2918 marked = false,last_read = NOW()
2919 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2920 } else if ($cmode == 1) {
2921 db_query($link, "UPDATE ttrss_user_entries SET
2923 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2925 db_query($link, "UPDATE ttrss_user_entries SET
2926 marked = NOT marked,last_read = NOW()
2927 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2931 function catchupArticlesById($link, $ids, $cmode) {
2935 foreach ($ids as $id) {
2936 array_push($tmp_ids, "ref_id = '$id'");
2939 $ids_qpart = join(" OR ", $tmp_ids);
2942 db_query($link, "UPDATE ttrss_user_entries SET
2943 unread = false,last_read = NOW()
2944 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2945 } else if ($cmode == 1) {
2946 db_query($link, "UPDATE ttrss_user_entries SET
2948 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2950 db_query($link, "UPDATE ttrss_user_entries SET
2951 unread = NOT unread,last_read = NOW()
2952 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2956 function catchupArticleById($link, $id, $cmode) {
2959 db_query($link, "UPDATE ttrss_user_entries SET
2960 unread = false,last_read = NOW()
2961 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2962 } else if ($cmode == 1) {
2963 db_query($link, "UPDATE ttrss_user_entries SET
2965 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2967 db_query($link, "UPDATE ttrss_user_entries SET
2968 unread = NOT unread,last_read = NOW()
2969 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2973 function make_guid_from_title($title) {
2974 return preg_replace("/[ \"\',.:;]/", "-",
2975 mb_strtolower(strip_tags($title), 'utf-8'));
2978 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
2979 $bottom = false, $rtl_content = false, $feed_id = 0,
2980 $is_cat = false, $search = false, $match_on = false,
2981 $search_mode = false, $offset = 0, $limit = 0) {
2983 $user_page_offset = $offset +
1;
2986 $class = "headlinesSubToolbar";
2987 $tid = "headlineActionsTop";
2989 $class = "headlinesSubToolbar";
2990 $tid = "headlineActionsBottom";
2993 print "<table class=\"$class\" id=\"$tid\"
2994 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3002 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3003 $page_next_link = "javascript:viewFeedGoPage(1)";
3004 $page_first_link = "javascript:viewFeedGoPage(0)";
3006 $catchup_page_link = "javascript:catchupPage()";
3007 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3009 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3011 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3012 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3013 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3015 $tog_unread_link = "javascript:selectionToggleUnread()";
3016 $tog_marked_link = "javascript:selectionToggleMarked()";
3020 $sel_all_link = "javascript:cdmSelectArticles('all')";
3021 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3022 $sel_none_link = "javascript:cdmSelectArticles('none')";
3024 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3025 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3029 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3031 print "<td class=\"headlineActions$rtl_cpart\">
3032 <ul class=\"headlineDropdownMenu\">
3035 <a href=\"$sel_all_link\">".__('All')."</a>,
3036 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3037 <a href=\"$sel_none_link\">".__('None')."</a></li>
3038 <li class=\"vsep\"> </li>
3039 <li class=\"top\">Toggle<ul>
3040 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3041 <li onclick=\"$tog_marked_link\">".__('Starred')."</li></ul></li>
3042 <li class=\"vsep\"> </li>
3043 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
3044 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
3045 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3046 <li class=\"vsep\"> </li>";
3048 if ($limit != 0 && !$search) {
3050 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3051 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3052 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3056 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3057 print "<li class=\"top3\">
3058 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3059 '$match_on', '$feed_id', '$is_cat');\">
3060 ".__('Convert to label')."</a></td>";
3066 // old style subtoolbar:
3068 print "<td class=\"headlineActions$rtl_cpart\">".
3070 <a href=\"$sel_all_link\">".__('All')."</a>,
3071 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3072 <a href=\"$sel_none_link\">".__('None')."</a>
3074 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3075 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3077 __('Mark as read:')."
3078 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3079 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3081 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3084 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3085 '$match_on', '$feed_id', '$is_cat');\">
3086 ".__('Convert to label')."</a>";
3093 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3094 print "<td class=\"headlineActions$rtl_cpart\">
3095 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3096 '$match_on', '$feed_id', '$is_cat');\">
3097 ".__('Convert to Label')."</a></td>";
3100 print "<td class=\"headlineTitle$rtl_cpart\">";
3102 if ($feed_site_url) {
3104 $target = "target=\"_blank\"";
3106 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
3112 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3115 if ($user_page_offset > 1) {
3116 print " [$user_page_offset] ";
3122 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3123 <img class=\"noborder\"
3124 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3129 print "</tr></table>";
3133 function outputFeedList($link, $tags = false) {
3135 print "<ul class=\"feedList\" id=\"feedList\">";
3137 $owner_uid = $_SESSION["uid"];
3141 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3142 print "<li class=\"feedCat\">".__('Special')."</li>";
3143 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3146 $num_starred = getFeedUnread($link, -1);
3150 if ($num_starred > 0) $class .= "Unread";
3152 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
3153 "images/mark_set.png", $link);
3155 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3161 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
3163 $result = db_query($link, "SELECT id,sql_exp,description FROM
3164 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3166 if (db_num_rows($result) > 0) {
3167 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3168 print "<li class=\"feedCat\">".__('Labels')."</li>";
3169 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3171 print "<li><hr></li>";
3175 while ($line = db_fetch_assoc($result)) {
3177 error_reporting (0);
3179 $label_id = -$line['id'] - 11;
3180 $count = getFeedUnread($link, $label_id);
3188 error_reporting (DEFAULT_ERROR_LEVEL
);
3190 printFeedEntry($label_id,
3191 $class, $line["description"],
3192 $count, "images/label.png", $link);
3196 if (db_num_rows($result) > 0) {
3197 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3204 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3205 print "<li><hr></li>";
3208 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3209 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3210 $order_by_qpart = "category,unread DESC,title";
3212 $order_by_qpart = "category,title";
3215 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3216 $order_by_qpart = "unread DESC,title";
3218 $order_by_qpart = "title";
3222 $result = db_query($link, "SELECT ttrss_feeds.*,
3223 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3224 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3225 WHERE feed_id = ttrss_feeds.id AND unread = true
3226 AND ttrss_user_entries.ref_id = ttrss_entries.id
3227 AND owner_uid = '$owner_uid') as unread,
3229 ttrss_feed_categories.title AS category,
3230 ttrss_feed_categories.collapsed
3231 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
3232 ON (ttrss_feed_categories.id = cat_id)
3234 ttrss_feeds.hidden = false AND
3235 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3236 ORDER BY $order_by_qpart");
3238 $actid = $_GET["actid"];
3248 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3250 while ($line = db_fetch_assoc($result)) {
3252 $feed = trim($line["title"]);
3254 if (!$feed) $feed = "[Untitled]";
3256 $feed_id = $line["id"];
3258 $subop = $_GET["subop"];
3260 $unread = $line["unread"];
3262 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3263 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3265 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3268 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3271 $rtl_tag = "dir=\"RTL\"";
3276 $tmp_result = db_query($link,
3277 "SELECT id,COUNT(unread) AS unread
3278 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
3279 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
3280 WHERE parent_feed = '$feed_id' AND unread = true
3281 GROUP BY ttrss_feeds.id");
3283 if (db_num_rows($tmp_result) > 0) {
3284 while ($l = db_fetch_assoc($tmp_result)) {
3285 $unread +
= $l["unread"];
3289 $cat_id = $line["cat_id"];
3291 $tmp_category = $line["category"];
3293 if (!$tmp_category) {
3294 $tmp_category = __("Uncategorized");
3297 // $class = ($lnum % 2) ? "even" : "odd";
3299 if ($line["last_error"]) {
3305 if ($unread > 0) $class .= "Unread";
3307 if ($actid == $feed_id) {
3308 $class .= "Selected";
3311 $total_unread +
= $unread;
3313 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3319 $category = $tmp_category;
3321 $collapsed = $line["collapsed"];
3323 // workaround for NULL category
3324 if ($category == __("Uncategorized")) {
3325 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3330 if ($collapsed == "t" ||
$collapsed == "1") {
3331 $holder_class = "invisible";
3334 $holder_class = "feedCatHolder";
3338 $cat_id = sprintf("%d", $cat_id);
3340 $cat_unread = getCategoryUnread($link, $cat_id);
3342 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3344 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3345 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3346 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3347 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3348 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3351 // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3352 // -> keyboard navigation, etc.
3353 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3356 printFeedEntry($feed_id, $class, $feed, $unread,
3357 ICONS_DIR
."/$feed_id.ico", $link, $rtl_content,
3358 $last_updated, $line["last_error"]);
3363 if (db_num_rows($result) == 0) {
3364 print "<li>".__('No feeds to display.')."</li>";
3371 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3372 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3373 post_int_id = ttrss_user_entries.int_id AND
3374 unread = true AND ref_id = ttrss_entries.id
3375 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3377 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3378 ORDER BY tag_name"); */
3380 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3381 print "<li class=\"feedCat\">".__('Tags')."</li>";
3382 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3385 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3386 FROM ttrss_user_entries WHERE int_id = post_int_id
3387 AND unread = true)) AS count FROM ttrss_tags
3388 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3392 while ($line = db_fetch_assoc($result)) {
3393 $tags[$line["tag_name"]] +
= $line["count"];
3396 foreach (array_keys($tags) as $tag) {
3398 $unread = $tags[$tag];
3406 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3410 if (db_num_rows($result) == 0) {
3411 print "<li>No tags to display.</li>";
3414 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3424 function get_article_tags($link, $id) {
3426 $a_id = db_escape_string($id);
3428 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
3429 owner_uid as owner FROM
3430 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3431 ref_id = '$a_id' LIMIT 1) ORDER BY tag_name");
3435 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3436 array_push($tags, $tmp_line["tag_name"]);
3442 function trim_value(&$value) {
3443 $value = trim($value);
3446 function trim_array($array) {
3448 array_walk($tmp, 'trim_value');
3452 function tag_is_valid($tag) {
3453 if ($tag == '') return false;
3454 if (preg_match("/^[0-9]*$/", $tag)) return false;
3456 $tag = iconv("utf-8", "utf-8", $tag);
3457 if (!$tag) return false;
3462 function render_login_form($link, $mobile = false) {
3464 require_once "login_form.php";
3466 require_once "mobile/login_form.php";
3470 // from http://developer.apple.com/internet/safari/faq.html
3471 function no_cache_incantation() {
3472 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3473 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3474 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3475 header("Cache-Control: post-check=0, pre-check=0", false);
3476 header("Pragma: no-cache"); // HTTP/1.0
3479 function format_warning($msg, $id = "") {
3480 return "<div class=\"warning\" id=\"$id\">
3481 <img src=\"images/sign_excl.png\">$msg</div>";
3484 function format_notice($msg) {
3485 return "<div class=\"notice\">
3486 <img src=\"images/sign_info.png\">$msg</div>";
3489 function format_error($msg) {
3490 return "<div class=\"error\">
3491 <img src=\"images/sign_excl.png\">$msg</div>";
3494 function print_notice($msg) {
3495 return print format_notice($msg);
3498 function print_warning($msg) {
3499 return print format_warning($msg);
3502 function print_error($msg) {
3503 return print format_error($msg);
3507 function T_sprintf() {
3508 $args = func_get_args();
3509 return vsprintf(__(array_shift($args)), $args);
3512 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
3514 /* we can figure out feed_id from article id anyway, why do we
3515 * pass feed_id here? */
3517 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3518 WHERE ref_id = '$id'");
3520 $feed_id = db_fetch_result($result, 0, "feed_id");
3522 print "<article id='$id'><![CDATA[";
3524 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3525 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3527 if (db_num_rows($result) == 1) {
3528 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3530 $rtl_content = false;
3534 $rtl_tag = "dir=\"RTL\"";
3541 if ($mark_as_read) {
3542 $result = db_query($link, "UPDATE ttrss_user_entries
3543 SET unread = false,last_read = NOW()
3544 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3547 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3548 SUBSTRING(updated,1,16) as updated,
3549 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3552 FROM ttrss_entries,ttrss_user_entries
3553 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3559 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3560 $link_target = "target=\"_new\"";
3563 $line = db_fetch_assoc($result);
3565 if ($line["icon_url"]) {
3566 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
3568 $feed_icon = " ";
3571 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
3572 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
3574 $entry_comments = "";
3577 $num_comments = $line["num_comments"];
3578 $entry_comments = "";
3580 if ($num_comments > 0) {
3581 if ($line["comments"]) {
3582 $comments_url = $line["comments"];
3584 $comments_url = $line["link"];
3586 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
3588 if ($line["comments"] && $line["link"] != $line["comments"]) {
3589 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
3593 print "<div class=\"postReply\">";
3595 print "<div class=\"postHeader\">";
3597 $entry_author = $line["author"];
3599 if ($entry_author) {
3600 $entry_author = __(" - by ") . $entry_author;
3603 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
3604 strtotime($line["updated"]));
3606 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3608 if ($line["link"]) {
3609 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
3610 $line["title"] . "</a>$entry_author</div>";
3612 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3615 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3616 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
3617 ORDER BY tag_name");
3624 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3626 $tag = $tmp_line["tag_name"];
3627 $tag_escaped = str_replace("'", "\\'", $tag);
3629 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
3631 if ($num_tags == 6) {
3632 $tags_str .= "<a href=\"javascript:showBlockElement('allEntryTags')\">...</a>";
3633 } else if ($num_tags < 6) {
3634 $tags_str .= $tag_str;
3636 $f_tags_str .= $tag_str;
3639 $tags_str = preg_replace("/, $/", "", $tags_str);
3640 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
3642 if (!$entry_comments) $entry_comments = " "; # placeholder
3644 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
3646 print "<div style='float : right'>$tags_str
3647 <a title=\"Edit tags for this article\"
3648 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
3649 <div clear='both'>$entry_comments</div>";
3653 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
3654 print "<div class=\"postContent\">";
3656 if (db_num_rows($tmp_result) > 0) {
3657 print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
3660 $line["content"] = sanitize_rss($link, $line["content"]);
3662 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3663 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
3666 print $line["content"] . "</div>";
3672 print "]]></article>";
3676 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
3677 $next_unread_feed, $offset) {
3679 $timing_info = getmicrotime();
3681 $topmost_article_ids = array();
3683 if (!$offset) $offset = 0;
3685 if ($subop == "undefined") $subop = "";
3687 if ($subop == "CatchupSelected") {
3688 $ids = split(",", db_escape_string($_GET["ids"]));
3689 $cmode = sprintf("%d", $_GET["cmode"]);
3691 catchupArticlesById($link, $ids, $cmode);
3694 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
3695 update_generic_feed($link, $feed, $cat_view);
3698 if ($subop == "MarkAllRead") {
3699 catchup_feed($link, $feed, $cat_view);
3701 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
3702 if ($next_unread_feed) {
3703 $feed = $next_unread_feed;
3709 $result = db_query($link,
3710 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
3712 if (db_num_rows($result) == 0) {
3713 print "<div align='center'>".__('Feed not found.')."</div>";
3718 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3720 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3721 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
3723 if (db_num_rows($result) == 1) {
3724 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3726 $rtl_content = false;
3730 $rtl_tag = "dir=\"RTL\"";
3736 $rtl_content = false;
3739 $script_dt_add = get_script_dt_add();
3741 /// START /////////////////////////////////////////////////////////////////////////////////
3743 $search = db_escape_string($_GET["query"]);
3744 $search_mode = db_escape_string($_GET["search_mode"]);
3745 $match_on = db_escape_string($_GET["match_on"]);
3751 $real_offset = $offset * $limit;
3753 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
3755 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
3756 $search, $search_mode, $match_on, false, $real_offset);
3758 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
3760 $result = $qfh_ret[0];
3761 $feed_title = $qfh_ret[1];
3762 $feed_site_url = $qfh_ret[2];
3763 $last_error = $qfh_ret[3];
3765 /// STOP //////////////////////////////////////////////////////////////////////////////////
3767 print "<div id=\"headlinesContainer\" $rtl_tag>";
3770 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
3774 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
3775 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
3778 print "<div id=\"headlinesInnerContainer\">";
3780 if (db_num_rows($result) > 0) {
3782 # print "\{$offset}";
3784 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3785 print "<table class=\"headlinesList\" id=\"headlinesList\"
3786 cellspacing=\"0\">";
3791 error_reporting (DEFAULT_ERROR_LEVEL
);
3795 while ($line = db_fetch_assoc($result)) {
3797 $class = ($lnum %
2) ?
"even" : "odd";
3800 $feed_id = $line["feed_id"];
3802 if (count($topmost_article_ids) < 5) {
3803 array_push($topmost_article_ids, $id);
3806 if ($line["last_read"] == "" &&
3807 ($line["unread"] != "t" && $line["unread"] != "1")) {
3809 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
3812 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
3816 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
3824 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
3825 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.png\"
3827 alt=\"Reset mark\" onclick='javascript:tMark($id)'>";
3829 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.png\"
3831 alt=\"Set mark\" onclick='javascript:tMark($id)'>";
3834 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
3835 # $line["title"] . "</a>";
3837 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
3838 $line["title"] . "</a>";
3840 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
3841 # $line["title"] . "</a>";
3843 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3844 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
3846 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3847 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
3850 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3851 $content_preview = truncate_string(strip_tags($line["content_preview"]),
3855 $entry_author = $line["author"];
3857 if ($entry_author) {
3858 $entry_author = " - by $entry_author";
3861 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3863 print "<tr class='$class' id='RROW-$id'>";
3865 print "<td class='hlUpdPic'>$update_pic</td>";
3867 print "<td class='hlSelectRow'>
3868 <input type=\"checkbox\" onclick=\"tSR(this)\"
3872 print "<td class='hlMarkedPic'>$marked_pic</td>";
3874 if ($line["feed_title"]) {
3875 print "<td class='hlContent'>$content_link</td>";
3876 print "<td class='hlFeed'>
3877 <a href=\"javascript:viewfeed($feed_id, '', false)\">".
3878 $line["feed_title"]."</a> </td>";
3880 print "<td class='hlContent' valign='middle'>";
3882 print "<a href=\"javascript:view($id,$feed_id);\">" .
3885 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3886 if ($content_preview) {
3887 print "<span class=\"contentPreview\"> - $content_preview</span>";
3895 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
3902 $add_class = "Unread";
3907 print "<div class=\"cdmArticle$add_class\" id=\"RROW-$id\">";
3909 print "<div class=\"cdmHeader\">";
3911 print "<div class=\"articleUpdated\">$updated_fmt</div>";
3913 print "<a class=\"title\"
3914 onclick=\"javascript:toggleUnread($id, 0)\"
3915 target=\"new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
3917 print $entry_author;
3919 if ($line["feed_title"]) {
3920 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
3925 print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
3927 print "<div class=\"cdmFooter\">";
3929 print "$marked_pic";
3931 print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
3932 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
3934 $tags = get_article_tags($link, $id);
3938 foreach ($tags as $tag) {
3940 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
3943 $tags_str = preg_replace("/, $/", "", $tags_str);
3945 if ($tags_str == "") $tags_str = "no tags";
3947 print " $tags_str <a title=\"Edit tags for this article\"
3948 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
3952 # print "<div align=\"center\"><a class=\"cdmToggleLink\"
3953 # href=\"javascript:toggleUnread($id)\">
3954 # Toggle unread</a></div>";
3963 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3967 // print_headline_subtoolbar($link,
3968 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
3972 print "<div class='whiteBox'>".__('No articles found.')."</div>";
3979 return $topmost_article_ids;
3982 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
3984 function printTagCloud($link) {
3986 /* get first ref_id to count from */
3992 if (DB_TYPE == "pgsql") {
3993 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3994 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3995 AND date_entered > NOW() - INTERVAL '30 days'";
3997 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3998 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3999 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
4002 $result = db_query($link, $query);
4003 $first_id = db_fetch_result($result, 0, "id"); */
4005 //AND post_int_id >= '$first_id'
4006 $query = "SELECT tag_name, COUNT(post_int_id) AS count
4007 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
4008 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
4010 $result = db_query($link, $query);
4014 while ($line = db_fetch_assoc($result)) {
4015 $tags[$line["tag_name"]] = $line["count"];
4020 $max_size = 32; // max font size in pixels
4021 $min_size = 11; // min font size in pixels
4023 // largest and smallest array values
4024 $max_qty = max(array_values($tags));
4025 $min_qty = min(array_values($tags));
4027 // find the range of values
4028 $spread = $max_qty - $min_qty;
4029 if ($spread == 0) { // we don't want to divide by zero
4033 // set the font-size increment
4034 $step = ($max_size - $min_size) / ($spread);
4036 // loop through the tag array
4037 foreach ($tags as $key => $value) {
4038 // calculate font-size
4039 // find the $value in excess of $min_qty
4040 // multiply by the font-size increment ($size)
4041 // and add the $min_size set above
4042 $size = round($min_size +
(($value - $min_qty) * $step));
4044 $key_escaped = str_replace("'", "\\'", $key);
4046 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
4047 $size . "px\" title=\"$value articles tagged with " .
4048 $key . '">' . $key . '</a> ';
4052 function print_checkpoint($n, $s) {
4053 $ts = getmicrotime();
4054 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
4058 function sanitize_tag($tag) {
4061 $tag = mb_strtolower($tag, 'utf-8');
4063 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
4065 // $tag = str_replace('"', "", $tag);
4066 // $tag = str_replace("+", " ", $tag);
4067 $tag = str_replace("technorati tag: ", "", $tag);