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';
12 * Return available translations names.
15 * @return array A array of available translations.
17 function get_translations() {
19 "auto" => "Detect automatically",
21 "fr_FR" => "Français",
22 "nb_NO" => "Norsk Bokmål",
24 "pt_BR" => "Portuguese/Brazil",
25 "zh_CN" => "Simplified Chinese");
30 if (ENABLE_TRANSLATIONS
== true) { // If translations are enabled.
31 require_once "accept-to-gettext.php";
32 require_once "gettext/gettext.inc";
34 function startup_gettext() {
36 # Get locale from Accept-Language header
37 $lang = al2gt(array_keys(get_translations()), "text/html");
39 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
40 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
43 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
44 $lang = $_COOKIE["ttrss_lang"];
48 _setlocale(LC_MESSAGES
, $lang);
49 _bindtextdomain("messages", "locale");
50 _textdomain("messages");
51 _bind_textdomain_codeset("messages", "UTF-8");
57 } else { // If translations are enabled.
61 function startup_gettext() {
65 } // If translations are enabled.
67 require_once 'db-prefs.php';
68 require_once 'compat.php';
69 require_once 'errors.php';
70 require_once 'version.php';
72 require_once 'phpmailer/class.phpmailer.php';
74 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION
. ')');
75 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
77 require_once "simplepie/simplepie.inc";
78 require_once "magpierss/rss_fetch.inc";
79 require_once 'magpierss/rss_utils.inc';
82 * Print a timestamped debug message.
84 * @param string $msg The debug message.
87 function _debug($msg) {
88 $ts = strftime("%H:%M:%S", time());
89 $ts = "$ts/" . posix_getpid();
94 * Purge a feed old posts.
96 * @param mixed $link A database connection.
97 * @param mixed $feed_id The id of the purged feed.
98 * @param mixed $purge_interval Olderness of purged posts.
99 * @param boolean $debug Set to True to enable the debug. False by default.
103 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
105 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
109 $result = db_query($link,
110 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
114 if (db_num_rows($result) == 1) {
115 $owner_uid = db_fetch_result($result, 0, "owner_uid");
118 if (!$owner_uid) return;
120 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
123 if (!$purge_unread) $query_limit = " unread = false AND ";
125 if (DB_TYPE
== "pgsql") {
126 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
127 marked = false AND feed_id = '$feed_id' AND
128 (SELECT date_entered FROM ttrss_entries WHERE
129 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
131 $pg_version = get_pgsql_version($link);
133 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
135 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
136 ttrss_entries.id = ref_id AND
138 feed_id = '$feed_id' AND
140 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
144 $result = db_query($link, "DELETE FROM ttrss_user_entries
146 WHERE ttrss_entries.id = ref_id AND
148 feed_id = '$feed_id' AND
150 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
153 $rows = pg_affected_rows($result);
157 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
158 marked = false AND feed_id = '$feed_id' AND
159 (SELECT date_entered FROM ttrss_entries WHERE
160 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
162 $result = db_query($link, "DELETE FROM ttrss_user_entries
163 USING ttrss_user_entries, ttrss_entries
164 WHERE ttrss_entries.id = ref_id AND
166 feed_id = '$feed_id' AND
168 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
170 $rows = mysql_affected_rows($link);
175 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
177 } // function purge_feed
180 * Purge old posts from old feeds.
182 * @param mixed $link A database connection
183 * @param boolean $do_output Set to true to enable printed output, false by default.
184 * @param integer $limit The maximal number of removed posts.
188 function global_purge_old_posts($link, $do_output = false, $limit = false) {
190 $random_qpart = sql_random_function();
193 $limit_qpart = "LIMIT $limit";
198 $result = db_query($link,
199 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
200 ORDER BY $random_qpart $limit_qpart");
202 while ($line = db_fetch_assoc($result)) {
204 $feed_id = $line["id"];
205 $purge_interval = $line["purge_interval"];
206 $owner_uid = $line["owner_uid"];
208 if ($purge_interval == 0) {
210 $tmp_result = db_query($link,
211 "SELECT value FROM ttrss_user_prefs WHERE
212 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
214 if (db_num_rows($tmp_result) != 0) {
215 $purge_interval = db_fetch_result($tmp_result, 0, "value");
220 // print "Feed $feed_id: purge interval = $purge_interval\n";
223 if ($purge_interval > 0) {
224 purge_feed($link, $feed_id, $purge_interval, $do_output);
228 // purge orphaned posts in main content table
229 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
230 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
233 $rows = db_affected_rows($link, $result);
234 _debug("Purged $rows orphaned posts.");
237 } // function global_purge_old_posts
239 function feed_purge_interval($link, $feed_id) {
241 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
242 WHERE id = '$feed_id'");
244 if (db_num_rows($result) == 1) {
245 $purge_interval = db_fetch_result($result, 0, "purge_interval");
246 $owner_uid = db_fetch_result($result, 0, "owner_uid");
248 if ($purge_interval == 0) $purge_interval = get_pref($link,
249 'PURGE_OLD_DAYS', $user_id);
251 return $purge_interval;
258 function purge_old_posts($link) {
260 $user_id = $_SESSION["uid"];
262 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
263 WHERE owner_uid = '$user_id'");
265 while ($line = db_fetch_assoc($result)) {
267 $feed_id = $line["id"];
268 $purge_interval = $line["purge_interval"];
270 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
272 if ($purge_interval > 0) {
273 purge_feed($link, $feed_id, $purge_interval);
277 // purge orphaned posts in main content table
278 db_query($link, "DELETE FROM ttrss_entries WHERE
279 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
282 function get_feed_update_interval($link, $feed_id) {
283 $result = db_query($link, "SELECT owner_uid, update_interval FROM
284 ttrss_feeds WHERE id = '$feed_id'");
286 if (db_num_rows($result) == 1) {
287 $update_interval = db_fetch_result($result, 0, "update_interval");
288 $owner_uid = db_fetch_result($result, 0, "owner_uid");
290 if ($update_interval != 0) {
291 return $update_interval;
293 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
301 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
303 if (WEB_DEMO_MODE
) return;
306 $user_id = $_SESSION["uid"];
307 purge_old_posts($link);
310 // db_query($link, "BEGIN");
312 if (MAX_UPDATE_TIME
> 0) {
313 if (DB_TYPE
== "mysql") {
316 $q_order = "RANDOM()";
319 $q_order = "last_updated DESC";
322 $result = db_query($link, "SELECT feed_url,id,
323 SUBSTRING(last_updated,1,19) AS last_updated,
324 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
329 while ($line = db_fetch_assoc($result)) {
330 $upd_intl = $line["update_interval"];
332 if (!$upd_intl ||
$upd_intl == 0) {
333 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
337 // Updates for this feed are disabled
341 if ($fetch ||
(!$line["last_updated"] ||
342 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
344 // print "<!-- feed: ".$line["feed_url"]." -->";
346 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
348 $upd_elapsed = time() - $upd_start;
350 if (MAX_UPDATE_TIME
> 0 && $upd_elapsed > MAX_UPDATE_TIME
) {
356 // db_query($link, "COMMIT");
360 function fetch_file_contents($url) {
361 if (USE_CURL_FOR_ICONS
) {
362 $tmpfile = tempnam(TMP_DIRECTORY
, "ttrss-tmp");
364 $ch = curl_init($url);
365 $fp = fopen($tmpfile, "w");
368 curl_setopt($ch, CURLOPT_FILE
, $fp);
369 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
370 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
376 $contents = file_get_contents($tmpfile);
382 return file_get_contents($url);
388 * Try to determine the favicon URL for a feed.
389 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
390 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
392 * @param string $url A feed or page URL
394 * @return mixed The favicon URL, or false if none was found.
396 function get_favicon_url($url) {
398 if ($html = @fetch_file_contents
($url)) {
400 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
401 // Attempt to grab a favicon link from their webpage url
402 $linkUrl = html_entity_decode($matches[1]);
404 if (substr($linkUrl, 0, 1) == '/') {
405 $urlParts = parse_url($url);
406 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
407 } else if (substr($linkUrl, 0, 7) == 'http://') {
408 $faviconURL = $linkUrl;
409 } else if (substr($url, -1, 1) == '/') {
410 $faviconURL = $url.$linkUrl;
412 $faviconURL = $url.'/'.$linkUrl;
416 // If unsuccessful, attempt to "guess" the favicon location
417 $urlParts = parse_url($url);
418 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
422 // Run a test to see if what we have attempted to get actually exists.
423 if(USE_CURL_FOR_ICONS ||
url_validate($faviconURL)) {
428 } // function get_favicon_url
431 * Check if a link is a valid and working URL.
433 * @param mixed $link A URL to check
435 * @return boolean True if the URL is valid, false otherwise.
437 function url_validate($link) {
439 $url_parts = @parse_url
($link);
441 if ( empty( $url_parts["host"] ) )
444 if ( !empty( $url_parts["path"] ) ) {
445 $documentpath = $url_parts["path"];
450 if ( !empty( $url_parts["query"] ) )
451 $documentpath .= "?" . $url_parts["query"];
453 $host = $url_parts["host"];
454 $port = $url_parts["port"];
459 $socket = @fsockopen
( $host, $port, $errno, $errstr, 30 );
464 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
466 $http_response = fgets( $socket, 22 );
468 $responses = "/(200 OK)|(30[0-9] Moved)/";
469 if ( preg_match($responses, $http_response) ) {
476 } // function url_validate
478 function check_feed_favicon($site_url, $feed, $link) {
479 $favicon_url = get_favicon_url($site_url);
481 # print "FAVICON [$site_url]: $favicon_url\n";
485 $icon_file = ICONS_DIR
. "/$feed.ico";
487 if ($favicon_url && !file_exists($icon_file)) {
488 $contents = fetch_file_contents($favicon_url);
490 $fp = fopen($icon_file, "w");
493 fwrite($fp, $contents);
495 chmod($icon_file, 0644);
499 error_reporting(DEFAULT_ERROR_LEVEL
);
503 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
505 if (!$_GET["daemon"] && !$ignore_daemon) {
509 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
510 _debug("update_rss_feed: start");
513 if (!$ignore_daemon) {
515 if (DB_TYPE
== "pgsql") {
516 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
518 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
521 $result = db_query($link, "SELECT id,update_interval,auth_login,
522 auth_pass,cache_images,update_method
523 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
527 $result = db_query($link, "SELECT id,update_interval,auth_login,
528 auth_pass,cache_images,update_method
529 FROM ttrss_feeds WHERE id = '$feed'");
533 if (db_num_rows($result) == 0) {
534 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
535 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
540 $update_method = db_fetch_result($result, 0, "update_method");
542 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
543 WHERE id = '$feed'");
545 $auth_login = db_fetch_result($result, 0, "auth_login");
546 $auth_pass = db_fetch_result($result, 0, "auth_pass");
548 if (ALLOW_SELECT_UPDATE_METHOD
) {
549 if (ENABLE_SIMPLEPIE
) {
550 $use_simplepie = $update_method != 1;
552 $use_simplepie = $update_method == 2;
555 $use_simplepie = ENABLE_SIMPLEPIE
;
558 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
559 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
562 if (!$use_simplepie) {
563 $auth_login = urlencode($auth_login);
564 $auth_pass = urlencode($auth_pass);
567 $update_interval = db_fetch_result($result, 0, "update_interval");
568 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
570 if ($update_interval < 0) { return; }
572 $feed = db_escape_string($feed);
574 $fetch_url = $feed_url;
576 if ($auth_login && $auth_pass) {
577 $url_parts = array();
578 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
580 if ($url_parts[1] && $url_parts[2]) {
581 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
586 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
587 _debug("update_rss_feed: fetching [$fetch_url]...");
590 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
594 if (!$use_simplepie) {
595 $rss = fetch_rss($fetch_url);
597 if (!is_dir(SIMPLEPIE_CACHE_DIR
)) {
598 mkdir(SIMPLEPIE_CACHE_DIR
);
601 $rss = new SimplePie();
602 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
603 # $rss->set_timeout(10);
604 $rss->set_feed_url($fetch_url);
605 $rss->set_output_encoding('UTF-8');
607 if (SIMPLEPIE_CACHE_IMAGES
&& $cache_images) {
608 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
609 _debug("enabling image cache");
612 $rss->set_image_handler('./image.php', 'i');
615 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
616 _debug("feed update interval (sec): " .
617 get_feed_update_interval($link, $feed)*60);
620 if (is_dir(SIMPLEPIE_CACHE_DIR
)) {
621 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR
);
622 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
630 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
631 _debug("update_rss_feed: fetch done, parsing...");
633 error_reporting (DEFAULT_ERROR_LEVEL
);
636 $feed = db_escape_string($feed);
638 if ($use_simplepie) {
639 $fetch_ok = !$rss->error();
646 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
647 _debug("update_rss_feed: processing feed data...");
650 // db_query($link, "BEGIN");
652 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
653 FROM ttrss_feeds WHERE id = '$feed'");
655 $registered_title = db_fetch_result($result, 0, "title");
656 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
657 $orig_site_url = db_fetch_result($result, 0, "site_url");
659 $owner_uid = db_fetch_result($result, 0, "owner_uid");
661 if ($use_simplepie) {
662 $site_url = $rss->get_link();
664 $site_url = $rss->channel
["link"];
667 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
668 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
669 _debug("update_rss_feed: checking favicon...");
672 check_feed_favicon($site_url, $feed, $link);
675 if (!$registered_title ||
$registered_title == "[Unknown]") {
677 if ($use_simplepie) {
678 $feed_title = db_escape_string($rss->get_title());
680 $feed_title = db_escape_string($rss->channel
["title"]);
683 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
684 _debug("update_rss_feed: registering title: $feed_title");
687 db_query($link, "UPDATE ttrss_feeds SET
688 title = '$feed_title' WHERE id = '$feed'");
691 // weird, weird Magpie
692 if (!$use_simplepie) {
693 if (!$site_url) $site_url = db_escape_string($rss->channel
["link_"]);
696 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
697 db_query($link, "UPDATE ttrss_feeds SET
698 site_url = '$site_url' WHERE id = '$feed'");
701 // print "I: " . $rss->channel["image"]["url"];
703 if (!$use_simplepie) {
704 $icon_url = $rss->image
["url"];
706 $icon_url = $rss->get_image_url();
709 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
710 $icon_url = db_escape_string($icon_url);
711 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
714 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
715 _debug("update_rss_feed: loading filters...");
720 $result = db_query($link, "SELECT reg_exp,
721 ttrss_filter_types.name AS name,
722 ttrss_filter_actions.name AS action,
725 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
727 owner_uid = $owner_uid AND
728 ttrss_filter_types.id = filter_type AND
729 ttrss_filter_actions.id = action_id AND
730 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
732 while ($line = db_fetch_assoc($result)) {
733 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
735 $filter["reg_exp"] = $line["reg_exp"];
736 $filter["action"] = $line["action"];
737 $filter["action_param"] = $line["action_param"];
738 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
740 array_push($filters[$line["name"]], $filter);
743 if ($use_simplepie) {
744 $iterator = $rss->get_items();
746 $iterator = $rss->items
;
747 if (!$iterator ||
!is_array($iterator)) $iterator = $rss->entries
;
748 if (!$iterator ||
!is_array($iterator)) $iterator = $rss;
751 if (!is_array($iterator)) {
752 /* db_query($link, "UPDATE ttrss_feeds
753 SET last_error = 'Parse error: can\'t find any articles.'
754 WHERE id = '$feed'"); */
756 // clear any errors and mark feed as updated if fetched okay
757 // even if it's blank
759 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
760 _debug("update_rss_feed: entry iterator is not an array, no articles?");
763 db_query($link, "UPDATE ttrss_feeds
764 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
766 return; // no articles
769 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
770 _debug("update_rss_feed: processing articles...");
773 foreach ($iterator as $item) {
775 if ($_GET['xdebug']) {
780 if ($use_simplepie) {
781 $entry_guid = $item->get_id();
782 if (!$entry_guid) $entry_guid = $item->get_link();
783 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
787 $entry_guid = $item["id"];
789 if (!$entry_guid) $entry_guid = $item["guid"];
790 if (!$entry_guid) $entry_guid = $item["link"];
791 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
794 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
795 _debug("update_rss_feed: guid $entry_guid");
798 if (!$entry_guid) continue;
800 $entry_timestamp = "";
802 if ($use_simplepie) {
803 $entry_timestamp = strtotime($item->get_date());
805 $rss_2_date = $item['pubdate'];
806 $rss_1_date = $item['dc']['date'];
807 $atom_date = $item['issued'];
808 if (!$atom_date) $atom_date = $item['updated'];
810 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
811 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
812 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
815 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
816 _debug("update_rss_feed: date $entry_timestamp");
819 if ($entry_timestamp == "" ||
$entry_timestamp == -1 ||
!$entry_timestamp) {
820 $entry_timestamp = time();
821 $no_orig_date = 'true';
823 $no_orig_date = 'false';
826 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
828 if ($use_simplepie) {
829 $entry_title = $item->get_title();
831 $entry_title = trim(strip_tags($item["title"]));
834 if ($use_simplepie) {
835 $entry_link = $item->get_link();
837 // strange Magpie workaround
838 $entry_link = $item["link_"];
839 if (!$entry_link) $entry_link = $item["link"];
842 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
843 _debug("update_rss_feed: title $entry_title");
846 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
848 $entry_link = strip_tags($entry_link);
850 if ($use_simplepie) {
851 $entry_content = $item->get_description();
853 $entry_content = $item["content:escaped"];
855 if (!$entry_content) $entry_content = $item["content:encoded"];
856 if (!$entry_content) $entry_content = $item["content"];
858 // Magpie bugs are getting ridiculous
859 if (trim($entry_content) == "Array") $entry_content = false;
861 if (!$entry_content) $entry_content = $item["atom_content"];
862 if (!$entry_content) $entry_content = $item["summary"];
863 if (!$entry_content) $entry_content = $item["description"];
866 if (is_array($entry_content)) {
867 $entry_content = $entry_content["encoded"];
868 if (!$entry_content) $entry_content = $entry_content["escaped"];
872 if ($_GET["xdebug"]) {
873 print "update_rss_feed: content: ";
874 print_r(htmlspecialchars($entry_content));
877 $entry_content_unescaped = $entry_content;
879 if ($use_simplepie) {
880 $entry_comments = strip_tags($item->data
["comments"]);
881 if ($item->get_author()) {
882 $entry_author_item = $item->get_author();
883 $entry_author = $entry_author_item->get_name();
884 if (!$entry_author) $entry_author = $entry_author_item->get_email();
887 $entry_comments = strip_tags($item["comments"]);
889 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
891 if ($item['author']) {
893 if (is_array($item['author'])) {
895 if (!$entry_author) {
896 $entry_author = db_escape_string(strip_tags($item['author']['name']));
899 if (!$entry_author) {
900 $entry_author = db_escape_string(strip_tags($item['author']['email']));
904 if (!$entry_author) {
905 $entry_author = db_escape_string(strip_tags($item['author']));
910 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
912 $entry_guid = db_escape_string(strip_tags($entry_guid));
913 $entry_guid = mb_substr($entry_guid, 0, 250);
915 $result = db_query($link, "SELECT id FROM ttrss_entries
916 WHERE guid = '$entry_guid'");
918 $entry_content = db_escape_string($entry_content);
920 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
922 $entry_title = db_escape_string($entry_title);
923 $entry_link = db_escape_string($entry_link);
924 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
925 $entry_author = mb_substr($entry_author, 0, 250);
927 if ($use_simplepie) {
928 $num_comments = 0; #FIXME#
930 $num_comments = db_escape_string($item["slash"]["comments"]);
933 if (!$num_comments) $num_comments = 0;
935 // parse <category> entries into tags
937 if ($use_simplepie) {
939 $additional_tags = array();
940 $additional_tags_src = $item->get_categories();
942 if (is_array($additional_tags_src)) {
943 foreach ($additional_tags_src as $tobj) {
944 array_push($additional_tags, $tobj->get_term());
948 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
949 _debug("update_rss_feed: category tags:");
950 print_r($additional_tags);
955 $t_ctr = $item['category#'];
957 $additional_tags = false;
960 $additional_tags = false;
961 } else if ($t_ctr > 0) {
962 $additional_tags = array($item['category']);
964 if ($item['category@term']) {
965 array_push($additional_tags, $item['category@term']);
968 for ($i = 0; $i <= $t_ctr; $i++
) {
969 if ($item["category#$i"]) {
970 array_push($additional_tags, $item["category#$i"]);
973 if ($item["category#$i@term"]) {
974 array_push($additional_tags, $item["category#$i@term"]);
979 // parse <dc:subject> elements
981 $t_ctr = $item['dc']['subject#'];
984 $additional_tags = array($item['dc']['subject']);
986 for ($i = 0; $i <= $t_ctr; $i++
) {
987 if ($item['dc']["subject#$i"]) {
988 array_push($additional_tags, $item['dc']["subject#$i"]);
996 $enclosures = array();
998 if ($use_simplepie) {
999 $encs = $item->get_enclosures();
1001 if (is_array($encs)) {
1002 foreach ($encs as $e) {
1004 $e->link
, $e->type
, $e->length
);
1006 array_push($enclosures, $e_item);
1011 $e_ctr = $item['enclosure#'];
1014 $e_item = array($item['enclosure@url'],
1015 $item['enclosure@type'],
1016 $item['enclosure@length']);
1018 array_push($enclosures, $e_item);
1020 for ($i = 0; $i <= $e_ctr; $i++
) {
1022 if ($item["enclosure#$i@url"]) {
1023 $e_item = array($item["enclosure#$i@url"],
1024 $item["enclosure#$i@type"],
1025 $item["enclosure#$i@length"]);
1026 array_push($enclosures, $e_item);
1035 // $entry_content = sanitize_rss($entry_content);
1037 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1038 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1041 db_query($link, "BEGIN");
1043 if (db_num_rows($result) == 0) {
1045 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1046 _debug("update_rss_feed: base guid not found");
1049 // base post entry does not exist, create it
1051 $result = db_query($link,
1052 "INSERT INTO ttrss_entries
1068 '$entry_timestamp_fmt',
1077 // we keep encountering the entry in feeds, so we need to
1078 // update date_entered column so that we don't get horrible
1079 // dupes when the entry gets purged and reinserted again e.g.
1080 // in the case of SLOW SLOW OMG SLOW updating feeds
1082 $base_entry_id = db_fetch_result($result, 0, "id");
1084 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1085 WHERE id = '$base_entry_id'");
1088 // now it should exist, if not - bad luck then
1090 $result = db_query($link, "SELECT
1091 id,content_hash,no_orig_date,title,
1092 substring(date_entered,1,19) as date_entered,
1093 substring(updated,1,19) as updated,
1097 WHERE guid = '$entry_guid'");
1102 if (db_num_rows($result) == 1) {
1104 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1105 _debug("update_rss_feed: base guid found, checking for user record");
1108 // this will be used below in update handler
1109 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1110 $orig_title = db_fetch_result($result, 0, "title");
1111 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1112 $orig_date_entered = strtotime(db_fetch_result($result,
1113 0, "date_entered"));
1115 $ref_id = db_fetch_result($result, 0, "id");
1116 $entry_ref_id = $ref_id;
1118 // check for user post link to main table
1120 // do we allow duplicate posts with same GUID in different feeds?
1121 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1122 $dupcheck_qpart = "AND feed_id = '$feed'";
1124 $dupcheck_qpart = "";
1127 // error_reporting(0);
1129 $article_filters = get_article_filters($filters, $entry_title,
1130 $entry_content, $entry_link);
1132 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1133 _debug("update_rss_feed: article filters: ");
1134 if (count($article_filters) != 0) {
1135 print_r($article_filters);
1139 if (find_article_filter($article_filters, "filter")) {
1143 // error_reporting (DEFAULT_ERROR_LEVEL);
1145 $result = db_query($link,
1146 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1147 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1150 // okay it doesn't exist - create user entry
1151 if (db_num_rows($result) == 0) {
1153 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1154 _debug("update_rss_feed: user record not found, creating...");
1157 if (!find_article_filter($article_filters, 'catchup')) {
1159 $last_read_qpart = 'NULL';
1162 $last_read_qpart = 'NOW()';
1165 if (find_article_filter($article_filters, 'mark')) {
1171 if (find_article_filter($article_filters, 'publish')) {
1172 $published = 'true';
1174 $published = 'false';
1177 $result = db_query($link,
1178 "INSERT INTO ttrss_user_entries
1179 (ref_id, owner_uid, feed_id, unread, last_read, marked, published)
1180 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1181 $last_read_qpart, $marked, $published)");
1183 $result = db_query($link,
1184 "SELECT int_id FROM ttrss_user_entries WHERE
1185 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1186 feed_id = '$feed' LIMIT 1");
1188 if (db_num_rows($result) == 1) {
1189 $entry_int_id = db_fetch_result($result, 0, "int_id");
1192 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1193 $entry_int_id = db_fetch_result($result, 0, "int_id");
1196 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1197 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1200 $post_needs_update = false;
1202 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1203 ($content_hash != $orig_content_hash)) {
1204 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1205 $post_needs_update = true;
1208 if (db_escape_string($orig_title) != $entry_title) {
1209 $post_needs_update = true;
1212 if ($orig_num_comments != $num_comments) {
1213 $post_needs_update = true;
1216 // this doesn't seem to be very reliable
1218 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1219 // $post_needs_update = true;
1222 // if post needs update, update it and mark all user entries
1223 // linking to this post as updated
1224 if ($post_needs_update) {
1226 if (defined('DAEMON_EXTENDED_DEBUG')) {
1227 _debug("update_rss_feed: post $entry_guid needs update...");
1230 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1232 db_query($link, "UPDATE ttrss_entries
1233 SET title = '$entry_title', content = '$entry_content',
1234 content_hash = '$content_hash',
1235 num_comments = '$num_comments'
1236 WHERE id = '$ref_id'");
1238 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1239 db_query($link, "UPDATE ttrss_user_entries
1240 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1242 db_query($link, "UPDATE ttrss_user_entries
1243 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1249 db_query($link, "COMMIT");
1251 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1252 _debug("update_rss_feed: looking for enclosures...");
1255 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1256 print_r($enclosures);
1259 db_query($link, "BEGIN");
1261 foreach ($enclosures as $enc) {
1262 $enc_url = db_escape_string($enc[0]);
1263 $enc_type = db_escape_string($enc[1]);
1264 $enc_dur = db_escape_string($enc[2]);
1266 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1267 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1269 if (db_num_rows($result) == 0) {
1270 db_query($link, "INSERT INTO ttrss_enclosures
1271 (content_url, content_type, title, duration, post_id) VALUES
1272 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1276 db_query($link, "COMMIT");
1278 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1279 _debug("update_rss_feed: looking for tags...");
1283 // <a href="..." rel="tag">Xorg</a>, //
1287 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1288 $entry_content_unescaped, $entry_tags);
1290 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1291 print_r($entry_tags);
1292 print "<br/></p>"; */
1294 $entry_tags = $entry_tags[1];
1296 # check for manual tags
1298 $tag_filter = find_article_filter($article_filters, "tag");
1302 $manual_tags = trim_array(split(",", $tag_filter[1]));
1304 foreach ($manual_tags as $tag) {
1305 if (tag_is_valid($tag)) {
1306 array_push($entry_tags, $tag);
1311 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1312 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1314 if ($additional_tags && is_array($additional_tags)) {
1315 foreach ($additional_tags as $tag) {
1316 if (tag_is_valid($tag) &&
1317 array_search($tag, $boring_tags) === FALSE) {
1318 array_push($entry_tags, $tag);
1323 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1325 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1326 print_r($entry_tags);
1329 if (count($entry_tags) > 0) {
1331 db_query($link, "BEGIN");
1333 foreach ($entry_tags as $tag) {
1335 $tag = sanitize_tag($tag);
1336 $tag = db_escape_string($tag);
1338 if (!tag_is_valid($tag)) continue;
1340 $result = db_query($link, "SELECT id FROM ttrss_tags
1341 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1342 owner_uid = '$owner_uid' LIMIT 1");
1344 // print db_fetch_result($result, 0, "id");
1346 if ($result && db_num_rows($result) == 0) {
1348 db_query($link, "INSERT INTO ttrss_tags
1349 (owner_uid,tag_name,post_int_id)
1350 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1354 db_query($link, "COMMIT");
1357 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1358 _debug("update_rss_feed: article processed");
1362 db_query($link, "UPDATE ttrss_feeds
1363 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1365 // db_query($link, "COMMIT");
1369 if ($use_simplepie) {
1370 $error_msg = mb_substr($rss->error(), 0, 250);
1372 $error_msg = mb_substr(magpie_error(), 0, 250);
1375 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1376 _debug("update_rss_feed: error fetching feed: $error_msg");
1379 $error_msg = db_escape_string($error_msg);
1382 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1383 last_updated = NOW() WHERE id = '$feed'");
1386 if ($use_simplepie) {
1390 if (defined('DAEMON_EXTENDED_DEBUG') ||
$_GET['xdebug']) {
1391 _debug("update_rss_feed: done");
1396 function print_select($id, $default, $values, $attributes = "") {
1397 print "<select name=\"$id\" id=\"$id\" $attributes>";
1398 foreach ($values as $v) {
1404 print "<option$sel>$v</option>";
1409 function print_select_hash($id, $default, $values, $attributes = "") {
1410 print "<select name=\"$id\" id='$id' $attributes>";
1411 foreach (array_keys($values) as $v) {
1417 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1423 function get_article_filters($filters, $title, $content, $link) {
1426 if ($filters["title"]) {
1427 foreach ($filters["title"] as $filter) {
1428 $reg_exp = $filter["reg_exp"];
1429 $inverse = $filter["inverse"];
1430 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1431 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1433 array_push($matches, array($filter["action"], $filter["action_param"]));
1438 if ($filters["content"]) {
1439 foreach ($filters["content"] as $filter) {
1440 $reg_exp = $filter["reg_exp"];
1441 $inverse = $filter["inverse"];
1443 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1444 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1446 array_push($matches, array($filter["action"], $filter["action_param"]));
1451 if ($filters["both"]) {
1452 foreach ($filters["both"] as $filter) {
1453 $reg_exp = $filter["reg_exp"];
1454 $inverse = $filter["inverse"];
1457 if (!preg_match("/$reg_exp/i", $title) ||
!preg_match("/$reg_exp/i", $content)) {
1458 array_push($matches, array($filter["action"], $filter["action_param"]));
1461 if (preg_match("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
1462 array_push($matches, array($filter["action"], $filter["action_param"]));
1468 if ($filters["link"]) {
1469 $reg_exp = $filter["reg_exp"];
1470 foreach ($filters["link"] as $filter) {
1471 $reg_exp = $filter["reg_exp"];
1472 $inverse = $filter["inverse"];
1474 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1475 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1477 array_push($matches, array($filter["action"], $filter["action_param"]));
1485 function find_article_filter($filters, $filter_name) {
1486 foreach ($filters as $f) {
1487 if ($f[0] == $filter_name) {
1494 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1495 $rtl_content = false, $last_updated = false, $last_error = false) {
1497 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1498 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1500 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1504 $rtl_tag = "dir=\"rtl\"";
1506 $rtl_tag = "dir=\"ltr\"";
1509 $error_notify_msg = "";
1512 $link_title = "Error: $last_error ($last_updated)";
1513 $error_notify_msg = "(Error)";
1514 } else if ($last_updated) {
1515 $link_title = "Updated: $last_updated";
1518 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1519 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1521 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1522 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1526 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1531 $fctr_class = "class=\"invisible\"";
1534 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1535 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1537 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1538 print "<div class=\"feedExtInfo\">
1539 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1546 function getmicrotime() {
1547 list($usec, $sec) = explode(" ",microtime());
1548 return ((float)$usec +
(float)$sec);
1551 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1552 foreach ($values as $v) {
1559 if ($v == $true_is) {
1560 $sel .= " value=\"1\"";
1562 $sel .= " value=\"0\"";
1565 print "<input class=\"noborder\"
1566 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
1571 function initialize_user_prefs($link, $uid) {
1573 $uid = db_escape_string($uid);
1575 db_query($link, "BEGIN");
1577 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1579 $u_result = db_query($link, "SELECT pref_name
1580 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1582 $active_prefs = array();
1584 while ($line = db_fetch_assoc($u_result)) {
1585 array_push($active_prefs, $line["pref_name"]);
1588 while ($line = db_fetch_assoc($result)) {
1589 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1590 // print "adding " . $line["pref_name"] . "<br>";
1592 db_query($link, "INSERT INTO ttrss_user_prefs
1593 (owner_uid,pref_name,value) VALUES
1594 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1599 db_query($link, "COMMIT");
1603 function lookup_user_id($link, $user) {
1605 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1608 if (db_num_rows($result) == 1) {
1609 return db_fetch_result($result, 0, "id");
1615 function http_authenticate_user($link) {
1617 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1619 if (!$_SERVER["PHP_AUTH_USER"]) {
1621 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1622 header('HTTP/1.0 401 Unauthorized');
1626 $auth_result = authenticate_user($link,
1627 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1629 if (!$auth_result) {
1630 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1631 header('HTTP/1.0 401 Unauthorized');
1639 function authenticate_user($link, $login, $password, $force_auth = false) {
1641 if (!SINGLE_USER_MODE
) {
1643 $pwd_hash1 = encrypt_password($password);
1644 $pwd_hash2 = encrypt_password($password, $login);
1646 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1647 && $_SERVER["REMOTE_USER"]) {
1649 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1651 $query = "SELECT id,login,access_level
1652 FROM ttrss_users WHERE
1656 $query = "SELECT id,login,access_level,pwd_hash
1657 FROM ttrss_users WHERE
1658 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1659 pwd_hash = '$pwd_hash2')";
1662 $result = db_query($link, $query);
1664 if (db_num_rows($result) == 1) {
1665 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1666 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1667 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1669 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1672 $user_theme = get_user_theme_path($link);
1674 $_SESSION["theme"] = $user_theme;
1675 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1676 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1678 initialize_user_prefs($link, $_SESSION["uid"]);
1687 $_SESSION["uid"] = 1;
1688 $_SESSION["name"] = "admin";
1690 $user_theme = get_user_theme_path($link);
1692 $_SESSION["theme"] = $user_theme;
1693 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1695 initialize_user_prefs($link, $_SESSION["uid"]);
1701 function make_password($length = 8) {
1704 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1708 while ($i < $length) {
1709 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1711 if (!strstr($password, $char)) {
1719 // this is called after user is created to initialize default feeds, labels
1722 // user preferences are checked on every login, not here
1724 function initialize_user($link, $uid) {
1726 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1727 values ('$uid','unread = true', 'Unread articles')");
1729 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1730 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1732 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1733 values ('$uid', 'Tiny Tiny RSS: New Releases',
1734 'http://tt-rss.spb.ru/releases.rss')");
1736 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1737 values ('$uid', 'Tiny Tiny RSS: Forum',
1738 'http://tt-rss.spb.ru/forum/rss.php')");
1741 function logout_user() {
1743 if (isset($_COOKIE[session_name()])) {
1744 setcookie(session_name(), '', time()-42000, '/');
1748 function get_script_urlpath() {
1749 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1752 function validate_session($link) {
1753 if (SINGLE_USER_MODE
) {
1757 if (SESSION_CHECK_ADDRESS
&& $_SESSION["uid"]) {
1758 if ($_SESSION["ip_address"]) {
1759 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1760 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1766 if ($_SESSION["uid"]) {
1768 $result = db_query($link,
1769 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1771 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1773 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1778 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1780 //print_r($_SESSION);
1782 if (time() > $_SESSION["cookie_lifetime"]) {
1790 function login_sequence($link, $mobile = false) {
1791 if (!SINGLE_USER_MODE
) {
1793 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1794 $swu = db_escape_string($_REQUEST["swu"]);
1796 $_SESSION["prefs_cache"] = false;
1797 return authenticate_user($link, $swu, null, true);
1801 $login_action = $_POST["login_action"];
1803 # try to authenticate user if called from login form
1804 if ($login_action == "do_login") {
1805 $login = $_POST["login"];
1806 $password = $_POST["password"];
1807 $remember_me = $_POST["remember_me"];
1809 if (authenticate_user($link, $login, $password)) {
1810 $_POST["password"] = "";
1812 $_SESSION["language"] = $_POST["language"];
1814 header("Location: " . $_SERVER["REQUEST_URI"]);
1819 $_SESSION["login_error_msg"] = "Incorrect username or password";
1823 // print session_id();
1824 // print_r($_SESSION);
1826 if (!$_SESSION["uid"] ||
!validate_session($link)) {
1827 render_login_form($link, $mobile);
1830 /* bump login timestamp */
1831 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1834 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1835 setcookie("ttrss_lang", $_SESSION["language"],
1836 time() + SESSION_COOKIE_LIFETIME
);
1841 return authenticate_user($link, "admin", null);
1845 function truncate_string($str, $max_len) {
1846 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1847 return mb_substr($str, 0, $max_len, "utf-8") . "…";
1853 function get_user_theme_path($link) {
1854 $result = db_query($link, "SELECT theme_path
1856 ttrss_themes,ttrss_users
1857 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1858 if (db_num_rows($result) != 0) {
1859 return db_fetch_result($result, 0, "theme_path");
1865 function smart_date_time($timestamp) {
1866 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1867 return date("G:i", $timestamp);
1868 } else if (date("Y", $timestamp) == date("Y")) {
1869 return date("M d, G:i", $timestamp);
1871 return date("Y/m/d, G:i", $timestamp);
1875 function smart_date($timestamp) {
1876 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1878 } else if (date("Y", $timestamp) == date("Y")) {
1879 return date("D m", $timestamp);
1881 return date("Y/m/d", $timestamp);
1885 function sql_bool_to_string($s) {
1886 if ($s == "t" ||
$s == "1") {
1893 function sql_bool_to_bool($s) {
1894 if ($s == "t" ||
$s == "1") {
1902 function toggleEvenOdd($a) {
1909 function sanity_check($link) {
1914 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1915 $schema_version = db_fetch_result($result, 0, "schema_version");
1917 if ($schema_version != SCHEMA_VERSION
) {
1921 if (DB_TYPE
== "mysql") {
1922 $result = db_query($link, "SELECT true", false);
1923 if (db_num_rows($result) != 1) {
1928 error_reporting (DEFAULT_ERROR_LEVEL
);
1930 if ($error_code != 0) {
1931 print_error_xml($error_code);
1938 function file_is_locked($filename) {
1939 if (function_exists('flock')) {
1941 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1942 error_reporting(DEFAULT_ERROR_LEVEL
);
1944 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1945 flock($fp, LOCK_UN
);
1956 function make_lockfile($filename) {
1957 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1959 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1966 function make_stampfile($filename) {
1967 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1969 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1970 fwrite($fp, time() . "\n");
1971 flock($fp, LOCK_UN
);
1979 function read_stampfile($filename) {
1982 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "r");
1983 error_reporting (DEFAULT_ERROR_LEVEL
);
1985 if (flock($fp, LOCK_EX
)) {
1986 $stamp = fgets($fp);
1987 flock($fp, LOCK_UN
);
1995 function sql_random_function() {
1996 if (DB_TYPE
== "mysql") {
2003 function catchup_feed($link, $feed, $cat_view) {
2005 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2010 $cat_qpart = "cat_id = '$feed'";
2012 $cat_qpart = "cat_id IS NULL";
2015 $tmp_result = db_query($link, "SELECT id
2016 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2019 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2021 $tmp_feed = $tmp_line["id"];
2023 db_query($link, "UPDATE ttrss_user_entries
2024 SET unread = false,last_read = NOW()
2025 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2028 } else if ($feed > 0) {
2030 $tmp_result = db_query($link, "SELECT id
2031 FROM ttrss_feeds WHERE parent_feed = '$feed'
2032 ORDER BY cat_id,title");
2034 $parent_ids = array();
2036 if (db_num_rows($tmp_result) > 0) {
2037 while ($p = db_fetch_assoc($tmp_result)) {
2038 array_push($parent_ids, "feed_id = " . $p["id"]);
2041 $children_qpart = implode(" OR ", $parent_ids);
2043 db_query($link, "UPDATE ttrss_user_entries
2044 SET unread = false,last_read = NOW()
2045 WHERE (feed_id = '$feed' OR $children_qpart)
2046 AND owner_uid = " . $_SESSION["uid"]);
2049 db_query($link, "UPDATE ttrss_user_entries
2050 SET unread = false,last_read = NOW()
2051 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2054 } else if ($feed < 0 && $feed > -10) { // special, like starred
2057 db_query($link, "UPDATE ttrss_user_entries
2058 SET unread = false,last_read = NOW()
2059 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2063 db_query($link, "UPDATE ttrss_user_entries
2064 SET unread = false,last_read = NOW()
2065 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2070 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2072 if (DB_TYPE
== "pgsql") {
2073 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
2075 $match_part = "date_entered > DATE_SUB(NOW(),
2076 INTERVAL $intl HOUR) ";
2079 $result = db_query($link, "SELECT id FROM ttrss_entries,
2080 ttrss_user_entries WHERE $match_part AND
2082 ttrss_user_entries.ref_id = ttrss_entries.id AND
2083 owner_uid = ".$_SESSION["uid"]);
2085 $affected_ids = array();
2087 while ($line = db_fetch_assoc($result)) {
2088 array_push($affected_ids, $line["id"]);
2091 catchupArticlesById($link, $affected_ids, 0);
2094 } else if ($feed < -10) { // label
2096 // TODO make this more efficient
2098 $label_id = -$feed - 11;
2100 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2101 WHERE id = '$label_id'");
2104 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2106 db_query($link, "BEGIN");
2108 $tmp2_result = db_query($link,
2112 ttrss_user_entries,ttrss_entries,ttrss_feeds
2114 ref_id = ttrss_entries.id AND
2115 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2117 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2119 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2120 db_query($link, "UPDATE
2123 unread = false, last_read = NOW()
2125 int_id = " . $tmp_line["int_id"]);
2128 db_query($link, "COMMIT");
2130 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2131 SET unread = false,last_read = NOW()
2134 AND owner_uid = ".$_SESSION["uid"]); */
2138 db_query($link, "BEGIN");
2140 $tag_name = db_escape_string($feed);
2142 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2143 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2145 while ($line = db_fetch_assoc($result)) {
2146 db_query($link, "UPDATE ttrss_user_entries SET
2147 unread = false, last_read = NOW()
2148 WHERE int_id = " . $line["post_int_id"]);
2150 db_query($link, "COMMIT");
2154 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2158 $cat_qpart = "cat_id = '$feed'";
2160 $cat_qpart = "cat_id IS NULL";
2163 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2164 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2166 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2167 $feed_url = $tmp_line["feed_url"];
2168 $feed_id = $tmp_line["id"];
2169 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2173 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2174 WHERE id = '$feed'");
2175 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2176 update_rss_feed($link, $feed_url, $feed, $force_update);
2180 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2181 /* getLabelCounters($link);
2182 getFeedCounters($link);
2183 getTagCounters($link);
2184 getGlobalCounters($link);
2185 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2186 getCategoryCounters($link);
2189 if (!$omode) $omode = "flc";
2191 getGlobalCounters($link);
2193 if (strchr($omode, "l")) getLabelCounters($link);
2194 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS
, $active_feed);
2195 if (strchr($omode, "t")) getTagCounters($link);
2196 if (strchr($omode, "c")) {
2197 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2198 getCategoryCounters($link);
2203 function getCategoryCounters($link) {
2204 # two special categories are -1 and -2 (all virtuals; all labels)
2206 $ctr = getCategoryUnread($link, -1);
2208 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2210 $ctr = getCategoryUnread($link, -2);
2212 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2214 $age_qpart = getMaxAgeSubquery();
2216 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
2217 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id
2218 AND id = ref_id AND $age_qpart
2219 AND unread = true)) AS unread FROM ttrss_feeds
2221 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2223 while ($line = db_fetch_assoc($result)) {
2224 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2225 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2226 $line["unread"]."\"/>";
2230 function getCategoryUnread($link, $cat) {
2235 $cat_query = "cat_id = '$cat'";
2237 $cat_query = "cat_id IS NULL";
2240 $age_qpart = getMaxAgeSubquery();
2242 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2244 AND owner_uid = " . $_SESSION["uid"]);
2246 $cat_feeds = array();
2247 while ($line = db_fetch_assoc($result)) {
2248 array_push($cat_feeds, "feed_id = " . $line["id"]);
2251 if (count($cat_feeds) == 0) return 0;
2253 $match_part = implode(" OR ", $cat_feeds);
2255 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2256 FROM ttrss_user_entries,ttrss_entries
2257 WHERE unread = true AND ($match_part) AND id = ref_id
2258 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2262 # this needs to be rewritten
2263 while ($line = db_fetch_assoc($result)) {
2264 $unread +
= $line["unread"];
2268 } else if ($cat == -1) {
2269 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3);
2270 } else if ($cat == -2) {
2272 $rv = getLabelCounters($link, false, true);
2275 foreach (array_keys($rv) as $k) {
2277 $ctr +
= $rv[$k]["counter"];
2285 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
2286 if (DB_TYPE
== "pgsql") {
2287 return "ttrss_entries.date_entered >
2288 NOW() - INTERVAL '$days days'";
2290 return "ttrss_entries.date_entered >
2291 DATE_SUB(NOW(), INTERVAL $days DAY)";
2295 function getFeedUnread($link, $feed, $is_cat = false) {
2296 $n_feed = sprintf("%d", $feed);
2298 $age_qpart = getMaxAgeSubquery();
2301 return getCategoryUnread($link, $n_feed);
2302 } else if ($n_feed == -1) {
2303 $match_part = "marked = true";
2304 } else if ($n_feed == -2) {
2305 $match_part = "published = true";
2306 } else if ($n_feed == -3) {
2307 $match_part = "unread = true";
2309 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2311 if (DB_TYPE
== "pgsql") {
2312 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2314 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2317 } else if ($n_feed > 0) {
2319 $result = db_query($link, "SELECT id FROM ttrss_feeds
2320 WHERE parent_feed = '$n_feed'
2322 AND owner_uid = " . $_SESSION["uid"]);
2324 if (db_num_rows($result) > 0) {
2326 $linked_feeds = array();
2327 while ($line = db_fetch_assoc($result)) {
2328 array_push($linked_feeds, "feed_id = " . $line["id"]);
2331 array_push($linked_feeds, "feed_id = $n_feed");
2333 $match_part = implode(" OR ", $linked_feeds);
2335 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2336 FROM ttrss_user_entries,ttrss_entries
2337 WHERE unread = true AND
2338 ttrss_user_entries.ref_id = ttrss_entries.id AND
2341 owner_uid = " . $_SESSION["uid"]);
2345 # this needs to be rewritten
2346 while ($line = db_fetch_assoc($result)) {
2347 $unread +
= $line["unread"];
2353 $match_part = "feed_id = '$n_feed'";
2355 } else if ($feed < -10) {
2357 $label_id = -$feed - 11;
2359 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2360 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2362 $match_part = db_fetch_result($result, 0, "sql_exp");
2367 $result = db_query($link, "SELECT count(int_id) AS unread
2368 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2369 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2370 ttrss_user_entries.ref_id = ttrss_entries.id AND
2371 ttrss_feeds.hidden = false AND
2373 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2377 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2378 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2379 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2380 AND unread = true AND $age_qpart AND
2381 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2384 $unread = db_fetch_result($result, 0, "unread");
2389 /* FIXME this needs reworking */
2391 function getGlobalUnread($link, $user_id = false) {
2394 $user_id = $_SESSION["uid"];
2397 $age_qpart = getMaxAgeSubquery();
2399 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2400 WHERE unread = true AND
2401 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2402 ttrss_user_entries.ref_id = ttrss_entries.id AND
2405 ttrss_user_entries.owner_uid = '$user_id'");
2406 $c_id = db_fetch_result($result, 0, "c_id");
2410 function getGlobalCounters($link, $global_unread = -1) {
2411 if ($global_unread == -1) {
2412 $global_unread = getGlobalUnread($link);
2414 print "<counter type=\"global\" id='global-unread'
2415 counter='$global_unread'/>";
2417 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2418 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2420 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2422 print "<counter type=\"global\" id='subscribed-feeds'
2423 counter='$subscribed_feeds'/>";
2427 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS
) {
2430 if (!$_SESSION["tctr_last_value"]) {
2431 $_SESSION["tctr_last_value"] = array();
2435 $old_counters = $_SESSION["tctr_last_value"];
2437 $tctrs_modified = false;
2439 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2440 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2441 ttrss_user_entries.ref_id = ttrss_entries.id AND
2442 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2443 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2445 select tag_name,0 as count FROM ttrss_tags
2446 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2448 $age_qpart = getMaxAgeSubquery();
2450 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2451 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2452 AND ref_id = id AND $age_qpart
2453 AND unread = true)) AS count FROM ttrss_tags
2454 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2455 ORDER BY count DESC LIMIT 55");
2459 while ($line = db_fetch_assoc($result)) {
2460 $tags[$line["tag_name"]] +
= $line["count"];
2463 foreach (array_keys($tags) as $tag) {
2464 $unread = $tags[$tag];
2466 $tag = htmlspecialchars($tag);
2468 if (!$smart_mode ||
$old_counters[$tag] != $unread) {
2469 $old_counters[$tag] = $unread;
2470 $tctrs_modified = true;
2471 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2476 if ($smart_mode && $tctrs_modified) {
2477 $_SESSION["tctr_last_value"] = $old_counters;
2482 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $ret_mode = false) {
2484 $age_qpart = getMaxAgeSubquery();
2487 if (!$_SESSION["lctr_last_value"]) {
2488 $_SESSION["lctr_last_value"] = array();
2494 $old_counters = $_SESSION["lctr_last_value"];
2495 $lctrs_modified = false;
2497 $count = getFeedUnread($link, -1);
2500 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2502 $ret_arr["-1"]["counter"] = $count;
2503 $ret_arr["-1"]["description"] = __("Starred articles");
2506 $count = getFeedUnread($link, -2);
2509 print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2511 $ret_arr["-2"]["counter"] = $count;
2512 $ret_arr["-2"]["description"] = __("Published articles");
2515 $count = getFeedUnread($link, -3);
2518 print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2520 $ret_arr["-3"]["counter"] = $count;
2521 $ret_arr["-3"]["description"] = __("Fresh articles");
2525 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2526 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2528 while ($line = db_fetch_assoc($result)) {
2530 $id = -$line["id"] - 11;
2532 $label_name = $line["description"];
2534 error_reporting (0);
2536 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2537 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2538 ttrss_feeds.hidden = false AND
2540 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2541 ttrss_user_entries.ref_id = ttrss_entries.id AND
2542 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2544 $count = db_fetch_result($tmp_result, 0, "count");
2546 if (!$smart_mode ||
$old_counters[$id] != $count) {
2547 $old_counters[$id] = $count;
2548 $lctrs_modified = true;
2550 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2552 $ret_arr[$id]["counter"] = $count;
2553 $ret_arr[$id]["description"] = $label_name;
2557 error_reporting (DEFAULT_ERROR_LEVEL
);
2560 if ($smart_mode && $lctrs_modified) {
2561 $_SESSION["lctr_last_value"] = $old_counters;
2567 /* function getFeedCounter($link, $id) {
2569 $result = db_query($link, "SELECT
2570 count(id) as count,last_error
2571 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2572 WHERE feed_id = '$id' AND unread = true
2573 AND ttrss_user_entries.feed_id = ttrss_feeds.id
2574 AND ttrss_user_entries.ref_id = ttrss_entries.id");
2576 $count = db_fetch_result($result, 0, "count");
2577 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2579 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
2582 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS
, $active_feed = false) {
2584 $age_qpart = getMaxAgeSubquery();
2587 if (!$_SESSION["fctr_last_value"]) {
2588 $_SESSION["fctr_last_value"] = array();
2592 $old_counters = $_SESSION["fctr_last_value"];
2594 /* $result = db_query($link, "SELECT id,last_error,parent_feed,
2595 SUBSTRING(last_updated,1,19) AS last_updated,
2597 FROM ttrss_entries,ttrss_user_entries
2598 WHERE feed_id = ttrss_feeds.id AND
2599 ttrss_user_entries.ref_id = ttrss_entries.id
2600 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2601 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2602 AND parent_feed IS NULL"); */
2604 $query = "SELECT ttrss_feeds.id,
2606 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
2608 COUNT(ttrss_entries.id) AS count
2610 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2611 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2612 AND ttrss_user_entries.unread = true)
2613 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2615 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2616 AND parent_feed IS NULL
2617 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2619 $result = db_query($link, $query);
2620 $fctrs_modified = false;
2622 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2624 while ($line = db_fetch_assoc($result)) {
2627 $count = $line["count"];
2628 $last_error = htmlspecialchars($line["last_error"]);
2630 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2631 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2633 $last_updated = date($short_date, strtotime($line["last_updated"]));
2636 $last_updated = htmlspecialchars($last_updated);
2638 $has_img = is_file(ICONS_DIR
. "/$id.ico");
2640 $tmp_result = db_query($link,
2641 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2642 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2643 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2644 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2645 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2647 if (db_num_rows($tmp_result) > 0) {
2648 while ($l = db_fetch_assoc($tmp_result)) {
2649 $count +
= $l["unread"];
2653 if (!$smart_mode ||
$old_counters[$id] != $count) {
2654 $old_counters[$id] = $count;
2655 $fctrs_modified = true;
2658 $error_part = "error=\"$last_error\"";
2664 $has_img_part = "hi=\"$has_img\"";
2669 if ($active_feed && $id == $active_feed) {
2670 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2672 $has_title_part = "";
2675 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2679 if ($smart_mode && $fctrs_modified) {
2680 $_SESSION["fctr_last_value"] = $old_counters;
2684 function get_script_dt_add() {
2685 if (strpos(VERSION
, ".99") === false) {
2692 function get_pgsql_version($link) {
2693 $result = db_query($link, "SELECT version() AS version");
2694 $version = split(" ", db_fetch_result($result, 0, "version"));
2698 function print_error_xml($code, $add_msg = "") {
2701 $error_msg = $ERRORS[$code];
2704 $error_msg = "$error_msg; $add_msg";
2707 print "<rpc-reply>";
2708 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2709 print "</rpc-reply>";
2712 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2713 $auth_login = '', $auth_pass = '') {
2715 # check for feed:http://url
2716 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2718 # check for feed://URL
2719 if (strpos($feed_link, "//") === 0) {
2720 $feed_link = "http:$feed_link";
2723 if ($feed_link == "") return;
2725 if ($cat_id == "0" ||
!$cat_id) {
2726 $cat_qpart = "NULL";
2728 $cat_qpart = "'$cat_id'";
2731 $result = db_query($link,
2732 "SELECT id FROM ttrss_feeds
2733 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2735 if (db_num_rows($result) == 0) {
2737 $result = db_query($link,
2738 "INSERT INTO ttrss_feeds
2739 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2740 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2741 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2743 $result = db_query($link,
2744 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2745 AND owner_uid = " . $_SESSION["uid"]);
2747 $feed_id = db_fetch_result($result, 0, "id");
2750 update_rss_feed($link, $feed_link, $feed_id, true);
2759 function print_feed_select($link, $id, $default_id = "",
2760 $attributes = "", $include_all_feeds = true) {
2762 print "<select id=\"$id\" name=\"$id\" $attributes>";
2763 if ($include_all_feeds) {
2764 print "<option value=\"0\">".__('All feeds')."</option>";
2767 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2768 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2770 if (db_num_rows($result) > 0 && $include_all_feeds) {
2771 print "<option disabled>--------</option>";
2774 while ($line = db_fetch_assoc($result)) {
2775 if ($line["id"] == $default_id) {
2776 $is_selected = "selected";
2780 printf("<option $is_selected value='%d'>%s</option>",
2781 $line["id"], htmlspecialchars($line["title"]));
2787 function print_feed_cat_select($link, $id, $default_id = "",
2788 $attributes = "", $include_all_cats = true) {
2790 print "<select id=\"$id\" name=\"$id\" $attributes>";
2792 if ($include_all_cats) {
2793 print "<option value=\"0\">".__('Uncategorized')."</option>";
2796 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2797 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2799 if (db_num_rows($result) > 0 && $include_all_cats) {
2800 print "<option disabled>--------</option>";
2803 while ($line = db_fetch_assoc($result)) {
2804 if ($line["id"] == $default_id) {
2805 $is_selected = "selected";
2809 printf("<option $is_selected value='%d'>%s</option>",
2810 $line["id"], htmlspecialchars($line["title"]));
2816 function checkbox_to_sql_bool($val) {
2817 return ($val == "on") ?
"true" : "false";
2820 function getFeedCatTitle($link, $id) {
2822 return __("Special");
2823 } else if ($id < -10) {
2824 return __("Labels");
2825 } else if ($id > 0) {
2826 $result = db_query($link, "SELECT ttrss_feed_categories.title
2827 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2828 cat_id = ttrss_feed_categories.id");
2829 if (db_num_rows($result) == 1) {
2830 return db_fetch_result($result, 0, "title");
2832 return __("Uncategorized");
2835 return "getFeedCatTitle($id) failed";
2840 function getFeedTitle($link, $id) {
2842 return __("Starred articles");
2843 } else if ($id == -2) {
2844 return __("Published articles");
2845 } else if ($id == -3) {
2846 return __("Fresh articles");
2847 } else if ($id < -10) {
2848 $label_id = -10 - $id;
2849 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2850 if (db_num_rows($result) == 1) {
2851 return db_fetch_result($result, 0, "description");
2853 return "Unknown label ($label_id)";
2856 } else if ($id > 0) {
2857 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2858 if (db_num_rows($result) == 1) {
2859 return db_fetch_result($result, 0, "title");
2861 return "Unknown feed ($id)";
2864 return "getFeedTitle($id) failed";
2869 function get_session_cookie_name() {
2870 return ((!defined('TTRSS_SESSION_NAME')) ?
"ttrss_sid" : TTRSS_SESSION_NAME
);
2873 function print_init_params($link) {
2874 print "<init-params>";
2875 if ($_SESSION["stored-params"]) {
2876 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2878 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2879 print "<param key=\"$key\" value=\"$value\"/>";
2884 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2885 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON
. "\"/>";
2886 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH
. "\"/>";
2887 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2889 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2890 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2892 print "<param key=\"hide_read_feeds\" value=\"" .
2893 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2895 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2896 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2898 print "<param key=\"confirm_feed_catchup\" value=\"" .
2899 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2901 print "<param key=\"cdm_auto_catchup\" value=\"" .
2902 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2904 print "<param key=\"icons_url\" value=\"" . ICONS_URL
. "\"/>";
2906 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME
. "\"/>";
2908 print "<param key=\"default_view_mode\" value=\"" .
2909 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2911 print "<param key=\"default_view_limit\" value=\"" .
2912 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2914 print "<param key=\"prefs_active_tab\" value=\"" .
2915 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2917 print "<param key=\"infobox_disable_overlay\" value=\"" .
2918 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2920 print "<param key=\"icons_location\" value=\"" .
2923 print "<param key=\"hide_read_shows_special\" value=\"" .
2924 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2926 print "</init-params>";
2929 function print_runtime_info($link) {
2930 print "<runtime-info>";
2932 if (ENABLE_UPDATE_DAEMON
) {
2933 print "<param key=\"daemon_is_running\" value=\"".
2934 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2936 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2938 $stamp = (int)read_stampfile("update_daemon.stamp");
2940 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2943 $stamp_delta = time() - $stamp;
2945 if ($stamp_delta > 1800) {
2949 $_SESSION["daemon_stamp_check"] = time();
2952 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2954 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2956 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2961 if (CHECK_FOR_NEW_VERSION
&& $_SESSION["access_level"] >= 10) {
2963 if ($_SESSION["last_version_check"] +
7200 < time()) {
2964 $new_version_details = check_for_update($link);
2966 print "<param key=\"new_version_available\" value=\"".
2967 sprintf("%d", $new_version_details != ""). "\"/>";
2969 $_SESSION["last_version_check"] = time();
2973 // print "<param key=\"new_version_available\" value=\"1\"/>";
2975 print "</runtime-info>";
2978 function getSearchSql($search, $match_on) {
2980 $search_query_part = "";
2982 $keywords = split(" ", $search);
2983 $query_keywords = array();
2985 if ($match_on == "both") {
2987 foreach ($keywords as $k) {
2988 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2989 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2992 $search_query_part = implode("AND", $query_keywords) . " AND ";
2994 } else if ($match_on == "title") {
2996 foreach ($keywords as $k) {
2997 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3000 $search_query_part = implode("AND", $query_keywords) . " AND ";
3002 } else if ($match_on == "content") {
3004 foreach ($keywords as $k) {
3005 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3009 $search_query_part = implode("AND", $query_keywords);
3011 return $search_query_part;
3014 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3016 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3020 $search_query_part = getSearchSql($search, $match_on);
3021 $search_query_part .= " AND ";
3024 $search_query_part = "";
3027 $view_query_part = "";
3029 if ($view_mode == "adaptive") {
3031 $view_query_part = " ";
3032 } else if ($feed != -1) {
3033 $unread = getFeedUnread($link, $feed, $cat_view);
3035 $view_query_part = " unread = true AND ";
3040 if ($view_mode == "marked") {
3041 $view_query_part = " marked = true AND ";
3044 if ($view_mode == "unread") {
3045 $view_query_part = " unread = true AND ";
3049 $limit_query_part = "LIMIT " . $limit;
3052 $vfeed_query_part = "";
3054 // override query strategy and enable feed display when searching globally
3055 if ($search && $search_mode == "all_feeds") {
3056 $query_strategy_part = "ttrss_entries.id > 0";
3057 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3058 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3059 $query_strategy_part = "ttrss_entries.id > 0";
3060 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3061 id = feed_id) as feed_title,";
3062 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3064 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3066 $tmp_result = false;
3069 $tmp_result = db_query($link, "SELECT id
3070 FROM ttrss_feeds WHERE cat_id = '$feed'");
3072 $tmp_result = db_query($link, "SELECT id
3073 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3074 WHERE id = '$feed') AND id != '$feed'");
3077 $cat_siblings = array();
3079 if (db_num_rows($tmp_result) > 0) {
3080 while ($p = db_fetch_assoc($tmp_result)) {
3081 array_push($cat_siblings, "feed_id = " . $p["id"]);
3084 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3085 $feed, implode(" OR ", $cat_siblings));
3088 $query_strategy_part = "ttrss_entries.id > 0";
3091 } else if ($feed >= 0) {
3096 $query_strategy_part = "cat_id = '$feed'";
3098 $query_strategy_part = "cat_id IS NULL";
3101 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3104 $tmp_result = db_query($link, "SELECT id
3105 FROM ttrss_feeds WHERE parent_feed = '$feed'
3106 ORDER BY cat_id,title");
3108 $parent_ids = array();
3110 if (db_num_rows($tmp_result) > 0) {
3111 while ($p = db_fetch_assoc($tmp_result)) {
3112 array_push($parent_ids, "feed_id = " . $p["id"]);
3115 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3116 $feed, implode(" OR ", $parent_ids));
3118 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3120 $query_strategy_part = "feed_id = '$feed'";
3123 } else if ($feed == -1) { // starred virtual feed
3124 $query_strategy_part = "marked = true";
3125 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3126 } else if ($feed == -2) { // published virtual feed
3127 $query_strategy_part = "published = true";
3128 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3129 } else if ($feed == -3) { // fresh virtual feed
3130 $query_strategy_part = "unread = true";
3132 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3134 if (DB_TYPE
== "pgsql") {
3135 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
3137 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3140 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3141 } else if ($feed <= -10) { // labels
3142 $label_id = -$feed - 11;
3144 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3145 WHERE id = '$label_id'");
3147 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
3149 if (!$query_strategy_part) {
3153 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3155 $query_strategy_part = "id > 0"; // dumb
3158 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3159 $order_by = "updated";
3161 $order_by = "updated DESC";
3164 if ($override_order) {
3165 $order_by = $override_order;
3170 if ($search && $search_mode == "all_feeds") {
3171 $feed_title = __("Search results")." ($search)";
3172 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3173 $feed_title = __("Search results")." ($search, $feed)";
3174 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3175 $feed_title = $feed;
3176 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3181 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3182 WHERE id = '$feed' AND owner_uid = $owner_uid");
3183 $feed_title = db_fetch_result($result, 0, "title");
3185 $feed_title = __("Uncategorized");
3189 $feed_title = __("Searched for")." $search ($feed_title)";
3194 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3195 WHERE id = '$feed' AND owner_uid = $owner_uid");
3197 $feed_title = db_fetch_result($result, 0, "title");
3198 $feed_site_url = db_fetch_result($result, 0, "site_url");
3199 $last_error = db_fetch_result($result, 0, "last_error");
3202 $feed_title = __("Searched for") . " $search ($feed_title)";
3206 } else if ($feed == -1) {
3207 $feed_title = __("Starred articles");
3208 } else if ($feed == -2) {
3209 $feed_title = __("Published articles");
3210 } else if ($feed == -3) {
3211 $feed_title = __("Fresh articles");
3212 } else if ($feed < -10) {
3213 $label_id = -$feed - 11;
3214 $result = db_query($link, "SELECT description FROM ttrss_labels
3215 WHERE id = '$label_id'");
3216 $feed_title = db_fetch_result($result, 0, "description");
3219 $feed_title = __("Searched for") . " $search ($feed_title)";
3225 if ($feed < -10) error_reporting (0);
3227 $content_query_part = "content as content_preview,";
3229 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3232 $feed_kind = "Feeds";
3234 $feed_kind = "Labels";
3237 if ($limit_query_part) {
3238 $offset_query_part = "OFFSET $offset";
3243 ttrss_entries.id,ttrss_entries.title,
3245 unread,feed_id,marked,published,link,last_read,
3246 SUBSTRING(last_read,1,19) as last_read_noms,
3249 SUBSTRING(updated,1,19) as updated_noms,
3252 ttrss_entries,ttrss_user_entries,ttrss_feeds
3254 ttrss_feeds.hidden = false AND
3255 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3256 ttrss_user_entries.ref_id = ttrss_entries.id AND
3257 ttrss_user_entries.owner_uid = '$owner_uid' AND
3260 $query_strategy_part ORDER BY $order_by
3261 $limit_query_part $offset_query_part";
3263 $result = db_query($link, $query);
3265 if ($_GET["debug"]) print $query;
3270 $feed_kind = "Tags";
3272 $result = db_query($link, "SELECT
3274 ttrss_entries.id as id,title,
3277 marked,link,last_read,
3278 SUBSTRING(last_read,1,19) as last_read_noms,
3281 SUBSTRING(updated,1,19) as updated_noms
3283 ttrss_entries,ttrss_user_entries,ttrss_tags
3285 ref_id = ttrss_entries.id AND
3286 ttrss_user_entries.owner_uid = '$owner_uid' AND
3287 post_int_id = int_id AND tag_name = '$feed' AND
3290 $query_strategy_part ORDER BY $order_by
3291 $limit_query_part");
3294 return array($result, $feed_title, $feed_site_url, $last_error);
3298 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3299 $search, $search_mode, $match_on) {
3301 $qfh_ret = queryFeedHeadlines($link, $feed,
3302 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3305 $result = $qfh_ret[0];
3306 $feed_title = htmlspecialchars($qfh_ret[1]);
3307 $feed_site_url = $qfh_ret[2];
3308 $last_error = $qfh_ret[3];
3310 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3312 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3313 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3314 <rss version=\"2.0\">
3316 <title>$feed_title</title>
3317 <link>$feed_site_url</link>
3318 <description>Feed generated by Tiny Tiny RSS</description>";
3320 while ($line = db_fetch_assoc($result)) {
3322 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3323 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3325 $tags = get_article_tags($link, $line["id"], $owner_uid);
3327 foreach ($tags as $tag) {
3328 print "<category>" . htmlspecialchars($tag) . "</category>";
3331 $rfc822_date = date('r', strtotime($line["updated"]));
3333 print "<pubDate>$rfc822_date</pubDate>";
3336 htmlspecialchars($line["title"]) . "</title>";
3338 print "<description><![CDATA[" .
3339 $line["content_preview"] . "]]></description>";
3344 print "</channel></rss>";
3348 function getCategoryTitle($link, $cat_id) {
3350 if ($cat_id == -1) {
3351 return __("Special");
3352 } else if ($cat_id == -2) {
3353 return __("Labels");
3356 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3359 if (db_num_rows($result) == 1) {
3360 return db_fetch_result($result, 0, "title");
3362 return "Uncategorized";
3367 // http://ru2.php.net/strip-tags
3369 function strip_tags_long($textstring, $allowed){
3370 while($textstring != strip_tags($textstring, $allowed))
3372 while (strlen($textstring) != 0)
3374 if (strlen($textstring) > 1024) {
3377 $otherlen = strlen($textstring);
3379 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3380 $safetext .= $temptext;
3381 $textstring = substr_replace($textstring,'',0,$otherlen);
3383 $textstring = $safetext;
3389 function sanitize_rss($link, $str, $force_strip_tags = false) {
3392 if (get_pref($link, "STRIP_UNSAFE_TAGS") ||
$force_strip_tags) {
3394 $res = strip_tags_long($res,
3395 "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
3397 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3398 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3405 * Send by mail a digest of last articles.
3407 * @param mixed $link The database connection.
3408 * @param integer $limit The maximum number of articles by digest.
3409 * @return boolean Return false if digests are not enabled.
3411 function send_headlines_digests($link, $limit = 100) {
3413 if (!DIGEST_ENABLE
) return false;
3415 $user_limit = DIGEST_EMAIL_LIMIT
;
3418 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3420 if (DB_TYPE
== "pgsql") {
3421 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3422 } else if (DB_TYPE
== "mysql") {
3423 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3426 $result = db_query($link, "SELECT id,email FROM ttrss_users
3427 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3429 while ($line = db_fetch_assoc($result)) {
3431 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3432 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3434 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3436 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3437 $digest = $tuple[0];
3438 $headlines_count = $tuple[1];
3439 $affected_ids = $tuple[2];
3440 $digest_text = $tuple[3];
3442 if ($headlines_count > 0) {
3444 $mail = new PHPMailer();
3446 $mail->PluginDir
= "phpmailer/";
3447 $mail->SetLanguage("en", "phpmailer/language/");
3449 $mail->CharSet
= "UTF-8";
3451 $mail->From
= DIGEST_FROM_ADDRESS
;
3452 $mail->FromName
= DIGEST_FROM_NAME
;
3453 $mail->AddAddress($line["email"], $line["login"]);
3455 if (DIGEST_SMTP_HOST
) {
3456 $mail->Host
= DIGEST_SMTP_HOST
;
3457 $mail->Mailer
= "smtp";
3458 $mail->Username
= DIGEST_SMTP_LOGIN
;
3459 $mail->Password
= DIGEST_SMTP_PASSWORD
;
3462 $mail->IsHTML(true);
3463 $mail->Subject
= DIGEST_SUBJECT
;
3464 $mail->Body
= $digest;
3465 $mail->AltBody
= $digest_text;
3467 $rc = $mail->Send();
3469 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
3473 if ($rc && $do_catchup) {
3474 print "Marking affected articles as read...\n";
3475 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3478 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3479 WHERE id = " . $line["id"]);
3481 print "No headlines\n";
3486 print "All done.\n";
3490 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3492 require_once "MiniTemplator.class.php";
3494 $tpl = new MiniTemplator
;
3495 $tpl_t = new MiniTemplator
;
3497 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3498 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3500 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3501 $tpl->setVariable('CUR_TIME', date('G:i'));
3503 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3504 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3506 $affected_ids = array();
3508 if (DB_TYPE
== "pgsql") {
3509 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3510 } else if (DB_TYPE
== "mysql") {
3511 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3514 $result = db_query($link, "SELECT ttrss_entries.title,
3515 ttrss_feeds.title AS feed_title,
3517 ttrss_user_entries.ref_id,
3519 SUBSTRING(content, 1, 120) AS excerpt,
3520 SUBSTRING(last_updated,1,19) AS last_updated
3522 ttrss_user_entries,ttrss_entries,ttrss_feeds
3524 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3525 AND include_in_digest = true
3528 AND ttrss_user_entries.owner_uid = $user_id
3530 ORDER BY ttrss_feeds.title, date_entered DESC
3533 $cur_feed_title = "";
3535 $headlines_count = db_num_rows($result);
3537 $headlines = array();
3539 while ($line = db_fetch_assoc($result)) {
3540 array_push($headlines, $line);
3543 for ($i = 0; $i < sizeof($headlines); $i++
) {
3545 $line = $headlines[$i];
3547 array_push($affected_ids, $line["ref_id"]);
3549 $updated = smart_date_time(strtotime($line["last_updated"]));
3551 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3552 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3553 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3554 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3555 $tpl->setVariable('ARTICLE_EXCERPT',
3556 truncate_string(strip_tags($line["excerpt"]), 100));
3558 $tpl->addBlock('article');
3560 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3561 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3562 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3563 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3564 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3565 // truncate_string(strip_tags($line["excerpt"]), 100));
3567 $tpl_t->addBlock('article');
3569 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
3570 $tpl->addBlock('feed');
3571 $tpl_t->addBlock('feed');
3576 $tpl->addBlock('digest');
3577 $tpl->generateOutputToString($tmp);
3579 $tpl_t->addBlock('digest');
3580 $tpl_t->generateOutputToString($tmp_t);
3582 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3585 function check_for_update($link, $brief_fmt = true) {
3586 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3588 if (!CHECK_FOR_NEW_VERSION ||
$_SESSION["access_level"] < 10) {
3593 if (ENABLE_SIMPLEPIE
) {
3594 $rss = new SimplePie();
3595 $rss->set_useragent(SIMPLEPIE_USERAGENT
. MAGPIE_USER_AGENT_EXT
);
3596 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3597 $rss->set_feed_url($fetch_url);
3598 $rss->set_output_encoding('UTF-8');
3601 $rss = fetch_rss($releases_feed);
3603 error_reporting (DEFAULT_ERROR_LEVEL
);
3607 if (ENABLE_SIMPLEPIE
) {
3608 $items = $rss->get_items();
3610 $items = $rss->items
;
3612 if (!$items ||
!is_array($items)) $items = $rss->entries
;
3613 if (!$items ||
!is_array($items)) $items = $rss;
3616 if (!is_array($items) ||
count($items) == 0) {
3620 $latest_item = $items[0];
3622 if (ENABLE_SIMPLEPIE
) {
3623 $last_title = $latest_item->get_title();
3625 $last_title = $latest_item["title"];
3628 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3630 if (ENABLE_SIMPLEPIE
) {
3631 $release_url = sanitize_rss($link, $latest_item->get_link());
3632 $content = sanitize_rss($link, $latest_item->get_description());
3634 $release_url = sanitize_rss($link, $latest_item["link"]);
3635 $content = sanitize_rss($link, $latest_item["description"]);
3638 if (version_compare(VERSION
, $latest_version) == -1) {
3640 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3641 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3642 <div id=\"milestoneDetails\">$content</div>");
3644 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3645 <div class='milestoneDetails'>$content</div>
3646 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3647 download and update information.";
3654 function markArticlesById($link, $ids, $cmode) {
3658 foreach ($ids as $id) {
3659 array_push($tmp_ids, "ref_id = '$id'");
3662 $ids_qpart = join(" OR ", $tmp_ids);
3665 db_query($link, "UPDATE ttrss_user_entries SET
3666 marked = false,last_read = NOW()
3667 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3668 } else if ($cmode == 1) {
3669 db_query($link, "UPDATE ttrss_user_entries SET
3671 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3673 db_query($link, "UPDATE ttrss_user_entries SET
3674 marked = NOT marked,last_read = NOW()
3675 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3679 function publishArticlesById($link, $ids, $cmode) {
3683 foreach ($ids as $id) {
3684 array_push($tmp_ids, "ref_id = '$id'");
3687 $ids_qpart = join(" OR ", $tmp_ids);
3690 db_query($link, "UPDATE ttrss_user_entries SET
3691 published = false,last_read = NOW()
3692 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3693 } else if ($cmode == 1) {
3694 db_query($link, "UPDATE ttrss_user_entries SET
3696 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3698 db_query($link, "UPDATE ttrss_user_entries SET
3699 published = NOT published,last_read = NOW()
3700 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3704 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3706 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3710 foreach ($ids as $id) {
3711 array_push($tmp_ids, "ref_id = '$id'");
3714 $ids_qpart = join(" OR ", $tmp_ids);
3717 db_query($link, "UPDATE ttrss_user_entries SET
3718 unread = false,last_read = NOW()
3719 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3720 } else if ($cmode == 1) {
3721 db_query($link, "UPDATE ttrss_user_entries SET
3723 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3725 db_query($link, "UPDATE ttrss_user_entries SET
3726 unread = NOT unread,last_read = NOW()
3727 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3731 function catchupArticleById($link, $id, $cmode) {
3734 db_query($link, "UPDATE ttrss_user_entries SET
3735 unread = false,last_read = NOW()
3736 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3737 } else if ($cmode == 1) {
3738 db_query($link, "UPDATE ttrss_user_entries SET
3740 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3742 db_query($link, "UPDATE ttrss_user_entries SET
3743 unread = NOT unread,last_read = NOW()
3744 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3748 function make_guid_from_title($title) {
3749 return preg_replace("/[ \"\',.:;]/", "-",
3750 mb_strtolower(strip_tags($title), 'utf-8'));
3753 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3754 $bottom = false, $rtl_content = false, $feed_id = 0,
3755 $is_cat = false, $search = false, $match_on = false,
3756 $search_mode = false, $offset = 0, $limit = 0) {
3758 $user_page_offset = $offset +
1;
3761 $class = "headlinesSubToolbar";
3762 $tid = "headlineActionsTop";
3764 $class = "headlinesSubToolbar";
3765 $tid = "headlineActionsBottom";
3768 print "<table class=\"$class\" id=\"$tid\"
3769 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3777 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3778 $page_next_link = "javascript:viewFeedGoPage(1)";
3779 $page_first_link = "javascript:viewFeedGoPage(0)";
3781 $catchup_page_link = "javascript:catchupPage()";
3782 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3783 $catchup_sel_link = "javascript:catchupSelection()";
3785 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3787 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3788 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3789 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3791 $tog_unread_link = "javascript:selectionToggleUnread()";
3792 $tog_marked_link = "javascript:selectionToggleMarked()";
3793 $tog_published_link = "javascript:selectionTogglePublished()";
3797 $sel_all_link = "javascript:cdmSelectArticles('all')";
3798 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3799 $sel_none_link = "javascript:cdmSelectArticles('none')";
3801 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3802 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3803 $tog_published_link = "javascript:selectionTogglePublished(true)";
3807 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3809 print "<td class=\"headlineActions$rtl_cpart\">
3810 <ul class=\"headlineDropdownMenu\">
3813 <a href=\"$sel_all_link\">".__('All')."</a>,
3814 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3815 <a href=\"$sel_none_link\">".__('None')."</a></li>
3816 <li class=\"vsep\"> </li>
3817 <li class=\"top\">".__('Toggle')."<ul>
3818 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3819 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3820 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3822 <li class=\"vsep\"> </li>
3823 <li class=\"top\">".__('Mark as read')."<ul>
3824 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3825 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->";
3827 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3830 <li><span class=\"insensitive\">--------</span></li>
3831 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3832 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3833 <li><span class=\"insensitive\">--------</span></li>";
3837 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3840 $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3842 if ($limit != 0 && !$search && $enable_pagination) {
3844 <li class=\"vsep\"> </li>
3845 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3846 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3847 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3851 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3853 <li class=\"vsep\"> </li>
3855 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3856 '$match_on', '$feed_id', '$is_cat');\">
3857 ".__('Convert to label')."</a></td>";
3863 // old style subtoolbar:
3865 print "<td class=\"headlineActions$rtl_cpart\">".
3867 <a href=\"$sel_all_link\">".__('All')."</a>,
3868 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3869 <a href=\"$sel_none_link\">".__('None')."</a>
3871 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3872 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3874 __('Mark as read:')."
3875 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3876 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3878 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS
) {
3881 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3882 '$match_on', '$feed_id', '$is_cat');\">
3883 ".__('Convert to label')."</a>";
3890 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3891 print "<td class=\"headlineActions$rtl_cpart\">
3892 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3893 '$match_on', '$feed_id', '$is_cat');\">
3894 ".__('Convert to Label')."</a></td>";
3897 print "<td class=\"headlineTitle$rtl_cpart\">";
3899 print "<span class=\"headlineInnerTitle\">";
3901 if ($feed_site_url) {
3903 $target = "target=\"_new\"";
3905 print "<a $target href=\"$feed_site_url\">".
3906 truncate_string($feed_title,30)."</a>";
3912 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3915 if ($user_page_offset > 1) {
3916 print " [$user_page_offset] ";
3924 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3925 <img class=\"noborder\"
3926 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3931 print "</tr></table>";
3935 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3937 $tmp_category = getCategoryTitle($link, $cat_id);
3938 $cat_unread = getCategoryUnread($link, $cat_id);
3941 $holder_style = "display:none;";
3948 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
3950 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3951 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3954 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3956 print "<span id=\"FCAP-$cat_id\">";
3959 print " <span id=\"FCATCTR-$cat_id\"
3960 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
3970 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3973 function outputFeedList($link, $tags = false) {
3975 print "<ul class=\"feedList\" id=\"feedList\">";
3977 $owner_uid = $_SESSION["uid"];
3981 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3983 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
3986 $cat_hidden = false;
3989 # print "<li class=\"feedCat\">".__('Special')."</li>";
3990 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3991 # print "<li class=\"feedCat\">".
3992 # "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
3993 # __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
3995 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
3996 # <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
3998 # $cat_unread = getCategoryUnread($link, -1);
3999 # $tmp_category = __("Special");
4000 # $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4002 printCategoryHeader($link, -1, $cat_hidden, false);
4005 $num_starred = getFeedUnread($link, -1);
4006 $num_published = getFeedUnread($link, -2);
4007 $num_fresh = getFeedUnread($link, -3);
4011 if ($num_fresh > 0) $class .= "Unread";
4013 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4014 "images/fresh.png", $link);
4018 if ($num_starred > 0) $class .= "Unread";
4020 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4023 $mark_img_ext = "gif";
4025 $mark_img_ext = "png";
4028 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4029 "images/mark_set.$mark_img_ext", $link);
4033 if ($num_published > 0) $class .= "Unread";
4035 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4036 "images/pub_set.gif", $link);
4038 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4044 if (GLOBAL_ENABLE_LABELS
&& get_pref($link, 'ENABLE_LABELS')) {
4046 $result = db_query($link, "SELECT id,sql_exp,description FROM
4047 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4049 if (db_num_rows($result) > 0) {
4050 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4052 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4055 $cat_hidden = false;
4058 printCategoryHeader($link, -2, $cat_hidden, false);
4060 # print "<li class=\"feedCat\">".
4061 # "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
4062 # __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
4064 # print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
4066 print "<li><hr></li>";
4070 while ($line = db_fetch_assoc($result)) {
4072 error_reporting (0);
4074 $label_id = -$line['id'] - 11;
4075 $count = getFeedUnread($link, $label_id);
4083 error_reporting (DEFAULT_ERROR_LEVEL
);
4085 printFeedEntry($label_id,
4086 $class, $line["description"],
4087 $count, "images/label.png", $link);
4091 if (db_num_rows($result) > 0) {
4092 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4099 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4100 print "<li><hr></li>";
4103 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4104 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4105 $order_by_qpart = "category,unread DESC,title";
4107 $order_by_qpart = "category,title";
4110 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4111 $order_by_qpart = "unread DESC,title";
4113 $order_by_qpart = "title";
4117 $age_qpart = getMaxAgeSubquery();
4119 $result = db_query($link, "SELECT ttrss_feeds.*,
4120 SUBSTRING(last_updated,1,19) AS last_updated_noms,
4121 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4122 WHERE feed_id = ttrss_feeds.id AND unread = true
4124 AND ttrss_user_entries.ref_id = ttrss_entries.id
4125 AND owner_uid = '$owner_uid') as unread,
4127 ttrss_feed_categories.title AS category,
4128 ttrss_feed_categories.collapsed
4129 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4130 ON (ttrss_feed_categories.id = cat_id)
4132 ttrss_feeds.hidden = false AND
4133 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4134 ORDER BY $order_by_qpart");
4136 $actid = $_GET["actid"];
4146 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4148 while ($line = db_fetch_assoc($result)) {
4150 $feed = trim($line["title"]);
4152 if (!$feed) $feed = "[Untitled]";
4154 $feed_id = $line["id"];
4156 $subop = $_GET["subop"];
4158 $unread = $line["unread"];
4160 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4161 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4163 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4166 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4169 $rtl_tag = "dir=\"RTL\"";
4174 $tmp_result = db_query($link,
4175 "SELECT id,COUNT(unread) AS unread
4176 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
4177 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
4178 WHERE parent_feed = '$feed_id' AND unread = true
4179 GROUP BY ttrss_feeds.id");
4181 if (db_num_rows($tmp_result) > 0) {
4182 while ($l = db_fetch_assoc($tmp_result)) {
4183 $unread +
= $l["unread"];
4187 $cat_id = $line["cat_id"];
4189 $tmp_category = $line["category"];
4191 if (!$tmp_category) {
4192 $tmp_category = __("Uncategorized");
4195 // $class = ($lnum % 2) ? "even" : "odd";
4197 if ($line["last_error"]) {
4203 if ($unread > 0) $class .= "Unread";
4205 if ($actid == $feed_id) {
4206 $class .= "Selected";
4209 $total_unread +
= $unread;
4211 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4217 $category = $tmp_category;
4219 $collapsed = $line["collapsed"];
4221 // workaround for NULL category
4222 if ($category == __("Uncategorized")) {
4223 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4228 if ($collapsed == "t" ||
$collapsed == "1") {
4229 $holder_class = "feedCatHolder";
4230 $holder_style = "display:none;";
4233 $holder_class = "feedCatHolder";
4238 $cat_id = sprintf("%d", $cat_id);
4240 $cat_unread = getCategoryUnread($link, $cat_id);
4242 $catctr_class = ($cat_unread > 0) ?
"catCtrHasUnread" : "catCtrNoUnread";
4244 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
4245 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
4246 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
4247 <span id=\"FCATCTR-$cat_id\"
4248 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
4251 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4254 printFeedEntry($feed_id, $class, $feed, $unread,
4255 ICONS_URL
."/$feed_id.ico", $link, $rtl_content,
4256 $last_updated, $line["last_error"]);
4261 if (db_num_rows($result) == 0) {
4262 print "<li>".__('No feeds to display.')."</li>";
4269 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4270 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4271 post_int_id = ttrss_user_entries.int_id AND
4272 unread = true AND ref_id = ttrss_entries.id
4273 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4275 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4276 ORDER BY tag_name"); */
4278 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4279 print "<li class=\"feedCat\">".__('Tags')."</li>";
4280 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4283 $age_qpart = getMaxAgeSubquery();
4285 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4286 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4287 AND ref_id = id AND $age_qpart
4288 AND unread = true)) AS count FROM ttrss_tags
4289 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4290 ORDER BY count DESC LIMIT 50");
4294 while ($line = db_fetch_assoc($result)) {
4295 $tags[$line["tag_name"]] +
= $line["count"];
4298 foreach (array_keys($tags) as $tag) {
4300 $unread = $tags[$tag];
4308 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4312 if (db_num_rows($result) == 0) {
4313 print "<li>No tags to display.</li>";
4316 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4326 function get_article_tags($link, $id, $owner_uid = 0) {
4328 $a_id = db_escape_string($id);
4330 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4332 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4333 owner_uid as owner FROM
4334 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4335 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4339 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4340 array_push($tags, $tmp_line["tag_name"]);
4346 function trim_value(&$value) {
4347 $value = trim($value);
4350 function trim_array($array) {
4352 array_walk($tmp, 'trim_value');
4356 function tag_is_valid($tag) {
4357 if ($tag == '') return false;
4358 if (preg_match("/^[0-9]*$/", $tag)) return false;
4360 $tag = iconv("utf-8", "utf-8", $tag);
4361 if (!$tag) return false;
4366 function render_login_form($link, $mobile = false) {
4368 require_once "login_form.php";
4370 require_once "mobile/login_form.php";
4374 // from http://developer.apple.com/internet/safari/faq.html
4375 function no_cache_incantation() {
4376 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4377 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4378 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4379 header("Cache-Control: post-check=0, pre-check=0", false);
4380 header("Pragma: no-cache"); // HTTP/1.0
4383 function format_warning($msg, $id = "") {
4384 return "<div class=\"warning\" id=\"$id\">
4385 <img src=\"images/sign_excl.gif\">$msg</div>";
4388 function format_notice($msg) {
4389 return "<div class=\"notice\">
4390 <img src=\"images/sign_info.gif\">$msg</div>";
4393 function format_error($msg) {
4394 return "<div class=\"error\">
4395 <img src=\"images/sign_excl.gif\">$msg</div>";
4398 function print_notice($msg) {
4399 return print format_notice($msg);
4402 function print_warning($msg) {
4403 return print format_warning($msg);
4406 function print_error($msg) {
4407 return print format_error($msg);
4411 function T_sprintf() {
4412 $args = func_get_args();
4413 return vsprintf(__(array_shift($args)), $args);
4416 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4418 /* we can figure out feed_id from article id anyway, why do we
4419 * pass feed_id here? */
4421 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4422 WHERE ref_id = '$id'");
4424 $feed_id = db_fetch_result($result, 0, "feed_id");
4426 print "<article id='$id'><![CDATA[";
4428 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4429 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4431 if (db_num_rows($result) == 1) {
4432 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4434 $rtl_content = false;
4438 $rtl_tag = "dir=\"RTL\"";
4445 if ($mark_as_read) {
4446 $result = db_query($link, "UPDATE ttrss_user_entries
4447 SET unread = false,last_read = NOW()
4448 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4451 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4452 SUBSTRING(updated,1,16) as updated,
4453 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4456 FROM ttrss_entries,ttrss_user_entries
4457 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4463 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4464 $link_target = "target=\"_new\"";
4467 $line = db_fetch_assoc($result);
4469 if ($line["icon_url"]) {
4470 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4472 $feed_icon = " ";
4475 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4476 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4478 $entry_comments = "";
4481 $num_comments = $line["num_comments"];
4482 $entry_comments = "";
4484 if ($num_comments > 0) {
4485 if ($line["comments"]) {
4486 $comments_url = $line["comments"];
4488 $comments_url = $line["link"];
4490 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4492 if ($line["comments"] && $line["link"] != $line["comments"]) {
4493 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4497 print "<div class=\"postReply\">";
4499 print "<div class=\"postHeader\">";
4501 $entry_author = $line["author"];
4503 if ($entry_author) {
4504 $entry_author = __(" - ") . $entry_author;
4507 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4508 strtotime($line["updated"]));
4510 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4512 if ($line["link"]) {
4513 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4514 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4516 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4519 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4520 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4521 ORDER BY tag_name"); */
4523 $tags = get_article_tags($link, $id);
4530 if ($_SESSION["theme"] == "3pane") {
4536 foreach ($tags as $tag) {
4538 $tag_escaped = str_replace("'", "\\'", $tag);
4540 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4542 if ($num_tags == $tag_limit) {
4543 $tags_str .= "…";
4545 } else if ($num_tags < $tag_limit) {
4546 $tags_str .= $tag_str;
4548 $f_tags_str .= $tag_str;
4551 $tags_str = preg_replace("/, $/", "", $tags_str);
4552 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4554 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4555 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4557 if (!$entry_comments) $entry_comments = " "; # placeholder
4559 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4561 print "<div style='float : right'>
4562 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4564 <a title=\"Edit tags for this article\"
4565 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4566 <div clear='both'>$entry_comments</div>";
4570 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4571 print "<div class=\"postContent\">";
4573 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4575 $line["content"] = sanitize_rss($link, $line["content"]);
4577 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4578 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4581 print $line["content"];
4583 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4586 if (db_num_rows($result) > 0) {
4587 print "<div class=\"postEnclosures\">";
4589 if (db_num_rows($result) == 1) {
4590 print __("Attachment:") . " ";
4592 print __("Attachments:") . " ";
4597 while ($line = db_fetch_assoc($result)) {
4599 $url = $line["content_url"];
4601 $filename = substr($url, strrpos($url, "/")+
1);
4603 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4604 $filename . " (" . $line["content_type"] . ")" . "</a>";
4606 array_push($entries, $entry);
4609 print join(", ", $entries);
4620 print "]]></article>";
4624 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4625 $next_unread_feed, $offset) {
4627 $disable_cache = false;
4629 $timing_info = getmicrotime();
4631 $topmost_article_ids = array();
4637 if ($subop == "undefined") $subop = "";
4639 if ($subop == "CatchupSelected") {
4640 $ids = split(",", db_escape_string($_GET["ids"]));
4641 $cmode = sprintf("%d", $_GET["cmode"]);
4643 catchupArticlesById($link, $ids, $cmode);
4646 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4647 update_generic_feed($link, $feed, $cat_view, true);
4650 if ($subop == "MarkAllRead") {
4651 catchup_feed($link, $feed, $cat_view);
4653 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4654 if ($next_unread_feed) {
4655 $feed = $next_unread_feed;
4661 $result = db_query($link,
4662 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4664 if (db_num_rows($result) == 0) {
4665 print "<div align='center'>".__('Feed not found.')."</div>";
4670 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4672 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4673 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4675 if (db_num_rows($result) == 1) {
4676 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4678 $rtl_content = false;
4682 $rtl_tag = "dir=\"RTL\"";
4688 $rtl_content = false;
4691 $script_dt_add = get_script_dt_add();
4693 /// START /////////////////////////////////////////////////////////////////////////////////
4695 $search = db_escape_string($_GET["query"]);
4698 $disable_cache = true;
4701 $search_mode = db_escape_string($_GET["search_mode"]);
4702 $match_on = db_escape_string($_GET["match_on"]);
4708 $real_offset = $offset * $limit;
4710 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4712 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4713 $search, $search_mode, $match_on, false, $real_offset);
4715 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4717 $result = $qfh_ret[0];
4718 $feed_title = $qfh_ret[1];
4719 $feed_site_url = $qfh_ret[2];
4720 $last_error = $qfh_ret[3];
4723 $feed_site_url = article_publish_url($link);
4726 /// STOP //////////////////////////////////////////////////////////////////////////////////
4729 print "<div id=\"headlinesContainer\" $rtl_tag>";
4732 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4736 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
4737 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
4740 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4743 $headlines_count = db_num_rows($result);
4745 if (db_num_rows($result) > 0) {
4747 # print "\{$offset}";
4749 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4750 print "<table class=\"headlinesList\" id=\"headlinesList\"
4751 cellspacing=\"0\">";
4754 $lnum = $limit*$offset;
4756 error_reporting (DEFAULT_ERROR_LEVEL
);
4760 while ($line = db_fetch_assoc($result)) {
4762 $class = ($lnum %
2) ?
"even" : "odd";
4765 $feed_id = $line["feed_id"];
4767 if (count($topmost_article_ids) < 5) {
4768 array_push($topmost_article_ids, $id);
4771 if ($line["last_read"] == "" &&
4772 ($line["unread"] != "t" && $line["unread"] != "1")) {
4774 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4777 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4781 if ($line["unread"] == "t" ||
$line["unread"] == "1") {
4789 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4792 $mark_img_ext = "gif";
4794 $mark_img_ext = "png";
4797 if ($line["marked"] == "t" ||
$line["marked"] == "1") {
4798 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4800 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4802 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4804 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4807 if ($line["published"] == "t" ||
$line["published"] == "1") {
4808 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4810 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4812 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4814 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4817 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4818 # $line["title"] . "</a>";
4820 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4821 $line["title"] . "</a>";
4823 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4824 # $line["title"] . "</a>";
4826 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4827 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4829 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4830 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4833 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4834 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4838 $entry_author = $line["author"];
4840 if ($entry_author) {
4841 $entry_author = " - $entry_author";
4844 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4846 print "<tr class='$class' id='RROW-$id'>";
4848 print "<td class='hlUpdPic'>$update_pic</td>";
4850 print "<td class='hlSelectRow'>
4851 <input type=\"checkbox\" onclick=\"tSR(this)\"
4855 print "<td class='hlMarkedPic'>$marked_pic</td>";
4856 print "<td class='hlMarkedPic'>$published_pic</td>";
4858 # if ($line["feed_title"]) {
4859 # print "<td class='hlContent'>$content_link</td>";
4860 # print "<td class='hlFeed'>
4861 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4862 # truncate_string($line["feed_title"],30)."</a> </td>";
4865 print "<td class='hlContent' valign='middle'>";
4867 print "<a href=\"javascript:view($id,$feed_id);\">" .
4870 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4871 if ($content_preview) {
4872 print "<span class=\"contentPreview\"> - $content_preview</span>";
4878 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4879 # $line["feed_title"]."</a>
4881 if ($line["feed_title"]) {
4882 print "<span class=\"hlFeed\">
4883 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4884 $line["feed_title"]."</a>)
4893 print "<td class=\"hlUpdated\"><nobr>$updated_fmt </nobr></td>";
4900 $add_class = "Unread";
4905 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
4910 $cdm_cstyle = "style=\"display : none\"";
4913 print "<div class=\"cdmArticle$add_class\"
4914 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)'
4915 onmouseout='cdmMouseOut(this)'>";
4917 print "<div class=\"cdmHeader\">";
4919 print "<div class=\"articleUpdated\">$updated_fmt</div>";
4921 print "<a class=\"title\"
4922 onclick=\"javascript:toggleUnread($id, 0)\"
4923 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4925 print $entry_author;
4928 print " <a id=\"CICH-$id\"
4929 href=\"javascript:cdmExpandArticle($id)\">
4930 (".__('Show article').")</a>";
4934 if ($line["feed_title"]) {
4935 print " (<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4940 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4941 $line["content_preview"] = preg_replace("/href=/i",
4942 "target=\"_new\" href=", $line["content_preview"]);
4945 print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
4947 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
4948 print $line["content_preview"];
4950 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4953 if (db_num_rows($e_result) > 0) {
4954 print "<div class=\"cdmEnclosures\">";
4956 if (db_num_rows($e_result) == 1) {
4957 print __("Attachment:") . " ";
4959 print __("Attachments:") . " ";
4964 while ($e_line = db_fetch_assoc($e_result)) {
4966 $url = $e_line["content_url"];
4968 $filename = substr($url, strrpos($url, "/")+
1);
4970 $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4971 $filename . " (" . $e_line["content_type"] . ")" . "</a>";
4973 array_push($entries, $entry);
4976 print join(", ", $entries);
4981 print "<br clear='both'>";
4984 /* if (!$expand_cdm) {
4985 print "<a id=\"CICH-$id\"
4986 href=\"javascript:cdmExpandArticle($id)\">
4992 print "<div class=\"cdmFooter\"><span class='s0'>";
4994 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
4996 print __("Select:").
4997 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
4998 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5000 print "</span><span class='s1'>$marked_pic</span> ";
5001 print "<span class='s1'>$published_pic</span> ";
5003 $tags = get_article_tags($link, $id);
5006 $full_tags_str = "";
5009 foreach ($tags as $tag) {
5011 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5012 if ($num_tags < 5) {
5013 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5014 } else if ($num_tags == 5) {
5015 $tags_str .= "…";
5019 $tags_str = preg_replace("/, $/", "", $tags_str);
5020 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5022 $all_tags_div = "<span class='cdmAllTagsCtr'>…<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5024 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5027 if ($tags_str == "") $tags_str = "no tags";
5029 // print "<img src='images/tag.png' class='markedPic'>";
5031 print "<span class='s1'>
5032 <img class='tagsPic' src='images/tag.png' alt='Tags'
5033 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5034 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5038 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5039 href=\"javascript:toggleUnread($id)\">
5050 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5054 // print_headline_subtoolbar($link,
5055 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5059 if (!$offset) print "<div class='whiteBox'>".__('No articles found.')."</div>";
5067 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
5070 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5072 function printTagCloud($link) {
5074 /* get first ref_id to count from */
5080 if (DB_TYPE == "pgsql") {
5081 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5082 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5083 AND date_entered > NOW() - INTERVAL '30 days'";
5085 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5086 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5087 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5090 $result = db_query($link, $query);
5091 $first_id = db_fetch_result($result, 0, "id"); */
5093 //AND post_int_id >= '$first_id'
5094 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5095 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5096 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5098 $result = db_query($link, $query);
5102 while ($line = db_fetch_assoc($result)) {
5103 $tags[$line["tag_name"]] = $line["count"];
5108 $max_size = 32; // max font size in pixels
5109 $min_size = 11; // min font size in pixels
5111 // largest and smallest array values
5112 $max_qty = max(array_values($tags));
5113 $min_qty = min(array_values($tags));
5115 // find the range of values
5116 $spread = $max_qty - $min_qty;
5117 if ($spread == 0) { // we don't want to divide by zero
5121 // set the font-size increment
5122 $step = ($max_size - $min_size) / ($spread);
5124 // loop through the tag array
5125 foreach ($tags as $key => $value) {
5126 // calculate font-size
5127 // find the $value in excess of $min_qty
5128 // multiply by the font-size increment ($size)
5129 // and add the $min_size set above
5130 $size = round($min_size +
(($value - $min_qty) * $step));
5132 $key_escaped = str_replace("'", "\\'", $key);
5134 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5135 $size . "px\" title=\"$value articles tagged with " .
5136 $key . '">' . $key . '</a> ';
5140 function print_checkpoint($n, $s) {
5141 $ts = getmicrotime();
5142 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5146 function sanitize_tag($tag) {
5149 $tag = mb_strtolower($tag, 'utf-8');
5151 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5153 // $tag = str_replace('"', "", $tag);
5154 // $tag = str_replace("+", " ", $tag);
5155 $tag = str_replace("technorati tag: ", "", $tag);
5160 function generate_publish_key() {
5161 return sha1(uniqid(rand(), true));
5164 function article_publish_url($link) {
5166 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5168 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5174 * Purge a feed contents, marked articles excepted.
5176 * @param mixed $link The database connection.
5177 * @param integer $id The id of the feed to purge.
5180 function clear_feed_articles($link, $id) {
5181 $result = db_query($link, "DELETE FROM ttrss_user_entries
5182 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5184 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5185 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5186 } // function clear_feed_articles
5189 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5191 * @return string The Mozilla Firefox feed adding URL.
5193 function add_feed_url() {
5194 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH
);
5195 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5197 } // function add_feed_url
5200 * Encrypt a password in SHA1.
5202 * @param string $pass The password to encrypt.
5203 * @param string $login A optionnal login.
5204 * @return string The encrypted password.
5206 function encrypt_password($pass, $login = '') {
5208 return "SHA1X:" . sha1("$login:$pass");
5210 return "SHA1:" . sha1($pass);
5212 } // function encrypt_password
5215 * Update a feed batch.
5216 * Used by daemons to update n feeds by run.
5217 * Only update feed needing a update, and not being processed
5218 * by another process.
5220 * @param mixed $link Database link
5221 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5222 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5223 * @param boolean $debug Set to false to disable debug output. Default to true.
5226 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT
, $from_http = false, $debug = true) {
5227 // Process all other feeds using last_updated and interval parameters
5229 // Test if the user has loggued in recently. If not, it does not update its feeds.
5230 if (DAEMON_UPDATE_LOGIN_LIMIT
> 0) {
5231 if (DB_TYPE
== "pgsql") {
5232 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT
." days'";
5234 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT
." DAY)";
5237 $login_thresh_qpart = "";
5240 // Test if the feed need a update (update interval exceded).
5241 if (DB_TYPE
== "pgsql") {
5242 $update_limit_qpart = "AND ((
5243 ttrss_feeds.update_interval = 0
5244 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5246 ttrss_feeds.update_interval > 0
5247 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5248 ) OR ttrss_feeds.last_updated IS NULL)";
5250 $update_limit_qpart = "AND ((
5251 ttrss_feeds.update_interval = 0
5252 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5254 ttrss_feeds.update_interval > 0
5255 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5256 ) OR ttrss_feeds.last_updated IS NULL)";
5259 // Test if feed is currently being updated by another process.
5260 if (DB_TYPE
== "pgsql") {
5261 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5263 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5266 // Test if there is a limit to number of updated feeds
5268 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5270 $random_qpart = sql_random_function();
5272 // We search for feed needing update.
5273 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5274 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated,
5275 ttrss_feeds.update_interval
5277 ttrss_feeds, ttrss_users, ttrss_user_prefs
5279 ttrss_feeds.owner_uid = ttrss_users.id
5280 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5281 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5282 $login_thresh_qpart $update_limit_qpart
5283 $updstart_thresh_qpart
5284 ORDER BY $random_qpart $query_limit");
5286 $user_prefs_cache = array();
5288 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5292 // Here is a little cache magic in order to minimize risk of double feed updates.
5293 $feeds_to_update = array();
5294 while ($line = db_fetch_assoc($result)) {
5295 $feeds_to_update[$line['id']] = $line;
5298 // We update the feed last update started date before anything else.
5299 // There is no lag due to feed contents downloads
5300 // It prevent an other process to update the same feed.
5301 $feed_ids = array_keys($feeds_to_update);
5303 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5304 WHERE id IN (%s)", implode(',', $feed_ids)));
5307 // For each feed, we call the feed update function.
5308 while ($line = array_pop($feeds_to_update)) {
5310 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5312 // We setup a alarm to alert if the feed take more than 300s to update.
5314 if(!$from_http) pcntl_alarm(300);
5315 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5316 // Cancel the alarm (the update went well)
5317 if(!$from_http) pcntl_alarm(0);
5319 sleep(1); // prevent flood (FIXME make this an option?)
5322 // Send feed digests by email if needed.
5323 if (DAEMON_SENDS_DIGESTS
) send_headlines_digests($link);
5325 } // function update_daemon_common