3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
9 require_once 'config.php';
11 function get_translations() {
13 "auto" => "Detect automatically",
15 "fr_FR" => "Français",
17 "zh_CN" => "Simplified Chinese");
22 if (ENABLE_TRANSLATIONS
== true) {
23 require_once "accept-to-gettext.php";
24 require_once "gettext/gettext.inc";
26 function startup_gettext() {
28 # Get locale from Accept-Language header
29 $lang = al2gt(array_keys(get_translations()), "text/html");
31 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
32 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
35 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
36 $lang = $_COOKIE["ttrss_lang"];
40 _setlocale(LC_MESSAGES
, $lang);
41 _bindtextdomain("messages", "locale");
42 _textdomain("messages");
43 _bind_textdomain_codeset("messages", "UTF-8");
53 function startup_gettext() {
59 require_once 'db-prefs.php';
60 require_once 'compat.php';
61 require_once 'errors.php';
62 require_once 'version.php';
64 require_once 'phpmailer/class.phpmailer.php';
66 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
67 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
69 if (ENABLE_SIMPLEPIE
) {
70 require_once "simplepie/simplepie.inc";
72 require_once "magpierss/rss_fetch.inc";
73 require_once 'magpierss/rss_utils.inc';
76 include_once "tw/tw-config.php";
77 include_once "tw/tw.php";
78 include_once TW_SETUP
. "paranoya.php";
80 $tw_parser = new twParser();
82 function _debug($msg) {
83 $ts = strftime("%H:%M:%S", time());
87 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
91 if (DB_TYPE
== "pgsql") {
92 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
93 marked = false AND feed_id = '$feed_id' AND
94 (SELECT date_entered FROM ttrss_entries WHERE
95 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
97 $pg_version = get_pgsql_version($link);
99 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
101 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
102 ttrss_entries.id = ref_id AND
104 feed_id = '$feed_id' AND
105 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
109 $result = db_query($link, "DELETE FROM ttrss_user_entries
111 WHERE ttrss_entries.id = ref_id AND
113 feed_id = '$feed_id' AND
114 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
117 $rows = pg_affected_rows($result);
121 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
122 marked = false AND feed_id = '$feed_id' AND
123 (SELECT date_entered FROM ttrss_entries WHERE
124 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
126 $result = db_query($link, "DELETE FROM ttrss_user_entries
127 USING ttrss_user_entries, ttrss_entries
128 WHERE ttrss_entries.id = ref_id AND
130 feed_id = '$feed_id' AND
131 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
133 $rows = mysql_affected_rows($link);
138 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
142 function global_purge_old_posts($link, $do_output = false, $limit = false) {
144 $random_qpart = sql_random_function();
147 $limit_qpart = "LIMIT $limit";
152 $result = db_query($link,
153 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
154 ORDER BY $random_qpart $limit_qpart");
156 while ($line = db_fetch_assoc($result)) {
158 $feed_id = $line["id"];
159 $purge_interval = $line["purge_interval"];
160 $owner_uid = $line["owner_uid"];
162 if ($purge_interval == 0) {
164 $tmp_result = db_query($link,
165 "SELECT value FROM ttrss_user_prefs WHERE
166 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
168 if (db_num_rows($tmp_result) != 0) {
169 $purge_interval = db_fetch_result($tmp_result, 0, "value");
174 // print "Feed $feed_id: purge interval = $purge_interval\n";
177 if ($purge_interval > 0) {
178 purge_feed($link, $feed_id, $purge_interval, $do_output);
182 // purge orphaned posts in main content table
183 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
184 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
187 $rows = db_affected_rows($link, $result);
188 _debug("Purged $rows orphaned posts.");
193 function purge_old_posts($link) {
195 $user_id = $_SESSION["uid"];
197 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
198 WHERE owner_uid = '$user_id'");
200 while ($line = db_fetch_assoc($result)) {
202 $feed_id = $line["id"];
203 $purge_interval = $line["purge_interval"];
205 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
207 if ($purge_interval > 0) {
208 purge_feed($link, $feed_id, $purge_interval);
212 // purge orphaned posts in main content table
213 db_query($link, "DELETE FROM ttrss_entries WHERE
214 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
217 function get_feed_update_interval($link, $feed_id) {
218 $result = db_query($link, "SELECT owner_uid, update_interval FROM
219 ttrss_feeds WHERE id = '$feed_id'");
221 if (db_num_rows($result) == 1) {
222 $update_interval = db_fetch_result($result, 0, "update_interval");
223 $owner_uid = db_fetch_result($result, 0, "owner_uid");
225 if ($update_interval != 0) {
226 return $update_interval;
228 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
236 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
238 if (WEB_DEMO_MODE
) return;
241 $user_id = $_SESSION["uid"];
242 purge_old_posts($link);
245 // db_query($link, "BEGIN");
247 if (MAX_UPDATE_TIME
> 0) {
248 if (DB_TYPE
== "mysql") {
251 $q_order = "RANDOM()";
254 $q_order = "last_updated DESC";
257 $result = db_query($link, "SELECT feed_url,id,
258 SUBSTRING(last_updated,1,19) AS last_updated,
259 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
264 while ($line = db_fetch_assoc($result)) {
265 $upd_intl = $line["update_interval"];
267 if (!$upd_intl ||
$upd_intl == 0) {
268 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
272 // Updates for this feed are disabled
276 if ($fetch ||
(!$line["last_updated"] ||
277 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
279 // print "<!-- feed: ".$line["feed_url"]." -->";
281 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
283 $upd_elapsed = time() - $upd_start;
285 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
291 // db_query($link, "COMMIT");
295 function fetch_file_contents($url) {
296 if (USE_CURL_FOR_ICONS
) {
297 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
299 $ch = curl_init($url);
300 $fp = fopen($tmpfile, "w");
303 curl_setopt($ch, CURLOPT_FILE
, $fp);
304 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
305 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
311 $contents = file_get_contents($tmpfile);
317 return file_get_contents($url);
322 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
323 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
325 function get_favicon_url($url) {
327 if ($html = @fetch_file_contents
($url)) {
329 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
330 // Attempt to grab a favicon link from their webpage url
331 $linkUrl = html_entity_decode($matches[1]);
333 if (substr($linkUrl, 0, 1) == '/') {
334 $urlParts = parse_url($url);
335 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
336 } else if (substr($linkUrl, 0, 7) == 'http://') {
337 $faviconURL = $linkUrl;
338 } else if (substr($url, -1, 1) == '/') {
339 $faviconURL = $url.$linkUrl;
341 $faviconURL = $url.'/'.$linkUrl;
345 // If unsuccessful, attempt to "guess" the favicon location
346 $urlParts = parse_url($url);
347 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
351 // Run a test to see if what we have attempted to get actually exists.
352 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
359 function url_validate($link) {
361 $url_parts = @parse_url
($link);
363 if ( empty( $url_parts["host"] ) )
366 if ( !empty( $url_parts["path"] ) ) {
367 $documentpath = $url_parts["path"];
372 if ( !empty( $url_parts["query"] ) )
373 $documentpath .= "?" . $url_parts["query"];
375 $host = $url_parts["host"];
376 $port = $url_parts["port"];
381 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
386 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
388 $http_response = fgets( $socket, 22 );
390 $responses = "/(200 OK)|(30[0-9] Moved)/";
391 if ( preg_match($responses, $http_response) ) {
400 function check_feed_favicon($site_url, $feed, $link) {
401 $favicon_url = get_favicon_url($site_url);
403 # print "FAVICON [$site_url]: $favicon_url\n";
407 $icon_file = ICONS_DIR
. "/$feed.ico";
409 if ($favicon_url && !file_exists($icon_file)) {
410 $contents = fetch_file_contents($favicon_url);
412 $fp = fopen($icon_file, "w");
415 fwrite($fp, $contents);
417 chmod($icon_file, 0644);
421 error_reporting(DEFAULT_ERROR_LEVEL
);
425 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
427 if (DAEMON_REFRESH_ONLY
&& !$_GET["daemon"] && !$ignore_daemon) {
431 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
432 _debug("update_rss_feed: start");
435 $result = db_query($link, "SELECT id,update_interval,auth_login,auth_pass,cache_images
436 FROM ttrss_feeds WHERE id = '$feed'");
438 if (db_num_rows($result) == 0) {
439 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
440 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND");
445 $auth_login = db_fetch_result($result, 0, "auth_login");
446 $auth_pass = db_fetch_result($result, 0, "auth_pass");
448 $update_interval = db_fetch_result($result, 0, "update_interval");
449 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
451 if ($update_interval < 0) { return; }
453 $feed = db_escape_string($feed);
455 $fetch_url = $feed_url;
457 if ($auth_login && $auth_pass) {
458 $url_parts = array();
459 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
461 if ($url_parts[1] && $url_parts[2]) {
462 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
467 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
468 _debug("update_rss_feed: fetching [$fetch_url]...");
471 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
475 if (!ENABLE_SIMPLEPIE
) {
476 $rss = fetch_rss($fetch_url);
478 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
479 mkdir(SIMPLEPIE_CACHE_DIR
);
482 $rss = new SimplePie();
483 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
484 $rss->set_timeout(MAGPIE_FETCH_TIME_OUT
);
485 $rss->set_feed_url($fetch_url);
486 $rss->set_output_encoding('UTF-8');
488 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
489 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
490 _debug("enabling image cache");
493 $rss->set_image_handler('./image.php', 'i');
496 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
497 _debug("feed update interval (sec): " .
498 get_feed_update_interval($link, $feed)*60);
501 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
502 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
503 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
511 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
512 _debug("update_rss_feed: fetch done, parsing...");
514 error_reporting (DEFAULT_ERROR_LEVEL
);
517 $feed = db_escape_string($feed);
519 if (ENABLE_SIMPLEPIE
) {
520 $fetch_ok = !$rss->error();
527 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
528 _debug("update_rss_feed: processing feed data...");
531 // db_query($link, "BEGIN");
533 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
534 FROM ttrss_feeds WHERE id = '$feed'");
536 $registered_title = db_fetch_result($result, 0, "title");
537 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
538 $orig_site_url = db_fetch_result($result, 0, "site_url");
540 $owner_uid = db_fetch_result($result, 0, "owner_uid");
542 if (ENABLE_SIMPLEPIE
) {
543 $site_url = $rss->get_link();
545 $site_url = $rss->channel
["link"];
548 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
549 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
550 _debug("update_rss_feed: checking favicon...");
553 check_feed_favicon($site_url, $feed, $link);
556 if (!$registered_title ||
$registered_title == "[Unknown]") {
558 if (ENABLE_SIMPLEPIE
) {
559 $feed_title = db_escape_string($rss->get_title());
561 $feed_title = db_escape_string($rss->channel
["title"]);
564 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
565 _debug("update_rss_feed: registering title: $feed_title");
568 db_query($link, "UPDATE ttrss_feeds SET
569 title = '$feed_title' WHERE id = '$feed'");
572 // weird, weird Magpie
573 if (!ENABLE_SIMPLEPIE
) {
574 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
577 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
578 db_query($link, "UPDATE ttrss_feeds SET
579 site_url = '$site_url' WHERE id = '$feed'");
582 // print "I: " . $rss->channel["image"]["url"];
584 if (!ENABLE_SIMPLEPIE
) {
585 $icon_url = $rss->image
["url"];
587 $icon_url = $rss->get_image_url();
590 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
591 $icon_url = db_escape_string($icon_url);
592 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
595 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
596 _debug("update_rss_feed: loading filters...");
601 $result = db_query($link, "SELECT reg_exp,
602 ttrss_filter_types.name AS name,
603 ttrss_filter_actions.name AS action,
606 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
608 owner_uid = $owner_uid AND
609 ttrss_filter_types.id = filter_type AND
610 ttrss_filter_actions.id = action_id AND
611 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
613 while ($line = db_fetch_assoc($result)) {
614 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
616 $filter["reg_exp"] = $line["reg_exp"];
617 $filter["action"] = $line["action"];
618 $filter["action_param"] = $line["action_param"];
619 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
621 array_push($filters[$line["name"]], $filter);
624 if (ENABLE_SIMPLEPIE
) {
625 $iterator = $rss->get_items();
627 $iterator = $rss->items
;
628 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
629 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
632 if (!is_array($iterator)) {
633 /* db_query($link, "UPDATE ttrss_feeds
634 SET last_error = 'Parse error: can\'t find any articles.'
635 WHERE id = '$feed'"); */
637 // clear any errors and mark feed as updated if fetched okay
638 // even if it's blank
640 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
641 _debug("update_rss_feed: entry iterator is not an array, no articles?");
644 db_query($link, "UPDATE ttrss_feeds
645 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
647 return; // no articles
650 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
651 _debug("update_rss_feed: processing articles...");
654 foreach ($iterator as $item) {
656 if (ENABLE_SIMPLEPIE
) {
657 $entry_guid = $item->get_id();
658 if (!$entry_guid) $entry_guid = $item->get_link();
659 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
663 $entry_guid = $item["id"];
665 if (!$entry_guid) $entry_guid = $item["guid"];
666 if (!$entry_guid) $entry_guid = $item["link"];
667 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
670 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
671 _debug("update_rss_feed: guid $entry_guid");
674 if (!$entry_guid) continue;
676 $entry_timestamp = "";
678 if (ENABLE_SIMPLEPIE
) {
679 $entry_timestamp = strtotime($item->get_date());
681 $rss_2_date = $item['pubdate'];
682 $rss_1_date = $item['dc']['date'];
683 $atom_date = $item['issued'];
684 if (!$atom_date) $atom_date = $item['updated'];
686 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
687 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
688 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
691 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
692 _debug("update_rss_feed: date $entry_timestamp");
695 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
696 $entry_timestamp = time();
697 $no_orig_date = 'true';
699 $no_orig_date = 'false';
702 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
704 if (ENABLE_SIMPLEPIE
) {
705 $entry_title = $item->get_title();
707 $entry_title = trim(strip_tags($item["title"]));
710 if (ENABLE_SIMPLEPIE
) {
711 $entry_link = $item->get_link();
713 // strange Magpie workaround
714 $entry_link = $item["link_"];
715 if (!$entry_link) $entry_link = $item["link"];
718 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
719 _debug("update_rss_feed: title $entry_title");
722 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
724 $entry_link = strip_tags($entry_link);
726 if (ENABLE_SIMPLEPIE
) {
727 $entry_content = $item->get_description();
729 $entry_content = $item["content:escaped"];
731 if (!$entry_content) $entry_content = $item["content:encoded"];
732 if (!$entry_content) $entry_content = $item["content"];
733 if (!$entry_content) $entry_content = $item["atom_content"];
734 if (!$entry_content) $entry_content = $item["summary"];
735 if (!$entry_content) $entry_content = $item["description"];
738 if (is_array($entry_content)) {
739 $entry_content = $entry_content["encoded"];
740 if (!$entry_content) $entry_content = $entry_content["escaped"];
745 // print_r(htmlspecialchars($entry_content));
748 $entry_content_unescaped = $entry_content;
750 if (ENABLE_SIMPLEPIE
) {
751 $entry_comments = strip_tags($item->data
["comments"]);
752 if ($item->get_author()) {
753 $entry_author = $item->get_author()->get_name();
756 $entry_comments = strip_tags($item["comments"]);
758 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
760 if ($item['author']) {
762 if (is_array($item['author'])) {
764 if (!$entry_author) {
765 $entry_author = db_escape_string(strip_tags($item['author']['name']));
768 if (!$entry_author) {
769 $entry_author = db_escape_string(strip_tags($item['author']['email']));
773 if (!$entry_author) {
774 $entry_author = db_escape_string(strip_tags($item['author']));
779 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
781 $entry_guid = db_escape_string(strip_tags($entry_guid));
783 $result = db_query($link, "SELECT id FROM ttrss_entries
784 WHERE guid = '$entry_guid'");
786 $entry_content = db_escape_string($entry_content);
788 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
790 $entry_title = db_escape_string($entry_title);
791 $entry_link = db_escape_string($entry_link);
792 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
793 $entry_author = mb_substr($entry_author, 0, 250);
795 if (ENABLE_SIMPLEPIE
) {
796 $num_comments = 0; #FIXME#
798 $num_comments = db_escape_string($item["slash"]["comments"]);
801 if (!$num_comments) $num_comments = 0;
803 // parse <category> entries into tags
805 if (ENABLE_SIMPLEPIE
) {
807 $additional_tags = array();
808 $additional_tags_src = $item->get_categories();
810 if (is_array($additional_tags_src)) {
811 foreach ($additional_tags_src as $tobj) {
812 array_push($additional_tags, $tobj->get_term());
816 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
817 _debug("update_rss_feed: category tags:");
818 print_r($additional_tags);
823 $t_ctr = $item['category#'];
825 $additional_tags = false;
828 $additional_tags = false;
829 } else if ($t_ctr == 1) {
830 $additional_tags = array($item['category']);
832 $additional_tags = array();
833 for ($i = 0; $i <= $t_ctr; $i++
) {
834 if ($item["category#$i"]) {
835 array_push($additional_tags, $item["category#$i"]);
840 // parse <dc:subject> elements
842 $t_ctr = $item['dc']['subject#'];
845 $additional_tags = array($item['dc']['subject']);
846 } else if ($t_ctr > 1) {
847 $additional_tags = array();
848 for ($i = 0; $i <= $t_ctr; $i++
) {
849 if ($item['dc']["subject#$i"]) {
850 array_push($additional_tags, $item['dc']["subject#$i"]);
858 // $entry_content = sanitize_rss($entry_content);
860 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
861 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
864 db_query($link, "BEGIN");
866 if (db_num_rows($result) == 0) {
868 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
869 _debug("update_rss_feed: base guid not found");
872 // base post entry does not exist, create it
874 $result = db_query($link,
875 "INSERT INTO ttrss_entries
891 '$entry_timestamp_fmt',
900 // we keep encountering the entry in feeds, so we need to
901 // update date_entered column so that we don't get horrible
902 // dupes when the entry gets purged and reinserted again e.g.
903 // in the case of SLOW SLOW OMG SLOW updating feeds
905 $base_entry_id = db_fetch_result($result, 0, "id");
907 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
908 WHERE id = '$base_entry_id'");
911 // now it should exist, if not - bad luck then
913 $result = db_query($link, "SELECT
914 id,content_hash,no_orig_date,title,
915 substring(date_entered,1,19) as date_entered,
916 substring(updated,1,19) as updated,
920 WHERE guid = '$entry_guid'");
922 if (db_num_rows($result) == 1) {
924 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
925 _debug("update_rss_feed: base guid found, checking for user record");
928 // this will be used below in update handler
929 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
930 $orig_title = db_fetch_result($result, 0, "title");
931 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
932 $orig_date_entered = strtotime(db_fetch_result($result,
935 $ref_id = db_fetch_result($result, 0, "id");
937 // check for user post link to main table
939 // do we allow duplicate posts with same GUID in different feeds?
940 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
941 $dupcheck_qpart = "AND feed_id = '$feed'";
943 $dupcheck_qpart = "";
946 // error_reporting(0);
948 $article_filters = get_article_filters($filters, $entry_title,
949 $entry_content, $entry_link);
951 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
952 _debug("update_rss_feed: article filters: ");
953 if (count($article_filters) != 0) {
954 print_r($article_filters);
958 if (find_article_filter($article_filters, "filter")) {
962 // error_reporting (DEFAULT_ERROR_LEVEL);
964 $result = db_query($link,
965 "SELECT ref_id FROM ttrss_user_entries WHERE
966 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
969 // okay it doesn't exist - create user entry
970 if (db_num_rows($result) == 0) {
972 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
973 _debug("update_rss_feed: user record not found, creating...");
976 if (!find_article_filter($article_filters, 'catchup')) {
978 $last_read_qpart = 'NULL';
981 $last_read_qpart = 'NOW()';
984 if (find_article_filter($article_filters, 'mark')) {
990 if (find_article_filter($article_filters, 'publish')) {
993 $published = 'false';
996 $result = db_query($link,
997 "INSERT INTO ttrss_user_entries
998 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
999 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1000 $last_read_qpart, $marked, $published)");
1003 $post_needs_update = false;
1005 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1006 ($content_hash != $orig_content_hash)) {
1007 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1008 $post_needs_update = true;
1011 if (db_escape_string($orig_title) != $entry_title) {
1012 $post_needs_update = true;
1015 if ($orig_num_comments != $num_comments) {
1016 $post_needs_update = true;
1019 // this doesn't seem to be very reliable
1021 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1022 // $post_needs_update = true;
1025 // if post needs update, update it and mark all user entries
1026 // linking to this post as updated
1027 if ($post_needs_update) {
1029 if (defined('DAEMON_EXTENDED_DEBUG')) {
1030 _debug("update_rss_feed: post $entry_guid needs update...");
1033 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1035 db_query($link, "UPDATE ttrss_entries
1036 SET title = '$entry_title', content = '$entry_content',
1037 content_hash = '$content_hash',
1038 num_comments = '$num_comments'
1039 WHERE id = '$ref_id'");
1041 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1042 db_query($link, "UPDATE ttrss_user_entries
1043 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1045 db_query($link, "UPDATE ttrss_user_entries
1046 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1052 db_query($link, "COMMIT");
1054 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1055 _debug("update_rss_feed: looking for tags...");
1059 // <a href="..." rel="tag">Xorg</a>, //
1063 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1064 $entry_content_unescaped, $entry_tags);
1066 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1067 print_r($entry_tags);
1068 print "<br/></p>"; */
1070 $entry_tags = $entry_tags[1];
1072 # check for manual tags
1074 $tag_filter = find_article_filter($article_filters, "tag");
1078 $manual_tags = trim_array(split(",", $tag_filter[1]));
1080 foreach ($manual_tags as $tag) {
1081 if (tag_is_valid($tag)) {
1082 array_push($entry_tags, $tag);
1087 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1088 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1090 if ($additional_tags && is_array($additional_tags)) {
1091 foreach ($additional_tags as $tag) {
1092 if (tag_is_valid($tag) &&
1093 array_search($tag, $boring_tags) === FALSE) {
1094 array_push($entry_tags, $tag);
1099 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1101 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1102 print_r($entry_tags);
1105 if (count($entry_tags) > 0) {
1107 db_query($link, "BEGIN");
1109 $result = db_query($link, "SELECT id,int_id
1110 FROM ttrss_entries,ttrss_user_entries
1111 WHERE guid = '$entry_guid'
1112 AND feed_id = '$feed' AND ref_id = id
1113 AND owner_uid = '$owner_uid'");
1115 if (db_num_rows($result) == 1) {
1117 $entry_id = db_fetch_result($result, 0, "id");
1118 $entry_int_id = db_fetch_result($result, 0, "int_id");
1120 foreach ($entry_tags as $tag) {
1122 $tag = sanitize_tag($tag);
1123 $tag = db_escape_string($tag);
1125 if (!tag_is_valid($tag)) continue;
1127 $result = db_query($link, "SELECT id FROM ttrss_tags
1128 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1129 owner_uid = '$owner_uid' LIMIT 1");
1131 // print db_fetch_result($result, 0, "id");
1133 if ($result && db_num_rows($result) == 0) {
1135 db_query($link, "INSERT INTO ttrss_tags
1136 (owner_uid,tag_name,post_int_id)
1137 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1141 db_query($link, "COMMIT");
1144 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1145 _debug("update_rss_feed: article processed");
1149 db_query($link, "UPDATE ttrss_feeds
1150 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1152 // db_query($link, "COMMIT");
1156 if (ENABLE_SIMPLEPIE
) {
1157 $error_msg = mb_substr($rss->error(), 0, 250);
1159 $error_msg = mb_substr(magpie_error(), 0, 250);
1162 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1163 _debug("update_rss_feed: error fetching feed: $error_msg");
1166 $error_msg = db_escape_string($error_msg);
1169 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1170 last_updated = NOW() WHERE id = '$feed'");
1173 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1174 _debug("update_rss_feed: done");
1179 function print_select($id, $default, $values, $attributes = "") {
1180 print "<select name=\"$id\" id=\"$id\" $attributes>";
1181 foreach ($values as $v) {
1187 print "<option$sel>$v</option>";
1192 function print_select_hash($id, $default, $values, $attributes = "") {
1193 print "<select name=\"$id\" id='$id' $attributes>";
1194 foreach (array_keys($values) as $v) {
1200 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1206 function get_article_filters($filters, $title, $content, $link) {
1209 if ($filters["title"]) {
1210 foreach ($filters["title"] as $filter) {
1211 $reg_exp = $filter["reg_exp"];
1212 $inverse = $filter["inverse"];
1213 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1214 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1216 array_push($matches, array($filter["action"], $filter["action_param"]));
1221 if ($filters["content"]) {
1222 foreach ($filters["content"] as $filter) {
1223 $reg_exp = $filter["reg_exp"];
1224 $inverse = $filter["inverse"];
1226 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1227 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1229 array_push($matches, array($filter["action"], $filter["action_param"]));
1234 if ($filters["both"]) {
1235 foreach ($filters["both"] as $filter) {
1236 $reg_exp = $filter["reg_exp"];
1237 $inverse = $filter["inverse"];
1240 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1241 array_push($matches, array($filter["action"], $filter["action_param"]));
1244 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1245 array_push($matches, array($filter["action"], $filter["action_param"]));
1251 if ($filters["link"]) {
1252 $reg_exp = $filter["reg_exp"];
1253 foreach ($filters["link"] as $filter) {
1254 $reg_exp = $filter["reg_exp"];
1255 $inverse = $filter["inverse"];
1257 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1258 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1260 array_push($matches, array($filter["action"], $filter["action_param"]));
1268 function find_article_filter($filters, $filter_name) {
1269 foreach ($filters as $f) {
1270 if ($f[0] == $filter_name) {
1277 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1278 $rtl_content = false, $last_updated = false, $last_error = false) {
1280 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1281 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1283 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1287 $rtl_tag = "dir=\"rtl\"";
1289 $rtl_tag = "dir=\"ltr\"";
1292 $error_notify_msg = "";
1295 $link_title = "Error: $last_error ($last_updated)";
1296 $error_notify_msg = "(Error)";
1297 } else if ($last_updated) {
1298 $link_title = "Updated: $last_updated";
1301 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1302 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1304 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1305 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1309 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1314 $fctr_class = "class=\"invisible\"";
1317 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1318 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1320 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1321 print "<div class=\"feedExtInfo\">
1322 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1329 function getmicrotime() {
1330 list($usec, $sec) = explode(" ",microtime());
1331 return ((float)$usec +
(float)$sec);
1334 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1335 foreach ($values as $v) {
1342 if ($v == $true_is) {
1343 $sel .= " value=\"1\"";
1345 $sel .= " value=\"0\"";
1348 print "<input class=\"noborder\"
1349 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1354 function initialize_user_prefs($link, $uid) {
1356 $uid = db_escape_string($uid);
1358 db_query($link, "BEGIN");
1360 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1362 $u_result = db_query($link, "SELECT pref_name
1363 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1365 $active_prefs = array();
1367 while ($line = db_fetch_assoc($u_result)) {
1368 array_push($active_prefs, $line["pref_name"]);
1371 while ($line = db_fetch_assoc($result)) {
1372 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1373 // print "adding " . $line["pref_name"] . "<br>";
1375 db_query($link, "INSERT INTO ttrss_user_prefs
1376 (owner_uid,pref_name,value) VALUES
1377 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1382 db_query($link, "COMMIT");
1386 function lookup_user_id($link, $user) {
1388 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1391 if (db_num_rows($result) == 1) {
1392 return db_fetch_result($result, 0, "id");
1398 function http_authenticate_user($link) {
1400 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1402 if (!$_SERVER["PHP_AUTH_USER"]) {
1404 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1405 header('HTTP/1.0 401 Unauthorized');
1409 $auth_result = authenticate_user($link,
1410 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1412 if (!$auth_result) {
1413 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1414 header('HTTP/1.0 401 Unauthorized');
1422 function authenticate_user($link, $login, $password, $force_auth = false) {
1424 if (!SINGLE_USER_MODE
) {
1426 $pwd_hash1 = encrypt_password($password);
1427 $pwd_hash2 = encrypt_password($password, $login);
1429 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1430 $query = "SELECT id,login,access_level
1431 FROM ttrss_users WHERE
1434 $query = "SELECT id,login,access_level,pwd_hash
1435 FROM ttrss_users WHERE
1436 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1437 pwd_hash = '$pwd_hash2')";
1440 $result = db_query($link, $query);
1442 if (db_num_rows($result) == 1) {
1443 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1444 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1445 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1447 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1450 $user_theme = get_user_theme_path($link);
1452 $_SESSION["theme"] = $user_theme;
1453 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1454 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1456 initialize_user_prefs($link, $_SESSION["uid"]);
1465 $_SESSION["uid"] = 1;
1466 $_SESSION["name"] = "admin";
1468 $user_theme = get_user_theme_path($link);
1470 $_SESSION["theme"] = $user_theme;
1471 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1473 initialize_user_prefs($link, $_SESSION["uid"]);
1479 function make_password($length = 8) {
1482 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1486 while ($i < $length) {
1487 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1489 if (!strstr($password, $char)) {
1497 // this is called after user is created to initialize default feeds, labels
1500 // user preferences are checked on every login, not here
1502 function initialize_user($link, $uid) {
1504 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1505 values ('$uid','unread = true', 'Unread articles')");
1507 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1508 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1510 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1511 values ('$uid', 'Tiny Tiny RSS: New Releases',
1512 'http://tt-rss.spb.ru/releases.rss')");
1514 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1515 values ('$uid', 'Tiny Tiny RSS: Forum',
1516 'http://tt-rss.spb.ru/forum/rss.php')");
1519 function logout_user() {
1521 if (isset($_COOKIE[session_name()])) {
1522 setcookie(session_name(), '', time()-42000, '/');
1526 function get_script_urlpath() {
1527 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1530 function validate_session($link) {
1531 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1532 if ($_SESSION["ip_address"]) {
1533 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1534 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1540 if ($_SESSION["uid"]) {
1542 $result = db_query($link,
1543 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1545 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1547 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1552 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1554 //print_r($_SESSION);
1556 if (time() > $_SESSION["cookie_lifetime"]) {
1564 function login_sequence($link, $mobile = false) {
1565 if (!SINGLE_USER_MODE
) {
1567 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1568 $swu = db_escape_string($_REQUEST["swu"]);
1570 $_SESSION["prefs_cache"] = false;
1571 return authenticate_user($link, $swu, null, true);
1575 $login_action = $_POST["login_action"];
1577 # try to authenticate user if called from login form
1578 if ($login_action == "do_login") {
1579 $login = $_POST["login"];
1580 $password = $_POST["password"];
1581 $remember_me = $_POST["remember_me"];
1583 if (authenticate_user($link, $login, $password)) {
1584 $_POST["password"] = "";
1586 $_SESSION["language"] = $_POST["language"];
1588 header("Location: " . $_SERVER["REQUEST_URI"]);
1593 $_SESSION["login_error_msg"] = "Incorrect username or password";
1597 // print session_id();
1598 // print_r($_SESSION);
1600 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1601 render_login_form($link, $mobile);
1604 /* bump login timestamp */
1605 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1608 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1609 setcookie("ttrss_lang", $_SESSION["language"],
1610 time() + SESSION_COOKIE_LIFETIME
);
1615 return authenticate_user($link, "admin", null);
1619 function truncate_string($str, $max_len) {
1620 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1621 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1627 function get_user_theme_path($link) {
1628 $result = db_query($link, "SELECT theme_path
1630 ttrss_themes,ttrss_users
1631 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1632 if (db_num_rows($result) != 0) {
1633 return db_fetch_result($result, 0, "theme_path");
1639 function smart_date_time($timestamp) {
1640 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1641 return date("G:i", $timestamp);
1642 } else if (date("Y", $timestamp) == date("Y")) {
1643 return date("M d, G:i", $timestamp);
1645 return date("Y/m/d, G:i", $timestamp);
1649 function smart_date($timestamp) {
1650 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1652 } else if (date("Y", $timestamp) == date("Y")) {
1653 return date("D m", $timestamp);
1655 return date("Y/m/d", $timestamp);
1659 function sql_bool_to_string($s) {
1660 if ($s == "t" ||
$s == "1") {
1667 function sql_bool_to_bool($s) {
1668 if ($s == "t" ||
$s == "1") {
1676 function toggleEvenOdd($a) {
1683 function sanity_check($link) {
1688 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1689 $schema_version = db_fetch_result($result, 0, "schema_version");
1691 if ($schema_version != SCHEMA_VERSION
) {
1695 if (DB_TYPE
== "mysql") {
1696 $result = db_query($link, "SELECT true", false);
1697 if (db_num_rows($result) != 1) {
1702 error_reporting (DEFAULT_ERROR_LEVEL
);
1704 if ($error_code != 0) {
1705 print_error_xml($error_code);
1712 function file_is_locked($filename) {
1714 $fp = fopen($filename, "r");
1715 error_reporting(DEFAULT_ERROR_LEVEL
);
1717 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1718 flock($fp, LOCK_UN
);
1728 function make_lockfile($filename) {
1729 $fp = fopen($filename, "w");
1731 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1738 function make_stampfile($filename) {
1739 $fp = fopen($filename, "w");
1741 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1742 fwrite($fp, time() . "\n");
1743 flock($fp, LOCK_UN
);
1751 function read_stampfile($filename) {
1754 $fp = fopen($filename, "r");
1755 error_reporting (DEFAULT_ERROR_LEVEL
);
1757 if (flock($fp, LOCK_EX
)) {
1758 $stamp = fgets($fp);
1759 flock($fp, LOCK_UN
);
1767 function sql_random_function() {
1768 if (DB_TYPE
== "mysql") {
1775 function catchup_feed($link, $feed, $cat_view) {
1777 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1782 $cat_qpart = "cat_id = '$feed'";
1784 $cat_qpart = "cat_id IS NULL";
1787 $tmp_result = db_query($link, "SELECT id
1788 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1791 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1793 $tmp_feed = $tmp_line["id"];
1795 db_query($link, "UPDATE ttrss_user_entries
1796 SET unread = false,last_read = NOW()
1797 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1800 } else if ($feed > 0) {
1802 $tmp_result = db_query($link, "SELECT id
1803 FROM ttrss_feeds WHERE parent_feed = '$feed'
1804 ORDER BY cat_id,title");
1806 $parent_ids = array();
1808 if (db_num_rows($tmp_result) > 0) {
1809 while ($p = db_fetch_assoc($tmp_result)) {
1810 array_push($parent_ids, "feed_id = " . $p["id"]);
1813 $children_qpart = implode(" OR ", $parent_ids);
1815 db_query($link, "UPDATE ttrss_user_entries
1816 SET unread = false,last_read = NOW()
1817 WHERE (feed_id = '$feed' OR $children_qpart)
1818 AND owner_uid = " . $_SESSION["uid"]);
1821 db_query($link, "UPDATE ttrss_user_entries
1822 SET unread = false,last_read = NOW()
1823 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1826 } else if ($feed < 0 && $feed > -10) { // special, like starred
1829 db_query($link, "UPDATE ttrss_user_entries
1830 SET unread = false,last_read = NOW()
1831 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1835 db_query($link, "UPDATE ttrss_user_entries
1836 SET unread = false,last_read = NOW()
1837 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
1842 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1844 if (DB_TYPE
== "pgsql") {
1845 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1847 $match_part .= " AND date_entered > DATE_SUB(NOW(),
1848 INTERVAL $intl HOUR) ";
1851 db_query($link, "UPDATE ttrss_user_entries
1852 SET unread = false,last_read = NOW()
1853 WHERE $match_part AND owner_uid = ".$_SESSION["uid"]);
1856 } else if ($feed < -10) { // label
1858 // TODO make this more efficient
1860 $label_id = -$feed - 11;
1862 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1863 WHERE id = '$label_id'");
1866 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1868 db_query($link, "BEGIN");
1870 $tmp2_result = db_query($link,
1874 ttrss_user_entries,ttrss_entries,ttrss_feeds
1876 ref_id = ttrss_entries.id AND
1877 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1879 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1881 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1882 db_query($link, "UPDATE
1885 unread = false, last_read = NOW()
1887 int_id = " . $tmp_line["int_id"]);
1890 db_query($link, "COMMIT");
1892 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1893 SET unread = false,last_read = NOW()
1896 AND owner_uid = ".$_SESSION["uid"]); */
1900 db_query($link, "BEGIN");
1902 $tag_name = db_escape_string($feed);
1904 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1905 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1907 while ($line = db_fetch_assoc($result)) {
1908 db_query($link, "UPDATE ttrss_user_entries SET
1909 unread = false, last_read = NOW()
1910 WHERE int_id = " . $line["post_int_id"]);
1912 db_query($link, "COMMIT");
1916 function update_generic_feed($link, $feed, $cat_view) {
1920 $cat_qpart = "cat_id = '$feed'";
1922 $cat_qpart = "cat_id IS NULL";
1925 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
1926 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1928 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1929 $feed_url = $tmp_line["feed_url"];
1930 $feed_id = $tmp_line["id"];
1931 update_rss_feed($link, $feed_url, $feed_id, ENABLE_UPDATE_DAEMON
);
1935 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1936 WHERE id = '$feed'");
1937 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1938 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON
);
1942 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1943 /* getLabelCounters($link);
1944 getFeedCounters($link);
1945 getTagCounters($link);
1946 getGlobalCounters($link);
1947 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1948 getCategoryCounters($link);
1951 if (!$omode) $omode = "flc";
1953 getGlobalCounters($link);
1955 if (strchr($omode, "l")) getLabelCounters($link);
1956 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
1957 if (strchr($omode, "t")) getTagCounters($link);
1958 if (strchr($omode, "c")) {
1959 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1960 getCategoryCounters($link);
1965 function getCategoryCounters($link) {
1966 # two special categories are -1 and -2 (all virtuals; all labels)
1968 $ctr = getCategoryUnread($link, -1);
1970 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
1972 $ctr = getCategoryUnread($link, -2);
1974 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
1976 $age_qpart = getMaxAgeSubquery();
1978 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1979 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
1980 AND id = ref_id AND $age_qpart
1981 AND unread = true)) AS unread FROM ttrss_feeds
1983 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1985 while ($line = db_fetch_assoc($result)) {
1986 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1987 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1988 $line["unread"]."\"/>";
1992 function getCategoryUnread($link, $cat) {
1997 $cat_query = "cat_id = '$cat'";
1999 $cat_query = "cat_id IS NULL";
2002 $age_qpart = getMaxAgeSubquery();
2004 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2006 AND owner_uid = " . $_SESSION["uid"]);
2008 $cat_feeds = array();
2009 while ($line = db_fetch_assoc($result)) {
2010 array_push($cat_feeds, "feed_id = " . $line["id"]);
2013 if (count($cat_feeds) == 0) return 0;
2015 $match_part = implode(" OR ", $cat_feeds);
2017 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2018 FROM ttrss_user_entries,ttrss_entries
2019 WHERE unread = true AND ($match_part) AND id = ref_id
2020 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2024 # this needs to be rewritten
2025 while ($line = db_fetch_assoc($result)) {
2026 $unread +
= $line["unread"];
2030 } else if ($cat == -1) {
2031 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2032 } else if ($cat == -2) {
2034 $rv = getLabelCounters($link, false, true);
2037 foreach (array_keys($rv) as $k) {
2039 $ctr +
= $rv[$k]["counter"];
2047 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2048 if (DB_TYPE
== "pgsql") {
2049 return "ttrss_entries.date_entered >
2050 NOW() - INTERVAL '$days days'";
2052 return "ttrss_entries.date_entered >
2053 DATE_SUB(NOW(), INTERVAL $days DAY)";
2057 function getFeedUnread($link, $feed, $is_cat = false) {
2058 $n_feed = sprintf("%d", $feed);
2060 $age_qpart = getMaxAgeSubquery();
2063 return getCategoryUnread($link, $n_feed);
2064 } else if ($n_feed == -1) {
2065 $match_part = "marked = true";
2066 } else if ($n_feed == -2) {
2067 $match_part = "published = true";
2068 } else if ($n_feed == -3) {
2069 $match_part = "unread = true";
2071 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2073 if (DB_TYPE
== "pgsql") {
2074 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2076 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2079 } else if ($n_feed > 0) {
2081 $result = db_query($link, "SELECT id FROM ttrss_feeds
2082 WHERE parent_feed = '$n_feed'
2084 AND owner_uid = " . $_SESSION["uid"]);
2086 if (db_num_rows($result) > 0) {
2088 $linked_feeds = array();
2089 while ($line = db_fetch_assoc($result)) {
2090 array_push($linked_feeds, "feed_id = " . $line["id"]);
2093 array_push($linked_feeds, "feed_id = $n_feed");
2095 $match_part = implode(" OR ", $linked_feeds);
2097 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2098 FROM ttrss_user_entries,ttrss_entries
2099 WHERE unread = true AND
2100 ttrss_user_entries.ref_id = ttrss_entries.id AND
2103 owner_uid = " . $_SESSION["uid"]);
2107 # this needs to be rewritten
2108 while ($line = db_fetch_assoc($result)) {
2109 $unread +
= $line["unread"];
2115 $match_part = "feed_id = '$n_feed'";
2117 } else if ($feed < -10) {
2119 $label_id = -$feed - 11;
2121 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2122 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2124 $match_part = db_fetch_result($result, 0, "sql_exp");
2129 $result = db_query($link, "SELECT count(int_id) AS unread
2130 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2131 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2132 ttrss_user_entries.ref_id = ttrss_entries.id AND
2133 ttrss_feeds.hidden = false AND
2135 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2139 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2140 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2141 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2142 AND unread = true AND $age_qpart AND
2143 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2146 $unread = db_fetch_result($result, 0, "unread");
2151 /* FIXME this needs reworking */
2153 function getGlobalUnread($link, $user_id = false) {
2156 $user_id = $_SESSION["uid"];
2159 $age_qpart = getMaxAgeSubquery();
2161 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2162 WHERE unread = true AND
2163 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2164 ttrss_user_entries.ref_id = ttrss_entries.id AND
2167 ttrss_user_entries.owner_uid = '$user_id'");
2168 $c_id = db_fetch_result($result, 0, "c_id");
2172 function getGlobalCounters($link, $global_unread = -1) {
2173 if ($global_unread == -1) {
2174 $global_unread = getGlobalUnread($link);
2176 print "<counter type=\"global\" id='global-unread'
2177 counter='$global_unread'/>";
2179 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2180 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2182 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2184 print "<counter type=\"global\" id='subscribed-feeds'
2185 counter='$subscribed_feeds'/>";
2189 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2192 if (!$_SESSION["tctr_last_value"]) {
2193 $_SESSION["tctr_last_value"] = array();
2197 $old_counters = $_SESSION["tctr_last_value"];
2199 $tctrs_modified = false;
2201 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2202 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2203 ttrss_user_entries.ref_id = ttrss_entries.id AND
2204 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2205 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2207 select tag_name,0 as count FROM ttrss_tags
2208 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2210 $age_qpart = getMaxAgeSubquery();
2212 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2213 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2214 AND ref_id = id AND $age_qpart
2215 AND unread = true)) AS count FROM ttrss_tags
2216 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2217 ORDER BY count DESC LIMIT 55");
2221 while ($line = db_fetch_assoc($result)) {
2222 $tags[$line["tag_name"]] +
= $line["count"];
2225 foreach (array_keys($tags) as $tag) {
2226 $unread = $tags[$tag];
2228 $tag = htmlspecialchars($tag);
2230 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2231 $old_counters[$tag] = $unread;
2232 $tctrs_modified = true;
2233 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2238 if ($smart_mode && $tctrs_modified) {
2239 $_SESSION["tctr_last_value"] = $old_counters;
2244 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2246 $age_qpart = getMaxAgeSubquery();
2249 if (!$_SESSION["lctr_last_value"]) {
2250 $_SESSION["lctr_last_value"] = array();
2256 $old_counters = $_SESSION["lctr_last_value"];
2257 $lctrs_modified = false;
2259 $count = getFeedUnread($link, -1);
2262 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2264 $ret_arr["-1"]["counter"] = $count;
2265 $ret_arr["-1"]["description"] = __("Starred articles");
2268 $count = getFeedUnread($link, -2);
2271 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2273 $ret_arr["-2"]["counter"] = $count;
2274 $ret_arr["-2"]["description"] = __("Published articles");
2277 $count = getFeedUnread($link, -3);
2280 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2282 $ret_arr["-3"]["counter"] = $count;
2283 $ret_arr["-3"]["description"] = __("Fresh articles");
2287 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2288 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2290 while ($line = db_fetch_assoc($result)) {
2292 $id = -$line["id"] - 11;
2294 $label_name = $line["description"];
2296 error_reporting (0);
2298 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2299 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2300 ttrss_feeds.hidden = false AND
2302 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2303 ttrss_user_entries.ref_id = ttrss_entries.id AND
2304 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2306 $count = db_fetch_result($tmp_result, 0, "count");
2308 if (!$smart_mode ||
$old_counters[$id] != $count) {
2309 $old_counters[$id] = $count;
2310 $lctrs_modified = true;
2312 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2314 $ret_arr[$id]["counter"] = $count;
2315 $ret_arr[$id]["description"] = $label_name;
2319 error_reporting (DEFAULT_ERROR_LEVEL
);
2322 if ($smart_mode && $lctrs_modified) {
2323 $_SESSION["lctr_last_value"] = $old_counters;
2329 /* function getFeedCounter($link, $id) {
2331 $result = db_query($link, "SELECT
2332 count(id) as count,last_error
2333 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2334 WHERE feed_id = '$id' AND unread = true
2335 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2336 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2338 $count = db_fetch_result($result, 0, "count");
2339 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2341 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2344 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2346 $age_qpart = getMaxAgeSubquery();
2349 if (!$_SESSION["fctr_last_value"]) {
2350 $_SESSION["fctr_last_value"] = array();
2354 $old_counters = $_SESSION["fctr_last_value"];
2356 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2357 SUBSTRING(last_updated,1,19) AS last_updated,
2359 FROM ttrss_entries,ttrss_user_entries
2360 WHERE feed_id = ttrss_feeds.id AND
2361 ttrss_user_entries.ref_id = ttrss_entries.id
2362 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2363 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2364 AND parent_feed IS NULL"); */
2366 $query = "SELECT ttrss_feeds.id,
2368 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2370 COUNT(ttrss_entries.id) AS count
2372 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2373 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2374 AND ttrss_user_entries.unread = true)
2375 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2377 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2378 AND parent_feed IS NULL
2379 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2381 $result = db_query($link, $query);
2382 $fctrs_modified = false;
2384 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2386 while ($line = db_fetch_assoc($result)) {
2389 $count = $line["count"];
2390 $last_error = htmlspecialchars($line["last_error"]);
2392 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2393 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2395 $last_updated = date($short_date, strtotime($line["last_updated"]));
2398 $last_updated = htmlspecialchars($last_updated);
2400 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2402 $tmp_result = db_query($link,
2403 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2404 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2405 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2406 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2407 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2409 if (db_num_rows($tmp_result) > 0) {
2410 while ($l = db_fetch_assoc($tmp_result)) {
2411 $count +
= $l["unread"];
2415 if (!$smart_mode ||
$old_counters[$id] != $count) {
2416 $old_counters[$id] = $count;
2417 $fctrs_modified = true;
2420 $error_part = "error=\"$last_error\"";
2426 $has_img_part = "hi=\"$has_img\"";
2431 if ($active_feed && $id == $active_feed) {
2432 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2434 $has_title_part = "";
2437 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2441 if ($smart_mode && $fctrs_modified) {
2442 $_SESSION["fctr_last_value"] = $old_counters;
2446 function get_script_dt_add() {
2447 if (strpos(VERSION
, ".99") === false) {
2454 function get_pgsql_version($link) {
2455 $result = db_query($link, "SELECT version() AS version");
2456 $version = split(" ", db_fetch_result($result, 0, "version"));
2460 function print_error_xml($code, $add_msg = "") {
2463 $error_msg = $ERRORS[$code];
2466 $error_msg = "$error_msg; $add_msg";
2469 print "<rpc-reply>";
2470 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2471 print "</rpc-reply>";
2474 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2475 $auth_login = '', $auth_pass = '') {
2477 # check for feed:http://url
2478 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2480 # check for feed://URL
2481 if (strpos($feed_link, "//") === 0) {
2482 $feed_link = "http:$feed_link";
2485 if ($feed_link == "") return;
2487 if ($cat_id == "0" ||
!$cat_id) {
2488 $cat_qpart = "NULL";
2490 $cat_qpart = "'$cat_id'";
2493 $result = db_query($link,
2494 "SELECT id FROM ttrss_feeds
2495 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2497 if (db_num_rows($result) == 0) {
2499 $result = db_query($link,
2500 "INSERT INTO ttrss_feeds
2501 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2502 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2503 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2505 $result = db_query($link,
2506 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2507 AND owner_uid = " . $_SESSION["uid"]);
2509 $feed_id = db_fetch_result($result, 0, "id");
2512 update_rss_feed($link, $feed_link, $feed_id, true);
2521 function print_feed_select($link, $id, $default_id = "",
2522 $attributes = "", $include_all_feeds = true) {
2524 print "<select id=\"$id\" name=\"$id\" $attributes>";
2525 if ($include_all_feeds) {
2526 print "<option value=\"0\">".__('All feeds')."</option>";
2529 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2530 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2532 if (db_num_rows($result) > 0 && $include_all_feeds) {
2533 print "<option disabled>--------</option>";
2536 while ($line = db_fetch_assoc($result)) {
2537 if ($line["id"] == $default_id) {
2538 $is_selected = "selected";
2542 printf("<option $is_selected value='%d'>%s</option>",
2543 $line["id"], htmlspecialchars($line["title"]));
2549 function print_feed_cat_select($link, $id, $default_id = "",
2550 $attributes = "", $include_all_cats = true) {
2552 print "<select id=\"$id\" name=\"$id\" $attributes>";
2554 if ($include_all_cats) {
2555 print "<option value=\"0\">".__('Uncategorized')."</option>";
2558 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2559 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2561 if (db_num_rows($result) > 0 && $include_all_cats) {
2562 print "<option disabled>--------</option>";
2565 while ($line = db_fetch_assoc($result)) {
2566 if ($line["id"] == $default_id) {
2567 $is_selected = "selected";
2571 printf("<option $is_selected value='%d'>%s</option>",
2572 $line["id"], htmlspecialchars($line["title"]));
2578 function checkbox_to_sql_bool($val) {
2579 return ($val == "on") ?
"true" : "false";
2582 function getFeedCatTitle($link, $id) {
2584 return __("Special");
2585 } else if ($id < -10) {
2586 return __("Labels");
2587 } else if ($id > 0) {
2588 $result = db_query($link, "SELECT ttrss_feed_categories.title
2589 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2590 cat_id = ttrss_feed_categories.id");
2591 if (db_num_rows($result) == 1) {
2592 return db_fetch_result($result, 0, "title");
2594 return __("Uncategorized");
2597 return "getFeedCatTitle($id) failed";
2602 function getFeedTitle($link, $id) {
2604 return __("Starred articles");
2605 } else if ($id == -2) {
2606 return __("Published articles");
2607 } else if ($id == -3) {
2608 return __("Fresh articles");
2609 } else if ($id < -10) {
2610 $label_id = -10 - $id;
2611 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2612 if (db_num_rows($result) == 1) {
2613 return db_fetch_result($result, 0, "description");
2615 return "Unknown label ($label_id)";
2618 } else if ($id > 0) {
2619 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2620 if (db_num_rows($result) == 1) {
2621 return db_fetch_result($result, 0, "title");
2623 return "Unknown feed ($id)";
2626 return "getFeedTitle($id) failed";
2631 function get_session_cookie_name() {
2632 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2635 function print_init_params($link) {
2636 print "<init-params>";
2637 if ($_SESSION["stored-params"]) {
2638 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2640 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2641 print "<param key=\"$key\" value=\"$value\"/>";
2646 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2647 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2648 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY
. "\"/>";
2650 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2651 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2653 print "<param key=\"hide_read_feeds\" value=\"" .
2654 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2656 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2657 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2659 print "<param key=\"confirm_feed_catchup\" value=\"" .
2660 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2662 print "<param key=\"cdm_auto_catchup\" value=\"" .
2663 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2665 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2667 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2669 print "<param key=\"default_view_mode\" value=\"" .
2670 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2672 print "<param key=\"default_view_limit\" value=\"" .
2673 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2675 print "<param key=\"prefs_active_tab\" value=\"" .
2676 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2678 print "<param key=\"infobox_disable_overlay\" value=\"" .
2679 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2681 print "<param key=\"icons_location\" value=\"" .
2684 print "</init-params>";
2687 function print_runtime_info($link) {
2688 print "<runtime-info>";
2689 if (ENABLE_UPDATE_DAEMON
) {
2690 print "<param key=\"daemon_is_running\" value=\"".
2691 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2693 if ($_SESSION["daemon_stamp_check"] +
600 < time()) {
2695 $stamp = (int)read_stampfile("update_daemon.stamp");
2698 if ($stamp +
86400*3 < time()) {
2699 print "<param key=\"daemon_stamp_ok\" value=\"0\"/>";
2701 print "<param key=\"daemon_stamp_ok\" value=\"1\"/>";
2704 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2706 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2709 $_SESSION["daemon_stamp_check"] = time();
2713 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2715 if ($_SESSION["last_version_check"] +
7200 < time()) {
2716 $new_version_details = check_for_update($link);
2718 print "<param key=\"new_version_available\" value=\"".
2719 sprintf("%d", $new_version_details != ""). "\"/>";
2721 $_SESSION["last_version_check"] = time();
2725 // print "<param key=\"new_version_available\" value=\"1\"/>";
2727 print "</runtime-info>";
2730 function getSearchSql($search, $match_on) {
2732 $search_query_part = "";
2734 $keywords = split(" ", $search);
2735 $query_keywords = array();
2737 if ($match_on == "both") {
2739 foreach ($keywords as $k) {
2740 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2741 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2744 $search_query_part = implode("AND", $query_keywords) . " AND ";
2746 } else if ($match_on == "title") {
2748 foreach ($keywords as $k) {
2749 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2752 $search_query_part = implode("AND", $query_keywords) . " AND ";
2754 } else if ($match_on == "content") {
2756 foreach ($keywords as $k) {
2757 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2761 $search_query_part = implode("AND", $query_keywords);
2763 return $search_query_part;
2766 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
2768 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2772 $search_query_part = getSearchSql($search, $match_on);
2773 $search_query_part .= " AND ";
2776 $search_query_part = "";
2779 $view_query_part = "";
2781 if ($view_mode == "adaptive") {
2783 $view_query_part = " ";
2784 } else if ($feed != -1) {
2785 $unread = getFeedUnread($link, $feed, $cat_view);
2787 $view_query_part = " unread = true AND ";
2792 if ($view_mode == "marked") {
2793 $view_query_part = " marked = true AND ";
2796 if ($view_mode == "unread") {
2797 $view_query_part = " unread = true AND ";
2801 $limit_query_part = "LIMIT " . $limit;
2804 $vfeed_query_part = "";
2806 // override query strategy and enable feed display when searching globally
2807 if ($search && $search_mode == "all_feeds") {
2808 $query_strategy_part = "ttrss_entries.id > 0";
2809 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2810 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2811 $query_strategy_part = "ttrss_entries.id > 0";
2812 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2813 id = feed_id) as feed_title,";
2814 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2816 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2818 $tmp_result = false;
2821 $tmp_result = db_query($link, "SELECT id
2822 FROM ttrss_feeds WHERE cat_id = '$feed'");
2824 $tmp_result = db_query($link, "SELECT id
2825 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2826 WHERE id = '$feed') AND id != '$feed'");
2829 $cat_siblings = array();
2831 if (db_num_rows($tmp_result) > 0) {
2832 while ($p = db_fetch_assoc($tmp_result)) {
2833 array_push($cat_siblings, "feed_id = " . $p["id"]);
2836 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2837 $feed, implode(" OR ", $cat_siblings));
2840 $query_strategy_part = "ttrss_entries.id > 0";
2843 } else if ($feed >= 0) {
2848 $query_strategy_part = "cat_id = '$feed'";
2850 $query_strategy_part = "cat_id IS NULL";
2853 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2856 $tmp_result = db_query($link, "SELECT id
2857 FROM ttrss_feeds WHERE parent_feed = '$feed'
2858 ORDER BY cat_id,title");
2860 $parent_ids = array();
2862 if (db_num_rows($tmp_result) > 0) {
2863 while ($p = db_fetch_assoc($tmp_result)) {
2864 array_push($parent_ids, "feed_id = " . $p["id"]);
2867 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2868 $feed, implode(" OR ", $parent_ids));
2870 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2872 $query_strategy_part = "feed_id = '$feed'";
2875 } else if ($feed == -1) { // starred virtual feed
2876 $query_strategy_part = "marked = true";
2877 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2878 } else if ($feed == -2) { // published virtual feed
2879 $query_strategy_part = "published = true";
2880 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2881 } else if ($feed == -3) { // fresh virtual feed
2882 $query_strategy_part = "unread = true";
2884 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2886 if (DB_TYPE
== "pgsql") {
2887 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2889 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2892 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2893 } else if ($feed <= -10) { // labels
2894 $label_id = -$feed - 11;
2896 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2897 WHERE id = '$label_id'");
2899 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2901 if (!$query_strategy_part) {
2905 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2907 $query_strategy_part = "id > 0"; // dumb
2910 if (get_pref($link, 'REVERSE_HEADLINES')) {
2911 $order_by = "updated";
2913 $order_by = "updated DESC";
2916 if ($override_order) {
2917 $order_by = $override_order;
2922 if ($search && $search_mode == "all_feeds") {
2923 $feed_title = __("Search results")." ($search)";
2924 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2925 $feed_title = __("Search results")." ($search, $feed)";
2926 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2927 $feed_title = $feed;
2928 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2933 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2934 WHERE id = '$feed' AND owner_uid = $owner_uid");
2935 $feed_title = db_fetch_result($result, 0, "title");
2937 $feed_title = __("Uncategorized");
2941 $feed_title = __("Searched for")." $search ($feed_title)";
2946 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2947 WHERE id = '$feed' AND owner_uid = $owner_uid");
2949 $feed_title = db_fetch_result($result, 0, "title");
2950 $feed_site_url = db_fetch_result($result, 0, "site_url");
2951 $last_error = db_fetch_result($result, 0, "last_error");
2954 $feed_title = __("Searched for") . " $search ($feed_title)";
2958 } else if ($feed == -1) {
2959 $feed_title = __("Starred articles");
2960 } else if ($feed == -2) {
2961 $feed_title = __("Published articles");
2962 } else if ($feed == -3) {
2963 $feed_title = __("Fresh articles");
2964 } else if ($feed < -10) {
2965 $label_id = -$feed - 11;
2966 $result = db_query($link, "SELECT description FROM ttrss_labels
2967 WHERE id = '$label_id'");
2968 $feed_title = db_fetch_result($result, 0, "description");
2971 $feed_title = __("Searched for") . " $search ($feed_title)";
2977 if ($feed < -10) error_reporting (0);
2979 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2982 $feed_kind = "Feeds";
2984 $feed_kind = "Labels";
2987 $content_query_part = "content as content_preview,";
2989 if ($limit_query_part) {
2990 $offset_query_part = "OFFSET $offset";
2995 ttrss_entries.id,ttrss_entries.title,
2997 unread,feed_id,marked,published,link,last_read,
2998 SUBSTRING(last_read,1,19) as last_read_noms,
3001 SUBSTRING(updated,1,19) as updated_noms,
3004 ttrss_entries,ttrss_user_entries,ttrss_feeds
3006 ttrss_feeds.hidden = false AND
3007 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3008 ttrss_user_entries.ref_id = ttrss_entries.id AND
3009 ttrss_user_entries.owner_uid = '$owner_uid' AND
3012 $query_strategy_part ORDER BY $order_by
3013 $limit_query_part $offset_query_part";
3015 $result = db_query($link, $query);
3017 if ($_GET["debug"]) print $query;
3022 $feed_kind = "Tags";
3024 $result = db_query($link, "SELECT
3026 ttrss_entries.id as id,title,
3029 marked,link,last_read,
3030 SUBSTRING(last_read,1,19) as last_read_noms,
3033 SUBSTRING(updated,1,19) as updated_noms
3035 ttrss_entries,ttrss_user_entries,ttrss_tags
3037 ref_id = ttrss_entries.id AND
3038 ttrss_user_entries.owner_uid = '$owner_uid' AND
3039 post_int_id = int_id AND tag_name = '$feed' AND
3042 $query_strategy_part ORDER BY $order_by
3043 $limit_query_part");
3046 return array($result, $feed_title, $feed_site_url, $last_error);
3050 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3051 $search, $search_mode, $match_on) {
3053 $qfh_ret = queryFeedHeadlines($link, $feed,
3054 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3057 $result = $qfh_ret[0];
3058 $feed_title = htmlspecialchars($qfh_ret[1]);
3059 $feed_site_url = $qfh_ret[2];
3060 $last_error = $qfh_ret[3];
3062 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3064 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3065 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3066 <rss version=\"2.0\">
3068 <title>$feed_title</title>
3069 <link>$feed_site_url</link>
3070 <description>Feed generated by Tiny Tiny RSS</description>";
3072 while ($line = db_fetch_assoc($result)) {
3074 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3075 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3077 $tags = get_article_tags($link, $line["id"], $owner_uid);
3079 foreach ($tags as $tag) {
3080 print "<category>" . htmlspecialchars($tag) . "</category>";
3083 $rfc822_date = date('r', strtotime($line["updated"]));
3085 print "<pubDate>$rfc822_date</pubDate>";
3088 htmlspecialchars($line["title"]) . "</title>";
3090 print "<description><![CDATA[" .
3091 $line["content_preview"] . "]]></description>";
3096 print "</channel></rss>";
3100 function getCategoryTitle($link, $cat_id) {
3102 if ($cat_id == -1) {
3103 return __("Special");
3104 } else if ($cat_id == -2) {
3105 return __("Labels");
3108 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3111 if (db_num_rows($result) == 1) {
3112 return db_fetch_result($result, 0, "title");
3114 return "Uncategorized";
3119 // http://ru2.php.net/strip-tags
3121 function strip_tags_long($textstring, $allowed){
3122 while($textstring != strip_tags($textstring, $allowed))
3124 while (strlen($textstring) != 0)
3126 if (strlen($textstring) > 1024) {
3129 $otherlen = strlen($textstring);
3131 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3132 $safetext .= $temptext;
3133 $textstring = substr_replace($textstring,'',0,$otherlen);
3135 $textstring = $safetext;
3141 function sanitize_rss($link, $str, $force_strip_tags = false) {
3144 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3146 global $tw_paranoya_setup;
3148 $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
3150 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3151 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3157 function send_headlines_digests($link, $limit = 100) {
3159 if (!DIGEST_ENABLE
) return false;
3161 $user_limit = DIGEST_EMAIL_LIMIT
;
3164 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3166 if (DB_TYPE
== "pgsql") {
3167 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3168 } else if (DB_TYPE
== "mysql") {
3169 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3172 $result = db_query($link, "SELECT id,email FROM ttrss_users
3173 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3175 while ($line = db_fetch_assoc($result)) {
3176 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3177 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3179 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3180 $digest = $tuple[0];
3181 $headlines_count = $tuple[1];
3183 if ($headlines_count > 0) {
3185 if (!DIGEST_SMTP_HOST
) {
3187 $rc = mail($line["login"] . " <" . $line["email"] . ">",
3188 "[tt-rss] New headlines for last 24 hours", $digest,
3189 "From: " . DIGEST_FROM_NAME
. " <" . DIGEST_FROM_ADDRESS
. ">\n".
3190 "Content-Type: text/plain; charset=\"utf-8\"\n".
3191 "Content-Transfer-Encoding: 8bit\n");
3195 $mail = new PHPMailer();
3197 $mail->PluginDir
= "phpmailer/";
3198 $mail->SetLanguage("en", "phpmailer/language/");
3200 $mail->CharSet
= "UTF-8";
3202 $mail->From
= DIGEST_FROM_ADDRESS
;
3203 $mail->FromName
= DIGEST_FROM_NAME
;
3204 $mail->AddAddress($line["email"], $line["login"]);
3205 $mail->Host
= DIGEST_SMTP_HOST
;
3206 $mail->Mailer
= "smtp";
3208 $mail->Username
= DIGEST_SMTP_LOGIN
;
3209 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3211 $mail->Subject
= "[tt-rss] New headlines for last 24 hours";
3212 $mail->Body
= $digest;
3214 $rc = $mail->Send();
3216 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3222 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3223 WHERE id = " . $line["id"]);
3225 print "No headlines\n";
3230 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
3234 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3235 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
3236 $tmp .= "=======================================================\n\n";
3238 if (DB_TYPE
== "pgsql") {
3239 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3240 } else if (DB_TYPE
== "mysql") {
3241 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3244 $result = db_query($link, "SELECT ttrss_entries.title,
3245 ttrss_feeds.title AS feed_title,
3248 SUBSTRING(last_updated,1,19) AS last_updated
3250 ttrss_user_entries,ttrss_entries,ttrss_feeds
3252 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3253 AND include_in_digest = true
3256 AND ttrss_user_entries.owner_uid = $user_id
3257 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
3260 $cur_feed_title = "";
3262 $headlines_count = db_num_rows($result);
3264 while ($line = db_fetch_assoc($result)) {
3265 $updated = smart_date_time(strtotime($line["last_updated"]));
3266 $feed_title = $line["feed_title"];
3268 if ($cur_feed_title != $feed_title) {
3269 $cur_feed_title = $feed_title;
3271 $tmp .= "$feed_title\n\n";
3274 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
3275 $tmp .= " " . trim($line["link"]) . "\n";
3280 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
3281 DIGEST_HOSTNAME
. "\n".
3282 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
3285 return array($tmp, $headlines_count);
3288 function check_for_update($link, $brief_fmt = true) {
3289 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3291 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3296 if (ENABLE_SIMPLEPIE
) {
3297 $rss = new SimplePie();
3298 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3299 $rss->set_timeout(MAGPIE_FETCH_TIME_OUT
);
3300 $rss->set_feed_url($fetch_url);
3301 $rss->set_output_encoding('UTF-8');
3304 $rss = fetch_rss($releases_feed);
3306 error_reporting (DEFAULT_ERROR_LEVEL
);
3310 if (ENABLE_SIMPLEPIE
) {
3311 $items = $rss->get_items();
3313 $items = $rss->items
;
3315 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3316 if (!$items ||
!is_array($items)) $items = $rss;
3319 if (!is_array($items) ||
count($items) == 0) {
3323 $latest_item = $items[0];
3325 if (ENABLE_SIMPLEPIE
) {
3326 $last_title = $latest_item->get_title();
3328 $last_title = $latest_item["title"];
3331 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3333 if (ENABLE_SIMPLEPIE
) {
3334 $release_url = sanitize_rss($link, $latest_item->get_link());
3335 $content = sanitize_rss($link, $latest_item->get_description());
3337 $release_url = sanitize_rss($link, $latest_item["link"]);
3338 $content = sanitize_rss($link, $latest_item["description"]);
3341 if (version_compare(VERSION
, $latest_version) == -1) {
3343 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3344 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3345 <div id=\"milestoneDetails\">$content</div>");
3347 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3348 <div class='milestoneDetails'>$content</div>
3349 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3350 download and update information.";
3357 function markArticlesById($link, $ids, $cmode) {
3361 foreach ($ids as $id) {
3362 array_push($tmp_ids, "ref_id = '$id'");
3365 $ids_qpart = join(" OR ", $tmp_ids);
3368 db_query($link, "UPDATE ttrss_user_entries SET
3369 marked = false,last_read = NOW()
3370 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3371 } else if ($cmode == 1) {
3372 db_query($link, "UPDATE ttrss_user_entries SET
3374 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3376 db_query($link, "UPDATE ttrss_user_entries SET
3377 marked = NOT marked,last_read = NOW()
3378 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3382 function publishArticlesById($link, $ids, $cmode) {
3386 foreach ($ids as $id) {
3387 array_push($tmp_ids, "ref_id = '$id'");
3390 $ids_qpart = join(" OR ", $tmp_ids);
3393 db_query($link, "UPDATE ttrss_user_entries SET
3394 published = false,last_read = NOW()
3395 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3396 } else if ($cmode == 1) {
3397 db_query($link, "UPDATE ttrss_user_entries SET
3399 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3401 db_query($link, "UPDATE ttrss_user_entries SET
3402 published = NOT published,last_read = NOW()
3403 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3407 function catchupArticlesById($link, $ids, $cmode) {
3411 foreach ($ids as $id) {
3412 array_push($tmp_ids, "ref_id = '$id'");
3415 $ids_qpart = join(" OR ", $tmp_ids);
3418 db_query($link, "UPDATE ttrss_user_entries SET
3419 unread = false,last_read = NOW()
3420 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3421 } else if ($cmode == 1) {
3422 db_query($link, "UPDATE ttrss_user_entries SET
3424 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3426 db_query($link, "UPDATE ttrss_user_entries SET
3427 unread = NOT unread,last_read = NOW()
3428 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3432 function catchupArticleById($link, $id, $cmode) {
3435 db_query($link, "UPDATE ttrss_user_entries SET
3436 unread = false,last_read = NOW()
3437 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3438 } else if ($cmode == 1) {
3439 db_query($link, "UPDATE ttrss_user_entries SET
3441 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3443 db_query($link, "UPDATE ttrss_user_entries SET
3444 unread = NOT unread,last_read = NOW()
3445 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3449 function make_guid_from_title($title) {
3450 return preg_replace("/[ \"\',.:;]/", "-",
3451 mb_strtolower(strip_tags($title), 'utf-8'));
3454 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3455 $bottom = false, $rtl_content = false, $feed_id = 0,
3456 $is_cat = false, $search = false, $match_on = false,
3457 $search_mode = false, $offset = 0, $limit = 0) {
3459 $user_page_offset = $offset +
1;
3462 $class = "headlinesSubToolbar";
3463 $tid = "headlineActionsTop";
3465 $class = "headlinesSubToolbar";
3466 $tid = "headlineActionsBottom";
3469 print "<table class=\"$class\" id=\"$tid\"
3470 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3478 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3479 $page_next_link = "javascript:viewFeedGoPage(1)";
3480 $page_first_link = "javascript:viewFeedGoPage(0)";
3482 $catchup_page_link = "javascript:catchupPage()";
3483 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3484 $catchup_sel_link = "javascript:catchupSelection()";
3486 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3488 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3489 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3490 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3492 $tog_unread_link = "javascript:selectionToggleUnread()";
3493 $tog_marked_link = "javascript:selectionToggleMarked()";
3494 $tog_published_link = "javascript:selectionTogglePublished()";
3498 $sel_all_link = "javascript:cdmSelectArticles('all')";
3499 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3500 $sel_none_link = "javascript:cdmSelectArticles('none')";
3502 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3503 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3504 $tog_published_link = "javascript:selectionTogglePublished(true)";
3508 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3510 print "<td class=\"headlineActions$rtl_cpart\">
3511 <ul class=\"headlineDropdownMenu\">
3514 <a href=\"$sel_all_link\">".__('All')."</a>,
3515 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3516 <a href=\"$sel_none_link\">".__('None')."</a></li>
3517 <li class=\"vsep\"> </li>
3518 <li class=\"top\">".__('Toggle')."<ul>
3519 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3520 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3521 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3523 <li class=\"vsep\"> </li>
3524 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
3525 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3526 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->
3527 <li><span class=\"insensitive\">--------</span></li>
3528 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3529 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3530 <li><span class=\"insensitive\">--------</span></li>
3531 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3534 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3536 if ($limit != 0 && !$search && $enable_pagination) {
3538 <li class=\"vsep\"> </li>
3539 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3540 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3541 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3545 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3547 <li class=\"vsep\"> </li>
3549 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3550 '$match_on', '$feed_id', '$is_cat');\">
3551 ".__('Convert to label')."</a></td>";
3557 // old style subtoolbar:
3559 print "<td class=\"headlineActions$rtl_cpart\">".
3561 <a href=\"$sel_all_link\">".__('All')."</a>,
3562 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3563 <a href=\"$sel_none_link\">".__('None')."</a>
3565 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3566 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3568 __('Mark as read:')."
3569 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3570 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3572 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3575 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3576 '$match_on', '$feed_id', '$is_cat');\">
3577 ".__('Convert to label')."</a>";
3584 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3585 print "<td class=\"headlineActions$rtl_cpart\">
3586 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3587 '$match_on', '$feed_id', '$is_cat');\">
3588 ".__('Convert to Label')."</a></td>";
3591 print "<td class=\"headlineTitle$rtl_cpart\">";
3593 if ($feed_site_url) {
3595 $target = "target=\"_new\"";
3597 print "<a $target href=\"$feed_site_url\">".
3598 truncate_string($feed_title,30)."</a>";
3604 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3607 if ($user_page_offset > 1) {
3608 print " [$user_page_offset] ";
3614 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3615 <img class=\"noborder\"
3616 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3621 print "</tr></table>";
3625 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3627 $tmp_category = getCategoryTitle($link, $cat_id);
3628 $cat_unread = getCategoryUnread($link, $cat_id);
3631 $holder_style = "display:none;";
3638 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3640 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3641 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3644 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3646 print "<span id=\"FCAP-$cat_id\">";
3649 print " <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3650 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
3660 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3663 function outputFeedList($link, $tags = false) {
3665 print "<ul class=\"feedList\" id=\"feedList\">";
3667 $owner_uid = $_SESSION["uid"];
3671 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3673 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
3676 $cat_hidden = false;
3679 # print "<li class=\"feedCat\">".__('Special')."</li>";
3680 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3681 # print "<li class=\"feedCat\">".
3682 # "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
3683 # __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
3685 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
3686 # <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
3688 # $cat_unread = getCategoryUnread($link, -1);
3689 # $tmp_category = __("Special");
3690 # $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3692 printCategoryHeader($link, -1, $cat_hidden, false);
3695 $num_starred = getFeedUnread($link, -1);
3696 $num_published = getFeedUnread($link, -2);
3697 $num_fresh = getFeedUnread($link, -3);
3701 if ($num_fresh > 0) $class .= "Unread";
3703 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
3704 "images/fresh.png", $link);
3708 if ($num_starred > 0) $class .= "Unread";
3710 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
3713 $mark_img_ext = "gif";
3715 $mark_img_ext = "png";
3718 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
3719 "images/mark_set.$mark_img_ext", $link);
3723 if ($num_published > 0) $class .= "Unread";
3725 printFeedEntry(-2, $class, __("Published articles"), $num_published,
3726 "images/pub_set.gif", $link);
3728 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3734 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
3736 $result = db_query($link, "SELECT id,sql_exp,description FROM
3737 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3739 if (db_num_rows($result) > 0) {
3740 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3742 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
3745 $cat_hidden = false;
3748 printCategoryHeader($link, -2, $cat_hidden, false);
3750 # print "<li class=\"feedCat\">".
3751 # "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
3752 # __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
3754 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
3756 print "<li><hr></li>";
3760 while ($line = db_fetch_assoc($result)) {
3762 error_reporting (0);
3764 $label_id = -$line['id'] - 11;
3765 $count = getFeedUnread($link, $label_id);
3773 error_reporting (DEFAULT_ERROR_LEVEL
);
3775 printFeedEntry($label_id,
3776 $class, $line["description"],
3777 $count, "images/label.png", $link);
3781 if (db_num_rows($result) > 0) {
3782 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3789 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3790 print "<li><hr></li>";
3793 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3794 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3795 $order_by_qpart = "category,unread DESC,title";
3797 $order_by_qpart = "category,title";
3800 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3801 $order_by_qpart = "unread DESC,title";
3803 $order_by_qpart = "title";
3807 $age_qpart = getMaxAgeSubquery();
3809 $result = db_query($link, "SELECT ttrss_feeds.*,
3810 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3811 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3812 WHERE feed_id = ttrss_feeds.id AND unread = true
3814 AND ttrss_user_entries.ref_id = ttrss_entries.id
3815 AND owner_uid = '$owner_uid') as unread,
3817 ttrss_feed_categories.title AS category,
3818 ttrss_feed_categories.collapsed
3819 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
3820 ON (ttrss_feed_categories.id = cat_id)
3822 ttrss_feeds.hidden = false AND
3823 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3824 ORDER BY $order_by_qpart");
3826 $actid = $_GET["actid"];
3836 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3838 while ($line = db_fetch_assoc($result)) {
3840 $feed = trim($line["title"]);
3842 if (!$feed) $feed = "[Untitled]";
3844 $feed_id = $line["id"];
3846 $subop = $_GET["subop"];
3848 $unread = $line["unread"];
3850 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3851 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3853 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3856 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3859 $rtl_tag = "dir=\"RTL\"";
3864 $tmp_result = db_query($link,
3865 "SELECT id,COUNT(unread) AS unread
3866 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
3867 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
3868 WHERE parent_feed = '$feed_id' AND unread = true
3869 GROUP BY ttrss_feeds.id");
3871 if (db_num_rows($tmp_result) > 0) {
3872 while ($l = db_fetch_assoc($tmp_result)) {
3873 $unread +
= $l["unread"];
3877 $cat_id = $line["cat_id"];
3879 $tmp_category = $line["category"];
3881 if (!$tmp_category) {
3882 $tmp_category = __("Uncategorized");
3885 // $class = ($lnum % 2) ? "even" : "odd";
3887 if ($line["last_error"]) {
3893 if ($unread > 0) $class .= "Unread";
3895 if ($actid == $feed_id) {
3896 $class .= "Selected";
3899 $total_unread +
= $unread;
3901 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3907 $category = $tmp_category;
3909 $collapsed = $line["collapsed"];
3911 // workaround for NULL category
3912 if ($category == __("Uncategorized")) {
3913 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3918 if ($collapsed == "t" ||
$collapsed == "1") {
3919 $holder_class = "feedCatHolder";
3920 $holder_style = "display:none;";
3923 $holder_class = "feedCatHolder";
3928 $cat_id = sprintf("%d", $cat_id);
3930 $cat_unread = getCategoryUnread($link, $cat_id);
3932 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3934 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3935 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3936 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3937 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3938 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3941 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3944 printFeedEntry($feed_id, $class, $feed, $unread,
3945 ICONS_DIR
."/$feed_id.ico", $link, $rtl_content,
3946 $last_updated, $line["last_error"]);
3951 if (db_num_rows($result) == 0) {
3952 print "<li>".__('No feeds to display.')."</li>";
3959 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3960 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3961 post_int_id = ttrss_user_entries.int_id AND
3962 unread = true AND ref_id = ttrss_entries.id
3963 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3965 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3966 ORDER BY tag_name"); */
3968 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3969 print "<li class=\"feedCat\">".__('Tags')."</li>";
3970 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3973 $age_qpart = getMaxAgeSubquery();
3975 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3976 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
3977 AND ref_id = id AND $age_qpart
3978 AND unread = true)) AS count FROM ttrss_tags
3979 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
3980 ORDER BY count DESC LIMIT 50");
3984 while ($line = db_fetch_assoc($result)) {
3985 $tags[$line["tag_name"]] +
= $line["count"];
3988 foreach (array_keys($tags) as $tag) {
3990 $unread = $tags[$tag];
3998 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4002 if (db_num_rows($result) == 0) {
4003 print "<li>No tags to display.</li>";
4006 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4016 function get_article_tags($link, $id, $owner_uid = 0) {
4018 $a_id = db_escape_string($id);
4020 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4022 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4023 owner_uid as owner FROM
4024 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4025 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4029 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4030 array_push($tags, $tmp_line["tag_name"]);
4036 function trim_value(&$value) {
4037 $value = trim($value);
4040 function trim_array($array) {
4042 array_walk($tmp, 'trim_value');
4046 function tag_is_valid($tag) {
4047 if ($tag == '') return false;
4048 if (preg_match("/^[0-9]*$/", $tag)) return false;
4050 $tag = iconv("utf-8", "utf-8", $tag);
4051 if (!$tag) return false;
4056 function render_login_form($link, $mobile = false) {
4058 require_once "login_form.php";
4060 require_once "mobile/login_form.php";
4064 // from http://developer.apple.com/internet/safari/faq.html
4065 function no_cache_incantation() {
4066 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4067 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4068 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4069 header("Cache-Control: post-check=0, pre-check=0", false);
4070 header("Pragma: no-cache"); // HTTP/1.0
4073 function format_warning($msg, $id = "") {
4074 return "<div class=\"warning\" id=\"$id\">
4075 <img src=\"images/sign_excl.gif\">$msg</div>";
4078 function format_notice($msg) {
4079 return "<div class=\"notice\">
4080 <img src=\"images/sign_info.gif\">$msg</div>";
4083 function format_error($msg) {
4084 return "<div class=\"error\">
4085 <img src=\"images/sign_excl.gif\">$msg</div>";
4088 function print_notice($msg) {
4089 return print format_notice($msg);
4092 function print_warning($msg) {
4093 return print format_warning($msg);
4096 function print_error($msg) {
4097 return print format_error($msg);
4101 function T_sprintf() {
4102 $args = func_get_args();
4103 return vsprintf(__(array_shift($args)), $args);
4106 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4108 /* we can figure out feed_id from article id anyway, why do we
4109 * pass feed_id here? */
4111 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4112 WHERE ref_id = '$id'");
4114 $feed_id = db_fetch_result($result, 0, "feed_id");
4116 print "<article id='$id'><![CDATA[";
4118 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4119 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4121 if (db_num_rows($result) == 1) {
4122 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4124 $rtl_content = false;
4128 $rtl_tag = "dir=\"RTL\"";
4135 if ($mark_as_read) {
4136 $result = db_query($link, "UPDATE ttrss_user_entries
4137 SET unread = false,last_read = NOW()
4138 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4141 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4142 SUBSTRING(updated,1,16) as updated,
4143 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4146 FROM ttrss_entries,ttrss_user_entries
4147 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4153 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4154 $link_target = "target=\"_new\"";
4157 $line = db_fetch_assoc($result);
4159 if ($line["icon_url"]) {
4160 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4162 $feed_icon = " ";
4165 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4166 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4168 $entry_comments = "";
4171 $num_comments = $line["num_comments"];
4172 $entry_comments = "";
4174 if ($num_comments > 0) {
4175 if ($line["comments"]) {
4176 $comments_url = $line["comments"];
4178 $comments_url = $line["link"];
4180 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4182 if ($line["comments"] && $line["link"] != $line["comments"]) {
4183 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4187 print "<div class=\"postReply\">";
4189 print "<div class=\"postHeader\">";
4191 $entry_author = $line["author"];
4193 if ($entry_author) {
4194 $entry_author = __(" - by ") . $entry_author;
4197 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4198 strtotime($line["updated"]));
4200 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4202 if ($line["link"]) {
4203 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4204 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4206 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4209 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4210 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4211 ORDER BY tag_name"); */
4213 $tags = get_article_tags($link, $id);
4220 foreach ($tags as $tag) {
4222 $tag_escaped = str_replace("'", "\\'", $tag);
4224 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4226 if ($num_tags == 6) {
4229 } else if ($num_tags < 6) {
4230 $tags_str .= $tag_str;
4232 $f_tags_str .= $tag_str;
4235 $tags_str = preg_replace("/, $/", "", $tags_str);
4236 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4238 $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4239 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4241 if (!$entry_comments) $entry_comments = " "; # placeholder
4243 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4245 print "<div style='float : right'>
4246 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4248 <a title=\"Edit tags for this article\"
4249 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4250 <div clear='both'>$entry_comments</div>";
4254 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4255 print "<div class=\"postContent\">";
4257 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4259 $line["content"] = sanitize_rss($link, $line["content"]);
4261 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4262 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4265 print $line["content"] . "</div>";
4271 print "]]></article>";
4275 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4276 $next_unread_feed, $offset) {
4278 $timing_info = getmicrotime();
4280 $topmost_article_ids = array();
4286 if ($subop == "undefined") $subop = "";
4288 if ($subop == "CatchupSelected") {
4289 $ids = split(",", db_escape_string($_GET["ids"]));
4290 $cmode = sprintf("%d", $_GET["cmode"]);
4292 catchupArticlesById($link, $ids, $cmode);
4295 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4296 update_generic_feed($link, $feed, $cat_view);
4299 if ($subop == "MarkAllRead") {
4300 catchup_feed($link, $feed, $cat_view);
4302 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4303 if ($next_unread_feed) {
4304 $feed = $next_unread_feed;
4310 $result = db_query($link,
4311 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4313 if (db_num_rows($result) == 0) {
4314 print "<div align='center'>".__('Feed not found.')."</div>";
4319 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4321 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4322 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4324 if (db_num_rows($result) == 1) {
4325 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4327 $rtl_content = false;
4331 $rtl_tag = "dir=\"RTL\"";
4337 $rtl_content = false;
4340 $script_dt_add = get_script_dt_add();
4342 /// START /////////////////////////////////////////////////////////////////////////////////
4344 $search = db_escape_string($_GET["query"]);
4345 $search_mode = db_escape_string($_GET["search_mode"]);
4346 $match_on = db_escape_string($_GET["match_on"]);
4352 $real_offset = $offset * $limit;
4354 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4356 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4357 $search, $search_mode, $match_on, false, $real_offset);
4359 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4361 $result = $qfh_ret[0];
4362 $feed_title = $qfh_ret[1];
4363 $feed_site_url = $qfh_ret[2];
4364 $last_error = $qfh_ret[3];
4367 $feed_site_url = article_publish_url($link);
4370 /// STOP //////////////////////////////////////////////////////////////////////////////////
4373 print "<div id=\"headlinesContainer\" $rtl_tag>";
4376 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4380 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4381 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4384 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4387 $headlines_count = db_num_rows($result);
4389 if (db_num_rows($result) > 0) {
4391 # print "\{$offset}";
4393 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4394 print "<table class=\"headlinesList\" id=\"headlinesList\"
4395 cellspacing=\"0\">";
4398 $lnum = $limit*$offset;
4400 error_reporting (DEFAULT_ERROR_LEVEL
);
4404 while ($line = db_fetch_assoc($result)) {
4406 $class = ($lnum %
2) ?
"even" : "odd";
4409 $feed_id = $line["feed_id"];
4411 if (count($topmost_article_ids) < 5) {
4412 array_push($topmost_article_ids, $id);
4415 if ($line["last_read"] == "" &&
4416 ($line["unread"] != "t" && $line["unread"] != "1")) {
4418 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4421 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4425 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4433 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4436 $mark_img_ext = "gif";
4438 $mark_img_ext = "png";
4441 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4442 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4444 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4446 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4448 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4451 if ($line["published"] == "t" ||
$line["published"] == "1") {
4452 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4454 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4456 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4458 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4461 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4462 # $line["title"] . "</a>";
4464 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4465 $line["title"] . "</a>";
4467 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4468 # $line["title"] . "</a>";
4470 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4471 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4473 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4474 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4477 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4478 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4482 $entry_author = $line["author"];
4484 if ($entry_author) {
4485 $entry_author = " - by $entry_author";
4488 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4490 print "<tr class='$class' id='RROW-$id'>";
4492 print "<td class='hlUpdPic'>$update_pic</td>";
4494 print "<td class='hlSelectRow'>
4495 <input type=\"checkbox\" onclick=\"tSR(this)\"
4499 print "<td class='hlMarkedPic'>$marked_pic</td>";
4500 print "<td class='hlMarkedPic'>$published_pic</td>";
4502 # if ($line["feed_title"]) {
4503 # print "<td class='hlContent'>$content_link</td>";
4504 # print "<td class='hlFeed'>
4505 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4506 # truncate_string($line["feed_title"],30)."</a> </td>";
4509 print "<td class='hlContent' valign='middle'>";
4511 print "<a href=\"javascript:view($id,$feed_id);\">" .
4514 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4515 if ($content_preview) {
4516 print "<span class=\"contentPreview\"> - $content_preview</span>";
4522 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4523 # $line["feed_title"]."</a>
4525 if ($line["feed_title"]) {
4526 print "<span class=\"hlFeed\">
4527 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4528 $line["feed_title"]."</a>)
4537 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
4544 $add_class = "Unread";
4549 print "<div class=\"cdmArticle$add_class\"
4550 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4551 onmouseout='cdmMouseOut(this)'>";
4553 print "<div class=\"cdmHeader\">";
4555 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4557 print "<a class=\"title\"
4558 onclick=\"javascript:toggleUnread($id, 0)\"
4559 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4561 print $entry_author;
4563 if ($line["feed_title"]) {
4564 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4569 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4570 $line["content_preview"] = preg_replace("/href=/i",
4571 "target=\"_new\" href=", $line["content_preview"]);
4574 print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
4576 print "<div class=\"cdmFooter\"><span class='s0'>";
4578 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
4580 print __("Select:").
4581 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
4582 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
4584 print "</span><span class='s1'>$marked_pic</span> ";
4585 print "<span class='s1'>$published_pic</span> ";
4587 $tags = get_article_tags($link, $id);
4590 $full_tags_str = "";
4593 foreach ($tags as $tag) {
4595 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
4596 if ($num_tags < 5) {
4597 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
4598 } else if ($num_tags == 5) {
4603 $tags_str = preg_replace("/, $/", "", $tags_str);
4604 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
4606 $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
4608 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4611 if ($tags_str == "") $tags_str = "no tags";
4613 // print "<img src='images/tag.png' class='markedPic'>";
4615 print "<span class='s1'>
4616 <img class='tagsPic' src='images/tag.png' alt='Tags'
4617 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
4618 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
4622 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
4623 href=\"javascript:toggleUnread($id)\">
4634 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4638 // print_headline_subtoolbar($link,
4639 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
4643 if (!$offset) print "<div class='whiteBox'>".__('No articles found.')."</div>";
4651 return array($topmost_article_ids, $headlines_count);
4654 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
4656 function printTagCloud($link) {
4658 /* get first ref_id to count from */
4664 if (DB_TYPE == "pgsql") {
4665 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
4666 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
4667 AND date_entered > NOW() - INTERVAL '30 days'";
4669 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
4670 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
4671 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
4674 $result = db_query($link, $query);
4675 $first_id = db_fetch_result($result, 0, "id"); */
4677 //AND post_int_id >= '$first_id'
4678 $query = "SELECT tag_name, COUNT(post_int_id) AS count
4679 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
4680 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
4682 $result = db_query($link, $query);
4686 while ($line = db_fetch_assoc($result)) {
4687 $tags[$line["tag_name"]] = $line["count"];
4692 $max_size = 32; // max font size in pixels
4693 $min_size = 11; // min font size in pixels
4695 // largest and smallest array values
4696 $max_qty = max(array_values($tags));
4697 $min_qty = min(array_values($tags));
4699 // find the range of values
4700 $spread = $max_qty - $min_qty;
4701 if ($spread == 0) { // we don't want to divide by zero
4705 // set the font-size increment
4706 $step = ($max_size - $min_size) / ($spread);
4708 // loop through the tag array
4709 foreach ($tags as $key => $value) {
4710 // calculate font-size
4711 // find the $value in excess of $min_qty
4712 // multiply by the font-size increment ($size)
4713 // and add the $min_size set above
4714 $size = round($min_size +
(($value - $min_qty) * $step));
4716 $key_escaped = str_replace("'", "\\'", $key);
4718 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
4719 $size . "px\" title=\"$value articles tagged with " .
4720 $key . '">' . $key . '</a> ';
4724 function print_checkpoint($n, $s) {
4725 $ts = getmicrotime();
4726 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
4730 function sanitize_tag($tag) {
4733 $tag = mb_strtolower($tag, 'utf-8');
4735 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
4737 // $tag = str_replace('"', "", $tag);
4738 // $tag = str_replace("+", " ", $tag);
4739 $tag = str_replace("technorati tag: ", "", $tag);
4744 function generate_publish_key() {
4745 return sha1(uniqid(rand(), true));
4748 function article_publish_url($link) {
4750 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
4752 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
4757 function clear_feed_articles($link, $id) {
4758 $result = db_query($link, "DELETE FROM ttrss_user_entries
4759 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
4761 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
4762 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
4765 function add_feed_url() {
4766 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
4767 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
4771 function encrypt_password($pass, $login = '') {
4773 return "SHA1X:" . sha1("$login:$pass");
4775 return "SHA1:" . sha1($pass);