]>
git.wh0rd.org - tt-rss.git/blob - functions.php
f6783ff94d16d153f37d8bde27fd3b87fa3ba280
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_unescape_string(db_fetch_result($result, 0, "auth_login"));
390 $auth_pass = db_unescape_string(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 db_query($link, "UPDATE ttrss_feeds
521 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
523 return; // no articles
526 if (defined('DAEMON_EXTENDED_DEBUG')) {
527 _debug("update_rss_feed: processing articles...");
530 foreach ($iterator as $item) {
532 $entry_guid = $item["id"];
534 if (!$entry_guid) $entry_guid = $item["guid"];
535 if (!$entry_guid) $entry_guid = $item["link"];
536 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
538 if (defined('DAEMON_EXTENDED_DEBUG')) {
539 _debug("update_rss_feed: guid $entry_guid");
542 if (!$entry_guid) continue;
544 $entry_timestamp = "";
546 $rss_2_date = $item['pubdate'];
547 $rss_1_date = $item['dc']['date'];
548 $atom_date = $item['issued'];
549 if (!$atom_date) $atom_date = $item['updated'];
551 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
552 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
553 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
555 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
556 $entry_timestamp = time();
557 $no_orig_date = 'true';
559 $no_orig_date = 'false';
562 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
564 $entry_title = trim(strip_tags($item["title"]));
566 // strange Magpie workaround
567 $entry_link = $item["link_"];
568 if (!$entry_link) $entry_link = $item["link"];
570 if (!$entry_title) continue;
571 # if (!$entry_link) continue;
573 $entry_link = strip_tags($entry_link);
575 $entry_content = $item["content:escaped"];
577 if (!$entry_content) $entry_content = $item["content:encoded"];
578 if (!$entry_content) $entry_content = $item["content"];
579 if (!$entry_content) $entry_content = $item["atom_content"];
580 if (!$entry_content) $entry_content = $item["summary"];
581 if (!$entry_content) $entry_content = $item["description"];
583 // if (!$entry_content) continue;
586 if (is_array($entry_content)) {
587 $entry_content = $entry_content["encoded"];
588 if (!$entry_content) $entry_content = $entry_content["escaped"];
592 // print_r(htmlspecialchars($entry_content));
595 $entry_content_unescaped = $entry_content;
597 $entry_comments = strip_tags($item["comments"]);
599 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
601 if ($item['author']) {
603 if (is_array($item['author'])) {
605 if (!$entry_author) {
606 $entry_author = db_escape_string(strip_tags($item['author']['name']));
609 if (!$entry_author) {
610 $entry_author = db_escape_string(strip_tags($item['author']['email']));
614 if (!$entry_author) {
615 $entry_author = db_escape_string(strip_tags($item['author']));
619 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
621 $entry_guid = db_escape_string(strip_tags($entry_guid));
623 $result = db_query($link, "SELECT id FROM ttrss_entries
624 WHERE guid = '$entry_guid'");
626 $entry_content = db_escape_string($entry_content);
628 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
630 $entry_title = db_escape_string($entry_title);
631 $entry_link = db_escape_string($entry_link);
632 $entry_comments = db_escape_string($entry_comments);
634 $num_comments = db_escape_string($item["slash"]["comments"]);
636 if (!$num_comments) $num_comments = 0;
638 // parse <category> entries into tags
640 $t_ctr = $item['category#'];
642 $additional_tags = false;
645 $additional_tags = false;
646 } else if ($t_ctr == 1) {
647 $additional_tags = array($item['category']);
649 $additional_tags = array();
650 for ($i = 0; $i <= $t_ctr; $i++
) {
651 if ($item["category#$i"]) {
652 array_push($additional_tags, $item["category#$i"]);
657 // parse <dc:subject> elements
659 $t_ctr = $item['dc']['subject#'];
662 $additional_tags = array($item['dc']['subject']);
663 } else if ($t_ctr > 1) {
664 $additional_tags = array();
665 for ($i = 0; $i <= $t_ctr; $i++
) {
666 if ($item['dc']["subject#$i"]) {
667 array_push($additional_tags, $item['dc']["subject#$i"]);
674 // $entry_content = sanitize_rss($entry_content);
676 if (defined('DAEMON_EXTENDED_DEBUG')) {
677 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
680 db_query($link, "BEGIN");
682 if (db_num_rows($result) == 0) {
684 if (defined('DAEMON_EXTENDED_DEBUG')) {
685 _debug("update_rss_feed: base guid not found");
688 // base post entry does not exist, create it
690 $result = db_query($link,
691 "INSERT INTO ttrss_entries
707 '$entry_timestamp_fmt',
716 // we keep encountering the entry in feeds, so we need to
717 // update date_entered column so that we don't get horrible
718 // dupes when the entry gets purged and reinserted again e.g.
719 // in the case of SLOW SLOW OMG SLOW updating feeds
721 $base_entry_id = db_fetch_result($result, 0, "id");
723 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
724 WHERE id = '$base_entry_id'");
727 // now it should exist, if not - bad luck then
729 $result = db_query($link, "SELECT
730 id,content_hash,no_orig_date,title,
731 substring(date_entered,1,19) as date_entered,
732 substring(updated,1,19) as updated,
736 WHERE guid = '$entry_guid'");
738 if (db_num_rows($result) == 1) {
740 if (defined('DAEMON_EXTENDED_DEBUG')) {
741 _debug("update_rss_feed: base guid found, checking for user record");
744 // this will be used below in update handler
745 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
746 $orig_title = db_fetch_result($result, 0, "title");
747 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
748 $orig_date_entered = strtotime(db_fetch_result($result,
751 $ref_id = db_fetch_result($result, 0, "id");
753 // check for user post link to main table
755 // do we allow duplicate posts with same GUID in different feeds?
756 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
757 $dupcheck_qpart = "AND feed_id = '$feed'";
759 $dupcheck_qpart = "";
762 // error_reporting(0);
764 $article_filters = get_article_filters($filters, $entry_title,
765 $entry_content, $entry_link);
767 if (defined('DAEMON_EXTENDED_DEBUG')) {
768 _debug("update_rss_feed: article filters: ");
769 if (count($article_filters) != 0) {
770 print_r($article_filters);
774 if (find_article_filter($article_filters, "filter")) {
778 // error_reporting (DEFAULT_ERROR_LEVEL);
780 $result = db_query($link,
781 "SELECT ref_id FROM ttrss_user_entries WHERE
782 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
785 // okay it doesn't exist - create user entry
786 if (db_num_rows($result) == 0) {
788 if (defined('DAEMON_EXTENDED_DEBUG')) {
789 _debug("update_rss_feed: user record not found, creating...");
792 if (!find_article_filter($article_filters, 'catchup')) {
794 $last_read_qpart = 'NULL';
797 $last_read_qpart = 'NOW()';
800 if (find_article_filter($article_filters, 'mark')) {
806 $result = db_query($link,
807 "INSERT INTO ttrss_user_entries
808 (ref_id, owner_uid, feed_id, unread, last_read, marked)
809 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
810 $last_read_qpart, $marked)");
813 $post_needs_update = false;
815 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
816 ($content_hash != $orig_content_hash)) {
817 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
818 $post_needs_update = true;
821 if (db_escape_string($orig_title) != $entry_title) {
822 $post_needs_update = true;
825 if ($orig_num_comments != $num_comments) {
826 $post_needs_update = true;
829 // this doesn't seem to be very reliable
831 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
832 // $post_needs_update = true;
835 // if post needs update, update it and mark all user entries
836 // linking to this post as updated
837 if ($post_needs_update) {
839 if (defined('DAEMON_EXTENDED_DEBUG')) {
840 _debug("update_rss_feed: post $entry_guid needs update...");
843 // print "<!-- post $orig_title needs update : $post_needs_update -->";
845 db_query($link, "UPDATE ttrss_entries
846 SET title = '$entry_title', content = '$entry_content',
847 content_hash = '$content_hash',
848 num_comments = '$num_comments'
849 WHERE id = '$ref_id'");
851 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
852 db_query($link, "UPDATE ttrss_user_entries
853 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
855 db_query($link, "UPDATE ttrss_user_entries
856 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
862 db_query($link, "COMMIT");
864 if (defined('DAEMON_EXTENDED_DEBUG')) {
865 _debug("update_rss_feed: looking for tags...");
869 // <a href="..." rel="tag">Xorg</a>, //
873 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
874 $entry_content_unescaped, $entry_tags);
876 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
877 print_r($entry_tags);
878 print "<br/></p>"; */
880 $entry_tags = $entry_tags[1];
882 # check for manual tags
884 $tag_filter = find_article_filter($article_filters, "tag");
888 $manual_tags = trim_array(split(",", $tag_filter[1]));
890 foreach ($manual_tags as $tag) {
891 if (tag_is_valid($tag)) {
892 array_push($entry_tags, $tag);
897 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
898 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
900 if ($additional_tags && is_array($additional_tags)) {
901 foreach ($additional_tags as $tag) {
902 if (tag_is_valid($tag) &&
903 array_search($tag, $boring_tags) === FALSE) {
904 array_push($entry_tags, $tag);
909 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
911 if (count($entry_tags) > 0) {
913 db_query($link, "BEGIN");
915 $result = db_query($link, "SELECT id,int_id
916 FROM ttrss_entries,ttrss_user_entries
917 WHERE guid = '$entry_guid'
918 AND feed_id = '$feed' AND ref_id = id
919 AND owner_uid = '$owner_uid'");
921 if (db_num_rows($result) == 1) {
923 $entry_id = db_fetch_result($result, 0, "id");
924 $entry_int_id = db_fetch_result($result, 0, "int_id");
926 foreach ($entry_tags as $tag) {
928 $tag = sanitize_tag($tag);
929 $tag = db_escape_string($tag);
931 if (!tag_is_valid($tag)) continue;
933 $result = db_query($link, "SELECT id FROM ttrss_tags
934 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
935 owner_uid = '$owner_uid' LIMIT 1");
937 // print db_fetch_result($result, 0, "id");
939 if ($result && db_num_rows($result) == 0) {
941 db_query($link, "INSERT INTO ttrss_tags
942 (owner_uid,tag_name,post_int_id)
943 VALUES ('$owner_uid','$tag', '$entry_int_id')");
947 db_query($link, "COMMIT");
951 db_query($link, "UPDATE ttrss_feeds
952 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
954 // db_query($link, "COMMIT");
957 $error_msg = db_escape_string(magpie_error());
959 "UPDATE ttrss_feeds SET last_error = '$error_msg',
960 last_updated = NOW() WHERE id = '$feed'");
963 if (defined('DAEMON_EXTENDED_DEBUG')) {
964 _debug("update_rss_feed: done");
969 function print_select($id, $default, $values, $attributes = "") {
970 print "<select name=\"$id\" id=\"$id\" $attributes>";
971 foreach ($values as $v) {
977 print "<option$sel>$v</option>";
982 function print_select_hash($id, $default, $values, $attributes = "") {
983 print "<select name=\"$id\" id='$id' $attributes>";
984 foreach (array_keys($values) as $v) {
990 print "<option $sel value=\"$v\">".$values[$v]."</option>";
996 function get_article_filters($filters, $title, $content, $link) {
999 if ($filters["title"]) {
1000 foreach ($filters["title"] as $filter) {
1001 $reg_exp = $filter["reg_exp"];
1002 $inverse = $filter["inverse"];
1003 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1004 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1006 array_push($matches, array($filter["action"], $filter["action_param"]));
1011 if ($filters["content"]) {
1012 foreach ($filters["content"] as $filter) {
1013 $reg_exp = $filter["reg_exp"];
1014 $inverse = $filter["inverse"];
1016 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1017 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1019 array_push($matches, array($filter["action"], $filter["action_param"]));
1024 if ($filters["both"]) {
1025 foreach ($filters["both"] as $filter) {
1026 $reg_exp = $filter["reg_exp"];
1027 $inverse = $filter["inverse"];
1030 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1031 array_push($matches, array($filter["action"], $filter["action_param"]));
1034 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1035 array_push($matches, array($filter["action"], $filter["action_param"]));
1041 if ($filters["link"]) {
1042 $reg_exp = $filter["reg_exp"];
1043 foreach ($filters["link"] as $filter) {
1044 $reg_exp = $filter["reg_exp"];
1045 $inverse = $filter["inverse"];
1047 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1048 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1050 array_push($matches, array($filter["action"], $filter["action_param"]));
1058 function find_article_filter($filters, $filter_name) {
1059 foreach ($filters as $f) {
1060 if ($f[0] == $filter_name) {
1067 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1068 $rtl_content = false, $last_updated = false, $last_error = false) {
1070 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1071 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1073 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1077 $rtl_tag = "dir=\"rtl\"";
1079 $rtl_tag = "dir=\"ltr\"";
1082 $error_notify_msg = "";
1085 $link_title = "Error: $last_error ($last_updated)";
1086 $error_notify_msg = "(Error)";
1087 } else if ($last_updated) {
1088 $link_title = "Updated: $last_updated";
1091 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1092 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1094 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1095 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1099 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1104 $fctr_class = "class=\"invisible\"";
1107 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1108 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1110 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1111 print "<div class=\"feedExtInfo\">
1112 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1119 function getmicrotime() {
1120 list($usec, $sec) = explode(" ",microtime());
1121 return ((float)$usec +
(float)$sec);
1124 function print_radio($id, $default, $values, $attributes = "") {
1125 foreach ($values as $v) {
1133 $sel .= " value=\"1\"";
1135 $sel .= " value=\"0\"";
1138 print "<input class=\"noborder\"
1139 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1144 function initialize_user_prefs($link, $uid) {
1146 $uid = db_escape_string($uid);
1148 db_query($link, "BEGIN");
1150 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1152 $u_result = db_query($link, "SELECT pref_name
1153 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1155 $active_prefs = array();
1157 while ($line = db_fetch_assoc($u_result)) {
1158 array_push($active_prefs, $line["pref_name"]);
1161 while ($line = db_fetch_assoc($result)) {
1162 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1163 // print "adding " . $line["pref_name"] . "<br>";
1165 db_query($link, "INSERT INTO ttrss_user_prefs
1166 (owner_uid,pref_name,value) VALUES
1167 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1172 db_query($link, "COMMIT");
1176 function lookup_user_id($link, $user) {
1178 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1181 if (db_num_rows($result) == 1) {
1182 return db_fetch_result($result, 0, "id");
1188 function http_authenticate_user($link) {
1190 if (!$_SERVER["PHP_AUTH_USER"]) {
1192 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1193 header('HTTP/1.0 401 Unauthorized');
1197 $auth_result = authenticate_user($link,
1198 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1200 if (!$auth_result) {
1201 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1202 header('HTTP/1.0 401 Unauthorized');
1210 function authenticate_user($link, $login, $password, $force_auth = false) {
1212 if (!SINGLE_USER_MODE
) {
1214 $pwd_hash = 'SHA1:' . sha1($password);
1216 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1217 $query = "SELECT id,login,access_level
1218 FROM ttrss_users WHERE
1221 $query = "SELECT id,login,access_level
1222 FROM ttrss_users WHERE
1223 login = '$login' AND pwd_hash = '$pwd_hash'";
1226 $result = db_query($link, $query);
1228 if (db_num_rows($result) == 1) {
1229 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1230 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1231 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1233 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1236 $user_theme = get_user_theme_path($link);
1238 $_SESSION["theme"] = $user_theme;
1239 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1241 initialize_user_prefs($link, $_SESSION["uid"]);
1250 $_SESSION["uid"] = 1;
1251 $_SESSION["name"] = "admin";
1253 $user_theme = get_user_theme_path($link);
1255 $_SESSION["theme"] = $user_theme;
1256 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1258 initialize_user_prefs($link, $_SESSION["uid"]);
1264 function make_password($length = 8) {
1267 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1271 while ($i < $length) {
1272 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1274 if (!strstr($password, $char)) {
1282 // this is called after user is created to initialize default feeds, labels
1285 // user preferences are checked on every login, not here
1287 function initialize_user($link, $uid) {
1289 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1290 values ('$uid','unread = true', 'Unread articles')");
1292 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1293 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1295 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1296 values ('$uid', 'Tiny Tiny RSS: New Releases',
1297 'http://tt-rss.spb.ru/releases.rss')");
1299 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1300 values ('$uid', 'Tiny Tiny RSS: Forum',
1301 'http://tt-rss.spb.ru/forum/rss.php')");
1304 function logout_user() {
1306 if (isset($_COOKIE[session_name()])) {
1307 setcookie(session_name(), '', time()-42000, '/');
1311 function get_script_urlpath() {
1312 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1315 function validate_session($link) {
1316 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1317 if ($_SESSION["ip_address"]) {
1318 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1319 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1325 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1327 //print_r($_SESSION);
1329 if (time() > $_SESSION["cookie_lifetime"]) {
1337 function login_sequence($link, $mobile = false) {
1338 if (!SINGLE_USER_MODE
) {
1340 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1341 $swu = db_escape_string($_REQUEST["swu"]);
1343 $_SESSION["prefs_cache"] = false;
1344 return authenticate_user($link, $swu, null, true);
1348 $login_action = $_POST["login_action"];
1350 # try to authenticate user if called from login form
1351 if ($login_action == "do_login") {
1352 $login = $_POST["login"];
1353 $password = $_POST["password"];
1354 $remember_me = $_POST["remember_me"];
1356 if (authenticate_user($link, $login, $password)) {
1357 $_POST["password"] = "";
1359 header("Location: " . $_SERVER["REQUEST_URI"]);
1364 $_SESSION["login_error_msg"] = "Incorrect username or password";
1368 // print session_id();
1369 // print_r($_SESSION);
1371 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1372 render_login_form($link, $mobile);
1375 /* bump login timestamp */
1376 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1381 return authenticate_user($link, "admin", null);
1385 function truncate_string($str, $max_len) {
1386 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1387 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1393 function get_user_theme_path($link) {
1394 $result = db_query($link, "SELECT theme_path
1396 ttrss_themes,ttrss_users
1397 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1398 if (db_num_rows($result) != 0) {
1399 return db_fetch_result($result, 0, "theme_path");
1405 function smart_date_time($timestamp) {
1406 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1407 return date("G:i", $timestamp);
1408 } else if (date("Y", $timestamp) == date("Y")) {
1409 return date("M d, G:i", $timestamp);
1411 return date("Y/m/d, G:i", $timestamp);
1415 function smart_date($timestamp) {
1416 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1418 } else if (date("Y", $timestamp) == date("Y")) {
1419 return date("D m", $timestamp);
1421 return date("Y/m/d", $timestamp);
1425 function sql_bool_to_string($s) {
1426 if ($s == "t" ||
$s == "1") {
1433 function sql_bool_to_bool($s) {
1434 if ($s == "t" ||
$s == "1") {
1442 function toggleEvenOdd($a) {
1449 function sanity_check($link) {
1454 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1455 $schema_version = db_fetch_result($result, 0, "schema_version");
1457 if ($schema_version != SCHEMA_VERSION
) {
1461 if (DB_TYPE
== "mysql") {
1462 $result = db_query($link, "SELECT true", false);
1463 if (db_num_rows($result) != 1) {
1468 error_reporting (DEFAULT_ERROR_LEVEL
);
1470 if ($error_code != 0) {
1471 print_error_xml($error_code);
1478 function file_is_locked($filename) {
1480 $fp = fopen($filename, "r");
1481 error_reporting(DEFAULT_ERROR_LEVEL
);
1483 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1484 flock($fp, LOCK_UN
);
1494 function make_lockfile($filename) {
1495 $fp = fopen($filename, "w");
1497 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1504 function sql_random_function() {
1505 if (DB_TYPE
== "mysql") {
1512 function catchup_feed($link, $feed, $cat_view) {
1514 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1519 $cat_qpart = "cat_id = '$feed'";
1521 $cat_qpart = "cat_id IS NULL";
1524 $tmp_result = db_query($link, "SELECT id
1525 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1528 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1530 $tmp_feed = $tmp_line["id"];
1532 db_query($link, "UPDATE ttrss_user_entries
1533 SET unread = false,last_read = NOW()
1534 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1537 } else if ($feed > 0) {
1539 $tmp_result = db_query($link, "SELECT id
1540 FROM ttrss_feeds WHERE parent_feed = '$feed'
1541 ORDER BY cat_id,title");
1543 $parent_ids = array();
1545 if (db_num_rows($tmp_result) > 0) {
1546 while ($p = db_fetch_assoc($tmp_result)) {
1547 array_push($parent_ids, "feed_id = " . $p["id"]);
1550 $children_qpart = implode(" OR ", $parent_ids);
1552 db_query($link, "UPDATE ttrss_user_entries
1553 SET unread = false,last_read = NOW()
1554 WHERE (feed_id = '$feed' OR $children_qpart)
1555 AND owner_uid = " . $_SESSION["uid"]);
1558 db_query($link, "UPDATE ttrss_user_entries
1559 SET unread = false,last_read = NOW()
1560 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1563 } else if ($feed < 0 && $feed > -10) { // special, like starred
1566 db_query($link, "UPDATE ttrss_user_entries
1567 SET unread = false,last_read = NOW()
1568 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1571 } else if ($feed < -10) { // label
1573 // TODO make this more efficient
1575 $label_id = -$feed - 11;
1577 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1578 WHERE id = '$label_id'");
1581 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1583 db_query($link, "BEGIN");
1585 $tmp2_result = db_query($link,
1589 ttrss_user_entries,ttrss_entries,ttrss_feeds
1591 ref_id = ttrss_entries.id AND
1592 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1594 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1596 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1597 db_query($link, "UPDATE
1600 unread = false, last_read = NOW()
1602 int_id = " . $tmp_line["int_id"]);
1605 db_query($link, "COMMIT");
1607 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1608 SET unread = false,last_read = NOW()
1611 AND owner_uid = ".$_SESSION["uid"]); */
1615 db_query($link, "BEGIN");
1617 $tag_name = db_escape_string($feed);
1619 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1620 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1622 while ($line = db_fetch_assoc($result)) {
1623 db_query($link, "UPDATE ttrss_user_entries SET
1624 unread = false, last_read = NOW()
1625 WHERE int_id = " . $line["post_int_id"]);
1627 db_query($link, "COMMIT");
1631 function update_generic_feed($link, $feed, $cat_view) {
1635 $cat_qpart = "cat_id = '$feed'";
1637 $cat_qpart = "cat_id IS NULL";
1640 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1641 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1643 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1644 $feed_url = $tmp_line["feed_url"];
1645 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1649 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1650 WHERE id = '$feed'");
1651 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1652 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1656 function getAllCounters($link, $omode = "tflc") {
1657 /* getLabelCounters($link);
1658 getFeedCounters($link);
1659 getTagCounters($link);
1660 getGlobalCounters($link);
1661 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1662 getCategoryCounters($link);
1665 if (!$omode) $omode = "tflc";
1667 getGlobalCounters($link);
1669 if (strchr($omode, "l")) getLabelCounters($link);
1670 if (strchr($omode, "f")) getFeedCounters($link);
1671 if (strchr($omode, "t")) getTagCounters($link);
1672 if (strchr($omode, "c")) {
1673 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1674 getCategoryCounters($link);
1679 function getCategoryCounters($link) {
1680 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1681 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id
1682 AND unread = true)) AS unread FROM ttrss_feeds
1684 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1686 while ($line = db_fetch_assoc($result)) {
1687 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1688 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1689 $line["unread"]."\"/>";
1693 function getCategoryUnread($link, $cat) {
1696 $cat_query = "cat_id = '$cat'";
1698 $cat_query = "cat_id IS NULL";
1701 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1703 AND owner_uid = " . $_SESSION["uid"]);
1705 $cat_feeds = array();
1706 while ($line = db_fetch_assoc($result)) {
1707 array_push($cat_feeds, "feed_id = " . $line["id"]);
1710 if (count($cat_feeds) == 0) return 0;
1712 $match_part = implode(" OR ", $cat_feeds);
1714 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1715 FROM ttrss_user_entries
1716 WHERE unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1720 # this needs to be rewritten
1721 while ($line = db_fetch_assoc($result)) {
1722 $unread +
= $line["unread"];
1729 function getFeedUnread($link, $feed, $is_cat = false) {
1730 $n_feed = sprintf("%d", $feed);
1733 return getCategoryUnread($link, $n_feed);
1734 } else if ($n_feed == -1) {
1735 $match_part = "marked = true";
1736 } else if ($n_feed > 0) {
1738 $result = db_query($link, "SELECT id FROM ttrss_feeds
1739 WHERE parent_feed = '$n_feed'
1741 AND owner_uid = " . $_SESSION["uid"]);
1743 if (db_num_rows($result) > 0) {
1745 $linked_feeds = array();
1746 while ($line = db_fetch_assoc($result)) {
1747 array_push($linked_feeds, "feed_id = " . $line["id"]);
1750 array_push($linked_feeds, "feed_id = $n_feed");
1752 $match_part = implode(" OR ", $linked_feeds);
1754 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1755 FROM ttrss_user_entries
1756 WHERE unread = true AND ($match_part)
1757 AND owner_uid = " . $_SESSION["uid"]);
1761 # this needs to be rewritten
1762 while ($line = db_fetch_assoc($result)) {
1763 $unread +
= $line["unread"];
1769 $match_part = "feed_id = '$n_feed'";
1771 } else if ($feed < -10) {
1773 $label_id = -$feed - 11;
1775 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1776 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1778 $match_part = db_fetch_result($result, 0, "sql_exp");
1783 $result = db_query($link, "SELECT count(int_id) AS unread
1784 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1785 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1786 ttrss_user_entries.ref_id = ttrss_entries.id AND
1787 ttrss_feeds.hidden = false AND
1788 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1792 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1793 FROM ttrss_tags,ttrss_user_entries
1794 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1795 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1798 $unread = db_fetch_result($result, 0, "unread");
1803 /* FIXME this needs reworking */
1805 function getGlobalUnread($link, $user_id = false) {
1808 $user_id = $_SESSION["uid"];
1811 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1812 WHERE unread = true AND
1813 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1814 ttrss_user_entries.ref_id = ttrss_entries.id AND
1816 ttrss_user_entries.owner_uid = '$user_id'");
1817 $c_id = db_fetch_result($result, 0, "c_id");
1821 function getGlobalCounters($link, $global_unread = -1) {
1822 if ($global_unread == -1) {
1823 $global_unread = getGlobalUnread($link);
1825 print "<counter type=\"global\" id='global-unread'
1826 counter='$global_unread'/>";
1828 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1829 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1831 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1833 print "<counter type=\"global\" id='subscribed-feeds'
1834 counter='$subscribed_feeds'/>";
1838 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1841 if (!$_SESSION["tctr_last_value"]) {
1842 $_SESSION["tctr_last_value"] = array();
1846 $old_counters = $_SESSION["tctr_last_value"];
1848 $tctrs_modified = false;
1850 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1851 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1852 ttrss_user_entries.ref_id = ttrss_entries.id AND
1853 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1854 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
1856 select tag_name,0 as count FROM ttrss_tags
1857 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1859 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1860 FROM ttrss_user_entries WHERE int_id = post_int_id
1861 AND unread = true)) AS count FROM ttrss_tags
1862 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1866 while ($line = db_fetch_assoc($result)) {
1867 $tags[$line["tag_name"]] +
= $line["count"];
1870 foreach (array_keys($tags) as $tag) {
1871 $unread = $tags[$tag];
1873 $tag = htmlspecialchars($tag);
1875 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
1876 $old_counters[$tag] = $unread;
1877 $tctrs_modified = true;
1878 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1883 if ($smart_mode && $tctrs_modified) {
1884 $_SESSION["tctr_last_value"] = $old_counters;
1889 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
1892 if (!$_SESSION["lctr_last_value"]) {
1893 $_SESSION["lctr_last_value"] = array();
1899 $old_counters = $_SESSION["lctr_last_value"];
1900 $lctrs_modified = false;
1902 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1903 WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND
1904 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1905 unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1907 $count = db_fetch_result($result, 0, "count");
1910 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1912 $ret_arr["-1"]["counter"] = $count;
1913 $ret_arr["-1"]["description"] = "Starred";
1916 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1917 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1919 while ($line = db_fetch_assoc($result)) {
1921 $id = -$line["id"] - 11;
1923 $label_name = $line["description"];
1925 error_reporting (0);
1927 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1928 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
1929 ttrss_feeds.hidden = false AND
1930 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1931 ttrss_user_entries.ref_id = ttrss_entries.id AND
1932 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1934 $count = db_fetch_result($tmp_result, 0, "count");
1936 if (!$smart_mode ||
$old_counters[$id] != $count) {
1937 $old_counters[$id] = $count;
1938 $lctrs_modified = true;
1940 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1942 $ret_arr[$id]["counter"] = $count;
1943 $ret_arr[$id]["description"] = $label_name;
1947 error_reporting (DEFAULT_ERROR_LEVEL
);
1950 if ($smart_mode && $lctrs_modified) {
1951 $_SESSION["lctr_last_value"] = $old_counters;
1957 /* function getFeedCounter($link, $id) {
1959 $result = db_query($link, "SELECT
1960 count(id) as count,last_error
1961 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1962 WHERE feed_id = '$id' AND unread = true
1963 AND ttrss_user_entries.feed_id = ttrss_feeds.id
1964 AND ttrss_user_entries.ref_id = ttrss_entries.id");
1966 $count = db_fetch_result($result, 0, "count");
1967 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1969 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
1972 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1975 if (!$_SESSION["fctr_last_value"]) {
1976 $_SESSION["fctr_last_value"] = array();
1980 $old_counters = $_SESSION["fctr_last_value"];
1982 $result = db_query($link, "SELECT id,last_error,parent_feed,
1983 SUBSTRING(last_updated,1,19) AS last_updated,
1985 FROM ttrss_entries,ttrss_user_entries
1986 WHERE feed_id = ttrss_feeds.id AND
1987 ttrss_user_entries.ref_id = ttrss_entries.id
1988 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1989 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1990 AND parent_feed IS NULL");
1992 $fctrs_modified = false;
1994 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1996 while ($line = db_fetch_assoc($result)) {
1999 $count = $line["count"];
2000 $last_error = htmlspecialchars($line["last_error"]);
2002 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2003 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2005 $last_updated = date($short_date, strtotime($line["last_updated"]));
2008 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2010 $tmp_result = db_query($link,
2011 "SELECT id,COUNT(unread) AS unread
2012 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2013 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2014 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
2016 if (db_num_rows($tmp_result) > 0) {
2017 while ($l = db_fetch_assoc($tmp_result)) {
2018 $count +
= $l["unread"];
2022 if (!$smart_mode ||
$old_counters[$id] != $count) {
2023 $old_counters[$id] = $count;
2024 $fctrs_modified = true;
2027 $error_part = "error=\"$last_error\"";
2033 $has_img_part = "hi=\"$has_img\"";
2038 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
2042 if ($smart_mode && $fctrs_modified) {
2043 $_SESSION["fctr_last_value"] = $old_counters;
2047 function get_script_dt_add() {
2048 if (strpos(VERSION
, ".99") === false) {
2055 function get_pgsql_version($link) {
2056 $result = db_query($link, "SELECT version() AS version");
2057 $version = split(" ", db_fetch_result($result, 0, "version"));
2061 function print_error_xml($code, $add_msg = "") {
2064 $error_msg = $ERRORS[$code];
2067 $error_msg = "$error_msg; $add_msg";
2070 print "<rpc-reply>";
2071 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2072 print "</rpc-reply>";
2075 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2076 $auth_login = '', $auth_pass = '') {
2078 # check for feed:http://url
2079 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2081 # check for feed://URL
2082 if (strpos($feed_link, "//") === 0) {
2083 $feed_link = "http:$feed_link";
2086 if ($feed_link == "") return;
2088 if ($cat_id == "0" ||
!$cat_id) {
2089 $cat_qpart = "NULL";
2091 $cat_qpart = "'$cat_id'";
2094 $result = db_query($link,
2095 "SELECT id FROM ttrss_feeds
2096 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2098 if (db_num_rows($result) == 0) {
2100 $result = db_query($link,
2101 "INSERT INTO ttrss_feeds
2102 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2103 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2104 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2106 $result = db_query($link,
2107 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2108 AND owner_uid = " . $_SESSION["uid"]);
2110 $feed_id = db_fetch_result($result, 0, "id");
2113 update_rss_feed($link, $feed_link, $feed_id, true);
2122 function print_feed_select($link, $id, $default_id = "",
2123 $attributes = "", $include_all_feeds = true) {
2125 print "<select id=\"$id\" name=\"$id\" $attributes>";
2126 if ($include_all_feeds) {
2127 print "<option value=\"0\">All feeds</option>";
2130 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2131 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2133 if (db_num_rows($result) > 0 && $include_all_feeds) {
2134 print "<option disabled>--------</option>";
2137 while ($line = db_fetch_assoc($result)) {
2138 if ($line["id"] == $default_id) {
2139 $is_selected = "selected";
2143 printf("<option $is_selected value='%d'>%s</option>",
2144 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2150 function print_feed_cat_select($link, $id, $default_id = "",
2151 $attributes = "", $include_all_cats = true) {
2153 print "<select id=\"$id\" name=\"$id\" $attributes>";
2155 if ($include_all_cats) {
2156 print "<option value=\"0\">".__('Uncategorized')."</option>";
2159 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2160 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2162 if (db_num_rows($result) > 0 && $include_all_cats) {
2163 print "<option disabled>--------</option>";
2166 while ($line = db_fetch_assoc($result)) {
2167 if ($line["id"] == $default_id) {
2168 $is_selected = "selected";
2172 printf("<option $is_selected value='%d'>%s</option>",
2173 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2179 function checkbox_to_sql_bool($val) {
2180 return ($val == "on") ?
"true" : "false";
2183 function getFeedCatTitle($link, $id) {
2185 return __("Special");
2186 } else if ($id < -10) {
2187 return __("Labels");
2188 } else if ($id > 0) {
2189 $result = db_query($link, "SELECT ttrss_feed_categories.title
2190 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2191 cat_id = ttrss_feed_categories.id");
2192 if (db_num_rows($result) == 1) {
2193 return db_fetch_result($result, 0, "title");
2195 return __("Uncategorized");
2198 return "getFeedCatTitle($id) failed";
2203 function getFeedTitle($link, $id) {
2205 return __("Starred articles");
2206 } else if ($id < -10) {
2207 $label_id = -10 - $id;
2208 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2209 if (db_num_rows($result) == 1) {
2210 return db_fetch_result($result, 0, "description");
2212 return "Unknown label ($label_id)";
2215 } else if ($id > 0) {
2216 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2217 if (db_num_rows($result) == 1) {
2218 return db_fetch_result($result, 0, "title");
2220 return "Unknown feed ($id)";
2223 return "getFeedTitle($id) failed";
2228 function get_session_cookie_name() {
2229 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2232 function print_init_params($link) {
2233 print "<init-params>";
2234 if ($_SESSION["stored-params"]) {
2235 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2237 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2238 print "<param key=\"$key\" value=\"$value\"/>";
2243 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2244 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2245 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY
. "\"/>";
2247 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2248 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2250 print "<param key=\"hide_read_feeds\" value=\"" .
2251 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2253 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2254 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2256 print "<param key=\"confirm_feed_catchup\" value=\"" .
2257 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2259 print "<param key=\"cdm_auto_catchup\" value=\"" .
2260 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2262 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2264 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2266 print "<param key=\"default_view_mode\" value=\"" .
2267 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2269 print "<param key=\"default_view_limit\" value=\"" .
2270 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2272 print "<param key=\"prefs_active_tab\" value=\"" .
2273 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2275 print "<param key=\"infobox_disable_overlay\" value=\"" .
2276 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2278 print "</init-params>";
2281 function print_runtime_info($link) {
2282 print "<runtime-info>";
2283 if (ENABLE_UPDATE_DAEMON
) {
2284 print "<param key=\"daemon_is_running\" value=\"".
2285 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2287 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2289 if ($_SESSION["last_version_check"] +
600 < time()) {
2290 $new_version_details = check_for_update($link);
2292 print "<param key=\"new_version_available\" value=\"".
2293 sprintf("%d", $new_version_details != ""). "\"/>";
2295 $_SESSION["last_version_check"] = time();
2299 print "</runtime-info>";
2302 function getSearchSql($search, $match_on) {
2304 $search_query_part = "";
2306 $keywords = split(" ", $search);
2307 $query_keywords = array();
2309 if ($match_on == "both") {
2311 foreach ($keywords as $k) {
2312 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2313 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2316 $search_query_part = implode("AND", $query_keywords) . " AND ";
2318 } else if ($match_on == "title") {
2320 foreach ($keywords as $k) {
2321 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2324 $search_query_part = implode("AND", $query_keywords) . " AND ";
2326 } else if ($match_on == "content") {
2328 foreach ($keywords as $k) {
2329 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2333 $search_query_part = implode("AND", $query_keywords);
2335 return $search_query_part;
2338 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2342 $search_query_part = getSearchSql($search, $match_on);
2343 $search_query_part .= " AND ";
2346 $search_query_part = "";
2349 $view_query_part = "";
2351 if ($view_mode == "adaptive") {
2353 $view_query_part = " ";
2354 } else if ($feed != -1) {
2355 $unread = getFeedUnread($link, $feed, $cat_view);
2357 $view_query_part = " unread = true AND ";
2362 if ($view_mode == "marked") {
2363 $view_query_part = " marked = true AND ";
2366 if ($view_mode == "unread") {
2367 $view_query_part = " unread = true AND ";
2371 $limit_query_part = "LIMIT " . $limit;
2374 $vfeed_query_part = "";
2376 // override query strategy and enable feed display when searching globally
2377 if ($search && $search_mode == "all_feeds") {
2378 $query_strategy_part = "ttrss_entries.id > 0";
2379 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2380 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2381 $query_strategy_part = "ttrss_entries.id > 0";
2382 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2383 id = feed_id) as feed_title,";
2384 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2386 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2388 $tmp_result = false;
2391 $tmp_result = db_query($link, "SELECT id
2392 FROM ttrss_feeds WHERE cat_id = '$feed'");
2394 $tmp_result = db_query($link, "SELECT id
2395 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2396 WHERE id = '$feed') AND id != '$feed'");
2399 $cat_siblings = array();
2401 if (db_num_rows($tmp_result) > 0) {
2402 while ($p = db_fetch_assoc($tmp_result)) {
2403 array_push($cat_siblings, "feed_id = " . $p["id"]);
2406 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2407 $feed, implode(" OR ", $cat_siblings));
2410 $query_strategy_part = "ttrss_entries.id > 0";
2413 } else if ($feed >= 0) {
2418 $query_strategy_part = "cat_id = '$feed'";
2420 $query_strategy_part = "cat_id IS NULL";
2423 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2426 $tmp_result = db_query($link, "SELECT id
2427 FROM ttrss_feeds WHERE parent_feed = '$feed'
2428 ORDER BY cat_id,title");
2430 $parent_ids = array();
2432 if (db_num_rows($tmp_result) > 0) {
2433 while ($p = db_fetch_assoc($tmp_result)) {
2434 array_push($parent_ids, "feed_id = " . $p["id"]);
2437 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2438 $feed, implode(" OR ", $parent_ids));
2440 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2442 $query_strategy_part = "feed_id = '$feed'";
2445 } else if ($feed == -1) { // starred virtual feed
2446 $query_strategy_part = "marked = true";
2447 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2448 } else if ($feed <= -10) { // labels
2449 $label_id = -$feed - 11;
2451 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2452 WHERE id = '$label_id'");
2454 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2456 if (!$query_strategy_part) {
2460 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2462 $query_strategy_part = "id > 0"; // dumb
2465 if (get_pref($link, 'REVERSE_HEADLINES')) {
2466 $order_by = "updated";
2468 $order_by = "updated DESC";
2471 if ($override_order) {
2472 $order_by = $override_order;
2477 if ($search && $search_mode == "all_feeds") {
2478 $feed_title = __("Search results")." ($search)";
2479 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2480 $feed_title = __("Search results")." ($search, $feed)";
2481 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2482 $feed_title = $feed;
2483 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2488 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2489 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2490 $feed_title = db_fetch_result($result, 0, "title");
2492 $feed_title = __("Uncategorized");
2496 $feed_title = __("Searched for")." $search ($feed_title)";
2501 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2502 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2504 $feed_title = db_fetch_result($result, 0, "title");
2505 $feed_site_url = db_fetch_result($result, 0, "site_url");
2506 $last_error = db_fetch_result($result, 0, "last_error");
2509 $feed_title = __("Searched for") . " $search ($feed_title)";
2513 } else if ($feed == -1) {
2514 $feed_title = __("Starred articles");
2515 } else if ($feed < -10) {
2516 $label_id = -$feed - 11;
2517 $result = db_query($link, "SELECT description FROM ttrss_labels
2518 WHERE id = '$label_id'");
2519 $feed_title = db_fetch_result($result, 0, "description");
2522 $feed_title = __("Searched for") . " $search ($feed_title)";
2528 $feed_title = db_unescape_string($feed_title);
2530 if ($feed < -10) error_reporting (0);
2532 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2535 $feed_kind = "Feeds";
2537 $feed_kind = "Labels";
2540 $content_query_part = "content as content_preview,";
2542 if ($limit_query_part) {
2543 $offset_query_part = "OFFSET $offset";
2548 ttrss_entries.id,ttrss_entries.title,
2550 unread,feed_id,marked,link,last_read,
2551 SUBSTRING(last_read,1,19) as last_read_noms,
2554 SUBSTRING(updated,1,19) as updated_noms,
2557 ttrss_entries,ttrss_user_entries,ttrss_feeds
2559 ttrss_feeds.hidden = false AND
2560 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2561 ttrss_user_entries.ref_id = ttrss_entries.id AND
2562 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2565 $query_strategy_part ORDER BY $order_by
2566 $limit_query_part $offset_query_part";
2568 $result = db_query($link, $query);
2570 if ($_GET["debug"]) print $query;
2575 $feed_kind = "Tags";
2577 $result = db_query($link, "SELECT
2579 ttrss_entries.id as id,title,
2582 marked,link,last_read,
2583 SUBSTRING(last_read,1,19) as last_read_noms,
2586 SUBSTRING(updated,1,19) as updated_noms
2588 ttrss_entries,ttrss_user_entries,ttrss_tags
2590 ref_id = ttrss_entries.id AND
2591 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2592 post_int_id = int_id AND tag_name = '$feed' AND
2595 $query_strategy_part ORDER BY $order_by
2596 $limit_query_part");
2599 return array($result, $feed_title, $feed_site_url, $last_error);
2603 function generate_syndicated_feed($link, $feed, $is_cat,
2604 $search, $search_mode, $match_on) {
2606 $qfh_ret = queryFeedHeadlines($link, $feed,
2607 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2609 $result = $qfh_ret[0];
2610 $feed_title = htmlspecialchars($qfh_ret[1]);
2611 $feed_site_url = $qfh_ret[2];
2612 $last_error = $qfh_ret[3];
2614 print "<rss version=\"2.0\">
2616 <title>$feed_title</title>
2617 <link>$feed_site_url</link>
2618 <generator>Tiny Tiny RSS v".VERSION
."</generator>";
2620 while ($line = db_fetch_assoc($result)) {
2622 print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2623 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2625 $rfc822_date = date('r', strtotime($line["updated"]));
2627 print "<pubDate>$rfc822_date</pubDate>";
2630 htmlspecialchars($line["title"]) . "</title>";
2632 print "<description>" .
2633 htmlspecialchars($line["content_preview"]) . "</description>";
2638 print "</channel></rss>";
2642 function getCategoryTitle($link, $cat_id) {
2644 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2647 if (db_num_rows($result) == 1) {
2648 return db_fetch_result($result, 0, "title");
2650 return "Uncategorized";
2654 // http://ru2.php.net/strip-tags
2656 function strip_tags_long($textstring, $allowed){
2657 while($textstring != strip_tags($textstring, $allowed))
2659 while (strlen($textstring) != 0)
2661 if (strlen($textstring) > 1024) {
2664 $otherlen = strlen($textstring);
2666 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
2667 $safetext .= $temptext;
2668 $textstring = substr_replace($textstring,'',0,$otherlen);
2670 $textstring = $safetext;
2676 function sanitize_rss($link, $str, $force_strip_tags = false) {
2679 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
2681 global $tw_paranoya_setup;
2683 $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
2685 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
2686 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
2692 function send_headlines_digests($link, $limit = 100) {
2694 if (!DIGEST_ENABLE
) return false;
2696 $user_limit = DIGEST_EMAIL_LIMIT
;
2699 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2701 if (DB_TYPE
== "pgsql") {
2702 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2703 } else if (DB_TYPE
== "mysql") {
2704 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2707 $result = db_query($link, "SELECT id,email FROM ttrss_users
2708 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2710 while ($line = db_fetch_assoc($result)) {
2711 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2712 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2714 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2715 $digest = $tuple[0];
2716 $headlines_count = $tuple[1];
2718 if ($headlines_count > 0) {
2719 $rc = mail($line["login"] . " <" . $line["email"] . ">",
2720 "[tt-rss] New headlines for last 24 hours", $digest,
2721 "From: " . MAIL_FROM
. "\n".
2722 "Content-Type: text/plain; charset=\"utf-8\"\n".
2723 "Content-Transfer-Encoding: 8bit\n");
2725 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2726 WHERE id = " . $line["id"]);
2728 print "No headlines\n";
2733 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2737 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2738 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
2739 $tmp .= "=======================================================\n\n";
2741 if (DB_TYPE
== "pgsql") {
2742 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2743 } else if (DB_TYPE
== "mysql") {
2744 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2747 $result = db_query($link, "SELECT ttrss_entries.title,
2748 ttrss_feeds.title AS feed_title,
2751 SUBSTRING(last_updated,1,19) AS last_updated
2753 ttrss_user_entries,ttrss_entries,ttrss_feeds
2755 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2756 AND include_in_digest = true
2758 AND ttrss_user_entries.owner_uid = $user_id
2759 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2762 $cur_feed_title = "";
2764 $headlines_count = db_num_rows($result);
2766 while ($line = db_fetch_assoc($result)) {
2767 $updated = smart_date_time(strtotime($line["last_updated"]));
2768 $feed_title = $line["feed_title"];
2770 if ($cur_feed_title != $feed_title) {
2771 $cur_feed_title = $feed_title;
2773 $tmp .= "$feed_title\n\n";
2776 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2777 $tmp .= " " . trim($line["link"]) . "\n";
2782 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
2783 DIGEST_HOSTNAME
. "\n".
2784 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2787 return array($tmp, $headlines_count);
2790 function check_for_update($link, $brief_fmt = true) {
2791 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2793 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
2798 $rss = fetch_rss($releases_feed);
2799 error_reporting (DEFAULT_ERROR_LEVEL
);
2803 $items = $rss->items
;
2805 if (!$items ||
!is_array($items)) $items = $rss->entries
;
2806 if (!$items ||
!is_array($items)) $items = $rss;
2808 if (!is_array($items) ||
count($items) == 0) {
2812 $latest_item = $items[0];
2814 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2816 $release_url = sanitize_rss($link, $latest_item["link"]);
2817 $content = sanitize_rss($link, $latest_item["description"]);
2819 if (version_compare(VERSION
, $latest_version) == -1) {
2821 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
2822 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2823 <div id=\"milestoneDetails\">$content</div>");
2825 return "New version of Tiny-Tiny RSS ($latest_version) is available:
2826 <div class='milestoneDetails'>$content</div>
2827 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2828 download and update information.";
2835 function markArticlesById($link, $ids, $cmode) {
2839 foreach ($ids as $id) {
2840 array_push($tmp_ids, "ref_id = '$id'");
2843 $ids_qpart = join(" OR ", $tmp_ids);
2846 db_query($link, "UPDATE ttrss_user_entries SET
2847 marked = false,last_read = NOW()
2848 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2849 } else if ($cmode == 1) {
2850 db_query($link, "UPDATE ttrss_user_entries SET
2852 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2854 db_query($link, "UPDATE ttrss_user_entries SET
2855 marked = NOT marked,last_read = NOW()
2856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2860 function catchupArticlesById($link, $ids, $cmode) {
2864 foreach ($ids as $id) {
2865 array_push($tmp_ids, "ref_id = '$id'");
2868 $ids_qpart = join(" OR ", $tmp_ids);
2871 db_query($link, "UPDATE ttrss_user_entries SET
2872 unread = false,last_read = NOW()
2873 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2874 } else if ($cmode == 1) {
2875 db_query($link, "UPDATE ttrss_user_entries SET
2877 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2879 db_query($link, "UPDATE ttrss_user_entries SET
2880 unread = NOT unread,last_read = NOW()
2881 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2885 function catchupArticleById($link, $id, $cmode) {
2888 db_query($link, "UPDATE ttrss_user_entries SET
2889 unread = false,last_read = NOW()
2890 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2891 } else if ($cmode == 1) {
2892 db_query($link, "UPDATE ttrss_user_entries SET
2894 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2896 db_query($link, "UPDATE ttrss_user_entries SET
2897 unread = NOT unread,last_read = NOW()
2898 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2902 function escape_for_form($s) {
2903 return htmlspecialchars(db_unescape_string($s));
2906 function make_guid_from_title($title) {
2907 return preg_replace("/[ \"\',.:;]/", "-",
2908 mb_strtolower(strip_tags($title), 'utf-8'));
2911 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
2912 $bottom = false, $rtl_content = false, $feed_id = 0,
2913 $is_cat = false, $search = false, $match_on = false,
2914 $search_mode = false, $offset = 0, $limit = 0) {
2916 $user_page_offset = $offset +
1;
2919 $class = "headlinesSubToolbar";
2920 $tid = "headlineActionsTop";
2922 $class = "headlinesSubToolbar";
2923 $tid = "headlineActionsBottom";
2926 print "<table class=\"$class\" id=\"$tid\"
2927 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2935 $page_prev_link = "javascript:viewFeedGoPage(-1)";
2936 $page_next_link = "javascript:viewFeedGoPage(1)";
2937 $page_first_link = "javascript:viewFeedGoPage(0)";
2939 $catchup_page_link = "javascript:catchupPage()";
2940 $catchup_feed_link = "javascript:catchupCurrentFeed()";
2942 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2944 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2945 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2946 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2948 $tog_unread_link = "javascript:selectionToggleUnread()";
2949 $tog_marked_link = "javascript:selectionToggleMarked()";
2953 $sel_all_link = "javascript:cdmSelectArticles('all')";
2954 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2955 $sel_none_link = "javascript:cdmSelectArticles('none')";
2957 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2958 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2962 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
2964 print "<td class=\"headlineActions$rtl_cpart\">
2965 <ul class=\"headlineDropdownMenu\">
2968 <a href=\"$sel_all_link\">".__('All')."</a>,
2969 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2970 <a href=\"$sel_none_link\">".__('None')."</a></li>
2971 <li class=\"vsep\"> </li>
2972 <li class=\"top\">Toggle<ul>
2973 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
2974 <li onclick=\"$tog_marked_link\">".__('Starred')."</li></ul></li>
2975 <li class=\"vsep\"> </li>
2976 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
2977 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
2978 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
2979 <li class=\"vsep\"> </li>";
2981 if ($limit != 0 && !$search) {
2983 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
2984 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
2985 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
2989 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
2990 print "<li class=\"top3\">
2991 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2992 '$match_on', '$feed_id', '$is_cat');\">
2993 ".__('Convert to label')."</a></td>";
2999 // old style subtoolbar:
3001 print "<td class=\"headlineActions$rtl_cpart\">".
3003 <a href=\"$sel_all_link\">".__('All')."</a>,
3004 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3005 <a href=\"$sel_none_link\">".__('None')."</a>
3007 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3008 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3010 __('Mark as read:')."
3011 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3012 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3014 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3017 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3018 '$match_on', '$feed_id', '$is_cat');\">
3019 ".__('Convert to label')."</a>";
3026 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3027 print "<td class=\"headlineActions$rtl_cpart\">
3028 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3029 '$match_on', '$feed_id', '$is_cat');\">
3030 ".__('Convert to Label')."</a></td>";
3033 print "<td class=\"headlineTitle$rtl_cpart\">";
3035 if ($feed_site_url) {
3037 $target = "target=\"_blank\"";
3039 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
3045 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3048 if ($user_page_offset > 1) {
3049 print " [$user_page_offset] ";
3055 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3056 <img class=\"noborder\"
3057 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3062 print "</tr></table>";
3066 function outputFeedList($link, $tags = false) {
3068 print "<ul class=\"feedList\" id=\"feedList\">";
3070 $owner_uid = $_SESSION["uid"];
3074 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3075 print "<li class=\"feedCat\">".__('Special')."</li>";
3076 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3079 $num_starred = getFeedUnread($link, -1);
3083 if ($num_starred > 0) $class .= "Unread";
3085 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
3086 "images/mark_set.png", $link);
3088 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3094 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
3096 $result = db_query($link, "SELECT id,sql_exp,description FROM
3097 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3099 if (db_num_rows($result) > 0) {
3100 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3101 print "<li class=\"feedCat\">".__('Labels')."</li>";
3102 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3104 print "<li><hr></li>";
3108 while ($line = db_fetch_assoc($result)) {
3110 error_reporting (0);
3112 $label_id = -$line['id'] - 11;
3113 $count = getFeedUnread($link, $label_id);
3121 error_reporting (DEFAULT_ERROR_LEVEL
);
3123 printFeedEntry($label_id,
3124 $class, db_unescape_string($line["description"]),
3125 $count, "images/label.png", $link);
3129 if (db_num_rows($result) > 0) {
3130 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3137 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3138 print "<li><hr></li>";
3141 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3142 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3143 $order_by_qpart = "category,unread DESC,title";
3145 $order_by_qpart = "category,title";
3148 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3149 $order_by_qpart = "unread DESC,title";
3151 $order_by_qpart = "title";
3155 $result = db_query($link, "SELECT ttrss_feeds.*,
3156 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3157 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3158 WHERE feed_id = ttrss_feeds.id AND unread = true
3159 AND ttrss_user_entries.ref_id = ttrss_entries.id
3160 AND owner_uid = '$owner_uid') as unread,
3162 ttrss_feed_categories.title AS category,
3163 ttrss_feed_categories.collapsed
3164 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
3165 ON (ttrss_feed_categories.id = cat_id)
3167 ttrss_feeds.hidden = false AND
3168 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3169 ORDER BY $order_by_qpart");
3171 $actid = $_GET["actid"];
3181 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3183 while ($line = db_fetch_assoc($result)) {
3185 $feed = trim(db_unescape_string($line["title"]));
3187 if (!$feed) $feed = "[Untitled]";
3189 $feed_id = $line["id"];
3191 $subop = $_GET["subop"];
3193 $unread = $line["unread"];
3195 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3196 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3198 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3201 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3204 $rtl_tag = "dir=\"RTL\"";
3209 $tmp_result = db_query($link,
3210 "SELECT id,COUNT(unread) AS unread
3211 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
3212 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
3213 WHERE parent_feed = '$feed_id' AND unread = true
3214 GROUP BY ttrss_feeds.id");
3216 if (db_num_rows($tmp_result) > 0) {
3217 while ($l = db_fetch_assoc($tmp_result)) {
3218 $unread +
= $l["unread"];
3222 $cat_id = $line["cat_id"];
3224 $tmp_category = $line["category"];
3226 if (!$tmp_category) {
3227 $tmp_category = __("Uncategorized");
3230 // $class = ($lnum % 2) ? "even" : "odd";
3232 if ($line["last_error"]) {
3238 if ($unread > 0) $class .= "Unread";
3240 if ($actid == $feed_id) {
3241 $class .= "Selected";
3244 $total_unread +
= $unread;
3246 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3252 $category = $tmp_category;
3254 $collapsed = $line["collapsed"];
3256 // workaround for NULL category
3257 if ($category == __("Uncategorized")) {
3258 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3263 if ($collapsed == "t" ||
$collapsed == "1") {
3264 $holder_class = "invisible";
3267 $holder_class = "feedCatHolder";
3271 $cat_id = sprintf("%d", $cat_id);
3273 $cat_unread = getCategoryUnread($link, $cat_id);
3275 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3277 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3278 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3279 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3280 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3281 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3284 // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3285 // -> keyboard navigation, etc.
3286 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3289 printFeedEntry($feed_id, $class, $feed, $unread,
3290 ICONS_DIR
."/$feed_id.ico", $link, $rtl_content,
3291 $last_updated, $line["last_error"]);
3296 if (db_num_rows($result) == 0) {
3297 print "<li>".__('No feeds to display.')."</li>";
3304 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3305 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3306 post_int_id = ttrss_user_entries.int_id AND
3307 unread = true AND ref_id = ttrss_entries.id
3308 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3310 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3311 ORDER BY tag_name"); */
3313 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3314 print "<li class=\"feedCat\">".__('Tags')."</li>";
3315 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3318 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3319 FROM ttrss_user_entries WHERE int_id = post_int_id
3320 AND unread = true)) AS count FROM ttrss_tags
3321 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3325 while ($line = db_fetch_assoc($result)) {
3326 $tags[$line["tag_name"]] +
= $line["count"];
3329 foreach (array_keys($tags) as $tag) {
3331 $unread = $tags[$tag];
3339 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3343 if (db_num_rows($result) == 0) {
3344 print "<li>No tags to display.</li>";
3347 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3357 function get_article_tags($link, $id) {
3359 $a_id = db_escape_string($id);
3361 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3362 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3363 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3367 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3368 array_push($tags, $tmp_line["tag_name"]);
3374 function trim_value(&$value) {
3375 $value = trim($value);
3378 function trim_array($array) {
3380 array_walk($tmp, 'trim_value');
3384 function tag_is_valid($tag) {
3385 if ($tag == '') return false;
3386 if (preg_match("/^[0-9]*$/", $tag)) return false;
3388 $tag = iconv("utf-8", "utf-8", $tag);
3389 if (!$tag) return false;
3394 function render_login_form($link, $mobile = false) {
3396 require_once "login_form.php";
3398 require_once "mobile/login_form.php";
3402 // from http://developer.apple.com/internet/safari/faq.html
3403 function no_cache_incantation() {
3404 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3405 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3406 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3407 header("Cache-Control: post-check=0, pre-check=0", false);
3408 header("Pragma: no-cache"); // HTTP/1.0
3411 function format_warning($msg, $id = "") {
3412 return "<div class=\"warning\" id=\"$id\">
3413 <img src=\"images/sign_excl.png\">$msg</div>";
3416 function format_notice($msg) {
3417 return "<div class=\"notice\">
3418 <img src=\"images/sign_info.png\">$msg</div>";
3421 function format_error($msg) {
3422 return "<div class=\"error\">
3423 <img src=\"images/sign_excl.png\">$msg</div>";
3426 function print_notice($msg) {
3427 return print format_notice($msg);
3430 function print_warning($msg) {
3431 return print format_warning($msg);
3434 function print_error($msg) {
3435 return print format_error($msg);
3439 function T_sprintf() {
3440 $args = func_get_args();
3441 return vsprintf(__(array_shift($args)), $args);
3444 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
3446 /* we can figure out feed_id from article id anyway, why do we
3447 * pass feed_id here? */
3449 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3450 WHERE ref_id = '$id'");
3452 $feed_id = db_fetch_result($result, 0, "feed_id");
3454 print "<article id='$id'><![CDATA[";
3456 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3457 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3459 if (db_num_rows($result) == 1) {
3460 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3462 $rtl_content = false;
3466 $rtl_tag = "dir=\"RTL\"";
3473 if ($mark_as_read) {
3474 $result = db_query($link, "UPDATE ttrss_user_entries
3475 SET unread = false,last_read = NOW()
3476 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3479 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3480 SUBSTRING(updated,1,16) as updated,
3481 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3484 FROM ttrss_entries,ttrss_user_entries
3485 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3491 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3492 $link_target = "target=\"_new\"";
3495 $line = db_fetch_assoc($result);
3497 if ($line["icon_url"]) {
3498 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
3500 $feed_icon = " ";
3503 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
3504 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
3506 $entry_comments = "";
3509 $num_comments = $line["num_comments"];
3510 $entry_comments = "";
3512 if ($num_comments > 0) {
3513 if ($line["comments"]) {
3514 $comments_url = $line["comments"];
3516 $comments_url = $line["link"];
3518 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
3520 if ($line["comments"] && $line["link"] != $line["comments"]) {
3521 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
3525 print "<div class=\"postReply\">";
3527 print "<div class=\"postHeader\">";
3529 $entry_author = $line["author"];
3531 if ($entry_author) {
3532 $entry_author = __(" - by ") . $entry_author;
3535 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
3536 strtotime($line["updated"]));
3538 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3540 if ($line["link"]) {
3541 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
3542 $line["title"] . "</a>$entry_author</div>";
3544 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3547 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3548 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
3549 ORDER BY tag_name");
3556 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3558 $tag = $tmp_line["tag_name"];
3559 $tag_escaped = str_replace("'", "\\'", $tag);
3561 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
3563 if ($num_tags == 6) {
3564 $tags_str .= "<a href=\"javascript:showBlockElement('allEntryTags')\">...</a>";
3565 } else if ($num_tags < 6) {
3566 $tags_str .= $tag_str;
3568 $f_tags_str .= $tag_str;
3571 $tags_str = preg_replace("/, $/", "", $tags_str);
3572 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
3574 if (!$entry_comments) $entry_comments = " "; # placeholder
3576 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
3578 print "<div style='float : right'>$tags_str
3579 <a title=\"Edit tags for this article\"
3580 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
3581 <div clear='both'>$entry_comments</div>";
3585 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
3586 print "<div class=\"postContent\">";
3588 if (db_num_rows($tmp_result) > 0) {
3589 print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
3592 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3593 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
3596 $line["content"] = sanitize_rss($link, $line["content"]);
3598 print $line["content"] . "</div>";
3604 print "]]></article>";
3608 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
3609 $next_unread_feed, $offset) {
3611 $timing_info = getmicrotime();
3613 $topmost_article_ids = array();
3615 if (!$offset) $offset = 0;
3617 if ($subop == "undefined") $subop = "";
3619 if ($subop == "CatchupSelected") {
3620 $ids = split(",", db_escape_string($_GET["ids"]));
3621 $cmode = sprintf("%d", $_GET["cmode"]);
3623 catchupArticlesById($link, $ids, $cmode);
3626 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
3627 update_generic_feed($link, $feed, $cat_view);
3630 if ($subop == "MarkAllRead") {
3631 catchup_feed($link, $feed, $cat_view);
3633 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
3634 if ($next_unread_feed) {
3635 $feed = $next_unread_feed;
3641 $result = db_query($link,
3642 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
3644 if (db_num_rows($result) == 0) {
3645 print "<div align='center'>".__('Feed not found.')."</div>";
3650 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3652 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3653 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
3655 if (db_num_rows($result) == 1) {
3656 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3658 $rtl_content = false;
3662 $rtl_tag = "dir=\"RTL\"";
3668 $rtl_content = false;
3671 $script_dt_add = get_script_dt_add();
3673 /// START /////////////////////////////////////////////////////////////////////////////////
3675 $search = db_escape_string($_GET["query"]);
3676 $search_mode = db_escape_string($_GET["search_mode"]);
3677 $match_on = db_escape_string($_GET["match_on"]);
3683 $real_offset = $offset * $limit;
3685 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
3687 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
3688 $search, $search_mode, $match_on, false, $real_offset);
3690 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
3692 $result = $qfh_ret[0];
3693 $feed_title = $qfh_ret[1];
3694 $feed_site_url = $qfh_ret[2];
3695 $last_error = $qfh_ret[3];
3697 /// STOP //////////////////////////////////////////////////////////////////////////////////
3699 print "<div id=\"headlinesContainer\" $rtl_tag>";
3702 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
3706 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
3707 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
3710 print "<div id=\"headlinesInnerContainer\">";
3712 if (db_num_rows($result) > 0) {
3714 # print "\{$offset}";
3716 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3717 print "<table class=\"headlinesList\" id=\"headlinesList\"
3718 cellspacing=\"0\">";
3723 error_reporting (DEFAULT_ERROR_LEVEL
);
3727 while ($line = db_fetch_assoc($result)) {
3729 $class = ($lnum %
2) ?
"even" : "odd";
3732 $feed_id = $line["feed_id"];
3734 if (count($topmost_article_ids) < 5) {
3735 array_push($topmost_article_ids, $id);
3738 if ($line["last_read"] == "" &&
3739 ($line["unread"] != "t" && $line["unread"] != "1")) {
3741 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
3744 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
3748 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
3756 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
3757 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.png\"
3759 alt=\"Reset mark\" onclick='javascript:tMark($id)'>";
3761 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.png\"
3763 alt=\"Set mark\" onclick='javascript:tMark($id)'>";
3766 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
3767 # $line["title"] . "</a>";
3769 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
3770 $line["title"] . "</a>";
3772 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
3773 # $line["title"] . "</a>";
3775 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3776 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
3778 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3779 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
3782 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3783 $content_preview = truncate_string(strip_tags($line["content_preview"]),
3787 $entry_author = $line["author"];
3789 if ($entry_author) {
3790 $entry_author = " - by $entry_author";
3793 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3795 print "<tr class='$class' id='RROW-$id'>";
3797 print "<td class='hlUpdPic'>$update_pic</td>";
3799 print "<td class='hlSelectRow'>
3800 <input type=\"checkbox\" onclick=\"tSR(this)\"
3804 print "<td class='hlMarkedPic'>$marked_pic</td>";
3806 if ($line["feed_title"]) {
3807 print "<td class='hlContent'>$content_link</td>";
3808 print "<td class='hlFeed'>
3809 <a href=\"javascript:viewfeed($feed_id, '', false)\">".
3810 $line["feed_title"]."</a> </td>";
3812 print "<td class='hlContent' valign='middle'>";
3814 print "<a href=\"javascript:view($id,$feed_id);\">" .
3817 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3818 if ($content_preview) {
3819 print "<span class=\"contentPreview\"> - $content_preview</span>";
3827 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
3834 $add_class = "Unread";
3839 print "<div class=\"cdmArticle$add_class\" id=\"RROW-$id\">";
3841 print "<div class=\"cdmHeader\">";
3843 print "<div class=\"articleUpdated\">$updated_fmt</div>";
3845 print "<a class=\"title\"
3846 onclick=\"javascript:toggleUnread($id, 0)\"
3847 target=\"new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
3849 print $entry_author;
3851 if ($line["feed_title"]) {
3852 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
3857 print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
3859 print "<div class=\"cdmFooter\">";
3861 print "$marked_pic";
3863 print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
3864 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
3866 $tags = get_article_tags($link, $id);
3870 foreach ($tags as $tag) {
3872 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
3875 $tags_str = preg_replace("/, $/", "", $tags_str);
3877 if ($tags_str == "") $tags_str = "no tags";
3879 print " $tags_str <a title=\"Edit tags for this article\"
3880 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
3884 # print "<div align=\"center\"><a class=\"cdmToggleLink\"
3885 # href=\"javascript:toggleUnread($id)\">
3886 # Toggle unread</a></div>";
3895 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3899 // print_headline_subtoolbar($link,
3900 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
3904 print "<div class='whiteBox'>".__('No articles found.')."</div>";
3911 return $topmost_article_ids;
3914 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
3916 function printTagCloud($link) {
3918 /* get first ref_id to count from */
3924 if (DB_TYPE == "pgsql") {
3925 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3926 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3927 AND date_entered > NOW() - INTERVAL '30 days'";
3929 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3930 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3931 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
3934 $result = db_query($link, $query);
3935 $first_id = db_fetch_result($result, 0, "id"); */
3937 //AND post_int_id >= '$first_id'
3938 $query = "SELECT tag_name, COUNT(post_int_id) AS count
3939 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
3940 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
3942 $result = db_query($link, $query);
3946 while ($line = db_fetch_assoc($result)) {
3947 $tags[$line["tag_name"]] = $line["count"];
3952 $max_size = 32; // max font size in pixels
3953 $min_size = 11; // min font size in pixels
3955 // largest and smallest array values
3956 $max_qty = max(array_values($tags));
3957 $min_qty = min(array_values($tags));
3959 // find the range of values
3960 $spread = $max_qty - $min_qty;
3961 if ($spread == 0) { // we don't want to divide by zero
3965 // set the font-size increment
3966 $step = ($max_size - $min_size) / ($spread);
3968 // loop through the tag array
3969 foreach ($tags as $key => $value) {
3970 // calculate font-size
3971 // find the $value in excess of $min_qty
3972 // multiply by the font-size increment ($size)
3973 // and add the $min_size set above
3974 $size = round($min_size +
(($value - $min_qty) * $step));
3976 echo "<a href=\"javascript:viewfeed('$key') \" style=\"font-size: " .
3977 $size . "px\" title=\"$value articles tagged with " .
3978 $key . '">' . $key . '</a> ';
3982 function print_checkpoint($n, $s) {
3983 $ts = getmicrotime();
3984 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3988 function sanitize_tag($tag) {
3991 $tag = mb_strtolower($tag, 'utf-8');
3993 $tag = str_replace('\"', "", $tag);
3994 $tag = str_replace('"', "", $tag);
3995 $tag = str_replace("+", " ", $tag);
3996 $tag = str_replace("technorati tag: ", "", $tag);