]>
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 'config.php';
10 require_once 'db-prefs.php';
11 require_once 'compat.php';
12 require_once 'errors.php';
13 require_once 'version.php';
15 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
16 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
18 require_once "magpierss/rss_fetch.inc";
19 require_once 'magpierss/rss_utils.inc';
21 require_once "accept-to-gettext.php";
22 require_once "gettext/gettext.inc";
24 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
28 if (DB_TYPE
== "pgsql") {
29 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
30 marked = false AND feed_id = '$feed_id' AND
31 (SELECT date_entered FROM ttrss_entries WHERE
32 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
34 $pg_version = get_pgsql_version($link);
36 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
38 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
39 ttrss_entries.id = ref_id AND
41 feed_id = '$feed_id' AND
42 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
46 $result = db_query($link, "DELETE FROM ttrss_user_entries
48 WHERE ttrss_entries.id = ref_id AND
50 feed_id = '$feed_id' AND
51 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
54 $rows = pg_affected_rows($result);
58 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
59 marked = false AND feed_id = '$feed_id' AND
60 (SELECT date_entered FROM ttrss_entries WHERE
61 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
63 $result = db_query($link, "DELETE FROM ttrss_user_entries
64 USING ttrss_user_entries, ttrss_entries
65 WHERE ttrss_entries.id = ref_id AND
67 feed_id = '$feed_id' AND
68 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
70 $rows = mysql_affected_rows($link);
75 print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
79 function global_purge_old_posts($link, $do_output = false, $limit = false) {
81 $random_qpart = sql_random_function();
84 $limit_qpart = "LIMIT $limit";
89 $result = db_query($link,
90 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
91 ORDER BY $random_qpart $limit_qpart");
93 while ($line = db_fetch_assoc($result)) {
95 $feed_id = $line["id"];
96 $purge_interval = $line["purge_interval"];
97 $owner_uid = $line["owner_uid"];
99 if ($purge_interval == 0) {
101 $tmp_result = db_query($link,
102 "SELECT value FROM ttrss_user_prefs WHERE
103 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
105 if (db_num_rows($tmp_result) != 0) {
106 $purge_interval = db_fetch_result($tmp_result, 0, "value");
111 // print "Feed $feed_id: purge interval = $purge_interval\n";
114 if ($purge_interval > 0) {
115 purge_feed($link, $feed_id, $purge_interval, $do_output);
119 // purge orphaned posts in main content table
120 db_query($link, "DELETE FROM ttrss_entries WHERE
121 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
125 function purge_old_posts($link) {
127 $user_id = $_SESSION["uid"];
129 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
130 WHERE owner_uid = '$user_id'");
132 while ($line = db_fetch_assoc($result)) {
134 $feed_id = $line["id"];
135 $purge_interval = $line["purge_interval"];
137 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
139 if ($purge_interval > 0) {
140 purge_feed($link, $feed_id, $purge_interval);
144 // purge orphaned posts in main content table
145 db_query($link, "DELETE FROM ttrss_entries WHERE
146 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
149 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
151 if (WEB_DEMO_MODE
) return;
154 $user_id = $_SESSION["uid"];
155 purge_old_posts($link);
158 // db_query($link, "BEGIN");
160 if (MAX_UPDATE_TIME
> 0) {
161 if (DB_TYPE
== "mysql") {
164 $q_order = "RANDOM()";
167 $q_order = "last_updated DESC";
170 $result = db_query($link, "SELECT feed_url,id,
171 SUBSTRING(last_updated,1,19) AS last_updated,
172 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
177 while ($line = db_fetch_assoc($result)) {
178 $upd_intl = $line["update_interval"];
180 if (!$upd_intl ||
$upd_intl == 0) {
181 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
185 // Updates for this feed are disabled
189 if ($fetch ||
(!$line["last_updated"] ||
190 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
192 // print "<!-- feed: ".$line["feed_url"]." -->";
194 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
196 $upd_elapsed = time() - $upd_start;
198 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
204 // db_query($link, "COMMIT");
208 function fetch_file_contents($url) {
209 if (USE_CURL_FOR_ICONS
) {
210 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
212 $ch = curl_init($url);
213 $fp = fopen($tmpfile, "w");
216 curl_setopt($ch, CURLOPT_FILE
, $fp);
222 $contents = file_get_contents($tmpfile);
228 return file_get_contents($url);
233 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
234 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
236 function get_favicon_url($url) {
238 if ($html = @fetch_file_contents
($url)) {
240 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
241 // Attempt to grab a favicon link from their webpage url
242 $linkUrl = html_entity_decode($matches[1]);
244 if (substr($linkUrl, 0, 1) == '/') {
245 $urlParts = parse_url($url);
246 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
247 } else if (substr($linkUrl, 0, 7) == 'http://') {
248 $faviconURL = $linkUrl;
249 } else if (substr($url, -1, 1) == '/') {
250 $faviconURL = $url.$linkUrl;
252 $faviconURL = $url.'/'.$linkUrl;
256 // If unsuccessful, attempt to "guess" the favicon location
257 $urlParts = parse_url($url);
258 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
262 // Run a test to see if what we have attempted to get actually exists.
263 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
270 function url_validate($link) {
272 $url_parts = @parse_url
($link);
274 if ( empty( $url_parts["host"] ) )
277 if ( !empty( $url_parts["path"] ) ) {
278 $documentpath = $url_parts["path"];
283 if ( !empty( $url_parts["query"] ) )
284 $documentpath .= "?" . $url_parts["query"];
286 $host = $url_parts["host"];
287 $port = $url_parts["port"];
292 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
297 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
299 $http_response = fgets( $socket, 22 );
301 $responses = "/(200 OK)|(30[0-9] Moved)/";
302 if ( preg_match($responses, $http_response) ) {
311 function check_feed_favicon($site_url, $feed, $link) {
312 $favicon_url = get_favicon_url($site_url);
314 # print "FAVICON [$site_url]: $favicon_url\n";
318 $icon_file = ICONS_DIR
. "/$feed.ico";
320 if ($favicon_url && !file_exists($icon_file)) {
321 $contents = fetch_file_contents($favicon_url);
323 $fp = fopen($icon_file, "w");
326 fwrite($fp, $contents);
328 chmod($icon_file, 0644);
332 error_reporting(DEFAULT_ERROR_LEVEL
);
336 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
338 if (DAEMON_REFRESH_ONLY
&& !$_GET["daemon"] && !$ignore_daemon) {
342 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass
343 FROM ttrss_feeds WHERE id = '$feed'");
345 $auth_login = db_unescape_string(db_fetch_result($result, 0, "auth_login"));
346 $auth_pass = db_unescape_string(db_fetch_result($result, 0, "auth_pass"));
348 $update_interval = db_fetch_result($result, 0, "update_interval");
350 if ($update_interval < 0) { return; }
352 $feed = db_escape_string($feed);
354 $fetch_url = $feed_url;
356 if ($auth_login && $auth_pass) {
357 $url_parts = array();
358 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
360 if ($url_parts[1] && $url_parts[2]) {
361 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
367 $rss = fetch_rss($fetch_url);
368 error_reporting (DEFAULT_ERROR_LEVEL
);
370 $feed = db_escape_string($feed);
374 // db_query($link, "BEGIN");
376 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
377 FROM ttrss_feeds WHERE id = '$feed'");
379 $registered_title = db_fetch_result($result, 0, "title");
380 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
381 $orig_site_url = db_fetch_result($result, 0, "site_url");
383 $owner_uid = db_fetch_result($result, 0, "owner_uid");
385 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
386 check_feed_favicon($rss->channel
["link"], $feed, $link);
389 if (!$registered_title ||
$registered_title == "[Unknown]") {
391 $feed_title = db_escape_string($rss->channel
["title"]);
393 db_query($link, "UPDATE ttrss_feeds SET
394 title = '$feed_title' WHERE id = '$feed'");
397 $site_url = $rss->channel
["link"];
398 // weird, weird Magpie
399 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
401 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
402 db_query($link, "UPDATE ttrss_feeds SET
403 site_url = '$site_url' WHERE id = '$feed'");
406 // print "I: " . $rss->channel["image"]["url"];
408 $icon_url = $rss->image
["url"];
410 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
411 $icon_url = db_escape_string($icon_url);
412 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
418 $result = db_query($link, "SELECT reg_exp,
419 ttrss_filter_types.name AS name,
420 ttrss_filter_actions.name AS action,
423 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
425 owner_uid = $owner_uid AND
426 ttrss_filter_types.id = filter_type AND
427 ttrss_filter_actions.id = action_id AND
428 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
430 while ($line = db_fetch_assoc($result)) {
431 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
433 $filter["reg_exp"] = $line["reg_exp"];
434 $filter["action"] = $line["action"];
435 $filter["action_param"] = $line["action_param"];
436 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
438 array_push($filters[$line["name"]], $filter);
441 $iterator = $rss->items
;
443 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
444 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
446 if (!is_array($iterator)) {
447 /* db_query($link, "UPDATE ttrss_feeds
448 SET last_error = 'Parse error: can\'t find any articles.'
449 WHERE id = '$feed'"); */
453 foreach ($iterator as $item) {
455 $entry_guid = $item["id"];
457 if (!$entry_guid) $entry_guid = $item["guid"];
458 if (!$entry_guid) $entry_guid = $item["link"];
459 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
461 if (!$entry_guid) continue;
463 $entry_timestamp = "";
465 $rss_2_date = $item['pubdate'];
466 $rss_1_date = $item['dc']['date'];
467 $atom_date = $item['issued'];
468 if (!$atom_date) $atom_date = $item['updated'];
470 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
471 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
472 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
474 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
475 $entry_timestamp = time();
476 $no_orig_date = 'true';
478 $no_orig_date = 'false';
481 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
483 $entry_title = trim(strip_tags($item["title"]));
485 // strange Magpie workaround
486 $entry_link = $item["link_"];
487 if (!$entry_link) $entry_link = $item["link"];
489 if (!$entry_title) continue;
490 # if (!$entry_link) continue;
492 $entry_link = strip_tags($entry_link);
494 $entry_content = $item["content:escaped"];
496 if (!$entry_content) $entry_content = $item["content:encoded"];
497 if (!$entry_content) $entry_content = $item["content"];
498 if (!$entry_content) $entry_content = $item["atom_content"];
499 if (!$entry_content) $entry_content = $item["summary"];
500 if (!$entry_content) $entry_content = $item["description"];
502 // if (!$entry_content) continue;
505 if (is_array($entry_content)) {
506 $entry_content = $entry_content["encoded"];
507 if (!$entry_content) $entry_content = $entry_content["escaped"];
511 // print_r(htmlspecialchars($entry_content));
514 $entry_content_unescaped = $entry_content;
515 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
517 $entry_comments = strip_tags($item["comments"]);
519 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
521 if ($item['author']) {
523 if (is_array($item['author'])) {
525 if (!$entry_author) {
526 $entry_author = db_escape_string(strip_tags($item['author']['name']));
529 if (!$entry_author) {
530 $entry_author = db_escape_string(strip_tags($item['author']['email']));
534 if (!$entry_author) {
535 $entry_author = db_escape_string(strip_tags($item['author']));
539 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
541 $entry_guid = db_escape_string(strip_tags($entry_guid));
543 $result = db_query($link, "SELECT id FROM ttrss_entries
544 WHERE guid = '$entry_guid'");
546 $entry_content = db_escape_string($entry_content);
547 $entry_title = db_escape_string($entry_title);
548 $entry_link = db_escape_string($entry_link);
549 $entry_comments = db_escape_string($entry_comments);
551 $num_comments = db_escape_string($item["slash"]["comments"]);
553 if (!$num_comments) $num_comments = 0;
555 /* $dc_subject = $item['dc']['subject'];
557 $subject_tags = false;
559 if (is_array($dc_subject)) {
560 $subject_tags = $dc_subject;
561 } else if ($dc_subject) {
562 $subject_tags = array($dc_subject);
567 $entry_content = sanitize_rss($entry_content);
569 db_query($link, "BEGIN");
571 if (db_num_rows($result) == 0) {
573 // base post entry does not exist, create it
575 $result = db_query($link,
576 "INSERT INTO ttrss_entries
592 '$entry_timestamp_fmt',
601 // we keep encountering the entry in feeds, so we need to
602 // update date_entered column so that we don't get horrible
603 // dupes when the entry gets purged and reinserted again e.g.
604 // in the case of SLOW SLOW OMG SLOW updating feeds
606 $base_entry_id = db_fetch_result($result, 0, "id");
608 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
609 WHERE id = '$base_entry_id'");
612 // now it should exist, if not - bad luck then
614 $result = db_query($link, "SELECT
615 id,content_hash,no_orig_date,title,
616 substring(date_entered,1,19) as date_entered,
617 substring(updated,1,19) as updated,
621 WHERE guid = '$entry_guid'");
623 if (db_num_rows($result) == 1) {
625 // this will be used below in update handler
626 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
627 $orig_title = db_fetch_result($result, 0, "title");
628 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
629 $orig_date_entered = strtotime(db_fetch_result($result,
632 $ref_id = db_fetch_result($result, 0, "id");
634 // check for user post link to main table
636 // do we allow duplicate posts with same GUID in different feeds?
637 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
638 $dupcheck_qpart = "AND feed_id = '$feed'";
640 $dupcheck_qpart = "";
643 // error_reporting(0);
645 $article_filters = get_article_filters($filters, $entry_title,
646 $entry_content, $entry_link);
648 if (find_article_filter($article_filters, "filter")) {
652 // error_reporting (DEFAULT_ERROR_LEVEL);
654 $result = db_query($link,
655 "SELECT ref_id FROM ttrss_user_entries WHERE
656 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
659 // okay it doesn't exist - create user entry
660 if (db_num_rows($result) == 0) {
662 if (!find_article_filter($article_filters, 'catchup')) {
664 $last_read_qpart = 'NULL';
667 $last_read_qpart = 'NOW()';
670 if (find_article_filter($article_filters, 'mark')) {
676 $result = db_query($link,
677 "INSERT INTO ttrss_user_entries
678 (ref_id, owner_uid, feed_id, unread, last_read, marked)
679 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
680 $last_read_qpart, $marked)");
683 $post_needs_update = false;
685 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
686 ($content_hash != $orig_content_hash)) {
687 $post_needs_update = true;
690 if ($orig_title != $entry_title) {
691 $post_needs_update = true;
694 if ($orig_num_comments != $num_comments) {
695 $post_needs_update = true;
698 // this doesn't seem to be very reliable
700 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
701 // $post_needs_update = true;
704 // if post needs update, update it and mark all user entries
705 // linking to this post as updated
706 if ($post_needs_update) {
708 // print "<!-- post $orig_title needs update : $post_needs_update -->";
710 db_query($link, "UPDATE ttrss_entries
711 SET title = '$entry_title', content = '$entry_content',
712 num_comments = '$num_comments'
713 WHERE id = '$ref_id'");
715 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
716 db_query($link, "UPDATE ttrss_user_entries
717 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
719 db_query($link, "UPDATE ttrss_user_entries
720 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
726 db_query($link, "COMMIT");
729 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
733 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i",
734 $entry_content_unescaped, $entry_tags);
736 // print "<br>$entry_title : $entry_content_unescaped<br>";
737 // print_r($entry_tags);
740 $entry_tags = $entry_tags[1];
742 # check for manual tags
744 $tag_filter = find_article_filter($article_filters, "tag");
748 $manual_tags = trim_array(split(",", $tag_filter[1]));
750 foreach ($manual_tags as $tag) {
751 if (tag_is_valid($tag)) {
752 array_push($entry_tags, $tag);
757 /* if ($subject_tags) {
758 foreach ($subject_tags as $tag) {
759 if (tag_is_valid($tag)) {
760 array_push($entry_tags, $tag);
765 if (count($entry_tags) > 0) {
767 db_query($link, "BEGIN");
769 $result = db_query($link, "SELECT id,int_id
770 FROM ttrss_entries,ttrss_user_entries
771 WHERE guid = '$entry_guid'
772 AND feed_id = '$feed' AND ref_id = id
773 AND owner_uid = '$owner_uid'");
775 if (db_num_rows($result) == 1) {
777 $entry_id = db_fetch_result($result, 0, "id");
778 $entry_int_id = db_fetch_result($result, 0, "int_id");
780 foreach ($entry_tags as $tag) {
781 $tag = db_escape_string(mb_strtolower(strip_tags($tag)));
783 $tag = str_replace("+", " ", $tag);
784 $tag = str_replace("technorati tag: ", "", $tag);
786 if (!tag_is_valid($tag)) continue;
788 $result = db_query($link, "SELECT id FROM ttrss_tags
789 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
790 owner_uid = '$owner_uid' LIMIT 1");
792 // print db_fetch_result($result, 0, "id");
794 if ($result && db_num_rows($result) == 0) {
796 // print "tagging $entry_id as $tag<br>";
798 db_query($link, "INSERT INTO ttrss_tags
799 (owner_uid,tag_name,post_int_id)
800 VALUES ('$owner_uid','$tag', '$entry_int_id')");
804 db_query($link, "COMMIT");
808 db_query($link, "UPDATE ttrss_feeds
809 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
811 // db_query($link, "COMMIT");
814 $error_msg = db_escape_string(magpie_error());
816 "UPDATE ttrss_feeds SET last_error = '$error_msg',
817 last_updated = NOW() WHERE id = '$feed'");
822 function print_select($id, $default, $values, $attributes = "") {
823 print "<select name=\"$id\" id=\"$id\" $attributes>";
824 foreach ($values as $v) {
830 print "<option$sel>$v</option>";
835 function print_select_hash($id, $default, $values, $attributes = "") {
836 print "<select name=\"$id\" id='$id' $attributes>";
837 foreach (array_keys($values) as $v) {
843 print "<option $sel value=\"$v\">".$values[$v]."</option>";
849 function get_article_filters($filters, $title, $content, $link) {
852 if ($filters["title"]) {
853 foreach ($filters["title"] as $filter) {
854 $reg_exp = $filter["reg_exp"];
855 $inverse = $filter["inverse"];
856 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
857 ($inverse && !preg_match("/$reg_exp/i", $title))) {
859 array_push($matches, array($filter["action"], $filter["action_param"]));
864 if ($filters["content"]) {
865 foreach ($filters["content"] as $filter) {
866 $reg_exp = $filter["reg_exp"];
867 $inverse = $filter["inverse"];
869 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
870 ($inverse && !preg_match("/$reg_exp/i", $content))) {
872 array_push($matches, array($filter["action"], $filter["action_param"]));
877 if ($filters["both"]) {
878 foreach ($filters["both"] as $filter) {
879 $reg_exp = $filter["reg_exp"];
880 $inverse = $filter["inverse"];
883 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
884 array_push($matches, array($filter["action"], $filter["action_param"]));
887 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
888 array_push($matches, array($filter["action"], $filter["action_param"]));
894 if ($filters["link"]) {
895 $reg_exp = $filter["reg_exp"];
896 foreach ($filters["link"] as $filter) {
897 $reg_exp = $filter["reg_exp"];
898 $inverse = $filter["inverse"];
900 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
901 ($inverse && !preg_match("/$reg_exp/i", $link))) {
903 array_push($matches, array($filter["action"], $filter["action_param"]));
911 function find_article_filter($filters, $filter_name) {
912 foreach ($filters as $f) {
913 if ($f[0] == $filter_name) {
920 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
921 $rtl_content = false, $last_updated = false, $last_error = false) {
923 if (file_exists($icon_file) && filesize($icon_file) > 0) {
924 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
926 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
930 $rtl_tag = "dir=\"rtl\"";
932 $rtl_tag = "dir=\"ltr\"";
935 $error_notify_msg = "";
938 $link_title = "Error: $last_error ($last_updated)";
939 $error_notify_msg = "(Error)";
940 } else if ($last_updated) {
941 $link_title = "Updated: $last_updated";
944 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
945 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
947 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
948 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
952 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
957 $fctr_class = "class=\"invisible\"";
960 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
961 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
963 if (get_pref($link, "EXTENDED_FEEDLIST")) {
964 print "<div class=\"feedExtInfo\">
965 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
972 function getmicrotime() {
973 list($usec, $sec) = explode(" ",microtime());
974 return ((float)$usec +
(float)$sec);
977 function print_radio($id, $default, $values, $attributes = "") {
978 foreach ($values as $v) {
986 $sel .= " value=\"1\"";
988 $sel .= " value=\"0\"";
991 print "<input class=\"noborder\"
992 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
997 function initialize_user_prefs($link, $uid) {
999 $uid = db_escape_string($uid);
1001 db_query($link, "BEGIN");
1003 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1005 $u_result = db_query($link, "SELECT pref_name
1006 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1008 $active_prefs = array();
1010 while ($line = db_fetch_assoc($u_result)) {
1011 array_push($active_prefs, $line["pref_name"]);
1014 while ($line = db_fetch_assoc($result)) {
1015 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1016 // print "adding " . $line["pref_name"] . "<br>";
1018 db_query($link, "INSERT INTO ttrss_user_prefs
1019 (owner_uid,pref_name,value) VALUES
1020 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1025 db_query($link, "COMMIT");
1029 function lookup_user_id($link, $user) {
1031 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1034 if (db_num_rows($result) == 1) {
1035 return db_fetch_result($result, 0, "id");
1041 function http_authenticate_user($link) {
1043 if (!$_SERVER["PHP_AUTH_USER"]) {
1045 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1046 header('HTTP/1.0 401 Unauthorized');
1050 $auth_result = authenticate_user($link,
1051 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1053 if (!$auth_result) {
1054 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1055 header('HTTP/1.0 401 Unauthorized');
1063 function authenticate_user($link, $login, $password, $force_auth = false) {
1065 if (!SINGLE_USER_MODE
) {
1067 $pwd_hash = 'SHA1:' . sha1($password);
1069 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1070 $query = "SELECT id,login,access_level
1071 FROM ttrss_users WHERE
1074 $query = "SELECT id,login,access_level
1075 FROM ttrss_users WHERE
1076 login = '$login' AND pwd_hash = '$pwd_hash'";
1079 $result = db_query($link, $query);
1081 if (db_num_rows($result) == 1) {
1082 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1083 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1084 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1086 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1089 $user_theme = get_user_theme_path($link);
1091 $_SESSION["theme"] = $user_theme;
1092 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1094 initialize_user_prefs($link, $_SESSION["uid"]);
1103 $_SESSION["uid"] = 1;
1104 $_SESSION["name"] = "admin";
1106 $user_theme = get_user_theme_path($link);
1108 $_SESSION["theme"] = $user_theme;
1109 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1111 initialize_user_prefs($link, $_SESSION["uid"]);
1117 function make_password($length = 8) {
1120 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1124 while ($i < $length) {
1125 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1127 if (!strstr($password, $char)) {
1135 // this is called after user is created to initialize default feeds, labels
1138 // user preferences are checked on every login, not here
1140 function initialize_user($link, $uid) {
1142 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1143 values ('$uid','unread = true', 'Unread articles')");
1145 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1146 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1148 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1149 values ('$uid', 'Tiny Tiny RSS: New Releases',
1150 'http://tt-rss.spb.ru/releases.rss')");
1152 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1153 values ('$uid', 'Tiny Tiny RSS: Forum',
1154 'http://tt-rss.spb.ru/forum/rss.php')");
1157 function logout_user() {
1159 if (isset($_COOKIE[session_name()])) {
1160 setcookie(session_name(), '', time()-42000, '/');
1164 function get_script_urlpath() {
1165 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1168 function validate_session($link) {
1169 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1170 if ($_SESSION["ip_address"]) {
1171 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1172 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1178 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1180 //print_r($_SESSION);
1182 if (time() > $_SESSION["cookie_lifetime"]) {
1190 function login_sequence($link) {
1191 if (!SINGLE_USER_MODE
) {
1193 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1194 $swu = db_escape_string($_REQUEST["swu"]);
1196 $_SESSION["prefs_cache"] = false;
1197 return authenticate_user($link, $swu, null, true);
1201 $login_action = $_POST["login_action"];
1203 # try to authenticate user if called from login form
1204 if ($login_action == "do_login") {
1205 $login = $_POST["login"];
1206 $password = $_POST["password"];
1207 $remember_me = $_POST["remember_me"];
1209 if (authenticate_user($link, $login, $password)) {
1210 $_POST["password"] = "";
1212 header("Location: " . $_SERVER["REQUEST_URI"]);
1217 $_SESSION["login_error_msg"] = "Incorrect username or password";
1221 // print session_id();
1222 // print_r($_SESSION);
1224 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1225 render_login_form($link);
1231 return authenticate_user($link, "admin", null);
1235 function truncate_string($str, $max_len) {
1236 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1237 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1243 function get_user_theme_path($link) {
1244 $result = db_query($link, "SELECT theme_path
1246 ttrss_themes,ttrss_users
1247 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1248 if (db_num_rows($result) != 0) {
1249 return db_fetch_result($result, 0, "theme_path");
1255 function smart_date_time($timestamp) {
1256 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1257 return date("G:i", $timestamp);
1258 } else if (date("Y", $timestamp) == date("Y")) {
1259 return date("M d, G:i", $timestamp);
1261 return date("Y/m/d G:i", $timestamp);
1265 function smart_date($timestamp) {
1266 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1268 } else if (date("Y", $timestamp) == date("Y")) {
1269 return date("D m", $timestamp);
1271 return date("Y/m/d", $timestamp);
1275 function sql_bool_to_string($s) {
1276 if ($s == "t" ||
$s == "1") {
1283 function sql_bool_to_bool($s) {
1284 if ($s == "t" ||
$s == "1") {
1292 function toggleEvenOdd($a) {
1299 function sanity_check($link) {
1304 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1305 $schema_version = db_fetch_result($result, 0, "schema_version");
1307 if ($schema_version != SCHEMA_VERSION
) {
1311 if (DB_TYPE
== "mysql") {
1312 $result = db_query($link, "SELECT true", false);
1313 if (db_num_rows($result) != 1) {
1318 error_reporting (DEFAULT_ERROR_LEVEL
);
1320 if ($error_code != 0) {
1321 print_error_xml($error_code);
1328 function file_is_locked($filename) {
1330 $fp = fopen($filename, "r");
1331 error_reporting(DEFAULT_ERROR_LEVEL
);
1333 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1334 flock($fp, LOCK_UN
);
1344 function make_lockfile($filename) {
1345 $fp = fopen($filename, "w");
1347 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1354 function sql_random_function() {
1355 if (DB_TYPE
== "mysql") {
1362 function catchup_feed($link, $feed, $cat_view) {
1364 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1369 $cat_qpart = "cat_id = '$feed'";
1371 $cat_qpart = "cat_id IS NULL";
1374 $tmp_result = db_query($link, "SELECT id
1375 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1378 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1380 $tmp_feed = $tmp_line["id"];
1382 db_query($link, "UPDATE ttrss_user_entries
1383 SET unread = false,last_read = NOW()
1384 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1387 } else if ($feed > 0) {
1389 $tmp_result = db_query($link, "SELECT id
1390 FROM ttrss_feeds WHERE parent_feed = '$feed'
1391 ORDER BY cat_id,title");
1393 $parent_ids = array();
1395 if (db_num_rows($tmp_result) > 0) {
1396 while ($p = db_fetch_assoc($tmp_result)) {
1397 array_push($parent_ids, "feed_id = " . $p["id"]);
1400 $children_qpart = implode(" OR ", $parent_ids);
1402 db_query($link, "UPDATE ttrss_user_entries
1403 SET unread = false,last_read = NOW()
1404 WHERE (feed_id = '$feed' OR $children_qpart)
1405 AND owner_uid = " . $_SESSION["uid"]);
1408 db_query($link, "UPDATE ttrss_user_entries
1409 SET unread = false,last_read = NOW()
1410 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1413 } else if ($feed < 0 && $feed > -10) { // special, like starred
1416 db_query($link, "UPDATE ttrss_user_entries
1417 SET unread = false,last_read = NOW()
1418 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1421 } else if ($feed < -10) { // label
1423 // TODO make this more efficient
1425 $label_id = -$feed - 11;
1427 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1428 WHERE id = '$label_id'");
1431 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1433 db_query($link, "BEGIN");
1435 $tmp2_result = db_query($link,
1439 ttrss_user_entries,ttrss_entries,ttrss_feeds
1441 ref_id = ttrss_entries.id AND
1442 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1444 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1446 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1447 db_query($link, "UPDATE
1450 unread = false, last_read = NOW()
1452 int_id = " . $tmp_line["int_id"]);
1455 db_query($link, "COMMIT");
1457 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1458 SET unread = false,last_read = NOW()
1461 AND owner_uid = ".$_SESSION["uid"]); */
1465 db_query($link, "BEGIN");
1467 $tag_name = db_escape_string($feed);
1469 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1470 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1472 while ($line = db_fetch_assoc($result)) {
1473 db_query($link, "UPDATE ttrss_user_entries SET
1474 unread = false, last_read = NOW()
1475 WHERE int_id = " . $line["post_int_id"]);
1477 db_query($link, "COMMIT");
1481 function update_generic_feed($link, $feed, $cat_view) {
1485 $cat_qpart = "cat_id = '$feed'";
1487 $cat_qpart = "cat_id IS NULL";
1490 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1491 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1493 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1494 $feed_url = $tmp_line["feed_url"];
1495 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1499 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1500 WHERE id = '$feed'");
1501 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1502 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1506 function getAllCounters($link, $omode = "tflc") {
1507 /* getLabelCounters($link);
1508 getFeedCounters($link);
1509 getTagCounters($link);
1510 getGlobalCounters($link);
1511 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1512 getCategoryCounters($link);
1515 if (!$omode) $omode = "tflc";
1517 getGlobalCounters($link);
1519 if (strchr($omode, "l")) getLabelCounters($link);
1520 if (strchr($omode, "f")) getFeedCounters($link);
1521 if (strchr($omode, "t")) getTagCounters($link);
1522 if (strchr($omode, "c")) {
1523 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1524 getCategoryCounters($link);
1529 function getCategoryCounters($link) {
1530 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1531 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id
1532 AND unread = true)) AS unread FROM ttrss_feeds
1534 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1536 while ($line = db_fetch_assoc($result)) {
1537 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1538 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1539 $line["unread"]."\"/>";
1543 function getCategoryUnread($link, $cat) {
1546 $cat_query = "cat_id = '$cat'";
1548 $cat_query = "cat_id IS NULL";
1551 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1553 AND owner_uid = " . $_SESSION["uid"]);
1555 $cat_feeds = array();
1556 while ($line = db_fetch_assoc($result)) {
1557 array_push($cat_feeds, "feed_id = " . $line["id"]);
1560 if (count($cat_feeds) == 0) return 0;
1562 $match_part = implode(" OR ", $cat_feeds);
1564 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1565 FROM ttrss_user_entries
1566 WHERE unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1570 # this needs to be rewritten
1571 while ($line = db_fetch_assoc($result)) {
1572 $unread +
= $line["unread"];
1579 function getFeedUnread($link, $feed, $is_cat = false) {
1580 $n_feed = sprintf("%d", $feed);
1583 return getCategoryUnread($link, $n_feed);
1584 } else if ($n_feed == -1) {
1585 $match_part = "marked = true";
1586 } else if ($n_feed > 0) {
1588 $result = db_query($link, "SELECT id FROM ttrss_feeds
1589 WHERE parent_feed = '$n_feed'
1591 AND owner_uid = " . $_SESSION["uid"]);
1593 if (db_num_rows($result) > 0) {
1595 $linked_feeds = array();
1596 while ($line = db_fetch_assoc($result)) {
1597 array_push($linked_feeds, "feed_id = " . $line["id"]);
1600 array_push($linked_feeds, "feed_id = $n_feed");
1602 $match_part = implode(" OR ", $linked_feeds);
1604 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1605 FROM ttrss_user_entries
1606 WHERE unread = true AND ($match_part)
1607 AND owner_uid = " . $_SESSION["uid"]);
1611 # this needs to be rewritten
1612 while ($line = db_fetch_assoc($result)) {
1613 $unread +
= $line["unread"];
1619 $match_part = "feed_id = '$n_feed'";
1621 } else if ($feed < -10) {
1623 $label_id = -$feed - 11;
1625 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1626 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1628 $match_part = db_fetch_result($result, 0, "sql_exp");
1633 $result = db_query($link, "SELECT count(int_id) AS unread
1634 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1635 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1636 ttrss_user_entries.ref_id = ttrss_entries.id AND
1637 ttrss_feeds.hidden = false AND
1638 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1642 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1643 FROM ttrss_tags,ttrss_user_entries
1644 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1645 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1648 $unread = db_fetch_result($result, 0, "unread");
1653 /* FIXME this needs reworking */
1655 function getGlobalUnread($link, $user_id = false) {
1658 $user_id = $_SESSION["uid"];
1661 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1662 WHERE unread = true AND
1663 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1664 ttrss_user_entries.ref_id = ttrss_entries.id AND
1666 ttrss_user_entries.owner_uid = '$user_id'");
1667 $c_id = db_fetch_result($result, 0, "c_id");
1671 function getGlobalCounters($link, $global_unread = -1) {
1672 if ($global_unread == -1) {
1673 $global_unread = getGlobalUnread($link);
1675 print "<counter type=\"global\" id='global-unread'
1676 counter='$global_unread'/>";
1678 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1679 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1681 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1683 print "<counter type=\"global\" id='subscribed-feeds'
1684 counter='$subscribed_feeds'/>";
1688 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1691 if (!$_SESSION["tctr_last_value"]) {
1692 $_SESSION["tctr_last_value"] = array();
1696 $old_counters = $_SESSION["tctr_last_value"];
1698 $tctrs_modified = false;
1700 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1701 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1702 ttrss_user_entries.ref_id = ttrss_entries.id AND
1703 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1704 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
1706 select tag_name,0 as count FROM ttrss_tags
1707 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1709 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1710 FROM ttrss_user_entries WHERE int_id = post_int_id
1711 AND unread = true)) AS count FROM ttrss_tags
1712 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1716 while ($line = db_fetch_assoc($result)) {
1717 $tags[$line["tag_name"]] +
= $line["count"];
1720 foreach (array_keys($tags) as $tag) {
1721 $unread = $tags[$tag];
1723 $tag = htmlspecialchars($tag);
1725 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
1726 $old_counters[$tag] = $unread;
1727 $tctrs_modified = true;
1728 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1733 if ($smart_mode && $tctrs_modified) {
1734 $_SESSION["tctr_last_value"] = $old_counters;
1739 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
1742 if (!$_SESSION["lctr_last_value"]) {
1743 $_SESSION["lctr_last_value"] = array();
1749 $old_counters = $_SESSION["lctr_last_value"];
1750 $lctrs_modified = false;
1752 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1753 WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND
1754 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1755 unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1757 $count = db_fetch_result($result, 0, "count");
1760 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1762 $ret_arr["-1"]["counter"] = $count;
1763 $ret_arr["-1"]["description"] = "Starred";
1766 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1767 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1769 while ($line = db_fetch_assoc($result)) {
1771 $id = -$line["id"] - 11;
1773 $label_name = $line["description"];
1775 error_reporting (0);
1777 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1778 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
1779 ttrss_feeds.hidden = false AND
1780 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1781 ttrss_user_entries.ref_id = ttrss_entries.id AND
1782 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1784 $count = db_fetch_result($tmp_result, 0, "count");
1786 if (!$smart_mode ||
$old_counters[$id] != $count) {
1787 $old_counters[$id] = $count;
1788 $lctrs_modified = true;
1790 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1792 $ret_arr[$id]["counter"] = $count;
1793 $ret_arr[$id]["description"] = $label_name;
1797 error_reporting (DEFAULT_ERROR_LEVEL
);
1800 if ($smart_mode && $lctrs_modified) {
1801 $_SESSION["lctr_last_value"] = $old_counters;
1807 /* function getFeedCounter($link, $id) {
1809 $result = db_query($link, "SELECT
1810 count(id) as count,last_error
1811 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1812 WHERE feed_id = '$id' AND unread = true
1813 AND ttrss_user_entries.feed_id = ttrss_feeds.id
1814 AND ttrss_user_entries.ref_id = ttrss_entries.id");
1816 $count = db_fetch_result($result, 0, "count");
1817 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1819 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
1822 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
1825 if (!$_SESSION["fctr_last_value"]) {
1826 $_SESSION["fctr_last_value"] = array();
1830 $old_counters = $_SESSION["fctr_last_value"];
1832 $result = db_query($link, "SELECT id,last_error,parent_feed,
1833 SUBSTRING(last_updated,1,19) AS last_updated,
1835 FROM ttrss_entries,ttrss_user_entries
1836 WHERE feed_id = ttrss_feeds.id AND
1837 ttrss_user_entries.ref_id = ttrss_entries.id
1838 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1839 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1840 AND parent_feed IS NULL");
1842 $fctrs_modified = false;
1844 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1846 while ($line = db_fetch_assoc($result)) {
1849 $count = $line["count"];
1850 $last_error = htmlspecialchars($line["last_error"]);
1852 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
1853 $last_updated = smart_date_time(strtotime($line["last_updated"]));
1855 $last_updated = date($short_date, strtotime($line["last_updated"]));
1858 $has_img = is_file(ICONS_DIR
. "/$id.ico");
1860 $tmp_result = db_query($link,
1861 "SELECT id,COUNT(unread) AS unread
1862 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
1863 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
1864 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
1866 if (db_num_rows($tmp_result) > 0) {
1867 while ($l = db_fetch_assoc($tmp_result)) {
1868 $count +
= $l["unread"];
1872 if (!$smart_mode ||
$old_counters[$id] != $count) {
1873 $old_counters[$id] = $count;
1874 $fctrs_modified = true;
1877 $error_part = "error=\"$last_error\"";
1883 $has_img_part = "hi=\"$has_img\"";
1888 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
1892 if ($smart_mode && $fctrs_modified) {
1893 $_SESSION["fctr_last_value"] = $old_counters;
1897 function get_script_dt_add() {
1898 if (strpos(VERSION
, "99") === false) {
1905 function get_pgsql_version($link) {
1906 $result = db_query($link, "SELECT version() AS version");
1907 $version = split(" ", db_fetch_result($result, 0, "version"));
1911 function print_error_xml($code, $add_msg = "") {
1914 $error_msg = $ERRORS[$code];
1917 $error_msg = "$error_msg; $add_msg";
1920 print "<rpc-reply>";
1921 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
1922 print "</rpc-reply>";
1925 function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
1927 # check for feed:http://url
1928 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
1930 # check for feed://URL
1931 if (strpos($feed_link, "//") === 0) {
1932 $feed_link = "http:$feed_link";
1935 if ($feed_link == "") return;
1937 if ($cat_id == "0" ||
!$cat_id) {
1938 $cat_qpart = "NULL";
1940 $cat_qpart = "'$cat_id'";
1943 $result = db_query($link,
1944 "SELECT id FROM ttrss_feeds
1945 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
1947 if (db_num_rows($result) == 0) {
1949 $result = db_query($link,
1950 "INSERT INTO ttrss_feeds (owner_uid,feed_url,title,cat_id)
1951 VALUES ('".$_SESSION["uid"]."', '$feed_link',
1952 '[Unknown]', $cat_qpart)");
1954 $result = db_query($link,
1955 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
1956 AND owner_uid = " . $_SESSION["uid"]);
1958 $feed_id = db_fetch_result($result, 0, "id");
1961 update_rss_feed($link, $feed_link, $feed_id, true);
1970 function print_feed_select($link, $id, $default_id = "",
1971 $attributes = "", $include_all_feeds = true) {
1973 print "<select id=\"$id\" name=\"$id\" $attributes>";
1974 if ($include_all_feeds) {
1975 print "<option value=\"0\">All feeds</option>";
1978 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1979 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1981 if (db_num_rows($result) > 0 && $include_all_feeds) {
1982 print "<option disabled>--------</option>";
1985 while ($line = db_fetch_assoc($result)) {
1986 if ($line["id"] == $default_id) {
1987 $is_selected = "selected";
1991 printf("<option $is_selected value='%d'>%s</option>",
1992 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
1998 function print_feed_cat_select($link, $id, $default_id = "",
1999 $attributes = "", $include_all_cats = true) {
2001 print "<select id=\"$id\" name=\"$id\" $attributes>";
2003 if ($include_all_cats) {
2004 print "<option value=\"0\">".__('Uncategorized')."</option>";
2007 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2008 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2010 if (db_num_rows($result) > 0 && $include_all_cats) {
2011 print "<option disabled>--------</option>";
2014 while ($line = db_fetch_assoc($result)) {
2015 if ($line["id"] == $default_id) {
2016 $is_selected = "selected";
2020 printf("<option $is_selected value='%d'>%s</option>",
2021 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2027 function checkbox_to_sql_bool($val) {
2028 return ($val == "on") ?
"true" : "false";
2031 function getFeedCatTitle($link, $id) {
2033 return __("Special");
2034 } else if ($id < -10) {
2035 return __("Labels");
2036 } else if ($id > 0) {
2037 $result = db_query($link, "SELECT ttrss_feed_categories.title
2038 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2039 cat_id = ttrss_feed_categories.id");
2040 if (db_num_rows($result) == 1) {
2041 return db_fetch_result($result, 0, "title");
2043 return __("Uncategorized");
2046 return "getFeedCatTitle($id) failed";
2051 function getFeedTitle($link, $id) {
2053 return __("Starred articles");
2054 } else if ($id < -10) {
2055 $label_id = -10 - $id;
2056 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2057 if (db_num_rows($result) == 1) {
2058 return db_fetch_result($result, 0, "description");
2060 return "Unknown label ($label_id)";
2063 } else if ($id > 0) {
2064 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2065 if (db_num_rows($result) == 1) {
2066 return db_fetch_result($result, 0, "title");
2068 return "Unknown feed ($id)";
2071 return "getFeedTitle($id) failed";
2076 function get_session_cookie_name() {
2077 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2080 function print_init_params($link) {
2081 print "<init-params>";
2082 if ($_SESSION["stored-params"]) {
2083 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2085 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2086 print "<param key=\"$key\" value=\"$value\"/>";
2091 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2092 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2093 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY
. "\"/>";
2095 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2096 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2098 print "<param key=\"hide_read_feeds\" value=\"" .
2099 sprintf("%d", get_pref($link, "HIDE_READ_FEEDS")) . "\"/>";
2101 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2102 sprintf("%d", get_pref($link, "FEEDS_SORT_BY_UNREAD")) . "\"/>";
2104 print "<param key=\"confirm_feed_catchup\" value=\"" .
2105 sprintf("%d", get_pref($link, "CONFIRM_FEED_CATCHUP")) . "\"/>";
2107 print "</init-params>";
2110 function print_runtime_info($link) {
2111 print "<runtime-info>";
2112 if (ENABLE_UPDATE_DAEMON
) {
2113 print "<param key=\"daemon_is_running\" value=\"".
2114 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2116 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2118 if ($_SESSION["last_version_check"] +
600 < time()) {
2119 $new_version_details = check_for_update($link);
2121 print "<param key=\"new_version_available\" value=\"".
2122 sprintf("%d", $new_version_details != ""). "\"/>";
2124 $_SESSION["last_version_check"] = time();
2128 print "</runtime-info>";
2131 function getSearchSql($search, $match_on) {
2133 $search_query_part = "";
2135 $keywords = split(" ", $search);
2136 $query_keywords = array();
2138 if ($match_on == "both") {
2140 foreach ($keywords as $k) {
2141 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2142 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2145 $search_query_part = implode("AND", $query_keywords) . " AND ";
2147 } else if ($match_on == "title") {
2149 foreach ($keywords as $k) {
2150 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2153 $search_query_part = implode("AND", $query_keywords) . " AND ";
2155 } else if ($match_on == "content") {
2157 foreach ($keywords as $k) {
2158 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2162 $search_query_part = implode("AND", $query_keywords);
2164 return $search_query_part;
2167 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2171 $search_query_part = getSearchSql($search, $match_on);
2172 $search_query_part .= " AND ";
2175 $search_query_part = "";
2178 $view_query_part = "";
2180 if ($view_mode == "adaptive") {
2182 $view_query_part = " ";
2183 } else if ($feed != -1) {
2184 $unread = getFeedUnread($link, $feed, $cat_view);
2186 $view_query_part = " unread = true AND ";
2191 if ($view_mode == "marked") {
2192 $view_query_part = " marked = true AND ";
2195 if ($view_mode == "unread") {
2196 $view_query_part = " unread = true AND ";
2200 $limit_query_part = "LIMIT " . $limit;
2203 $vfeed_query_part = "";
2205 // override query strategy and enable feed display when searching globally
2206 if ($search && $search_mode == "all_feeds") {
2207 $query_strategy_part = "ttrss_entries.id > 0";
2208 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2209 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2210 $query_strategy_part = "ttrss_entries.id > 0";
2211 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2212 id = feed_id) as feed_title,";
2213 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2215 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2217 $tmp_result = false;
2220 $tmp_result = db_query($link, "SELECT id
2221 FROM ttrss_feeds WHERE cat_id = '$feed'");
2223 $tmp_result = db_query($link, "SELECT id
2224 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2225 WHERE id = '$feed') AND id != '$feed'");
2228 $cat_siblings = array();
2230 if (db_num_rows($tmp_result) > 0) {
2231 while ($p = db_fetch_assoc($tmp_result)) {
2232 array_push($cat_siblings, "feed_id = " . $p["id"]);
2235 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2236 $feed, implode(" OR ", $cat_siblings));
2239 $query_strategy_part = "ttrss_entries.id > 0";
2242 } else if ($feed >= 0) {
2247 $query_strategy_part = "cat_id = '$feed'";
2249 $query_strategy_part = "cat_id IS NULL";
2252 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2255 $tmp_result = db_query($link, "SELECT id
2256 FROM ttrss_feeds WHERE parent_feed = '$feed'
2257 ORDER BY cat_id,title");
2259 $parent_ids = array();
2261 if (db_num_rows($tmp_result) > 0) {
2262 while ($p = db_fetch_assoc($tmp_result)) {
2263 array_push($parent_ids, "feed_id = " . $p["id"]);
2266 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2267 $feed, implode(" OR ", $parent_ids));
2269 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2271 $query_strategy_part = "feed_id = '$feed'";
2274 } else if ($feed == -1) { // starred virtual feed
2275 $query_strategy_part = "marked = true";
2276 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2277 } else if ($feed <= -10) { // labels
2278 $label_id = -$feed - 11;
2280 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2281 WHERE id = '$label_id'");
2283 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2287 $query_strategy_part = "id > 0"; // dumb
2290 if (get_pref($link, 'REVERSE_HEADLINES')) {
2291 $order_by = "updated";
2293 $order_by = "updated DESC";
2296 if ($override_order) {
2297 $order_by = $override_order;
2302 if ($search && $search_mode == "all_feeds") {
2303 $feed_title = __("Global search results")." ($search)";
2304 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2305 $feed_title = __("Tag search results")." ($search, $feed)";
2306 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2307 $feed_title = $feed;
2308 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2313 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2314 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2315 $feed_title = db_fetch_result($result, 0, "title");
2317 $feed_title = __("Uncategorized");
2321 $feed_title = __("Category search results")." ($search, $feed_title)";
2326 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2327 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2329 $feed_title = db_fetch_result($result, 0, "title");
2330 $feed_site_url = db_fetch_result($result, 0, "site_url");
2331 $last_error = db_fetch_result($result, 0, "last_error");
2334 $feed_title = __("Feed search results") . " ($search, $feed_title)";
2338 } else if ($feed == -1) {
2339 $feed_title = __("Starred articles");
2340 } else if ($feed < -10) {
2341 $label_id = -$feed - 11;
2342 $result = db_query($link, "SELECT description FROM ttrss_labels
2343 WHERE id = '$label_id'");
2344 $feed_title = db_fetch_result($result, 0, "description");
2347 $feed_title = __("Label search results") . " ($search, $feed_title)";
2353 $feed_title = db_unescape_string($feed_title);
2355 if ($feed < -10) error_reporting (0);
2357 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2360 $feed_kind = "Feeds";
2362 $feed_kind = "Labels";
2365 $content_query_part = "content as content_preview,";
2367 if ($limit_query_part) {
2368 $offset_query_part = "OFFSET $offset";
2373 ttrss_entries.id,ttrss_entries.title,
2374 SUBSTRING(updated,1,16) as updated,
2375 unread,feed_id,marked,link,last_read,
2376 SUBSTRING(last_read,1,19) as last_read_noms,
2379 SUBSTRING(updated,1,19) as updated_noms,
2382 ttrss_entries,ttrss_user_entries,ttrss_feeds
2384 ttrss_feeds.hidden = false AND
2385 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2386 ttrss_user_entries.ref_id = ttrss_entries.id AND
2387 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2390 $query_strategy_part ORDER BY $order_by
2391 $limit_query_part $offset_query_part";
2393 $result = db_query($link, $query);
2395 if ($_GET["debug"]) print $query;
2400 $feed_kind = "Tags";
2402 $result = db_query($link, "SELECT
2404 ttrss_entries.id as id,title,
2405 SUBSTRING(updated,1,16) as updated,
2407 marked,link,last_read,
2408 SUBSTRING(last_read,1,19) as last_read_noms,
2411 SUBSTRING(updated,1,19) as updated_noms
2413 ttrss_entries,ttrss_user_entries,ttrss_tags
2415 ref_id = ttrss_entries.id AND
2416 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2417 post_int_id = int_id AND tag_name = '$feed' AND
2420 $query_strategy_part ORDER BY $order_by
2421 $limit_query_part");
2424 return array($result, $feed_title, $feed_site_url, $last_error);
2428 function generate_syndicated_feed($link, $feed, $is_cat,
2429 $search, $search_mode, $match_on) {
2431 $qfh_ret = queryFeedHeadlines($link, $feed,
2432 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2434 $result = $qfh_ret[0];
2435 $feed_title = htmlspecialchars($qfh_ret[1]);
2436 $feed_site_url = $qfh_ret[2];
2437 $last_error = $qfh_ret[3];
2439 print "<rss version=\"2.0\">
2441 <title>$feed_title</title>
2442 <link>$feed_site_url</link>
2443 <generator>Tiny Tiny RSS v".VERSION
."</generator>";
2445 while ($line = db_fetch_assoc($result)) {
2447 print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2448 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2450 $rfc822_date = date('r', strtotime($line["updated"]));
2452 print "<pubDate>$rfc822_date</pubDate>";
2455 htmlspecialchars($line["title"]) . "</title>";
2457 print "<description>" .
2458 htmlspecialchars($line["content_preview"]) . "</description>";
2463 print "</channel></rss>";
2467 function getCategoryTitle($link, $cat_id) {
2469 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2472 if (db_num_rows($result) == 1) {
2473 return db_fetch_result($result, 0, "title");
2475 return "Uncategorized";
2479 function sanitize_rss($str) {
2482 $res = preg_replace('/<script.*?>/i',
2483 "<p class=\"scriptWarn\">Disabled script: ", $res);
2485 $res = preg_replace('/<\/script.*?>/i', "</p>", $res);
2487 /* $res = preg_replace('/<embed.*?>/i', "", $res);
2489 $res = preg_replace('/<object.*?>.*?<\/object>/i',
2490 "<p class=\"objectWarn\">(Disabled html object
2491 - flash or other embedded content)</p>", $res); */
2496 function send_headlines_digests($link, $limit = 100) {
2498 if (!DIGEST_ENABLE
) return false;
2500 $user_limit = DIGEST_EMAIL_LIMIT
;
2503 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2505 if (DB_TYPE
== "pgsql") {
2506 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2507 } else if (DB_TYPE
== "mysql") {
2508 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2511 $result = db_query($link, "SELECT id,email FROM ttrss_users
2512 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2514 while ($line = db_fetch_assoc($result)) {
2515 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2516 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2518 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2519 $digest = $tuple[0];
2520 $headlines_count = $tuple[1];
2522 if ($headlines_count > 0) {
2523 $rc = mail($line["login"] . " <" . $line["email"] . ">",
2524 "[tt-rss] New headlines for last 24 hours", $digest,
2525 "From: " . MAIL_FROM
. "\n".
2526 "Content-Type: text/plain; charset=\"utf-8\"\n".
2527 "Content-Transfer-Encoding: 8bit\n");
2529 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2530 WHERE id = " . $line["id"]);
2532 print "No headlines\n";
2537 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2541 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2542 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
2543 $tmp .= "=======================================================\n\n";
2545 if (DB_TYPE
== "pgsql") {
2546 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2547 } else if (DB_TYPE
== "mysql") {
2548 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2551 $result = db_query($link, "SELECT ttrss_entries.title,
2552 ttrss_feeds.title AS feed_title,
2555 SUBSTRING(last_updated,1,19) AS last_updated
2557 ttrss_user_entries,ttrss_entries,ttrss_feeds
2559 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2560 AND include_in_digest = true
2562 AND ttrss_user_entries.owner_uid = $user_id
2563 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2566 $cur_feed_title = "";
2568 $headlines_count = db_num_rows($result);
2570 while ($line = db_fetch_assoc($result)) {
2571 $updated = smart_date_time(strtotime($line["last_updated"]));
2572 $feed_title = $line["feed_title"];
2574 if ($cur_feed_title != $feed_title) {
2575 $cur_feed_title = $feed_title;
2577 $tmp .= "$feed_title\n\n";
2580 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2581 $tmp .= " " . trim($line["link"]) . "\n";
2586 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
2587 DIGEST_HOSTNAME
. "\n".
2588 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2591 return array($tmp, $headlines_count);
2594 function check_for_update($link, $brief_fmt = true) {
2595 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2597 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
2602 $rss = fetch_rss($releases_feed);
2603 error_reporting (DEFAULT_ERROR_LEVEL
);
2607 $items = $rss->items
;
2609 if (!$items ||
!is_array($items)) $items = $rss->entries
;
2610 if (!$items ||
!is_array($items)) $items = $rss;
2612 if (!is_array($items) ||
count($items) == 0) {
2616 $latest_item = $items[0];
2618 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2620 $release_url = sanitize_rss($latest_item["link"]);
2621 $content = sanitize_rss($latest_item["description"]);
2623 if (version_compare(VERSION
, $latest_version) == -1) {
2625 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
2626 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2627 <div id=\"milestoneDetails\">$content</div>");
2629 return "New version of Tiny-Tiny RSS ($latest_version) is available:
2630 <div class='milestoneDetails'>$content</div>
2631 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2632 download and update information.";
2639 function markArticlesById($link, $ids, $cmode) {
2643 foreach ($ids as $id) {
2644 array_push($tmp_ids, "ref_id = '$id'");
2647 $ids_qpart = join(" OR ", $tmp_ids);
2650 db_query($link, "UPDATE ttrss_user_entries SET
2651 marked = false,last_read = NOW()
2652 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2653 } else if ($cmode == 1) {
2654 db_query($link, "UPDATE ttrss_user_entries SET
2656 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2658 db_query($link, "UPDATE ttrss_user_entries SET
2659 marked = NOT marked,last_read = NOW()
2660 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2664 function catchupArticlesById($link, $ids, $cmode) {
2668 foreach ($ids as $id) {
2669 array_push($tmp_ids, "ref_id = '$id'");
2672 $ids_qpart = join(" OR ", $tmp_ids);
2675 db_query($link, "UPDATE ttrss_user_entries SET
2676 unread = false,last_read = NOW()
2677 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2678 } else if ($cmode == 1) {
2679 db_query($link, "UPDATE ttrss_user_entries SET
2681 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2683 db_query($link, "UPDATE ttrss_user_entries SET
2684 unread = NOT unread,last_read = NOW()
2685 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2689 function escape_for_form($s) {
2690 return htmlspecialchars(db_unescape_string($s));
2693 function make_guid_from_title($title) {
2694 return preg_replace("/[ \"\',.:;]/", "-",
2695 mb_strtolower(strip_tags($title)));
2698 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
2699 $bottom = false, $rtl_content = false, $feed_id = 0,
2700 $is_cat = false, $search = false, $match_on = false,
2701 $search_mode = false, $offset = 0, $limit = 0) {
2703 $user_page_offset = $offset +
1;
2706 $class = "headlinesSubToolbar";
2707 $tid = "headlineActionsTop";
2709 $class = "headlinesSubToolbar";
2710 $tid = "headlineActionsBottom";
2713 print "<table class=\"$class\" id=\"$tid\"
2714 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2722 $page_prev_link = "javascript:viewFeedGoPage(-1)";
2723 $page_next_link = "javascript:viewFeedGoPage(1)";
2724 $page_first_link = "javascript:viewFeedGoPage(0)";
2726 $catchup_page_link = "javascript:catchupPage()";
2727 $catchup_feed_link = "javascript:catchupCurrentFeed()";
2729 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2731 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2732 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2733 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2735 $tog_unread_link = "javascript:selectionToggleUnread()";
2736 $tog_marked_link = "javascript:selectionToggleMarked()";
2740 $sel_all_link = "javascript:cdmSelectArticles('all')";
2741 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2742 $sel_none_link = "javascript:cdmSelectArticles('none')";
2744 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2745 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2749 if (!strstr($_SESSION["client.userAgent"], "MSIE")) {
2751 print "<td class=\"headlineActions$rtl_cpart\">
2752 <ul class=\"headlineDropdownMenu\">
2755 <a href=\"$sel_all_link\">All</a>,
2756 <a href=\"$sel_unread_link\">Unread</a>,
2757 <a href=\"$sel_none_link\">None</a></li>
2758 <li class=\"vsep\"> </li>
2759 <li class=\"top\">Selection<ul>
2760 <li onclick=\"$tog_unread_link\">Toggle unread</li>
2761 <li onclick=\"$tog_marked_link\">Toggle starred</li></ul></li>
2762 <li class=\"vsep\"> </li>
2763 <li class=\"top\"><a href=\"$catchup_page_link\">Mark as read</a><ul>
2764 <li onclick=\"$catchup_page_link\">This page</li>
2765 <li onclick=\"$catchup_feed_link\">Entire feed</li></ul></li>
2766 <li class=\"vsep\"> </li>
2767 <!-- <li class=\"top2\">
2769 <a href=\"$page_prev_link\">Previous</a>,
2770 <a href=\"$page_next_link\">Next</a></li> -->";
2774 <li class=\"top\"><a href=\"$page_next_link\">Next page</a><ul>
2775 <li onclick=\"$page_prev_link\">Previous page</li>
2776 <li onclick=\"$page_first_link\">First page</li></ul></li>
2784 // old style subtoolbar:
2786 print "<td class=\"headlineActions$rtl_cpart\">".
2788 <a href=\"$sel_all_link\">All</a>,
2789 <a href=\"$sel_unread_link\">Unread</a>,
2790 <a href=\"$sel_none_link\">None</a>
2792 __('Toggle:')." <a href=\"$tog_unread_link\">Unread</a>,
2793 <a href=\"$tog_marked_link\">Starred</a>
2795 __('Mark as read:')."
2796 <a href=\"#\" onclick=\"$catchup_page_link\">Page</a>,
2797 <a href=\"#\" onclick=\"$catchup_feed_link\">Feed</a>";
2802 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
2803 print "<td class=\"headlineActions$rtl_cpart\">
2804 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2805 '$match_on', '$feed_id', '$is_cat');\">
2806 ".__('Convert to Label')."</a></td>";
2809 print "<td class=\"headlineTitle$rtl_cpart\">";
2811 if ($feed_site_url) {
2813 $target = "target=\"_blank\"";
2815 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
2821 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
2824 if ($user_page_offset > 1) {
2825 print " [$user_page_offset] ";
2831 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
2832 <img class=\"noborder\"
2833 alt=\"Generated feed\" src=\"images/feed-icon-12x12.png\">
2838 print "</tr></table>";
2842 function outputFeedList($link, $tags = false) {
2844 print "<ul class=\"feedList\" id=\"feedList\">\n";
2846 $owner_uid = $_SESSION["uid"];
2850 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2851 print "<li class=\"feedCat\">".__('Special')."</li>";
2852 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2855 $num_starred = getFeedUnread($link, -1);
2859 if ($num_starred > 0) $class .= "Unread";
2861 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
2862 "images/mark_set.png", $link);
2864 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2870 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
2872 $result = db_query($link, "SELECT id,sql_exp,description FROM
2873 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
2875 if (db_num_rows($result) > 0) {
2876 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2877 print "<li class=\"feedCat\">".__('Labels')."</li>";
2878 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2880 print "<li><hr></li>";
2884 while ($line = db_fetch_assoc($result)) {
2886 error_reporting (0);
2888 $label_id = -$line['id'] - 11;
2889 $count = getFeedUnread($link, $label_id);
2897 error_reporting (DEFAULT_ERROR_LEVEL
);
2899 printFeedEntry($label_id,
2900 $class, db_unescape_string($line["description"]),
2901 $count, "images/label.png", $link);
2905 if (db_num_rows($result) > 0) {
2906 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2913 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
2914 print "<li><hr></li>";
2917 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2918 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
2919 $order_by_qpart = "category,unread DESC,title";
2921 $order_by_qpart = "category,title";
2924 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
2925 $order_by_qpart = "unread DESC,title";
2927 $order_by_qpart = "title";
2931 $result = db_query($link, "SELECT ttrss_feeds.*,
2932 SUBSTRING(last_updated,1,19) AS last_updated_noms,
2933 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
2934 WHERE feed_id = ttrss_feeds.id AND unread = true
2935 AND ttrss_user_entries.ref_id = ttrss_entries.id
2936 AND owner_uid = '$owner_uid') as unread,
2938 ttrss_feed_categories.title AS category,
2939 ttrss_feed_categories.collapsed
2940 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
2941 ON (ttrss_feed_categories.id = cat_id)
2943 ttrss_feeds.hidden = false AND
2944 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
2945 ORDER BY $order_by_qpart");
2947 $actid = $_GET["actid"];
2957 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2959 while ($line = db_fetch_assoc($result)) {
2961 $feed = db_unescape_string($line["title"]);
2962 $feed_id = $line["id"];
2964 $subop = $_GET["subop"];
2966 $unread = $line["unread"];
2968 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2969 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
2971 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
2974 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
2977 $rtl_tag = "dir=\"RTL\"";
2982 $tmp_result = db_query($link,
2983 "SELECT id,COUNT(unread) AS unread
2984 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2985 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2986 WHERE parent_feed = '$feed_id' AND unread = true
2987 GROUP BY ttrss_feeds.id");
2989 if (db_num_rows($tmp_result) > 0) {
2990 while ($l = db_fetch_assoc($tmp_result)) {
2991 $unread +
= $l["unread"];
2995 $cat_id = $line["cat_id"];
2997 $tmp_category = $line["category"];
2999 if (!$tmp_category) {
3000 $tmp_category = __("Uncategorized");
3003 // $class = ($lnum % 2) ? "even" : "odd";
3005 if ($line["last_error"]) {
3011 if ($unread > 0) $class .= "Unread";
3013 if ($actid == $feed_id) {
3014 $class .= "Selected";
3017 $total_unread +
= $unread;
3019 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3025 $category = $tmp_category;
3027 $collapsed = $line["collapsed"];
3029 // workaround for NULL category
3030 if ($category == __("Uncategorized")) {
3031 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3036 if ($collapsed == "t" ||
$collapsed == "1") {
3037 $holder_class = "invisible";
3044 $cat_id = sprintf("%d", $cat_id);
3046 $cat_unread = getCategoryUnread($link, $cat_id);
3048 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3050 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3051 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3052 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3053 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3054 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3057 // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3058 // -> keyboard navigation, etc.
3059 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3062 printFeedEntry($feed_id, $class, $feed, $unread,
3063 "icons/$feed_id.ico", $link, $rtl_content,
3064 $last_updated, $line["last_error"]);
3069 if (db_num_rows($result) == 0) {
3070 print "<li>".__('No feeds to display.')."</li>";
3077 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3078 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3079 post_int_id = ttrss_user_entries.int_id AND
3080 unread = true AND ref_id = ttrss_entries.id
3081 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3083 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3084 ORDER BY tag_name"); */
3086 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3087 print "<li class=\"feedCat\">".__('Tags')."</li>";
3088 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3091 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3092 FROM ttrss_user_entries WHERE int_id = post_int_id
3093 AND unread = true)) AS count FROM ttrss_tags
3094 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3098 while ($line = db_fetch_assoc($result)) {
3099 $tags[$line["tag_name"]] +
= $line["count"];
3102 foreach (array_keys($tags) as $tag) {
3104 $unread = $tags[$tag];
3112 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3116 if (db_num_rows($result) == 0) {
3117 print "<li>No tags to display.</li>";
3120 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3130 function get_article_tags($link, $id) {
3132 $a_id = db_escape_string($id);
3134 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3135 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3136 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3140 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3141 array_push($tags, $tmp_line["tag_name"]);
3147 function trim_value(&$value) {
3148 $value = trim($value);
3151 function trim_array($array) {
3153 array_walk($tmp, 'trim_value');
3157 function tag_is_valid($tag) {
3158 if ($tag == '') return false;
3159 if (preg_match("/^[0-9]*$/", $tag)) return false;
3161 $tag = iconv("utf-8", "utf-8", $tag);
3162 if (!$tag) return false;
3167 function render_login_form($link) {
3168 require_once "login_form.php";
3171 // from http://developer.apple.com/internet/safari/faq.html
3172 function no_cache_incantation() {
3173 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3174 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3175 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3176 header("Cache-Control: post-check=0, pre-check=0", false);
3177 header("Pragma: no-cache"); // HTTP/1.0
3180 function format_warning($msg, $id = "") {
3181 return "<div class=\"warning\" id=\"$id\">
3182 <img src=\"images/sign_excl.png\">$msg</div>";
3185 function format_notice($msg) {
3186 return "<div class=\"notice\">
3187 <img src=\"images/sign_info.png\">$msg</div>";
3190 function startup_gettext() {
3192 # Get locale from Accept-Language header
3193 $lang = al2gt(array("en_US", "ru_RU"), "text/html");
3196 _setlocale(LC_MESSAGES
, $lang);
3197 _bindtextdomain("messages", "locale");
3198 _textdomain("messages");
3199 _bind_textdomain_codeset("messages", "UTF-8");