]>
git.wh0rd.org - tt-rss.git/blob - functions.php
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 "accept-to-gettext.php";
10 require_once "gettext/gettext.inc";
12 require_once 'config.php';
14 if (ENABLE_TRANSLATIONS
== true) {
18 require_once 'db-prefs.php';
19 require_once 'compat.php';
20 require_once 'errors.php';
21 require_once 'version.php';
23 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
24 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
26 require_once "magpierss/rss_fetch.inc";
27 require_once 'magpierss/rss_utils.inc';
29 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
33 if (DB_TYPE
== "pgsql") {
34 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
35 marked = false AND feed_id = '$feed_id' AND
36 (SELECT date_entered FROM ttrss_entries WHERE
37 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
39 $pg_version = get_pgsql_version($link);
41 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
43 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
44 ttrss_entries.id = ref_id AND
46 feed_id = '$feed_id' AND
47 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
51 $result = db_query($link, "DELETE FROM ttrss_user_entries
53 WHERE ttrss_entries.id = ref_id AND
55 feed_id = '$feed_id' AND
56 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
59 $rows = pg_affected_rows($result);
63 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
64 marked = false AND feed_id = '$feed_id' AND
65 (SELECT date_entered FROM ttrss_entries WHERE
66 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
68 $result = db_query($link, "DELETE FROM ttrss_user_entries
69 USING ttrss_user_entries, ttrss_entries
70 WHERE ttrss_entries.id = ref_id AND
72 feed_id = '$feed_id' AND
73 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
75 $rows = mysql_affected_rows($link);
80 print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
84 function global_purge_old_posts($link, $do_output = false, $limit = false) {
86 $random_qpart = sql_random_function();
89 $limit_qpart = "LIMIT $limit";
94 $result = db_query($link,
95 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
96 ORDER BY $random_qpart $limit_qpart");
98 while ($line = db_fetch_assoc($result)) {
100 $feed_id = $line["id"];
101 $purge_interval = $line["purge_interval"];
102 $owner_uid = $line["owner_uid"];
104 if ($purge_interval == 0) {
106 $tmp_result = db_query($link,
107 "SELECT value FROM ttrss_user_prefs WHERE
108 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
110 if (db_num_rows($tmp_result) != 0) {
111 $purge_interval = db_fetch_result($tmp_result, 0, "value");
116 // print "Feed $feed_id: purge interval = $purge_interval\n";
119 if ($purge_interval > 0) {
120 purge_feed($link, $feed_id, $purge_interval, $do_output);
124 // purge orphaned posts in main content table
125 db_query($link, "DELETE FROM ttrss_entries WHERE
126 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
130 function purge_old_posts($link) {
132 $user_id = $_SESSION["uid"];
134 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
135 WHERE owner_uid = '$user_id'");
137 while ($line = db_fetch_assoc($result)) {
139 $feed_id = $line["id"];
140 $purge_interval = $line["purge_interval"];
142 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
144 if ($purge_interval > 0) {
145 purge_feed($link, $feed_id, $purge_interval);
149 // purge orphaned posts in main content table
150 db_query($link, "DELETE FROM ttrss_entries WHERE
151 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
154 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
156 if (WEB_DEMO_MODE
) return;
159 $user_id = $_SESSION["uid"];
160 purge_old_posts($link);
163 // db_query($link, "BEGIN");
165 if (MAX_UPDATE_TIME
> 0) {
166 if (DB_TYPE
== "mysql") {
169 $q_order = "RANDOM()";
172 $q_order = "last_updated DESC";
175 $result = db_query($link, "SELECT feed_url,id,
176 SUBSTRING(last_updated,1,19) AS last_updated,
177 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
182 while ($line = db_fetch_assoc($result)) {
183 $upd_intl = $line["update_interval"];
185 if (!$upd_intl ||
$upd_intl == 0) {
186 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
190 // Updates for this feed are disabled
194 if ($fetch ||
(!$line["last_updated"] ||
195 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
197 // print "<!-- feed: ".$line["feed_url"]." -->";
199 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
201 $upd_elapsed = time() - $upd_start;
203 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
209 // db_query($link, "COMMIT");
213 function fetch_file_contents($url) {
214 if (USE_CURL_FOR_ICONS
) {
215 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
217 $ch = curl_init($url);
218 $fp = fopen($tmpfile, "w");
221 curl_setopt($ch, CURLOPT_FILE
, $fp);
227 $contents = file_get_contents($tmpfile);
233 return file_get_contents($url);
238 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
239 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
241 function get_favicon_url($url) {
243 if ($html = @fetch_file_contents
($url)) {
245 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
246 // Attempt to grab a favicon link from their webpage url
247 $linkUrl = html_entity_decode($matches[1]);
249 if (substr($linkUrl, 0, 1) == '/') {
250 $urlParts = parse_url($url);
251 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
252 } else if (substr($linkUrl, 0, 7) == 'http://') {
253 $faviconURL = $linkUrl;
254 } else if (substr($url, -1, 1) == '/') {
255 $faviconURL = $url.$linkUrl;
257 $faviconURL = $url.'/'.$linkUrl;
261 // If unsuccessful, attempt to "guess" the favicon location
262 $urlParts = parse_url($url);
263 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
267 // Run a test to see if what we have attempted to get actually exists.
268 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
275 function url_validate($link) {
277 $url_parts = @parse_url
($link);
279 if ( empty( $url_parts["host"] ) )
282 if ( !empty( $url_parts["path"] ) ) {
283 $documentpath = $url_parts["path"];
288 if ( !empty( $url_parts["query"] ) )
289 $documentpath .= "?" . $url_parts["query"];
291 $host = $url_parts["host"];
292 $port = $url_parts["port"];
297 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
302 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
304 $http_response = fgets( $socket, 22 );
306 $responses = "/(200 OK)|(30[0-9] Moved)/";
307 if ( preg_match($responses, $http_response) ) {
316 function check_feed_favicon($site_url, $feed, $link) {
317 $favicon_url = get_favicon_url($site_url);
319 # print "FAVICON [$site_url]: $favicon_url\n";
323 $icon_file = ICONS_DIR
. "/$feed.ico";
325 if ($favicon_url && !file_exists($icon_file)) {
326 $contents = fetch_file_contents($favicon_url);
328 $fp = fopen($icon_file, "w");
331 fwrite($fp, $contents);
333 chmod($icon_file, 0644);
337 error_reporting(DEFAULT_ERROR_LEVEL
);
341 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
343 if (DAEMON_REFRESH_ONLY
&& !$_GET["daemon"] && !$ignore_daemon) {
347 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass
348 FROM ttrss_feeds WHERE id = '$feed'");
350 $auth_login = db_unescape_string(db_fetch_result($result, 0, "auth_login"));
351 $auth_pass = db_unescape_string(db_fetch_result($result, 0, "auth_pass"));
353 $update_interval = db_fetch_result($result, 0, "update_interval");
355 if ($update_interval < 0) { return; }
357 $feed = db_escape_string($feed);
359 $fetch_url = $feed_url;
361 if ($auth_login && $auth_pass) {
362 $url_parts = array();
363 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
365 if ($url_parts[1] && $url_parts[2]) {
366 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
372 $rss = fetch_rss($fetch_url);
373 error_reporting (DEFAULT_ERROR_LEVEL
);
375 $feed = db_escape_string($feed);
379 // db_query($link, "BEGIN");
381 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
382 FROM ttrss_feeds WHERE id = '$feed'");
384 $registered_title = db_fetch_result($result, 0, "title");
385 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
386 $orig_site_url = db_fetch_result($result, 0, "site_url");
388 $owner_uid = db_fetch_result($result, 0, "owner_uid");
390 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
391 check_feed_favicon($rss->channel
["link"], $feed, $link);
394 if (!$registered_title ||
$registered_title == "[Unknown]") {
396 $feed_title = db_escape_string($rss->channel
["title"]);
398 db_query($link, "UPDATE ttrss_feeds SET
399 title = '$feed_title' WHERE id = '$feed'");
402 $site_url = $rss->channel
["link"];
403 // weird, weird Magpie
404 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
406 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
407 db_query($link, "UPDATE ttrss_feeds SET
408 site_url = '$site_url' WHERE id = '$feed'");
411 // print "I: " . $rss->channel["image"]["url"];
413 $icon_url = $rss->image
["url"];
415 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
416 $icon_url = db_escape_string($icon_url);
417 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
423 $result = db_query($link, "SELECT reg_exp,
424 ttrss_filter_types.name AS name,
425 ttrss_filter_actions.name AS action,
428 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
430 owner_uid = $owner_uid AND
431 ttrss_filter_types.id = filter_type AND
432 ttrss_filter_actions.id = action_id AND
433 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
435 while ($line = db_fetch_assoc($result)) {
436 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
438 $filter["reg_exp"] = $line["reg_exp"];
439 $filter["action"] = $line["action"];
440 $filter["action_param"] = $line["action_param"];
441 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
443 array_push($filters[$line["name"]], $filter);
446 $iterator = $rss->items
;
448 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
449 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
451 if (!is_array($iterator)) {
452 /* db_query($link, "UPDATE ttrss_feeds
453 SET last_error = 'Parse error: can\'t find any articles.'
454 WHERE id = '$feed'"); */
458 foreach ($iterator as $item) {
460 $entry_guid = $item["id"];
462 if (!$entry_guid) $entry_guid = $item["guid"];
463 if (!$entry_guid) $entry_guid = $item["link"];
464 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
466 if (!$entry_guid) continue;
468 $entry_timestamp = "";
470 $rss_2_date = $item['pubdate'];
471 $rss_1_date = $item['dc']['date'];
472 $atom_date = $item['issued'];
473 if (!$atom_date) $atom_date = $item['updated'];
475 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
476 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
477 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
479 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
480 $entry_timestamp = time();
481 $no_orig_date = 'true';
483 $no_orig_date = 'false';
486 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
488 $entry_title = trim(strip_tags($item["title"]));
490 // strange Magpie workaround
491 $entry_link = $item["link_"];
492 if (!$entry_link) $entry_link = $item["link"];
494 if (!$entry_title) continue;
495 # if (!$entry_link) continue;
497 $entry_link = strip_tags($entry_link);
499 $entry_content = $item["content:escaped"];
501 if (!$entry_content) $entry_content = $item["content:encoded"];
502 if (!$entry_content) $entry_content = $item["content"];
503 if (!$entry_content) $entry_content = $item["atom_content"];
504 if (!$entry_content) $entry_content = $item["summary"];
505 if (!$entry_content) $entry_content = $item["description"];
507 // if (!$entry_content) continue;
510 if (is_array($entry_content)) {
511 $entry_content = $entry_content["encoded"];
512 if (!$entry_content) $entry_content = $entry_content["escaped"];
516 // print_r(htmlspecialchars($entry_content));
519 $entry_content_unescaped = $entry_content;
520 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
522 $entry_comments = strip_tags($item["comments"]);
524 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
526 if ($item['author']) {
528 if (is_array($item['author'])) {
530 if (!$entry_author) {
531 $entry_author = db_escape_string(strip_tags($item['author']['name']));
534 if (!$entry_author) {
535 $entry_author = db_escape_string(strip_tags($item['author']['email']));
539 if (!$entry_author) {
540 $entry_author = db_escape_string(strip_tags($item['author']));
544 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
546 $entry_guid = db_escape_string(strip_tags($entry_guid));
548 $result = db_query($link, "SELECT id FROM ttrss_entries
549 WHERE guid = '$entry_guid'");
551 $entry_content = db_escape_string($entry_content);
552 $entry_title = db_escape_string($entry_title);
553 $entry_link = db_escape_string($entry_link);
554 $entry_comments = db_escape_string($entry_comments);
556 $num_comments = db_escape_string($item["slash"]["comments"]);
558 if (!$num_comments) $num_comments = 0;
560 /* $dc_subject = $item['dc']['subject'];
562 $subject_tags = false;
564 if (is_array($dc_subject)) {
565 $subject_tags = $dc_subject;
566 } else if ($dc_subject) {
567 $subject_tags = array($dc_subject);
572 $entry_content = sanitize_rss($entry_content);
574 db_query($link, "BEGIN");
576 if (db_num_rows($result) == 0) {
578 // base post entry does not exist, create it
580 $result = db_query($link,
581 "INSERT INTO ttrss_entries
597 '$entry_timestamp_fmt',
606 // we keep encountering the entry in feeds, so we need to
607 // update date_entered column so that we don't get horrible
608 // dupes when the entry gets purged and reinserted again e.g.
609 // in the case of SLOW SLOW OMG SLOW updating feeds
611 $base_entry_id = db_fetch_result($result, 0, "id");
613 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
614 WHERE id = '$base_entry_id'");
617 // now it should exist, if not - bad luck then
619 $result = db_query($link, "SELECT
620 id,content_hash,no_orig_date,title,
621 substring(date_entered,1,19) as date_entered,
622 substring(updated,1,19) as updated,
626 WHERE guid = '$entry_guid'");
628 if (db_num_rows($result) == 1) {
630 // this will be used below in update handler
631 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
632 $orig_title = db_fetch_result($result, 0, "title");
633 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
634 $orig_date_entered = strtotime(db_fetch_result($result,
637 $ref_id = db_fetch_result($result, 0, "id");
639 // check for user post link to main table
641 // do we allow duplicate posts with same GUID in different feeds?
642 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
643 $dupcheck_qpart = "AND feed_id = '$feed'";
645 $dupcheck_qpart = "";
648 // error_reporting(0);
650 $article_filters = get_article_filters($filters, $entry_title,
651 $entry_content, $entry_link);
653 if (find_article_filter($article_filters, "filter")) {
657 // error_reporting (DEFAULT_ERROR_LEVEL);
659 $result = db_query($link,
660 "SELECT ref_id FROM ttrss_user_entries WHERE
661 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
664 // okay it doesn't exist - create user entry
665 if (db_num_rows($result) == 0) {
667 if (!find_article_filter($article_filters, 'catchup')) {
669 $last_read_qpart = 'NULL';
672 $last_read_qpart = 'NOW()';
675 if (find_article_filter($article_filters, 'mark')) {
681 $result = db_query($link,
682 "INSERT INTO ttrss_user_entries
683 (ref_id, owner_uid, feed_id, unread, last_read, marked)
684 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
685 $last_read_qpart, $marked)");
688 $post_needs_update = false;
690 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
691 ($content_hash != $orig_content_hash)) {
692 $post_needs_update = true;
695 if ($orig_title != $entry_title) {
696 $post_needs_update = true;
699 if ($orig_num_comments != $num_comments) {
700 $post_needs_update = true;
703 // this doesn't seem to be very reliable
705 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
706 // $post_needs_update = true;
709 // if post needs update, update it and mark all user entries
710 // linking to this post as updated
711 if ($post_needs_update) {
713 // print "<!-- post $orig_title needs update : $post_needs_update -->";
715 db_query($link, "UPDATE ttrss_entries
716 SET title = '$entry_title', content = '$entry_content',
717 num_comments = '$num_comments'
718 WHERE id = '$ref_id'");
720 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
721 db_query($link, "UPDATE ttrss_user_entries
722 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
724 db_query($link, "UPDATE ttrss_user_entries
725 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
731 db_query($link, "COMMIT");
734 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
738 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i",
739 $entry_content_unescaped, $entry_tags);
741 // print "<br>$entry_title : $entry_content_unescaped<br>";
742 // print_r($entry_tags);
745 $entry_tags = $entry_tags[1];
747 # check for manual tags
749 $tag_filter = find_article_filter($article_filters, "tag");
753 $manual_tags = trim_array(split(",", $tag_filter[1]));
755 foreach ($manual_tags as $tag) {
756 if (tag_is_valid($tag)) {
757 array_push($entry_tags, $tag);
762 /* if ($subject_tags) {
763 foreach ($subject_tags as $tag) {
764 if (tag_is_valid($tag)) {
765 array_push($entry_tags, $tag);
770 if (count($entry_tags) > 0) {
772 db_query($link, "BEGIN");
774 $result = db_query($link, "SELECT id,int_id
775 FROM ttrss_entries,ttrss_user_entries
776 WHERE guid = '$entry_guid'
777 AND feed_id = '$feed' AND ref_id = id
778 AND owner_uid = '$owner_uid'");
780 if (db_num_rows($result) == 1) {
782 $entry_id = db_fetch_result($result, 0, "id");
783 $entry_int_id = db_fetch_result($result, 0, "int_id");
785 foreach ($entry_tags as $tag) {
786 $tag = db_escape_string(mb_strtolower(strip_tags($tag)));
788 $tag = str_replace("+", " ", $tag);
789 $tag = str_replace("technorati tag: ", "", $tag);
791 if (!tag_is_valid($tag)) continue;
793 $result = db_query($link, "SELECT id FROM ttrss_tags
794 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
795 owner_uid = '$owner_uid' LIMIT 1");
797 // print db_fetch_result($result, 0, "id");
799 if ($result && db_num_rows($result) == 0) {
801 // print "tagging $entry_id as $tag<br>";
803 db_query($link, "INSERT INTO ttrss_tags
804 (owner_uid,tag_name,post_int_id)
805 VALUES ('$owner_uid','$tag', '$entry_int_id')");
809 db_query($link, "COMMIT");
813 db_query($link, "UPDATE ttrss_feeds
814 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
816 // db_query($link, "COMMIT");
819 $error_msg = db_escape_string(magpie_error());
821 "UPDATE ttrss_feeds SET last_error = '$error_msg',
822 last_updated = NOW() WHERE id = '$feed'");
827 function print_select($id, $default, $values, $attributes = "") {
828 print "<select name=\"$id\" id=\"$id\" $attributes>";
829 foreach ($values as $v) {
835 print "<option$sel>$v</option>";
840 function print_select_hash($id, $default, $values, $attributes = "") {
841 print "<select name=\"$id\" id='$id' $attributes>";
842 foreach (array_keys($values) as $v) {
848 print "<option $sel value=\"$v\">".$values[$v]."</option>";
854 function get_article_filters($filters, $title, $content, $link) {
857 if ($filters["title"]) {
858 foreach ($filters["title"] as $filter) {
859 $reg_exp = $filter["reg_exp"];
860 $inverse = $filter["inverse"];
861 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
862 ($inverse && !preg_match("/$reg_exp/i", $title))) {
864 array_push($matches, array($filter["action"], $filter["action_param"]));
869 if ($filters["content"]) {
870 foreach ($filters["content"] as $filter) {
871 $reg_exp = $filter["reg_exp"];
872 $inverse = $filter["inverse"];
874 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
875 ($inverse && !preg_match("/$reg_exp/i", $content))) {
877 array_push($matches, array($filter["action"], $filter["action_param"]));
882 if ($filters["both"]) {
883 foreach ($filters["both"] as $filter) {
884 $reg_exp = $filter["reg_exp"];
885 $inverse = $filter["inverse"];
888 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
889 array_push($matches, array($filter["action"], $filter["action_param"]));
892 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
893 array_push($matches, array($filter["action"], $filter["action_param"]));
899 if ($filters["link"]) {
900 $reg_exp = $filter["reg_exp"];
901 foreach ($filters["link"] as $filter) {
902 $reg_exp = $filter["reg_exp"];
903 $inverse = $filter["inverse"];
905 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
906 ($inverse && !preg_match("/$reg_exp/i", $link))) {
908 array_push($matches, array($filter["action"], $filter["action_param"]));
916 function find_article_filter($filters, $filter_name) {
917 foreach ($filters as $f) {
918 if ($f[0] == $filter_name) {
925 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
926 $rtl_content = false, $last_updated = false, $last_error = false) {
928 if (file_exists($icon_file) && filesize($icon_file) > 0) {
929 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
931 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
935 $rtl_tag = "dir=\"rtl\"";
937 $rtl_tag = "dir=\"ltr\"";
940 $error_notify_msg = "";
943 $link_title = "Error: $last_error ($last_updated)";
944 $error_notify_msg = "(Error)";
945 } else if ($last_updated) {
946 $link_title = "Updated: $last_updated";
949 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
950 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
952 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
953 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
957 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
962 $fctr_class = "class=\"invisible\"";
965 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
966 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
968 if (get_pref($link, "EXTENDED_FEEDLIST")) {
969 print "<div class=\"feedExtInfo\">
970 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
977 function getmicrotime() {
978 list($usec, $sec) = explode(" ",microtime());
979 return ((float)$usec +
(float)$sec);
982 function print_radio($id, $default, $values, $attributes = "") {
983 foreach ($values as $v) {
991 $sel .= " value=\"1\"";
993 $sel .= " value=\"0\"";
996 print "<input class=\"noborder\"
997 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1002 function initialize_user_prefs($link, $uid) {
1004 $uid = db_escape_string($uid);
1006 db_query($link, "BEGIN");
1008 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1010 $u_result = db_query($link, "SELECT pref_name
1011 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1013 $active_prefs = array();
1015 while ($line = db_fetch_assoc($u_result)) {
1016 array_push($active_prefs, $line["pref_name"]);
1019 while ($line = db_fetch_assoc($result)) {
1020 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1021 // print "adding " . $line["pref_name"] . "<br>";
1023 db_query($link, "INSERT INTO ttrss_user_prefs
1024 (owner_uid,pref_name,value) VALUES
1025 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1030 db_query($link, "COMMIT");
1034 function lookup_user_id($link, $user) {
1036 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1039 if (db_num_rows($result) == 1) {
1040 return db_fetch_result($result, 0, "id");
1046 function http_authenticate_user($link) {
1048 if (!$_SERVER["PHP_AUTH_USER"]) {
1050 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1051 header('HTTP/1.0 401 Unauthorized');
1055 $auth_result = authenticate_user($link,
1056 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1058 if (!$auth_result) {
1059 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1060 header('HTTP/1.0 401 Unauthorized');
1068 function authenticate_user($link, $login, $password, $force_auth = false) {
1070 if (!SINGLE_USER_MODE
) {
1072 $pwd_hash = 'SHA1:' . sha1($password);
1074 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1075 $query = "SELECT id,login,access_level
1076 FROM ttrss_users WHERE
1079 $query = "SELECT id,login,access_level
1080 FROM ttrss_users WHERE
1081 login = '$login' AND pwd_hash = '$pwd_hash'";
1084 $result = db_query($link, $query);
1086 if (db_num_rows($result) == 1) {
1087 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1088 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1089 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1091 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1094 $user_theme = get_user_theme_path($link);
1096 $_SESSION["theme"] = $user_theme;
1097 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1099 initialize_user_prefs($link, $_SESSION["uid"]);
1108 $_SESSION["uid"] = 1;
1109 $_SESSION["name"] = "admin";
1111 $user_theme = get_user_theme_path($link);
1113 $_SESSION["theme"] = $user_theme;
1114 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1116 initialize_user_prefs($link, $_SESSION["uid"]);
1122 function make_password($length = 8) {
1125 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1129 while ($i < $length) {
1130 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1132 if (!strstr($password, $char)) {
1140 // this is called after user is created to initialize default feeds, labels
1143 // user preferences are checked on every login, not here
1145 function initialize_user($link, $uid) {
1147 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1148 values ('$uid','unread = true', 'Unread articles')");
1150 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1151 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1153 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1154 values ('$uid', 'Tiny Tiny RSS: New Releases',
1155 'http://tt-rss.spb.ru/releases.rss')");
1157 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1158 values ('$uid', 'Tiny Tiny RSS: Forum',
1159 'http://tt-rss.spb.ru/forum/rss.php')");
1162 function logout_user() {
1164 if (isset($_COOKIE[session_name()])) {
1165 setcookie(session_name(), '', time()-42000, '/');
1169 function get_script_urlpath() {
1170 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1173 function validate_session($link) {
1174 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1175 if ($_SESSION["ip_address"]) {
1176 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1177 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1183 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1185 //print_r($_SESSION);
1187 if (time() > $_SESSION["cookie_lifetime"]) {
1195 function login_sequence($link) {
1196 if (!SINGLE_USER_MODE
) {
1198 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1199 $swu = db_escape_string($_REQUEST["swu"]);
1201 $_SESSION["prefs_cache"] = false;
1202 return authenticate_user($link, $swu, null, true);
1206 $login_action = $_POST["login_action"];
1208 # try to authenticate user if called from login form
1209 if ($login_action == "do_login") {
1210 $login = $_POST["login"];
1211 $password = $_POST["password"];
1212 $remember_me = $_POST["remember_me"];
1214 if (authenticate_user($link, $login, $password)) {
1215 $_POST["password"] = "";
1217 header("Location: " . $_SERVER["REQUEST_URI"]);
1222 $_SESSION["login_error_msg"] = "Incorrect username or password";
1226 // print session_id();
1227 // print_r($_SESSION);
1229 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1230 render_login_form($link);
1236 return authenticate_user($link, "admin", null);
1240 function truncate_string($str, $max_len) {
1241 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1242 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1248 function get_user_theme_path($link) {
1249 $result = db_query($link, "SELECT theme_path
1251 ttrss_themes,ttrss_users
1252 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1253 if (db_num_rows($result) != 0) {
1254 return db_fetch_result($result, 0, "theme_path");
1260 function smart_date_time($timestamp) {
1261 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1262 return date("G:i", $timestamp);
1263 } else if (date("Y", $timestamp) == date("Y")) {
1264 return date("M d, G:i", $timestamp);
1266 return date("Y/m/d G:i", $timestamp);
1270 function smart_date($timestamp) {
1271 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1273 } else if (date("Y", $timestamp) == date("Y")) {
1274 return date("D m", $timestamp);
1276 return date("Y/m/d", $timestamp);
1280 function sql_bool_to_string($s) {
1281 if ($s == "t" ||
$s == "1") {
1288 function sql_bool_to_bool($s) {
1289 if ($s == "t" ||
$s == "1") {
1297 function toggleEvenOdd($a) {
1304 function sanity_check($link) {
1309 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1310 $schema_version = db_fetch_result($result, 0, "schema_version");
1312 if ($schema_version != SCHEMA_VERSION
) {
1316 if (DB_TYPE
== "mysql") {
1317 $result = db_query($link, "SELECT true", false);
1318 if (db_num_rows($result) != 1) {
1323 error_reporting (DEFAULT_ERROR_LEVEL
);
1325 if ($error_code != 0) {
1326 print_error_xml($error_code);
1333 function file_is_locked($filename) {
1335 $fp = fopen($filename, "r");
1336 error_reporting(DEFAULT_ERROR_LEVEL
);
1338 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1339 flock($fp, LOCK_UN
);
1349 function make_lockfile($filename) {
1350 $fp = fopen($filename, "w");
1352 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1359 function sql_random_function() {
1360 if (DB_TYPE
== "mysql") {
1367 function catchup_feed($link, $feed, $cat_view) {
1369 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1374 $cat_qpart = "cat_id = '$feed'";
1376 $cat_qpart = "cat_id IS NULL";
1379 $tmp_result = db_query($link, "SELECT id
1380 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1383 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1385 $tmp_feed = $tmp_line["id"];
1387 db_query($link, "UPDATE ttrss_user_entries
1388 SET unread = false,last_read = NOW()
1389 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1392 } else if ($feed > 0) {
1394 $tmp_result = db_query($link, "SELECT id
1395 FROM ttrss_feeds WHERE parent_feed = '$feed'
1396 ORDER BY cat_id,title");
1398 $parent_ids = array();
1400 if (db_num_rows($tmp_result) > 0) {
1401 while ($p = db_fetch_assoc($tmp_result)) {
1402 array_push($parent_ids, "feed_id = " . $p["id"]);
1405 $children_qpart = implode(" OR ", $parent_ids);
1407 db_query($link, "UPDATE ttrss_user_entries
1408 SET unread = false,last_read = NOW()
1409 WHERE (feed_id = '$feed' OR $children_qpart)
1410 AND owner_uid = " . $_SESSION["uid"]);
1413 db_query($link, "UPDATE ttrss_user_entries
1414 SET unread = false,last_read = NOW()
1415 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1418 } else if ($feed < 0 && $feed > -10) { // special, like starred
1421 db_query($link, "UPDATE ttrss_user_entries
1422 SET unread = false,last_read = NOW()
1423 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1426 } else if ($feed < -10) { // label
1428 // TODO make this more efficient
1430 $label_id = -$feed - 11;
1432 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1433 WHERE id = '$label_id'");
1436 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1438 db_query($link, "BEGIN");
1440 $tmp2_result = db_query($link,
1444 ttrss_user_entries,ttrss_entries,ttrss_feeds
1446 ref_id = ttrss_entries.id AND
1447 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1449 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1451 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1452 db_query($link, "UPDATE
1455 unread = false, last_read = NOW()
1457 int_id = " . $tmp_line["int_id"]);
1460 db_query($link, "COMMIT");
1462 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1463 SET unread = false,last_read = NOW()
1466 AND owner_uid = ".$_SESSION["uid"]); */
1470 db_query($link, "BEGIN");
1472 $tag_name = db_escape_string($feed);
1474 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1475 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1477 while ($line = db_fetch_assoc($result)) {
1478 db_query($link, "UPDATE ttrss_user_entries SET
1479 unread = false, last_read = NOW()
1480 WHERE int_id = " . $line["post_int_id"]);
1482 db_query($link, "COMMIT");
1486 function update_generic_feed($link, $feed, $cat_view) {
1490 $cat_qpart = "cat_id = '$feed'";
1492 $cat_qpart = "cat_id IS NULL";
1495 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1496 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1498 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1499 $feed_url = $tmp_line["feed_url"];
1500 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1504 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1505 WHERE id = '$feed'");
1506 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1507 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1511 function getAllCounters($link, $omode = "tflc") {
1512 /* getLabelCounters($link);
1513 getFeedCounters($link);
1514 getTagCounters($link);
1515 getGlobalCounters($link);
1516 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1517 getCategoryCounters($link);
1520 if (!$omode) $omode = "tflc";
1522 getGlobalCounters($link);
1524 if (strchr($omode, "l")) getLabelCounters($link);
1525 if (strchr($omode, "f")) getFeedCounters($link);
1526 if (strchr($omode, "t")) getTagCounters($link);
1527 if (strchr($omode, "c")) {
1528 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1529 getCategoryCounters($link);
1534 function getCategoryCounters($link) {
1535 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1536 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id
1537 AND unread = true)) AS unread FROM ttrss_feeds
1539 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1541 while ($line = db_fetch_assoc($result)) {
1542 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1543 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1544 $line["unread"]."\"/>";
1548 function getCategoryUnread($link, $cat) {
1551 $cat_query = "cat_id = '$cat'";
1553 $cat_query = "cat_id IS NULL";
1556 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1558 AND owner_uid = " . $_SESSION["uid"]);
1560 $cat_feeds = array();
1561 while ($line = db_fetch_assoc($result)) {
1562 array_push($cat_feeds, "feed_id = " . $line["id"]);
1565 if (count($cat_feeds) == 0) return 0;
1567 $match_part = implode(" OR ", $cat_feeds);
1569 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1570 FROM ttrss_user_entries
1571 WHERE unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1575 # this needs to be rewritten
1576 while ($line = db_fetch_assoc($result)) {
1577 $unread +
= $line["unread"];
1584 function getFeedUnread($link, $feed, $is_cat = false) {
1585 $n_feed = sprintf("%d", $feed);
1588 return getCategoryUnread($link, $n_feed);
1589 } else if ($n_feed == -1) {
1590 $match_part = "marked = true";
1591 } else if ($n_feed > 0) {
1593 $result = db_query($link, "SELECT id FROM ttrss_feeds
1594 WHERE parent_feed = '$n_feed'
1596 AND owner_uid = " . $_SESSION["uid"]);
1598 if (db_num_rows($result) > 0) {
1600 $linked_feeds = array();
1601 while ($line = db_fetch_assoc($result)) {
1602 array_push($linked_feeds, "feed_id = " . $line["id"]);
1605 array_push($linked_feeds, "feed_id = $n_feed");
1607 $match_part = implode(" OR ", $linked_feeds);
1609 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1610 FROM ttrss_user_entries
1611 WHERE unread = true AND ($match_part)
1612 AND owner_uid = " . $_SESSION["uid"]);
1616 # this needs to be rewritten
1617 while ($line = db_fetch_assoc($result)) {
1618 $unread +
= $line["unread"];
1624 $match_part = "feed_id = '$n_feed'";
1626 } else if ($feed < -10) {
1628 $label_id = -$feed - 11;
1630 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1631 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1633 $match_part = db_fetch_result($result, 0, "sql_exp");
1638 $result = db_query($link, "SELECT count(int_id) AS unread
1639 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1640 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1641 ttrss_user_entries.ref_id = ttrss_entries.id AND
1642 ttrss_feeds.hidden = false AND
1643 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1647 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1648 FROM ttrss_tags,ttrss_user_entries
1649 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1650 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1653 $unread = db_fetch_result($result, 0, "unread");
1658 /* FIXME this needs reworking */
1660 function getGlobalUnread($link, $user_id = false) {
1663 $user_id = $_SESSION["uid"];
1666 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1667 WHERE unread = true AND
1668 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1669 ttrss_user_entries.ref_id = ttrss_entries.id AND
1671 ttrss_user_entries.owner_uid = '$user_id'");
1672 $c_id = db_fetch_result($result, 0, "c_id");
1676 function getGlobalCounters($link, $global_unread = -1) {
1677 if ($global_unread == -1) {
1678 $global_unread = getGlobalUnread($link);
1680 print "<counter type=\"global\" id='global-unread'
1681 counter='$global_unread'/>";
1683 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1684 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1686 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1688 print "<counter type=\"global\" id='subscribed-feeds'
1689 counter='$subscribed_feeds'/>";
1693 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1696 if (!$_SESSION["tctr_last_value"]) {
1697 $_SESSION["tctr_last_value"] = array();
1701 $old_counters = $_SESSION["tctr_last_value"];
1703 $tctrs_modified = false;
1705 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1706 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1707 ttrss_user_entries.ref_id = ttrss_entries.id AND
1708 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1709 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
1711 select tag_name,0 as count FROM ttrss_tags
1712 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1714 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1715 FROM ttrss_user_entries WHERE int_id = post_int_id
1716 AND unread = true)) AS count FROM ttrss_tags
1717 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1721 while ($line = db_fetch_assoc($result)) {
1722 $tags[$line["tag_name"]] +
= $line["count"];
1725 foreach (array_keys($tags) as $tag) {
1726 $unread = $tags[$tag];
1728 $tag = htmlspecialchars($tag);
1730 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
1731 $old_counters[$tag] = $unread;
1732 $tctrs_modified = true;
1733 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1738 if ($smart_mode && $tctrs_modified) {
1739 $_SESSION["tctr_last_value"] = $old_counters;
1744 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
1747 if (!$_SESSION["lctr_last_value"]) {
1748 $_SESSION["lctr_last_value"] = array();
1754 $old_counters = $_SESSION["lctr_last_value"];
1755 $lctrs_modified = false;
1757 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1758 WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND
1759 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1760 unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1762 $count = db_fetch_result($result, 0, "count");
1765 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1767 $ret_arr["-1"]["counter"] = $count;
1768 $ret_arr["-1"]["description"] = "Starred";
1771 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1772 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1774 while ($line = db_fetch_assoc($result)) {
1776 $id = -$line["id"] - 11;
1778 $label_name = $line["description"];
1780 error_reporting (0);
1782 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1783 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
1784 ttrss_feeds.hidden = false AND
1785 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1786 ttrss_user_entries.ref_id = ttrss_entries.id AND
1787 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1789 $count = db_fetch_result($tmp_result, 0, "count");
1791 if (!$smart_mode ||
$old_counters[$id] != $count) {
1792 $old_counters[$id] = $count;
1793 $lctrs_modified = true;
1795 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1797 $ret_arr[$id]["counter"] = $count;
1798 $ret_arr[$id]["description"] = $label_name;
1802 error_reporting (DEFAULT_ERROR_LEVEL
);
1805 if ($smart_mode && $lctrs_modified) {
1806 $_SESSION["lctr_last_value"] = $old_counters;
1812 /* function getFeedCounter($link, $id) {
1814 $result = db_query($link, "SELECT
1815 count(id) as count,last_error
1816 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1817 WHERE feed_id = '$id' AND unread = true
1818 AND ttrss_user_entries.feed_id = ttrss_feeds.id
1819 AND ttrss_user_entries.ref_id = ttrss_entries.id");
1821 $count = db_fetch_result($result, 0, "count");
1822 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1824 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
1827 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1830 if (!$_SESSION["fctr_last_value"]) {
1831 $_SESSION["fctr_last_value"] = array();
1835 $old_counters = $_SESSION["fctr_last_value"];
1837 $result = db_query($link, "SELECT id,last_error,parent_feed,
1838 SUBSTRING(last_updated,1,19) AS last_updated,
1840 FROM ttrss_entries,ttrss_user_entries
1841 WHERE feed_id = ttrss_feeds.id AND
1842 ttrss_user_entries.ref_id = ttrss_entries.id
1843 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1844 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1845 AND parent_feed IS NULL");
1847 $fctrs_modified = false;
1849 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1851 while ($line = db_fetch_assoc($result)) {
1854 $count = $line["count"];
1855 $last_error = htmlspecialchars($line["last_error"]);
1857 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
1858 $last_updated = smart_date_time(strtotime($line["last_updated"]));
1860 $last_updated = date($short_date, strtotime($line["last_updated"]));
1863 $has_img = is_file(ICONS_DIR
. "/$id.ico");
1865 $tmp_result = db_query($link,
1866 "SELECT id,COUNT(unread) AS unread
1867 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
1868 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
1869 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
1871 if (db_num_rows($tmp_result) > 0) {
1872 while ($l = db_fetch_assoc($tmp_result)) {
1873 $count +
= $l["unread"];
1877 if (!$smart_mode ||
$old_counters[$id] != $count) {
1878 $old_counters[$id] = $count;
1879 $fctrs_modified = true;
1882 $error_part = "error=\"$last_error\"";
1888 $has_img_part = "hi=\"$has_img\"";
1893 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
1897 if ($smart_mode && $fctrs_modified) {
1898 $_SESSION["fctr_last_value"] = $old_counters;
1902 function get_script_dt_add() {
1903 if (strpos(VERSION
, "99") === false) {
1910 function get_pgsql_version($link) {
1911 $result = db_query($link, "SELECT version() AS version");
1912 $version = split(" ", db_fetch_result($result, 0, "version"));
1916 function print_error_xml($code, $add_msg = "") {
1919 $error_msg = $ERRORS[$code];
1922 $error_msg = "$error_msg; $add_msg";
1925 print "<rpc-reply>";
1926 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
1927 print "</rpc-reply>";
1930 function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
1932 # check for feed:http://url
1933 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
1935 # check for feed://URL
1936 if (strpos($feed_link, "//") === 0) {
1937 $feed_link = "http:$feed_link";
1940 if ($feed_link == "") return;
1942 if ($cat_id == "0" ||
!$cat_id) {
1943 $cat_qpart = "NULL";
1945 $cat_qpart = "'$cat_id'";
1948 $result = db_query($link,
1949 "SELECT id FROM ttrss_feeds
1950 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
1952 if (db_num_rows($result) == 0) {
1954 $result = db_query($link,
1955 "INSERT INTO ttrss_feeds (owner_uid,feed_url,title,cat_id)
1956 VALUES ('".$_SESSION["uid"]."', '$feed_link',
1957 '[Unknown]', $cat_qpart)");
1959 $result = db_query($link,
1960 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
1961 AND owner_uid = " . $_SESSION["uid"]);
1963 $feed_id = db_fetch_result($result, 0, "id");
1966 update_rss_feed($link, $feed_link, $feed_id, true);
1975 function print_feed_select($link, $id, $default_id = "",
1976 $attributes = "", $include_all_feeds = true) {
1978 print "<select id=\"$id\" name=\"$id\" $attributes>";
1979 if ($include_all_feeds) {
1980 print "<option value=\"0\">All feeds</option>";
1983 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1984 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1986 if (db_num_rows($result) > 0 && $include_all_feeds) {
1987 print "<option disabled>--------</option>";
1990 while ($line = db_fetch_assoc($result)) {
1991 if ($line["id"] == $default_id) {
1992 $is_selected = "selected";
1996 printf("<option $is_selected value='%d'>%s</option>",
1997 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2003 function print_feed_cat_select($link, $id, $default_id = "",
2004 $attributes = "", $include_all_cats = true) {
2006 print "<select id=\"$id\" name=\"$id\" $attributes>";
2008 if ($include_all_cats) {
2009 print "<option value=\"0\">".__('Uncategorized')."</option>";
2012 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2013 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2015 if (db_num_rows($result) > 0 && $include_all_cats) {
2016 print "<option disabled>--------</option>";
2019 while ($line = db_fetch_assoc($result)) {
2020 if ($line["id"] == $default_id) {
2021 $is_selected = "selected";
2025 printf("<option $is_selected value='%d'>%s</option>",
2026 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2032 function checkbox_to_sql_bool($val) {
2033 return ($val == "on") ?
"true" : "false";
2036 function getFeedCatTitle($link, $id) {
2038 return __("Special");
2039 } else if ($id < -10) {
2040 return __("Labels");
2041 } else if ($id > 0) {
2042 $result = db_query($link, "SELECT ttrss_feed_categories.title
2043 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2044 cat_id = ttrss_feed_categories.id");
2045 if (db_num_rows($result) == 1) {
2046 return db_fetch_result($result, 0, "title");
2048 return __("Uncategorized");
2051 return "getFeedCatTitle($id) failed";
2056 function getFeedTitle($link, $id) {
2058 return __("Starred articles");
2059 } else if ($id < -10) {
2060 $label_id = -10 - $id;
2061 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2062 if (db_num_rows($result) == 1) {
2063 return db_fetch_result($result, 0, "description");
2065 return "Unknown label ($label_id)";
2068 } else if ($id > 0) {
2069 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2070 if (db_num_rows($result) == 1) {
2071 return db_fetch_result($result, 0, "title");
2073 return "Unknown feed ($id)";
2076 return "getFeedTitle($id) failed";
2081 function get_session_cookie_name() {
2082 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2085 function print_init_params($link) {
2086 print "<init-params>";
2087 if ($_SESSION["stored-params"]) {
2088 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2090 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2091 print "<param key=\"$key\" value=\"$value\"/>";
2096 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2097 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2098 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY
. "\"/>";
2100 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2101 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2103 print "<param key=\"hide_read_feeds\" value=\"" .
2104 sprintf("%d", get_pref($link, "HIDE_READ_FEEDS")) . "\"/>";
2106 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2107 sprintf("%d", get_pref($link, "FEEDS_SORT_BY_UNREAD")) . "\"/>";
2109 print "<param key=\"confirm_feed_catchup\" value=\"" .
2110 sprintf("%d", get_pref($link, "CONFIRM_FEED_CATCHUP")) . "\"/>";
2112 print "</init-params>";
2115 function print_runtime_info($link) {
2116 print "<runtime-info>";
2117 if (ENABLE_UPDATE_DAEMON
) {
2118 print "<param key=\"daemon_is_running\" value=\"".
2119 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2121 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2123 if ($_SESSION["last_version_check"] +
600 < time()) {
2124 $new_version_details = check_for_update($link);
2126 print "<param key=\"new_version_available\" value=\"".
2127 sprintf("%d", $new_version_details != ""). "\"/>";
2129 $_SESSION["last_version_check"] = time();
2133 print "</runtime-info>";
2136 function getSearchSql($search, $match_on) {
2138 $search_query_part = "";
2140 $keywords = split(" ", $search);
2141 $query_keywords = array();
2143 if ($match_on == "both") {
2145 foreach ($keywords as $k) {
2146 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2147 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2150 $search_query_part = implode("AND", $query_keywords) . " AND ";
2152 } else if ($match_on == "title") {
2154 foreach ($keywords as $k) {
2155 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2158 $search_query_part = implode("AND", $query_keywords) . " AND ";
2160 } else if ($match_on == "content") {
2162 foreach ($keywords as $k) {
2163 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2167 $search_query_part = implode("AND", $query_keywords);
2169 return $search_query_part;
2172 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2176 $search_query_part = getSearchSql($search, $match_on);
2177 $search_query_part .= " AND ";
2180 $search_query_part = "";
2183 $view_query_part = "";
2185 if ($view_mode == "adaptive") {
2187 $view_query_part = " ";
2188 } else if ($feed != -1) {
2189 $unread = getFeedUnread($link, $feed, $cat_view);
2191 $view_query_part = " unread = true AND ";
2196 if ($view_mode == "marked") {
2197 $view_query_part = " marked = true AND ";
2200 if ($view_mode == "unread") {
2201 $view_query_part = " unread = true AND ";
2205 $limit_query_part = "LIMIT " . $limit;
2208 $vfeed_query_part = "";
2210 // override query strategy and enable feed display when searching globally
2211 if ($search && $search_mode == "all_feeds") {
2212 $query_strategy_part = "ttrss_entries.id > 0";
2213 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2214 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2215 $query_strategy_part = "ttrss_entries.id > 0";
2216 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2217 id = feed_id) as feed_title,";
2218 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2220 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2222 $tmp_result = false;
2225 $tmp_result = db_query($link, "SELECT id
2226 FROM ttrss_feeds WHERE cat_id = '$feed'");
2228 $tmp_result = db_query($link, "SELECT id
2229 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2230 WHERE id = '$feed') AND id != '$feed'");
2233 $cat_siblings = array();
2235 if (db_num_rows($tmp_result) > 0) {
2236 while ($p = db_fetch_assoc($tmp_result)) {
2237 array_push($cat_siblings, "feed_id = " . $p["id"]);
2240 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2241 $feed, implode(" OR ", $cat_siblings));
2244 $query_strategy_part = "ttrss_entries.id > 0";
2247 } else if ($feed >= 0) {
2252 $query_strategy_part = "cat_id = '$feed'";
2254 $query_strategy_part = "cat_id IS NULL";
2257 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2260 $tmp_result = db_query($link, "SELECT id
2261 FROM ttrss_feeds WHERE parent_feed = '$feed'
2262 ORDER BY cat_id,title");
2264 $parent_ids = array();
2266 if (db_num_rows($tmp_result) > 0) {
2267 while ($p = db_fetch_assoc($tmp_result)) {
2268 array_push($parent_ids, "feed_id = " . $p["id"]);
2271 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2272 $feed, implode(" OR ", $parent_ids));
2274 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2276 $query_strategy_part = "feed_id = '$feed'";
2279 } else if ($feed == -1) { // starred virtual feed
2280 $query_strategy_part = "marked = true";
2281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2282 } else if ($feed <= -10) { // labels
2283 $label_id = -$feed - 11;
2285 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2286 WHERE id = '$label_id'");
2288 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2290 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2292 $query_strategy_part = "id > 0"; // dumb
2295 if (get_pref($link, 'REVERSE_HEADLINES')) {
2296 $order_by = "updated";
2298 $order_by = "updated DESC";
2301 if ($override_order) {
2302 $order_by = $override_order;
2307 if ($search && $search_mode == "all_feeds") {
2308 $feed_title = __("Global search results")." ($search)";
2309 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2310 $feed_title = __("Tag search results")." ($search, $feed)";
2311 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2312 $feed_title = $feed;
2313 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2318 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2319 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2320 $feed_title = db_fetch_result($result, 0, "title");
2322 $feed_title = __("Uncategorized");
2326 $feed_title = __("Category search results")." ($search, $feed_title)";
2331 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2332 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2334 $feed_title = db_fetch_result($result, 0, "title");
2335 $feed_site_url = db_fetch_result($result, 0, "site_url");
2336 $last_error = db_fetch_result($result, 0, "last_error");
2339 $feed_title = __("Feed search results") . " ($search, $feed_title)";
2343 } else if ($feed == -1) {
2344 $feed_title = __("Starred articles");
2345 } else if ($feed < -10) {
2346 $label_id = -$feed - 11;
2347 $result = db_query($link, "SELECT description FROM ttrss_labels
2348 WHERE id = '$label_id'");
2349 $feed_title = db_fetch_result($result, 0, "description");
2352 $feed_title = __("Label search results") . " ($search, $feed_title)";
2358 $feed_title = db_unescape_string($feed_title);
2360 if ($feed < -10) error_reporting (0);
2362 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2365 $feed_kind = "Feeds";
2367 $feed_kind = "Labels";
2370 $content_query_part = "content as content_preview,";
2372 if ($limit_query_part) {
2373 $offset_query_part = "OFFSET $offset";
2378 ttrss_entries.id,ttrss_entries.title,
2379 SUBSTRING(updated,1,16) as updated,
2380 unread,feed_id,marked,link,last_read,
2381 SUBSTRING(last_read,1,19) as last_read_noms,
2384 SUBSTRING(updated,1,19) as updated_noms,
2387 ttrss_entries,ttrss_user_entries,ttrss_feeds
2389 ttrss_feeds.hidden = false AND
2390 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2391 ttrss_user_entries.ref_id = ttrss_entries.id AND
2392 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2395 $query_strategy_part ORDER BY $order_by
2396 $limit_query_part $offset_query_part";
2398 $result = db_query($link, $query);
2400 if ($_GET["debug"]) print $query;
2405 $feed_kind = "Tags";
2407 $result = db_query($link, "SELECT
2409 ttrss_entries.id as id,title,
2410 SUBSTRING(updated,1,16) as updated,
2412 marked,link,last_read,
2413 SUBSTRING(last_read,1,19) as last_read_noms,
2416 SUBSTRING(updated,1,19) as updated_noms
2418 ttrss_entries,ttrss_user_entries,ttrss_tags
2420 ref_id = ttrss_entries.id AND
2421 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2422 post_int_id = int_id AND tag_name = '$feed' AND
2425 $query_strategy_part ORDER BY $order_by
2426 $limit_query_part");
2429 return array($result, $feed_title, $feed_site_url, $last_error);
2433 function generate_syndicated_feed($link, $feed, $is_cat,
2434 $search, $search_mode, $match_on) {
2436 $qfh_ret = queryFeedHeadlines($link, $feed,
2437 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2439 $result = $qfh_ret[0];
2440 $feed_title = htmlspecialchars($qfh_ret[1]);
2441 $feed_site_url = $qfh_ret[2];
2442 $last_error = $qfh_ret[3];
2444 print "<rss version=\"2.0\">
2446 <title>$feed_title</title>
2447 <link>$feed_site_url</link>
2448 <generator>Tiny Tiny RSS v".VERSION
."</generator>";
2450 while ($line = db_fetch_assoc($result)) {
2452 print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2453 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2455 $rfc822_date = date('r', strtotime($line["updated"]));
2457 print "<pubDate>$rfc822_date</pubDate>";
2460 htmlspecialchars($line["title"]) . "</title>";
2462 print "<description>" .
2463 htmlspecialchars($line["content_preview"]) . "</description>";
2468 print "</channel></rss>";
2472 function getCategoryTitle($link, $cat_id) {
2474 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2477 if (db_num_rows($result) == 1) {
2478 return db_fetch_result($result, 0, "title");
2480 return "Uncategorized";
2484 function sanitize_rss($str) {
2487 $res = preg_replace('/<script.*?>/i',
2488 "<p class=\"scriptWarn\">Disabled script: ", $res);
2490 $res = preg_replace('/<\/script.*?>/i', "</p>", $res);
2492 /* $res = preg_replace('/<embed.*?>/i', "", $res);
2494 $res = preg_replace('/<object.*?>.*?<\/object>/i',
2495 "<p class=\"objectWarn\">(Disabled html object
2496 - flash or other embedded content)</p>", $res); */
2501 function send_headlines_digests($link, $limit = 100) {
2503 if (!DIGEST_ENABLE
) return false;
2505 $user_limit = DIGEST_EMAIL_LIMIT
;
2508 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2510 if (DB_TYPE
== "pgsql") {
2511 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2512 } else if (DB_TYPE
== "mysql") {
2513 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2516 $result = db_query($link, "SELECT id,email FROM ttrss_users
2517 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2519 while ($line = db_fetch_assoc($result)) {
2520 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2521 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2523 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2524 $digest = $tuple[0];
2525 $headlines_count = $tuple[1];
2527 if ($headlines_count > 0) {
2528 $rc = mail($line["login"] . " <" . $line["email"] . ">",
2529 "[tt-rss] New headlines for last 24 hours", $digest,
2530 "From: " . MAIL_FROM
. "\n".
2531 "Content-Type: text/plain; charset=\"utf-8\"\n".
2532 "Content-Transfer-Encoding: 8bit\n");
2534 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2535 WHERE id = " . $line["id"]);
2537 print "No headlines\n";
2542 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2546 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2547 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
2548 $tmp .= "=======================================================\n\n";
2550 if (DB_TYPE
== "pgsql") {
2551 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2552 } else if (DB_TYPE
== "mysql") {
2553 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2556 $result = db_query($link, "SELECT ttrss_entries.title,
2557 ttrss_feeds.title AS feed_title,
2560 SUBSTRING(last_updated,1,19) AS last_updated
2562 ttrss_user_entries,ttrss_entries,ttrss_feeds
2564 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2565 AND include_in_digest = true
2567 AND ttrss_user_entries.owner_uid = $user_id
2568 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2571 $cur_feed_title = "";
2573 $headlines_count = db_num_rows($result);
2575 while ($line = db_fetch_assoc($result)) {
2576 $updated = smart_date_time(strtotime($line["last_updated"]));
2577 $feed_title = $line["feed_title"];
2579 if ($cur_feed_title != $feed_title) {
2580 $cur_feed_title = $feed_title;
2582 $tmp .= "$feed_title\n\n";
2585 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2586 $tmp .= " " . trim($line["link"]) . "\n";
2591 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
2592 DIGEST_HOSTNAME
. "\n".
2593 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2596 return array($tmp, $headlines_count);
2599 function check_for_update($link, $brief_fmt = true) {
2600 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2602 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
2607 $rss = fetch_rss($releases_feed);
2608 error_reporting (DEFAULT_ERROR_LEVEL
);
2612 $items = $rss->items
;
2614 if (!$items ||
!is_array($items)) $items = $rss->entries
;
2615 if (!$items ||
!is_array($items)) $items = $rss;
2617 if (!is_array($items) ||
count($items) == 0) {
2621 $latest_item = $items[0];
2623 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2625 $release_url = sanitize_rss($latest_item["link"]);
2626 $content = sanitize_rss($latest_item["description"]);
2628 if (version_compare(VERSION
, $latest_version) == -1) {
2630 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
2631 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2632 <div id=\"milestoneDetails\">$content</div>");
2634 return "New version of Tiny-Tiny RSS ($latest_version) is available:
2635 <div class='milestoneDetails'>$content</div>
2636 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2637 download and update information.";
2644 function markArticlesById($link, $ids, $cmode) {
2648 foreach ($ids as $id) {
2649 array_push($tmp_ids, "ref_id = '$id'");
2652 $ids_qpart = join(" OR ", $tmp_ids);
2655 db_query($link, "UPDATE ttrss_user_entries SET
2656 marked = false,last_read = NOW()
2657 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2658 } else if ($cmode == 1) {
2659 db_query($link, "UPDATE ttrss_user_entries SET
2661 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2663 db_query($link, "UPDATE ttrss_user_entries SET
2664 marked = NOT marked,last_read = NOW()
2665 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2669 function catchupArticlesById($link, $ids, $cmode) {
2673 foreach ($ids as $id) {
2674 array_push($tmp_ids, "ref_id = '$id'");
2677 $ids_qpart = join(" OR ", $tmp_ids);
2680 db_query($link, "UPDATE ttrss_user_entries SET
2681 unread = false,last_read = NOW()
2682 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2683 } else if ($cmode == 1) {
2684 db_query($link, "UPDATE ttrss_user_entries SET
2686 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2688 db_query($link, "UPDATE ttrss_user_entries SET
2689 unread = NOT unread,last_read = NOW()
2690 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2694 function escape_for_form($s) {
2695 return htmlspecialchars(db_unescape_string($s));
2698 function make_guid_from_title($title) {
2699 return preg_replace("/[ \"\',.:;]/", "-",
2700 mb_strtolower(strip_tags($title)));
2703 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
2704 $bottom = false, $rtl_content = false, $feed_id = 0,
2705 $is_cat = false, $search = false, $match_on = false,
2706 $search_mode = false, $offset = 0, $limit = 0) {
2708 $user_page_offset = $offset +
1;
2711 $class = "headlinesSubToolbar";
2712 $tid = "headlineActionsTop";
2714 $class = "headlinesSubToolbar";
2715 $tid = "headlineActionsBottom";
2718 print "<table class=\"$class\" id=\"$tid\"
2719 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2727 $page_prev_link = "javascript:viewFeedGoPage(-1)";
2728 $page_next_link = "javascript:viewFeedGoPage(1)";
2729 $page_first_link = "javascript:viewFeedGoPage(0)";
2731 $catchup_page_link = "javascript:catchupPage()";
2732 $catchup_feed_link = "javascript:catchupCurrentFeed()";
2734 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2736 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2737 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2738 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2740 $tog_unread_link = "javascript:selectionToggleUnread()";
2741 $tog_marked_link = "javascript:selectionToggleMarked()";
2745 $sel_all_link = "javascript:cdmSelectArticles('all')";
2746 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2747 $sel_none_link = "javascript:cdmSelectArticles('none')";
2749 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2750 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2754 if (!strstr($_SESSION["client.userAgent"], "MSIE")) {
2756 print "<td class=\"headlineActions$rtl_cpart\">
2757 <ul class=\"headlineDropdownMenu\">
2760 <a href=\"$sel_all_link\">".__('All')."</a>,
2761 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2762 <a href=\"$sel_none_link\">".__('None')."</a></li>
2763 <li class=\"vsep\"> </li>
2764 <li class=\"top\">Selection<ul>
2765 <li onclick=\"$tog_unread_link\">".__('Toggle unread')."</li>
2766 <li onclick=\"$tog_marked_link\">".__('Toggle starred')."</li></ul></li>
2767 <li class=\"vsep\"> </li>
2768 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
2769 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
2770 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
2771 <li class=\"vsep\"> </li>";
2775 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
2776 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
2777 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
2785 // old style subtoolbar:
2787 print "<td class=\"headlineActions$rtl_cpart\">".
2789 <a href=\"$sel_all_link\">".__('All')."</a>,
2790 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2791 <a href=\"$sel_none_link\">".__('None')."</a>
2793 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
2794 <a href=\"$tog_marked_link\">".__('Starred')."</a>
2796 __('Mark as read:')."
2797 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
2798 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
2803 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
2804 print "<td class=\"headlineActions$rtl_cpart\">
2805 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2806 '$match_on', '$feed_id', '$is_cat');\">
2807 ".__('Convert to Label')."</a></td>";
2810 print "<td class=\"headlineTitle$rtl_cpart\">";
2812 if ($feed_site_url) {
2814 $target = "target=\"_blank\"";
2816 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
2822 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
2825 if ($user_page_offset > 1) {
2826 print " [$user_page_offset] ";
2832 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
2833 <img class=\"noborder\"
2834 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
2839 print "</tr></table>";
2843 function outputFeedList($link, $tags = false) {
2845 print "<ul class=\"feedList\" id=\"feedList\">\n";
2847 $owner_uid = $_SESSION["uid"];
2851 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2852 print "<li class=\"feedCat\">".__('Special')."</li>";
2853 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2856 $num_starred = getFeedUnread($link, -1);
2860 if ($num_starred > 0) $class .= "Unread";
2862 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
2863 "images/mark_set.png", $link);
2865 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2871 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
2873 $result = db_query($link, "SELECT id,sql_exp,description FROM
2874 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
2876 if (db_num_rows($result) > 0) {
2877 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2878 print "<li class=\"feedCat\">".__('Labels')."</li>";
2879 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2881 print "<li><hr></li>";
2885 while ($line = db_fetch_assoc($result)) {
2887 error_reporting (0);
2889 $label_id = -$line['id'] - 11;
2890 $count = getFeedUnread($link, $label_id);
2898 error_reporting (DEFAULT_ERROR_LEVEL
);
2900 printFeedEntry($label_id,
2901 $class, db_unescape_string($line["description"]),
2902 $count, "images/label.png", $link);
2906 if (db_num_rows($result) > 0) {
2907 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2914 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
2915 print "<li><hr></li>";
2918 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2919 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
2920 $order_by_qpart = "category,unread DESC,title";
2922 $order_by_qpart = "category,title";
2925 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
2926 $order_by_qpart = "unread DESC,title";
2928 $order_by_qpart = "title";
2932 $result = db_query($link, "SELECT ttrss_feeds.*,
2933 SUBSTRING(last_updated,1,19) AS last_updated_noms,
2934 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
2935 WHERE feed_id = ttrss_feeds.id AND unread = true
2936 AND ttrss_user_entries.ref_id = ttrss_entries.id
2937 AND owner_uid = '$owner_uid') as unread,
2939 ttrss_feed_categories.title AS category,
2940 ttrss_feed_categories.collapsed
2941 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
2942 ON (ttrss_feed_categories.id = cat_id)
2944 ttrss_feeds.hidden = false AND
2945 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
2946 ORDER BY $order_by_qpart");
2948 $actid = $_GET["actid"];
2958 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2960 while ($line = db_fetch_assoc($result)) {
2962 $feed = db_unescape_string($line["title"]);
2963 $feed_id = $line["id"];
2965 $subop = $_GET["subop"];
2967 $unread = $line["unread"];
2969 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2970 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
2972 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
2975 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
2978 $rtl_tag = "dir=\"RTL\"";
2983 $tmp_result = db_query($link,
2984 "SELECT id,COUNT(unread) AS unread
2985 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2986 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2987 WHERE parent_feed = '$feed_id' AND unread = true
2988 GROUP BY ttrss_feeds.id");
2990 if (db_num_rows($tmp_result) > 0) {
2991 while ($l = db_fetch_assoc($tmp_result)) {
2992 $unread +
= $l["unread"];
2996 $cat_id = $line["cat_id"];
2998 $tmp_category = $line["category"];
3000 if (!$tmp_category) {
3001 $tmp_category = __("Uncategorized");
3004 // $class = ($lnum % 2) ? "even" : "odd";
3006 if ($line["last_error"]) {
3012 if ($unread > 0) $class .= "Unread";
3014 if ($actid == $feed_id) {
3015 $class .= "Selected";
3018 $total_unread +
= $unread;
3020 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3026 $category = $tmp_category;
3028 $collapsed = $line["collapsed"];
3030 // workaround for NULL category
3031 if ($category == __("Uncategorized")) {
3032 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3037 if ($collapsed == "t" ||
$collapsed == "1") {
3038 $holder_class = "invisible";
3045 $cat_id = sprintf("%d", $cat_id);
3047 $cat_unread = getCategoryUnread($link, $cat_id);
3049 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3051 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3052 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3053 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3054 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3055 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3058 // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3059 // -> keyboard navigation, etc.
3060 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3063 printFeedEntry($feed_id, $class, $feed, $unread,
3064 "icons/$feed_id.ico", $link, $rtl_content,
3065 $last_updated, $line["last_error"]);
3070 if (db_num_rows($result) == 0) {
3071 print "<li>".__('No feeds to display.')."</li>";
3078 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3079 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3080 post_int_id = ttrss_user_entries.int_id AND
3081 unread = true AND ref_id = ttrss_entries.id
3082 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3084 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3085 ORDER BY tag_name"); */
3087 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3088 print "<li class=\"feedCat\">".__('Tags')."</li>";
3089 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3092 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3093 FROM ttrss_user_entries WHERE int_id = post_int_id
3094 AND unread = true)) AS count FROM ttrss_tags
3095 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3099 while ($line = db_fetch_assoc($result)) {
3100 $tags[$line["tag_name"]] +
= $line["count"];
3103 foreach (array_keys($tags) as $tag) {
3105 $unread = $tags[$tag];
3113 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3117 if (db_num_rows($result) == 0) {
3118 print "<li>No tags to display.</li>";
3121 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3131 function get_article_tags($link, $id) {
3133 $a_id = db_escape_string($id);
3135 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3136 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3137 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3141 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3142 array_push($tags, $tmp_line["tag_name"]);
3148 function trim_value(&$value) {
3149 $value = trim($value);
3152 function trim_array($array) {
3154 array_walk($tmp, 'trim_value');
3158 function tag_is_valid($tag) {
3159 if ($tag == '') return false;
3160 if (preg_match("/^[0-9]*$/", $tag)) return false;
3162 $tag = iconv("utf-8", "utf-8", $tag);
3163 if (!$tag) return false;
3168 function render_login_form($link) {
3169 require_once "login_form.php";
3172 // from http://developer.apple.com/internet/safari/faq.html
3173 function no_cache_incantation() {
3174 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3175 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3176 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3177 header("Cache-Control: post-check=0, pre-check=0", false);
3178 header("Pragma: no-cache"); // HTTP/1.0
3181 function format_warning($msg, $id = "") {
3182 return "<div class=\"warning\" id=\"$id\">
3183 <img src=\"images/sign_excl.png\">$msg</div>";
3186 function format_notice($msg) {
3187 return "<div class=\"notice\">
3188 <img src=\"images/sign_info.png\">$msg</div>";
3191 function startup_gettext() {
3193 # Get locale from Accept-Language header
3194 $lang = al2gt(array("en_US", "ru_RU"), "text/html");
3197 _setlocale(LC_MESSAGES
, $lang);
3198 _bindtextdomain("messages", "locale");
3199 _textdomain("messages");
3200 _bind_textdomain_codeset("messages", "UTF-8");