]> git.wh0rd.org - tt-rss.git/blobdiff - functions.php
add multiprocess update daemon
[tt-rss.git] / functions.php
index fd8f4da00af40d0c95818d75508e25f8754a0210..9bd98795b646009b0126868ee3efd06ecf7218ab 100644 (file)
@@ -13,7 +13,9 @@
                                        "auto"  => "Detect automatically",
                                        "en_US" => "English",
                                        "fr_FR" => "Français",
+                                       "nb_NO" => "Norsk Bokmål",
                                        "ru_RU" => "Русский",
+                                       "pt_BR" => "Portuguese/Brazil",
                                        "zh_CN" => "Simplified Chinese");
 
                return $tr;
        require_once 'errors.php';
        require_once 'version.php';
 
+       require_once 'phpmailer/class.phpmailer.php';
+
        define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
        define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
 
-       require_once "magpierss/rss_fetch.inc";
-       require_once 'magpierss/rss_utils.inc';
-
-       include_once "tw/tw-config.php";
-       include_once "tw/tw.php";
-       include_once TW_SETUP . "paranoya.php";
-
-       $tw_parser = new twParser();
+       if (ENABLE_SIMPLEPIE) {
+               require_once "simplepie/simplepie.inc";
+       } else {
+               require_once "magpierss/rss_fetch.inc";
+               require_once 'magpierss/rss_utils.inc';
+       }
 
        function _debug($msg) {
                $ts = strftime("%H:%M:%S", time());
 
        function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
 
+               if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
+
                $rows = -1;
 
+               $result = db_query($link, 
+                       "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
+
+               $owner_uid = false;
+
+               if (db_num_rows($result) == 1) {
+                       $owner_uid = db_fetch_result($result, 0, "owner_uid");
+               }
+
+               if (!$owner_uid) return;
+
+               $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
+                       $owner_uid, false);
+
+               if (!$purge_unread) $query_limit = " unread = false AND ";
+
                if (DB_TYPE == "pgsql") {
 /*                     $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
                                marked = false AND feed_id = '$feed_id' AND
                                        ttrss_entries.id = ref_id AND 
                                        marked = false AND 
                                        feed_id = '$feed_id' AND 
+                                       $query_limit
                                        ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
 
                        } else {
                                        WHERE ttrss_entries.id = ref_id AND 
                                        marked = false AND 
                                        feed_id = '$feed_id' AND 
+                                       $query_limit
                                        ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
                        }
 
                                WHERE ttrss_entries.id = ref_id AND 
                                marked = false AND 
                                feed_id = '$feed_id' AND 
+                               $query_limit
                                ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
                                        
                        $rows = mysql_affected_rows($link);
                }       
 
                // purge orphaned posts in main content table
-               db_query($link, "DELETE FROM ttrss_entries WHERE 
+               $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
                        (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
 
+               if ($do_output) {
+                       $rows = db_affected_rows($link, $result);
+                       _debug("Purged $rows orphaned posts.");
+               }
+
+       }
+
+       function feed_purge_interval($link, $feed_id) {
+
+               $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds 
+                       WHERE id = '$feed_id'");
+
+               if (db_num_rows($result) == 1) {
+                       $purge_interval = db_fetch_result($result, 0, "purge_interval");
+                       $owner_uid = db_fetch_result($result, 0, "owner_uid");
+
+                       if ($purge_interval == 0) $purge_interval = get_pref($link, 
+                               'PURGE_OLD_DAYS', $user_id);
+
+                       return $purge_interval;
+
+               } else {
+                       return -1;
+               }
        }
 
        function purge_old_posts($link) {
                        (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
        }
 
+       function get_feed_update_interval($link, $feed_id) {
+               $result = db_query($link, "SELECT owner_uid, update_interval FROM
+                       ttrss_feeds WHERE id = '$feed_id'");
+
+               if (db_num_rows($result) == 1) {
+                       $update_interval = db_fetch_result($result, 0, "update_interval");
+                       $owner_uid = db_fetch_result($result, 0, "owner_uid");
+
+                       if ($update_interval != 0) {
+                               return $update_interval;
+                       } else {
+                               return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
+                       }
+
+               } else {
+                       return -1;
+               }
+       }
+
        function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
 
                if (WEB_DEMO_MODE) return;
 
        function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
 
-               if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
+               if (!$_GET["daemon"] && !$ignore_daemon) {
                        return;                 
                }
 
                        _debug("update_rss_feed: start");
                }
 
-               $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
-                       FROM ttrss_feeds WHERE id = '$feed'");
+               if (DB_TYPE == "pgsql") {
+                               $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started >= NOW() - INTERVAL '120 seconds')";
+                       } else {
+                               $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started >= DATE_SUB(NOW(), INTERVAL 120 SECOND))";
+                       }                       
+
+               $result = db_query($link, "SELECT id,update_interval,auth_login,
+                       auth_pass,cache_images
+                       FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
+
+               if (db_num_rows($result) == 0) {
+                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                               _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
+                       }               
+                       return;
+               }
+
+               db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
+                       WHERE id = '$feed'");
 
                $auth_login = db_fetch_result($result, 0, "auth_login");
                $auth_pass = db_fetch_result($result, 0, "auth_pass");
 
+               if (!ENABLE_SIMPLEPIE) {
+                       $auth_login = urlencode($auth_login);
+                       $auth_pass = urlencode($auth_pass);
+               }
+
                $update_interval = db_fetch_result($result, 0, "update_interval");
+               $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
 
                if ($update_interval < 0) { return; }
 
                }
 
                if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
-                       _debug("update_rss_feed: fetching...");
+                       _debug("update_rss_feed: fetching [$fetch_url]...");
                }
 
-               if (!defined('DAEMON_EXTENDED_DEBUG')) {
+               if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
                        error_reporting(0);
                }
 
-               $rss = fetch_rss($fetch_url);
+               if (!ENABLE_SIMPLEPIE) {
+                       $rss = fetch_rss($fetch_url);
+               } else {
+                       if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
+                               mkdir(SIMPLEPIE_CACHE_DIR);
+                       }
+
+                       $rss = new SimplePie();
+                       $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
+//                     $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
+                       $rss->set_feed_url($fetch_url);
+                       $rss->set_output_encoding('UTF-8');
+
+                       if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       _debug("enabling image cache");
+                               }
+
+                               $rss->set_image_handler('./image.php', 'i');
+                       }
+
+                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                               _debug("feed update interval (sec): " .
+                                       get_feed_update_interval($link, $feed)*60);
+                       }
+
+                       if (is_dir(SIMPLEPIE_CACHE_DIR)) {
+                               $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
+                               $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
+                       }
+
+                       $rss->init();
+               }
+
+//             print_r($rss);
 
                if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                        _debug("update_rss_feed: fetch done, parsing...");
 
                $feed = db_escape_string($feed);
 
-               if ($rss) {
+               if (ENABLE_SIMPLEPIE) {
+                       $fetch_ok = !$rss->error();
+               } else {
+                       $fetch_ok = !!$rss;
+               }
+
+               if ($fetch_ok) {
 
                        if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                _debug("update_rss_feed: processing feed data...");
 
                        $owner_uid = db_fetch_result($result, 0, "owner_uid");
 
+                       if (ENABLE_SIMPLEPIE) {
+                               $site_url = $rss->get_link();
+                       } else {
+                               $site_url = $rss->channel["link"];
+                       }
+
                        if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
                                if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: checking favicon...");
                                }
-                               check_feed_favicon($rss->channel["link"], $feed, $link);
+
+                               check_feed_favicon($site_url, $feed, $link);
                        }
 
                        if (!$registered_title || $registered_title == "[Unknown]") {
 
-                               $feed_title = db_escape_string($rss->channel["title"]);
+                               if (ENABLE_SIMPLEPIE) {
+                                       $feed_title = db_escape_string($rss->get_title());
+                               } else {
+                                       $feed_title = db_escape_string($rss->channel["title"]);
+                               }
 
                                if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: registering title: $feed_title");
                                        title = '$feed_title' WHERE id = '$feed'");
                        }
 
-                       $site_url = $rss->channel["link"];
                        // weird, weird Magpie
-                       if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
+                       if (!ENABLE_SIMPLEPIE) {
+                               if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
+                       }
 
                        if ($site_url && $orig_site_url != db_escape_string($site_url)) {
                                db_query($link, "UPDATE ttrss_feeds SET 
 
 //                     print "I: " . $rss->channel["image"]["url"];
 
-                       $icon_url = $rss->image["url"];
+                       if (!ENABLE_SIMPLEPIE) {
+                               $icon_url = $rss->image["url"];
+                       } else {
+                               $icon_url = $rss->get_image_url();
+                       }
 
                        if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
                                $icon_url = db_escape_string($icon_url);
                                db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
                        }
 
-                       if (defined('DAEMON_EXTENDED_DEBUG' || $_GET['xdebug'])) {
+                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                _debug("update_rss_feed: loading filters...");
                        }
 
                                array_push($filters[$line["name"]], $filter);
                        }
 
-                       $iterator = $rss->items;
-
-                       if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
-                       if (!$iterator || !is_array($iterator)) $iterator = $rss;
+                       if (ENABLE_SIMPLEPIE) {
+                               $iterator = $rss->get_items();
+                       } else {
+                               $iterator = $rss->items;
+                               if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
+                               if (!$iterator || !is_array($iterator)) $iterator = $rss;
+                       }
 
                        if (!is_array($iterator)) {
                                /* db_query($link, "UPDATE ttrss_feeds 
                                // clear any errors and mark feed as updated if fetched okay
                                // even if it's blank
 
-                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: entry iterator is not an array, no articles?");
                                }
 
                                return; // no articles
                        }
 
-                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                _debug("update_rss_feed: processing articles...");
                        }
 
                        foreach ($iterator as $item) {
 
-                               $entry_guid = $item["id"];
+                               if ($_GET['xdebug']) {
+                                       print_r($item);
+
+                               }
+
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_guid = $item->get_id();
+                                       if (!$entry_guid) $entry_guid = $item->get_link();
+                                       if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
 
-                               if (!$entry_guid) $entry_guid = $item["guid"];
-                               if (!$entry_guid) $entry_guid = $item["link"];
-                               if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
+                               } else {
+
+                                       $entry_guid = $item["id"];
+
+                                       if (!$entry_guid) $entry_guid = $item["guid"];
+                                       if (!$entry_guid) $entry_guid = $item["link"];
+                                       if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
+                               }
 
-                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: guid $entry_guid");
                                }
 
 
                                $entry_timestamp = "";
 
-                               $rss_2_date = $item['pubdate'];
-                               $rss_1_date = $item['dc']['date'];
-                               $atom_date = $item['issued'];
-                               if (!$atom_date) $atom_date = $item['updated'];
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_timestamp = strtotime($item->get_date());
+                               } else {
+                                       $rss_2_date = $item['pubdate'];
+                                       $rss_1_date = $item['dc']['date'];
+                                       $atom_date = $item['issued'];
+                                       if (!$atom_date) $atom_date = $item['updated'];
                        
-                               if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
-                               if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
-                               if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
-                               
+                                       if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
+                                       if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
+                                       if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
+                               }
+
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       _debug("update_rss_feed: date $entry_timestamp");
+                               }
+
                                if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
                                        $entry_timestamp = time();
                                        $no_orig_date = 'true';
 
                                $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
 
-                               $entry_title = trim(strip_tags($item["title"]));
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_title = $item->get_title();
+                               } else {
+                                       $entry_title = trim(strip_tags($item["title"]));
+                               }
 
-                               // strange Magpie workaround
-                               $entry_link = $item["link_"];
-                               if (!$entry_link) $entry_link = $item["link"];
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_link = $item->get_link();
+                               } else {
+                                       // strange Magpie workaround
+                                       $entry_link = $item["link_"];
+                                       if (!$entry_link) $entry_link = $item["link"];
+                               }
+
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       _debug("update_rss_feed: title $entry_title");
+                               }
 
-                               if (!$entry_title) continue;
-#                                      if (!$entry_link) continue;
+                               if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
 
                                $entry_link = strip_tags($entry_link);
 
-                               $entry_content = $item["content:escaped"];
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_content = $item->get_description();
+                               } else {
+                                       $entry_content = $item["content:escaped"];
+
+                                       if (!$entry_content) $entry_content = $item["content:encoded"];
+                                       if (!$entry_content) $entry_content = $item["content"];
 
-                               if (!$entry_content) $entry_content = $item["content:encoded"];
-                               if (!$entry_content) $entry_content = $item["content"];
-                               if (!$entry_content) $entry_content = $item["atom_content"];
-                               if (!$entry_content) $entry_content = $item["summary"];
-                               if (!$entry_content) $entry_content = $item["description"];
+                                       // Magpie bugs are getting ridiculous
+                                       if (trim($entry_content) == "Array") $entry_content = false;
 
-//                             if (!$entry_content) continue;
+                                       if (!$entry_content) $entry_content = $item["atom_content"];
+                                       if (!$entry_content) $entry_content = $item["summary"];
+                                       if (!$entry_content) $entry_content = $item["description"];
 
-                               // WTF
-                               if (is_array($entry_content)) {
-                                       $entry_content = $entry_content["encoded"];
-                                       if (!$entry_content) $entry_content = $entry_content["escaped"];
+                                       // WTF
+                                       if (is_array($entry_content)) {
+                                               $entry_content = $entry_content["encoded"];
+                                               if (!$entry_content) $entry_content = $entry_content["escaped"];
+                                       } 
                                }
 
-//                             print_r($item);
-//                             print_r(htmlspecialchars($entry_content));
-//                             print "<br>";
+                               if ($_GET["xdebug"]) {
+                                       print "update_rss_feed: content: ";
+                                       print_r(htmlspecialchars($entry_content));
+                               }
 
                                $entry_content_unescaped = $entry_content;
 
-                               $entry_comments = strip_tags($item["comments"]);
-
-                               $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
-
-                               if ($item['author']) {
-
-                                       if (is_array($item['author'])) {
+                               if (ENABLE_SIMPLEPIE) {
+                                       $entry_comments = strip_tags($item->data["comments"]);
+                                       if ($item->get_author()) {
+                                               $entry_author_item = $item->get_author();
+                                               $entry_author = $entry_author_item->get_name();                                                 
+                                       }
+                               } else {
+                                       $entry_comments = strip_tags($item["comments"]);
+                               
+                                       $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
 
-                                               if (!$entry_author) {
-                                                       $entry_author = db_escape_string(strip_tags($item['author']['name']));
+                                       if ($item['author']) {
+       
+                                               if (is_array($item['author'])) {
+       
+                                                       if (!$entry_author) {
+                                                               $entry_author = db_escape_string(strip_tags($item['author']['name']));
+                                                       }
+       
+                                                       if (!$entry_author) {
+                                                               $entry_author = db_escape_string(strip_tags($item['author']['email']));
+                                                       }
                                                }
-
+       
                                                if (!$entry_author) {
-                                                       $entry_author = db_escape_string(strip_tags($item['author']['email']));
+                                                       $entry_author = db_escape_string(strip_tags($item['author']));
                                                }
                                        }
-
-                                       if (!$entry_author) {
-                                               $entry_author = db_escape_string(strip_tags($item['author']));
-                                       }
                                }
 
                                if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
 
                                $entry_guid = db_escape_string(strip_tags($entry_guid));
+                               $entry_guid = mb_substr($entry_guid, 0, 250);
 
                                $result = db_query($link, "SELECT id FROM       ttrss_entries 
                                        WHERE guid = '$entry_guid'");
                                $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
                                $entry_author = mb_substr($entry_author, 0, 250);
 
-                               $num_comments = db_escape_string($item["slash"]["comments"]);
+                               if (ENABLE_SIMPLEPIE) {
+                                       $num_comments = 0; #FIXME#
+                               } else {
+                                       $num_comments = db_escape_string($item["slash"]["comments"]);
+                               }
 
                                if (!$num_comments) $num_comments = 0;
 
                                // parse <category> entries into tags
 
-                               $t_ctr = $item['category#'];
+                               if (ENABLE_SIMPLEPIE) {
 
-                               $additional_tags = false;
+                                       $additional_tags = array();
+                                       $additional_tags_src = $item->get_categories();
+                                       
+                                       if (is_array($additional_tags_src)) {
+                                               foreach ($additional_tags_src as $tobj) {
+                                                       array_push($additional_tags, $tobj->get_term());
+                                               }
+                                       }
+
+                                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                               _debug("update_rss_feed: category tags:");
+                                               print_r($additional_tags);
+                                       }
 
-                               if ($t_ctr == 0) {
-                                       $additional_tags = false;
-                               } else if ($t_ctr == 1) {
-                                       $additional_tags = array($item['category']);
                                } else {
-                                       $additional_tags = array();
-                                       for ($i = 0; $i <= $t_ctr; $i++ ) {
-                                               if ($item["category#$i"]) {
-                                                       array_push($additional_tags, $item["category#$i"]);
+
+                                       $t_ctr = $item['category#'];
+
+                                       $additional_tags = false;
+       
+                                       if ($t_ctr == 0) {
+                                               $additional_tags = false;
+                                       } else if ($t_ctr > 0) {
+                                               $additional_tags = array($item['category']);
+
+                                               if ($item['category@term']) {
+                                                       array_push($additional_tags, $item['category@term']);
+                                               }
+
+                                               for ($i = 0; $i <= $t_ctr; $i++ ) {
+                                                       if ($item["category#$i"]) {
+                                                               array_push($additional_tags, $item["category#$i"]);
+                                                       }
+
+                                                       if ($item["category#$i@term"]) {
+                                                               array_push($additional_tags, $item["category#$i@term"]);
+                                                       }
+                                               }
+                                       }
+       
+                                       // parse <dc:subject> elements
+       
+                                       $t_ctr = $item['dc']['subject#'];
+       
+                                       if ($t_ctr > 0) {
+                                               $additional_tags = array($item['dc']['subject']);
+
+                                               for ($i = 0; $i <= $t_ctr; $i++ ) {
+                                                       if ($item['dc']["subject#$i"]) {
+                                                               array_push($additional_tags, $item['dc']["subject#$i"]);
+                                                       }
                                                }
                                        }
                                }
 
-                               // parse <dc:subject> elements
+                               // enclosures
 
-                               $t_ctr = $item['dc']['subject#'];
+                               $enclosures = array();
 
-                               if ($t_ctr == 1) {
-                                       $additional_tags = array($item['dc']['subject']);
-                               } else if ($t_ctr > 1) {
-                                       $additional_tags = array();
-                                       for ($i = 0; $i <= $t_ctr; $i++ ) {
-                                               if ($item['dc']["subject#$i"]) {
-                                                       array_push($additional_tags, $item['dc']["subject#$i"]);
+                               if (ENABLE_SIMPLEPIE) {
+                                       $encs = $item->get_enclosures();
+
+                                       if (is_array($encs)) {
+                                               foreach ($encs as $e) {
+                                                       $e_item = array(
+                                                               $e->link, $e->type, $e->length);
+       
+                                                       array_push($enclosures, $e_item);
                                                }
                                        }
+
+                               } else {
+                                       $e_ctr = $item['enclosure#'];
+
+                                       if ($e_ctr > 0) {
+                                               $e_item = array($item['enclosure@url'],
+                                                       $item['enclosure@type'],
+                                                       $item['enclosure@length']);
+
+                                               array_push($enclosures, $e_item);
+
+                                               for ($i = 0; $i <= $e_ctr; $i++ ) {
+
+                                                       if ($item["enclosure#$i@url"]) {
+                                                               $e_item = array($item["enclosure#$i@url"],
+                                                                       $item["enclosure#$i@type"],
+                                                                       $item["enclosure#$i@length"]);
+                                                               array_push($enclosures, $e_item);
+                                                       }
+                                               }
+                                       }
+
                                }
 
                                # sanitize content
                                
 //                             $entry_content = sanitize_rss($entry_content);
 
-                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
                                }
 
 
                                if (db_num_rows($result) == 0) {
 
-                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                                _debug("update_rss_feed: base guid not found");
                                        }
 
                                                ttrss_entries 
                                        WHERE guid = '$entry_guid'");
 
+                               $entry_ref_id = 0;
+                               $entry_int_id = 0;
+
                                if (db_num_rows($result) == 1) {
 
-                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                                _debug("update_rss_feed: base guid found, checking for user record");
                                        }
 
                                                0, "date_entered"));
 
                                        $ref_id = db_fetch_result($result, 0, "id");
+                                       $entry_ref_id = $ref_id;
 
                                        // check for user post link to main table
 
                                        $article_filters = get_article_filters($filters, $entry_title, 
                                                        $entry_content, $entry_link);
 
-                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                                _debug("update_rss_feed: article filters: ");
                                                if (count($article_filters) != 0) {
                                                        print_r($article_filters);
 //                                     error_reporting (DEFAULT_ERROR_LEVEL);
 
                                        $result = db_query($link,
-                                               "SELECT ref_id FROM ttrss_user_entries WHERE
+                                               "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
                                                        ref_id = '$ref_id' AND owner_uid = '$owner_uid'
                                                        $dupcheck_qpart");
 
                                        // okay it doesn't exist - create user entry
                                        if (db_num_rows($result) == 0) {
 
-                                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                                        _debug("update_rss_feed: user record not found, creating...");
                                                }
 
                                                                (ref_id, owner_uid, feed_id, unread, last_read, marked, published) 
                                                        VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
                                                                $last_read_qpart, $marked, $published)");
+
+                                               $result = db_query($link, 
+                                                       "SELECT int_id FROM ttrss_user_entries WHERE
+                                                               ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
+                                                               feed_id = '$feed' LIMIT 1");
+
+                                               if (db_num_rows($result) == 1) {
+                                                       $entry_int_id = db_fetch_result($result, 0, "int_id");
+                                               }
+                                       } else {
+                                               $entry_ref_id = db_fetch_result($result, 0, "ref_id");
+                                               $entry_int_id = db_fetch_result($result, 0, "int_id");
                                        }
-                                       
+
+                                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                               _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
+                                       }
+
                                        $post_needs_update = false;
 
                                        if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
 
                                db_query($link, "COMMIT");
 
-                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       _debug("update_rss_feed: looking for enclosures...");
+                               }
+
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       print_r($enclosures);
+                               }
+
+                               db_query($link, "BEGIN");
+
+                               foreach ($enclosures as $enc) {
+                                       $enc_url = db_escape_string($enc[0]);
+                                       $enc_type = db_escape_string($enc[1]);
+                                       $enc_dur = db_escape_string($enc[2]);
+
+                                       $result = db_query($link, "SELECT id FROM ttrss_enclosures
+                                               WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
+
+                                       if (db_num_rows($result) == 0) {
+                                               db_query($link, "INSERT INTO ttrss_enclosures
+                                                       (content_url, content_type, title, duration, post_id) VALUES
+                                                       ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
+                                       }
+                               }
+
+                               db_query($link, "COMMIT");
+
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                                        _debug("update_rss_feed: looking for tags...");
                                }
 
 
 //                             print "<p>TAGS: "; print_r($entry_tags); print "</p>";
 
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       print_r($entry_tags);
+                               }
+
                                if (count($entry_tags) > 0) {
                                
                                        db_query($link, "BEGIN");
                        
-                                       $result = db_query($link, "SELECT id,int_id 
-                                               FROM ttrss_entries,ttrss_user_entries 
-                                               WHERE guid = '$entry_guid' 
-                                               AND feed_id = '$feed' AND ref_id = id
-                                               AND owner_uid = '$owner_uid'");
-
-                                       if (db_num_rows($result) == 1) {
-
-                                               $entry_id = db_fetch_result($result, 0, "id");
-                                               $entry_int_id = db_fetch_result($result, 0, "int_id");
-                                               
                                                foreach ($entry_tags as $tag) {
 
                                                        $tag = sanitize_tag($tag);
                                                                        VALUES ('$owner_uid','$tag', '$entry_int_id')");
                                                        }                                                       
                                                }
-                                       }
+
                                        db_query($link, "COMMIT");
                                } 
+
+                               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                                       _debug("update_rss_feed: article processed");
+                               }
                        } 
 
                        db_query($link, "UPDATE ttrss_feeds 
 //                     db_query($link, "COMMIT");
 
                } else {
-                       $error_msg = mb_substr(db_escape_string(magpie_error()), 0, 250);
+
+                       if (ENABLE_SIMPLEPIE) {
+                               $error_msg = mb_substr($rss->error(), 0, 250);
+                       } else {
+                               $error_msg = mb_substr(magpie_error(), 0, 250);
+                       }
+
+                       if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
+                               _debug("update_rss_feed: error fetching feed: $error_msg");
+                       }
+
+                       $error_msg = db_escape_string($error_msg);
+
                        db_query($link, 
                                "UPDATE ttrss_feeds SET last_error = '$error_msg', 
                                        last_updated = NOW() WHERE id = '$feed'");
                }
 
-               if (defined('DAEMON_EXTENDED_DEBUG')) {
+               if (ENABLE_SIMPLEPIE) {
+                       unset($rss);
+               }
+
+               if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
                        _debug("update_rss_feed: done");
                }
 
 
                if (!SINGLE_USER_MODE) {
 
-                       $pwd_hash = 'SHA1:' . sha1($password);
+                       $pwd_hash1 = encrypt_password($password);
+                       $pwd_hash2 = encrypt_password($password, $login);
+
+                       if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH 
+                                       && $_SERVER["REMOTE_USER"]) {
+
+                               $login = db_escape_string($_SERVER["REMOTE_USER"]);
 
-                       if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
                                $query = "SELECT id,login,access_level
                    FROM ttrss_users WHERE
-                        login = '$login'";
+                                       login = '$login'";
+
                        } else {
-                               $query = "SELECT id,login,access_level
+                               $query = "SELECT id,login,access_level,pwd_hash
                    FROM ttrss_users WHERE
-                        login = '$login' AND pwd_hash = '$pwd_hash'";
+                                       login = '$login' AND (pwd_hash = '$pwd_hash1' OR
+                                               pwd_hash = '$pwd_hash2')";
                        }
 
                        $result = db_query($link, $query);
        
                                $_SESSION["theme"] = $user_theme;
                                $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
+                               $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
        
                                initialize_user_prefs($link, $_SESSION["uid"]);
        
 
                db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
                        values ('$uid','last_read is null and unread = false', 'Updated articles')");
-               
+
                db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
                        values ('$uid', 'Tiny Tiny RSS: New Releases',
                        'http://tt-rss.spb.ru/releases.rss')");
        }
 
        function validate_session($link) {
+               if (SINGLE_USER_MODE) { 
+                       return true;
+               }
+
                if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
                        if ($_SESSION["ip_address"]) {
                                if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
                        }
                }
 
+               if ($_SESSION["uid"]) {
+
+                       $result = db_query($link, 
+                               "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
+
+                       $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
+
+                       if ($pwd_hash != $_SESSION["pwd_hash"]) {
+                               return false;
+                       }
+               }
+
 /*             if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
 
                        //print_r($_SESSION);
 
        function truncate_string($str, $max_len) {
                if (mb_strlen($str, "utf-8") > $max_len - 3) {
-                       return mb_substr($str, 0, $max_len, "utf-8") . "...";
+                       return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
                } else {
                        return $str;
                }
        }
 
        function file_is_locked($filename) {
-               error_reporting(0);
-               $fp = fopen($filename, "r");
-               error_reporting(DEFAULT_ERROR_LEVEL);
-               if ($fp) {
-                       if (flock($fp, LOCK_EX | LOCK_NB)) {
-                               flock($fp, LOCK_UN);
+               if (function_exists('flock')) {
+                       error_reporting(0);
+                       $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
+                       error_reporting(DEFAULT_ERROR_LEVEL);
+                       if ($fp) {
+                               if (flock($fp, LOCK_EX | LOCK_NB)) {
+                                       flock($fp, LOCK_UN);
+                                       fclose($fp);
+                                       return false;
+                               }
                                fclose($fp);
-                               return false;
+                               return true;
                        }
-                       fclose($fp);
-                       return true;
                }
                return false;
        }
 
        function make_lockfile($filename) {
-               $fp = fopen($filename, "w");
+               $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
 
                if (flock($fp, LOCK_EX | LOCK_NB)) {            
                        return $fp;
        }
 
        function make_stampfile($filename) {
-               $fp = fopen($filename, "w");
+               $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
 
                if (flock($fp, LOCK_EX | LOCK_NB)) {
                        fwrite($fp, time() . "\n");
        function read_stampfile($filename) {
 
                error_reporting(0);
-               $fp = fopen($filename, "r");
+               $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
                error_reporting (DEFAULT_ERROR_LEVEL);
 
                if (flock($fp, LOCK_EX)) {
                                                        WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
                                        }
 
+                                       if ($feed == -3) {
+
+                                               $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
+
+                                               if (DB_TYPE == "pgsql") {
+                                                       $match_part = "date_entered > NOW() - INTERVAL '$intl hour' "; 
+                                               } else {
+                                                       $match_part = "date_entered > DATE_SUB(NOW(), 
+                                                               INTERVAL $intl HOUR) ";
+                                               }
+
+                                               $result = db_query($link, "SELECT id FROM ttrss_entries, 
+                                                       ttrss_user_entries WHERE $match_part AND
+                                                       unread = true AND
+                                                       ttrss_user_entries.ref_id = ttrss_entries.id AND        
+                                                       owner_uid = ".$_SESSION["uid"]);
+
+                                               $affected_ids = array();
+
+                                               while ($line = db_fetch_assoc($result)) {
+                                                       array_push($affected_ids, $line["id"]);
+                                               }
+
+                                               catchupArticlesById($link, $affected_ids, 0);
+                                       }
+
                                } else if ($feed < -10) { // label
 
                                        // TODO make this more efficient
                        }
        }
 
-       function update_generic_feed($link, $feed, $cat_view) {
+       function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
                        if ($cat_view) {
 
                                if ($feed > 0) {
                                        $cat_qpart = "cat_id IS NULL";
                                }
                                
-                               $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
+                               $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
                                        WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
 
                                while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
                                        $feed_url = $tmp_line["feed_url"];
-                                       update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
+                                       $feed_id = $tmp_line["id"];
+                                       update_rss_feed($link, $feed_url, $feed_id, $force_update);
                                }
 
                        } else {
                                $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
                                        WHERE id = '$feed'");
                                $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
-                               update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
+                               update_rss_feed($link, $feed_url, $feed, $force_update);
                        }
        }
 
-       function getAllCounters($link, $omode = "flc") {
+       function getAllCounters($link, $omode = "flc", $active_feed = false) {
 /*             getLabelCounters($link);
                getFeedCounters($link);
                getTagCounters($link);
                getGlobalCounters($link);
 
                if (strchr($omode, "l")) getLabelCounters($link);
-               if (strchr($omode, "f")) getFeedCounters($link);
+               if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
                if (strchr($omode, "t")) getTagCounters($link);
                if (strchr($omode, "c")) {                      
                        if (get_pref($link, 'ENABLE_FEED_CATS')) {
 
                print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
 
+               $age_qpart = getMaxAgeSubquery();
+
                $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
-                               FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id 
+                               FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id 
+                                       AND id = ref_id AND $age_qpart 
                                        AND unread = true)) AS unread FROM ttrss_feeds 
                        WHERE 
                                hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
                        } else {
                                $cat_query = "cat_id IS NULL";
                        }
-       
+
+                       $age_qpart = getMaxAgeSubquery();
+
                        $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
                                        AND hidden = false
                                        AND owner_uid = " . $_SESSION["uid"]);
                        $match_part = implode(" OR ", $cat_feeds);
        
                        $result = db_query($link, "SELECT COUNT(int_id) AS unread 
-                               FROM ttrss_user_entries 
-                               WHERE   unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
+                               FROM ttrss_user_entries,ttrss_entries 
+                               WHERE   unread = true AND ($match_part) AND id = ref_id 
+                               AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
        
                        $unread = 0;
        
        
                        return $unread;
                } else if ($cat == -1) {
-                       return getFeedUnread($link, -1) + getFeedUnread($link, -2);
+                       return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
                } else if ($cat == -2) {
 
                        $rv = getLabelCounters($link, false, true);
                }
        }
 
+       function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
+               if (DB_TYPE == "pgsql") {
+                       return "ttrss_entries.date_entered > 
+                               NOW() - INTERVAL '$days days'";
+               } else {
+                       return "ttrss_entries.date_entered > 
+                               DATE_SUB(NOW(), INTERVAL $days DAY)";
+               }
+       }
+
        function getFeedUnread($link, $feed, $is_cat = false) {
                $n_feed = sprintf("%d", $feed);
 
+               $age_qpart = getMaxAgeSubquery();
+
                if ($is_cat) {
                        return getCategoryUnread($link, $n_feed);               
                } else if ($n_feed == -1) {
                        $match_part = "marked = true";
                } else if ($n_feed == -2) {
                        $match_part = "published = true";
+               } else if ($n_feed == -3) {
+                       $match_part = "unread = true";
+
+                       $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
+
+                       if (DB_TYPE == "pgsql") {
+                               $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' "; 
+                       } else {
+                               $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
+                       }
+
                } else if ($n_feed > 0) {
 
                        $result = db_query($link, "SELECT id FROM ttrss_feeds 
                                $match_part = implode(" OR ", $linked_feeds);
 
                                $result = db_query($link, "SELECT COUNT(int_id) AS unread 
-                                       FROM ttrss_user_entries
-                                       WHERE   unread = true AND ($match_part) 
-                                       AND owner_uid = " . $_SESSION["uid"]);
+                                       FROM ttrss_user_entries,ttrss_entries
+                                       WHERE   unread = true AND
+                                       ttrss_user_entries.ref_id = ttrss_entries.id AND
+                                       $age_qpart AND
+                                       ($match_part) AND
+                                       owner_uid = " . $_SESSION["uid"]);
 
                                $unread = 0;
 
                                ttrss_user_entries.feed_id = ttrss_feeds.id AND
                                ttrss_user_entries.ref_id = ttrss_entries.id AND 
                                ttrss_feeds.hidden = false AND
+                               $age_qpart AND
                                unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
                                
                } else {
                
                        $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
-                               FROM ttrss_tags,ttrss_user_entries 
-                               WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
+                               FROM ttrss_tags,ttrss_user_entries,ttrss_entries 
+                               WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id 
+                               AND unread = true AND $age_qpart AND
                                        ttrss_tags.owner_uid = " . $_SESSION["uid"]);
                }
                
                        $user_id = $_SESSION["uid"];
                }
 
+               $age_qpart = getMaxAgeSubquery();
+
                $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
                        WHERE unread = true AND 
                        ttrss_user_entries.feed_id = ttrss_feeds.id AND
                        ttrss_user_entries.ref_id = ttrss_entries.id AND 
                        hidden = false AND
+                       $age_qpart AND
                        ttrss_user_entries.owner_uid = '$user_id'");
                $c_id = db_fetch_result($result, 0, "c_id");
                return $c_id;
                        select tag_name,0 as count FROM ttrss_tags
                        WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
 
+               $age_qpart = getMaxAgeSubquery();
+
                $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
-                       FROM ttrss_user_entries WHERE int_id = post_int_id 
+                       FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
+                               AND ref_id = id AND $age_qpart
                                AND unread = true)) AS count FROM ttrss_tags 
                                WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
                                ORDER BY count DESC LIMIT 55");
 
        function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
 
+               $age_qpart = getMaxAgeSubquery();
+
                if ($smart_mode) {
                        if (!$_SESSION["lctr_last_value"]) {
                                $_SESSION["lctr_last_value"] = array();
                $old_counters = $_SESSION["lctr_last_value"];
                $lctrs_modified = false;
 
-               $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
-                       WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
-                       ttrss_user_entries.feed_id = ttrss_feeds.id AND
-                       hidden = false AND unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
-
-               $count = db_fetch_result($result, 0, "count");
+               $count = getFeedUnread($link, -1);
 
                if (!$ret_mode) {
                        print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
                        $ret_arr["-1"]["description"] = __("Starred articles");
                }
 
-               $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
-                       WHERE published = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
-                       ttrss_user_entries.feed_id = ttrss_feeds.id AND
-                       hidden = false AND unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
-
-               $count = db_fetch_result($result, 0, "count");
+               $count = getFeedUnread($link, -2);
 
                if (!$ret_mode) {
                        print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
                        $ret_arr["-2"]["description"] = __("Published articles");
                }
 
+               $count = getFeedUnread($link, -3);
+
+               if (!$ret_mode) {
+                       print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
+               } else {
+                       $ret_arr["-3"]["counter"] = $count;
+                       $ret_arr["-3"]["description"] = __("Fresh articles");
+               }
+
 
                $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
                        ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
                        $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
                                WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
                                ttrss_feeds.hidden = false AND
+                               $age_qpart AND
                                ttrss_user_entries.feed_id = ttrss_feeds.id AND
                                ttrss_user_entries.ref_id = ttrss_entries.id AND 
                                ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
                        print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
        } */
 
-       function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
+       function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
+
+               $age_qpart = getMaxAgeSubquery();
 
                if ($smart_mode) {
                        if (!$_SESSION["fctr_last_value"]) {
                        FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
                        AND parent_feed IS NULL"); */
 
-               $result = db_query($link, "SELECT ttrss_feeds.id,
+               $query = "SELECT ttrss_feeds.id,
+                               ttrss_feeds.title,
                                SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated, 
                                last_error, 
                                COUNT(ttrss_entries.id) AS count 
                                LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id 
                                        AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid 
                                        AND ttrss_user_entries.unread = true) 
-                               LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id) 
-                       WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
+                               LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
+                                       $age_qpart) 
+                       WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."  
                                AND parent_feed IS NULL 
-                       GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error");
+                       GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
 
+               $result = db_query($link, $query);
                $fctrs_modified = false;
 
                $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
                                $last_updated = date($short_date, strtotime($line["last_updated"]));
                        }                               
 
+                       $last_updated = htmlspecialchars($last_updated);
+
                        $has_img = is_file(ICONS_DIR . "/$id.ico");
 
                        $tmp_result = db_query($link,
-                               "SELECT id,COUNT(unread) AS unread
+                               "SELECT ttrss_feeds.id,COUNT(unread) AS unread
                                FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
                                        ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
-                               WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
+                               LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id) 
+                               WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
                        
                        if (db_num_rows($tmp_result) > 0) {                             
                                while ($l = db_fetch_assoc($tmp_result)) {
                                        $has_img_part = "";
                                }                               
 
-                               print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
+                               if ($active_feed && $id == $active_feed) {
+                                       $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
+                               } else {
+                                       $has_title_part = "";
+                               }
+
+                               print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
                        }
                }
 
                        return __("Starred articles");
                } else if ($id == -2) {
                        return __("Published articles");
+               } else if ($id == -3) {
+                       return __("Fresh articles");
                } else if ($id < -10) {
                        $label_id = -10 - $id;
                        $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
                        }
                }
 
+               print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
                print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
                print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
-               print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY . "\"/>";
+               print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
 
                print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
                        get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
                print "<param key=\"icons_location\" value=\"" . 
                        ICONS_URL . "\"/>";
 
+               print "<param key=\"hide_read_shows_special\" value=\"" . 
+                       (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
+
                print "</init-params>";
        }
 
        function print_runtime_info($link) {
                print "<runtime-info>";
+
                if (ENABLE_UPDATE_DAEMON) {
                        print "<param key=\"daemon_is_running\" value=\"".
                                sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
 
-                       if ($_SESSION["daemon_stamp_check"] + 600 < time()) {
+                       if (time() - $_SESSION["daemon_stamp_check"] > 30) {
 
                                $stamp = (int)read_stampfile("update_daemon.stamp");
 
+//                             print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
+
                                if ($stamp) {
-                                       if ($stamp + 86400*3 < time()) {
-                                               print "<param key=\"daemon_stamp_ok\" value=\"0\"/>";
+                                       $stamp_delta = time() - $stamp;
+
+                                       if ($stamp_delta > 1800) {
+                                               $stamp_check = 0;
                                        } else {
-                                               print "<param key=\"daemon_stamp_ok\" value=\"1\"/>";
+                                               $stamp_check = 1;
+                                               $_SESSION["daemon_stamp_check"] = time();
                                        }
 
+                                       print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
+
                                        $stamp_fmt = date("Y.m.d, G:i", $stamp);
 
                                        print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
                                }
-
-                               $_SESSION["daemon_stamp_check"] = time();
                        }
                }
 
                        }
                }
 
+//             print "<param key=\"new_version_available\" value=\"1\"/>";
+
                print "</runtime-info>";
        }
 
                                $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
                        } else if ($feed == -2) { // published virtual feed
                                $query_strategy_part = "published = true";
+                               $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
+                       } else if ($feed == -3) { // fresh virtual feed
+                               $query_strategy_part = "unread = true";
+
+                               $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
+
+                               if (DB_TYPE == "pgsql") {
+                                       $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' "; 
+                               } else {
+                                       $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
+                               }
+
                                $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
                        } else if ($feed <= -10) { // labels
                                $label_id = -$feed - 11;
                                $feed_title = __("Starred articles");
                        } else if ($feed == -2) {
                                $feed_title = __("Published articles");
+                       } else if ($feed == -3) {
+                               $feed_title = __("Fresh articles");
                        } else if ($feed < -10) {
                                $label_id = -$feed - 11;
                                $result = db_query($link, "SELECT description FROM ttrss_labels
 
                        if ($feed < -10) error_reporting (0);
 
+                       $content_query_part = "content as content_preview,";
+
                        if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
        
                                if ($feed >= 0) {
                                        $feed_kind = "Labels";
                                }
        
-                               $content_query_part = "content as content_preview,";
-
                                if ($limit_query_part) {
                                        $offset_query_part = "OFFSET $offset";
                                }
                $res = $str;
 
                if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
-                       global $tw_parser;
-                       global $tw_paranoya_setup;
 
-                       $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
+                       $res = strip_tags_long($res, 
+                               "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
 
 //                     $res = preg_replace("/\r\n|\n|\r/", "", $res);
 //                     $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");                       
                                WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
 
                while ($line = db_fetch_assoc($result)) {
+
                        if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
                                print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
 
+                               $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
+
                                $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
                                $digest = $tuple[0];
                                $headlines_count = $tuple[1];
+                               $affected_ids = $tuple[2];
+                               $digest_text = $tuple[3];
 
                                if ($headlines_count > 0) {
-                                       $rc = mail($line["login"] . " <" . $line["email"] . ">",
-                                               "[tt-rss] New headlines for last 24 hours", $digest,
-                                               "From: " . MAIL_FROM . "\n".
-                                               "Content-Type: text/plain; charset=\"utf-8\"\n".
-                                               "Content-Transfer-Encoding: 8bit\n");
+
+                                       $mail = new PHPMailer();
+
+                                       $mail->PluginDir = "phpmailer/";
+                                       $mail->SetLanguage("en", "phpmailer/language/");
+
+                                       $mail->CharSet = "UTF-8";
+
+                                       $mail->From = DIGEST_FROM_ADDRESS;
+                                       $mail->FromName = DIGEST_FROM_NAME;
+                                       $mail->AddAddress($line["email"], $line["login"]);
+
+                                       if (DIGEST_SMTP_HOST) {
+                                               $mail->Host = DIGEST_SMTP_HOST;
+                                               $mail->Mailer = "smtp";
+                                               $mail->Username = DIGEST_SMTP_LOGIN;
+                                               $mail->Password = DIGEST_SMTP_PASSWORD;
+                                       }
+
+                                       $mail->IsHTML(true);
+                                       $mail->Subject = DIGEST_SUBJECT;
+                                       $mail->Body = $digest;
+                                       $mail->AltBody = $digest_text;
+
+                                       $rc = $mail->Send();
+
+                                       if (!$rc) print "ERROR: " . $mail->ErrorInfo;
+
                                        print "RC=$rc\n";
+
+                                       if ($rc && $do_catchup) {
+                                               print "Marking affected articles as read...\n";
+                                               catchupArticlesById($link, $affected_ids, 0, $line["id"]);
+                                       }
+
                                        db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
                                                        WHERE id = " . $line["id"]);
                                } else {
                        }
                }
 
-//             $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
+               print "All done.\n";
 
        }
 
        function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
-               $tmp =  __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";       
-               $tmp .= "=======================================================\n\n";
+
+               require_once "MiniTemplator.class.php";
+
+               $tpl = new MiniTemplator;
+               $tpl_t = new MiniTemplator;
+
+               $tpl->readTemplateFromFile("templates/digest_template_html.txt");
+               $tpl_t->readTemplateFromFile("templates/digest_template.txt");
+
+               $tpl->setVariable('CUR_DATE', date('Y/m/d'));
+               $tpl->setVariable('CUR_TIME', date('G:i'));
+
+               $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
+               $tpl_t->setVariable('CUR_TIME', date('G:i'));
+
+               $affected_ids = array();
 
                if (DB_TYPE == "pgsql") {
                        $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
                $result = db_query($link, "SELECT ttrss_entries.title,
                                ttrss_feeds.title AS feed_title,
                                date_entered,
+                               ttrss_user_entries.ref_id,
                                link,
+                               SUBSTRING(content, 1, 120) AS excerpt,
                                SUBSTRING(last_updated,1,19) AS last_updated
                        FROM 
                                ttrss_user_entries,ttrss_entries,ttrss_feeds 
                                ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
                                AND include_in_digest = true
                                AND $interval_query
+                               AND hidden = false
                                AND ttrss_user_entries.owner_uid = $user_id
-                               AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
+                               AND unread = true 
+                       ORDER BY ttrss_feeds.title, date_entered DESC
                        LIMIT $limit");
 
                $cur_feed_title = "";
 
                $headlines_count = db_num_rows($result);
 
+               $headlines = array();
+
                while ($line = db_fetch_assoc($result)) {
+                       array_push($headlines, $line);
+               }
+
+               for ($i = 0; $i < sizeof($headlines); $i++) {   
+
+                       $line = $headlines[$i];
+
+                       array_push($affected_ids, $line["ref_id"]);
+
                        $updated = smart_date_time(strtotime($line["last_updated"]));
-                       $feed_title = $line["feed_title"];
 
-                       if ($cur_feed_title != $feed_title) {
-                               $cur_feed_title = $feed_title;
+                       $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
+                       $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
+                       $tpl->setVariable('ARTICLE_LINK', $line["link"]);
+                       $tpl->setVariable('ARTICLE_UPDATED', $updated);
+                       $tpl->setVariable('ARTICLE_EXCERPT', 
+                               truncate_string(strip_tags($line["excerpt"]), 100));
+
+                       $tpl->addBlock('article');
+
+                       $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
+                       $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
+                       $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
+                       $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
+//                     $tpl_t->setVariable('ARTICLE_EXCERPT', 
+//                             truncate_string(strip_tags($line["excerpt"]), 100));
 
-                               $tmp .= "$feed_title\n\n";
+                       $tpl_t->addBlock('article');
+
+                       if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
+                               $tpl->addBlock('feed');
+                               $tpl_t->addBlock('feed');
                        }
 
-                       $tmp .= " * " . trim($line["title"]) . " - $updated\n";
-                       $tmp .= "   " . trim($line["link"]) . "\n";
-                       $tmp .= "\n";
                }
 
-               $tmp .= "--- \n";
-               $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") . 
-                       DIGEST_HOSTNAME . "\n".
-                       __("To unsubscribe, visit your configuration options or contact instance owner.\n");
-                       
+               $tpl->addBlock('digest');
+               $tpl->generateOutputToString($tmp);
 
-               return array($tmp, $headlines_count);
+               $tpl_t->addBlock('digest');
+               $tpl_t->generateOutputToString($tmp_t);
+
+               return array($tmp, $headlines_count, $affected_ids, $tmp_t);
        }
 
        function check_for_update($link, $brief_fmt = true) {
                }
 
                error_reporting(0);
-               $rss = fetch_rss($releases_feed);
+               if (ENABLE_SIMPLEPIE) {
+                       $rss = new SimplePie();
+                       $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
+//                     $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
+                       $rss->set_feed_url($fetch_url);
+                       $rss->set_output_encoding('UTF-8');
+                       $rss->init();
+               } else {
+                       $rss = fetch_rss($releases_feed);
+               }
                error_reporting (DEFAULT_ERROR_LEVEL);
 
                if ($rss) {
 
-                       $items = $rss->items;
+                       if (ENABLE_SIMPLEPIE) {
+                               $items = $rss->get_items();
+                       } else {
+                               $items = $rss->items;
 
-                       if (!$items || !is_array($items)) $items = $rss->entries;
-                       if (!$items || !is_array($items)) $items = $rss;
+                               if (!$items || !is_array($items)) $items = $rss->entries;
+                               if (!$items || !is_array($items)) $items = $rss;
+                       }
 
                        if (!is_array($items) || count($items) == 0) {
                                return;
 
                        $latest_item = $items[0];
 
-                       $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
+                       if (ENABLE_SIMPLEPIE) {
+                               $last_title = $latest_item->get_title();
+                       } else {
+                               $last_title = $latest_item["title"];
+                       }
 
-                       $release_url = sanitize_rss($link, $latest_item["link"]);
-                       $content = sanitize_rss($link, $latest_item["description"]);
+                       $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
+
+                       if (ENABLE_SIMPLEPIE) {
+                               $release_url = sanitize_rss($link, $latest_item->get_link());
+                               $content = sanitize_rss($link, $latest_item->get_description());
+                       } else {
+                               $release_url = sanitize_rss($link, $latest_item["link"]);
+                               $content = sanitize_rss($link, $latest_item["description"]);
+                       }
 
                        if (version_compare(VERSION, $latest_version) == -1) {
                                if ($brief_fmt) {
                }
        }
 
-       function catchupArticlesById($link, $ids, $cmode) {
+       function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
+
+               if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
                $tmp_ids = array();
 
                if ($cmode == 0) {
                        db_query($link, "UPDATE ttrss_user_entries SET 
                        unread = false,last_read = NOW()
-                       WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
+                       WHERE ($ids_qpart) AND owner_uid = $owner_uid");
                } else if ($cmode == 1) {
                        db_query($link, "UPDATE ttrss_user_entries SET 
                        unread = true
-                       WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
+                       WHERE ($ids_qpart) AND owner_uid = $owner_uid");
                } else {
                        db_query($link, "UPDATE ttrss_user_entries SET 
                        unread = NOT unread,last_read = NOW()
-                       WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
+                       WHERE ($ids_qpart) AND owner_uid = $owner_uid");
                }
        }
 
                                                <li onclick=\"$tog_published_link\">".__('Published')."</li>
                                                </ul></li>
                                        <li class=\"vsep\">&nbsp;</li>
-                                       <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
+                                       <li class=\"top\">".__('Mark as read')."<ul>
                                                <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
-                                               <li onclick=\"$catchup_page_link\">".__('This page')."</li>
+                                               <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->
+                                               <li><span class=\"insensitive\">--------</span></li>
+                                               <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
+                                               <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
+                                               <li><span class=\"insensitive\">--------</span></li>
                                                <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
                                        ";
 
 } */
 
                        print "<td class=\"headlineTitle$rtl_cpart\">";
-               
+
+                       print "<span class=\"headlineInnerTitle\">";
+
                        if ($feed_site_url) {
                                if (!$bottom) {
                                        $target = "target=\"_new\"";
                                }
-                               print "<a $target href=\"$feed_site_url\">$feed_title</a>";
+                               print "<a $target href=\"$feed_site_url\">".
+                                       truncate_string($feed_title,30)."</a>";
                        } else {
                                print $feed_title;
                        }
                                print " [$user_page_offset] ";
                        }
 
+                       print "</span>";
+
                        if (!$bottom) {
                                print "
                                        <a target=\"_new\" 
 
                        if ($hidden) {
                                $holder_style = "display:none;";
-                               $ellipsis = "...";
+                               $ellipsis = "";
                        } else {
                                $holder_style = "";
                                $ellipsis = "";
                                print "<span id=\"FCAP-$cat_id\">";
                        }
 
-                       print " <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\" 
+                       print " <span id=\"FCATCTR-$cat_id\" 
                                class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
 
                        if ($can_browse) {
 
                $num_starred = getFeedUnread($link, -1);
                $num_published = getFeedUnread($link, -2);
+               $num_fresh = getFeedUnread($link, -3);
+
+               $class = "virt";
+
+               if ($num_fresh > 0) $class .= "Unread";
+
+               printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh, 
+                       "images/fresh.png", $link);
 
                $class = "virt";
 
                if ($num_starred > 0) $class .= "Unread";
 
+               $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
+
+               if ($is_ie) {
+                       $mark_img_ext = "gif";
+               } else {
+                       $mark_img_ext = "png";
+               }
+
                printFeedEntry(-1, $class, __("Starred articles"), $num_starred, 
-                       "images/mark_set.png", $link);
+                       "images/mark_set.$mark_img_ext", $link);
 
                $class = "virt";
 
                if ($num_published > 0) $class .= "Unread";
 
                printFeedEntry(-2, $class, __("Published articles"), $num_published, 
-                       "images/pub_set.png", $link);
+                       "images/pub_set.gif", $link);
 
                if (get_pref($link, 'ENABLE_FEED_CATS')) {
                        print "</ul>";
                                }
                        }
 
+                       $age_qpart = getMaxAgeSubquery();
+
                        $result = db_query($link, "SELECT ttrss_feeds.*,
                                SUBSTRING(last_updated,1,19) AS last_updated_noms,
                                (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
                                        WHERE feed_id = ttrss_feeds.id AND unread = true
+                                               AND $age_qpart
                                                AND ttrss_user_entries.ref_id = ttrss_entries.id
                                                AND owner_uid = '$owner_uid') as unread,
                                cat_id,last_error,
                                        if ($collapsed == "t" || $collapsed == "1") {
                                                $holder_class = "feedCatHolder";
                                                $holder_style = "display:none;";
-                                               $ellipsis = "...";
+                                               $ellipsis = "";
                                        } else {
                                                $holder_class = "feedCatHolder";
                                                $holder_style = "";
                                        print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
                                                <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
                                                        <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
-                                                       <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\" 
+                                                       <span id=\"FCATCTR-$cat_id\" 
                                                        class=\"$catctr_class\">($cat_unread)</span> $ellipsis
                                                        </a></li>";
 
                                print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
                        }
 
+                       $age_qpart = getMaxAgeSubquery();
+
                        $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
-                               FROM ttrss_user_entries WHERE int_id = post_int_id 
+                               FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
+                                       AND ref_id = id AND $age_qpart
                                        AND unread = true)) AS count FROM ttrss_tags 
                                        WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
                                        ORDER BY count DESC LIMIT 50");
 
        function format_warning($msg, $id = "") {
                return "<div class=\"warning\" id=\"$id\"> 
-                       <img src=\"images/sign_excl.png\">$msg</div>";
+                       <img src=\"images/sign_excl.gif\">$msg</div>";
        }
 
        function format_notice($msg) {
                return "<div class=\"notice\"> 
-                       <img src=\"images/sign_info.png\">$msg</div>";
+                       <img src=\"images/sign_info.gif\">$msg</div>";
        }
 
        function format_error($msg) {
                return "<div class=\"error\"> 
-                       <img src=\"images/sign_excl.png\">$msg</div>";
+                       <img src=\"images/sign_excl.gif\">$msg</div>";
        }
 
        function print_notice($msg) {
 
                        $num_tags = 0;
 
+                       if ($_SESSION["theme"] == "3pane") {
+                               $tag_limit = 3;
+                       } else {
+                               $tag_limit = 6;
+                       }
+
                        foreach ($tags as $tag) {
                                $num_tags++;
                                $tag_escaped = str_replace("'", "\\'", $tag);
 
                                $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
                                
-                               if ($num_tags == 6) {
-                                       $tags_str .= "...";
+                               if ($num_tags == $tag_limit) {
+                                       $tags_str .= "&hellip;";
 
-                               } else if ($num_tags < 6) {
+                               } else if ($num_tags < $tag_limit) {
                                        $tags_str .= $tag_str;
                                }
                                $f_tags_str .= $tag_str;
                        $tags_str = preg_replace("/, $/", "", $tags_str);
                        $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
 
-                       $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
+                       $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
                        $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
 
                        if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
                                $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
                        }
 
-                       print $line["content"] . "</div>";
+                       print $line["content"];
+
+                       $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
+                               post_id = '$id'");
+
+                       if (db_num_rows($result) > 0) {
+                               print "<div class=\"postEnclosures\">";
+
+                               if (db_num_rows($result) == 1) {
+                                       print __("Attachment:") . " ";
+                               } else {
+                                       print __("Attachments:") . " ";
+                               }
+
+                               $entries = array();
+
+                               while ($line = db_fetch_assoc($result)) {
+
+                                       $url = $line["content_url"];
+
+                                       $filename = substr($url, strrpos($url, "/")+1);
+
+                                       $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
+                                               $filename . " (" . $line["content_type"] . ")" . "</a>";
+
+                                       array_push($entries, $entry);
+                               }
+
+                               print join(", ", $entries);
+
+                               print "</div>";
+                       }
+               
+                       print "</div>";
                        
                        print "</div>";
 
        function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
                                        $next_unread_feed, $offset) {
 
+               $disable_cache = false;
+
                $timing_info = getmicrotime();
 
                $topmost_article_ids = array();
                }
 
                if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
-                       update_generic_feed($link, $feed, $cat_view);
+                       update_generic_feed($link, $feed, $cat_view, true);
                }
 
                if ($subop == "MarkAllRead")  {
                /// START /////////////////////////////////////////////////////////////////////////////////
 
                $search = db_escape_string($_GET["query"]);
+
+               if ($search) { 
+                       $disable_cache = true;
+               }
+
                $search_mode = db_escape_string($_GET["search_mode"]);
                $match_on = db_escape_string($_GET["match_on"]);
 
                        print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
                }
 
+               $headlines_count = db_num_rows($result);
+
                if (db_num_rows($result) > 0) {
 
 #                      print "\{$offset}";
                                        cellspacing=\"0\">";
                        }
 
-                       $lnum = 0;
-       
+                       $lnum = $limit*$offset;
+
                        error_reporting (DEFAULT_ERROR_LEVEL);
        
                        $num_unread = 0;
                                } else {
                                        $is_unread = false;
                                }
-       
+
+                               $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
+
+                               if ($is_ie) {
+                                       $mark_img_ext = "gif";
+                               } else {
+                                       $mark_img_ext = "png";
+                               }
+
                                if ($line["marked"] == "t" || $line["marked"] == "1") {
-                                       $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.png\" 
+                                       $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\" 
                                                class=\"markedPic\"
-                                               alt=\"Reset mark\" onclick='javascript:tMark($id)'>";
+                                               alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
                                } else {
-                                       $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.png\" 
+                                       $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\" 
                                                class=\"markedPic\"
-                                               alt=\"Set mark\" onclick='javascript:tMark($id)'>";
+                                               alt=\"Star article\" onclick='javascript:tMark($id)'>";
                                }
 
                                if ($line["published"] == "t" || $line["published"] == "1") {
-                                       $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.png\" 
+                                       $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\" 
                                                class=\"markedPic\"
-                                               alt=\"Unpublish\" onclick='javascript:tPub($id)'>";
+                                               alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
                                } else {
-                                       $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.png\" 
+                                       $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\" 
                                                class=\"markedPic\"
-                                               alt=\"Publish\" onclick='javascript:tPub($id)'>";
+                                               alt=\"Publish article\" onclick='javascript:tPub($id)'>";
                                }
 
 #                              $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
                                        print "<td class='hlMarkedPic'>$marked_pic</td>";
                                        print "<td class='hlMarkedPic'>$published_pic</td>";
 
-                                       if ($line["feed_title"]) {                      
-                                               print "<td class='hlContent'>$content_link</td>";
-                                               print "<td class='hlFeed'>
-                                                       <a href=\"javascript:viewfeed($feed_id, '', false)\">".
-                                                               $line["feed_title"]."</a>&nbsp;</td>";
-                                       } else {                        
-                                               print "<td class='hlContent' valign='middle'>";
-
-                                               print "<a href=\"javascript:view($id,$feed_id);\">" .
-                                                       $line["title"];
-
-                                               if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
-                                                       if ($content_preview) {
-                                                               print "<span class=\"contentPreview\"> - $content_preview</span>";
-                                                       }
+#                                      if ($line["feed_title"]) {                      
+#                                              print "<td class='hlContent'>$content_link</td>";
+#                                              print "<td class='hlFeed'>
+#                                                      <a href=\"javascript:viewfeed($feed_id, '', false)\">".
+#                                                              truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
+#                                      } else {                        
+
+                                       print "<td class='hlContent' valign='middle'>";
+
+                                       print "<a href=\"javascript:view($id,$feed_id);\">" .
+                                               $line["title"];
+
+                                       if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
+                                               if ($content_preview) {
+                                                       print "<span class=\"contentPreview\"> - $content_preview</span>";
                                                }
-               
-                                               print "</a>";
-                                               print "</td>";
                                        }
+
+                                       print "</a>";
+
+#                                                      <a href=\"javascript:viewfeed($feed_id, '', false)\">".
+#                                                      $line["feed_title"]."</a>       
+
+                                       if ($line["feed_title"]) {                      
+                                               print "<span class=\"hlFeed\">
+                                                       (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
+                                                       $line["feed_title"]."</a>)
+                                               </span>";
+                                       }
+
+
+                                       print "</td>";
+                                       
+#                                      }
                                        
                                        print "<td class=\"hlUpdated\"><nobr>$updated_fmt&nbsp;</nobr></td>";
                
                                        } else {
                                                $add_class = "";
                                        }       
-                                       
+
+                                       $expand_cdm = get_pref($link, 'CDM_EXPANDED');
+
+                                       if ($expand_cdm) {
+                                               $cdm_cstyle = "";
+                                       } else {
+                                               $cdm_cstyle = "style=\"display : none\"";
+                                       }
+
                                        print "<div class=\"cdmArticle$add_class\" 
                                                id=\"RROW-$id\" onmouseover='cdmMouseIn(this)' 
                                                onmouseout='cdmMouseOut(this)'>";
 
                                        print $entry_author;
 
+                                       if (!$expand_cdm) {
+                                               print "&nbsp;<a id=\"CICH-$id\" 
+                                                       href=\"javascript:cdmExpandArticle($id)\">
+                                                       (".__('Show article').")</a>";
+                                       } 
+
+
                                        if ($line["feed_title"]) {      
                                                print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
                                        }
                                                        "target=\"_new\" href=", $line["content_preview"]);
                                        }
 
-                                       print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
+                                       print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
+
+//                                     print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
+                                       print $line["content_preview"];
+
+                                       $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
+                                               post_id = '$id'");
+
+                                       if (db_num_rows($e_result) > 0) {
+                               print "<div class=\"cdmEnclosures\">";
+
+                               if (db_num_rows($e_result) == 1) {
+                                       print __("Attachment:") . " ";
+                               } else {
+                                       print __("Attachments:") . " ";
+                               }
+
+                               $entries = array();
+
+                               while ($e_line = db_fetch_assoc($e_result)) {
+
+                                       $url = $e_line["content_url"];
+
+                                       $filename = substr($url, strrpos($url, "/")+1);
+
+                                       $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
+                                               $filename . " (" . $e_line["content_type"] . ")" . "</a>";
+
+                                       array_push($entries, $entry);
+                               }
+
+                               print join(", ", $entries);
+
+                               print "</div>";
+                       }
+
+                                       print "<br clear='both'>";
+//                                     print "</div>";
+
+/*                                     if (!$expand_cdm) {
+                                               print "<a id=\"CICH-$id\" 
+                                                       href=\"javascript:cdmExpandArticle($id)\">
+                                                       Show article</a>";
+                                       } */
+
+                                       print "</div>";
 
                                        print "<div class=\"cdmFooter\"><span class='s0'>";
 
                                                if ($num_tags < 5) {
                                                        $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, "; 
                                                } else if ($num_tags == 5) {
-                                                       $tags_str .= "...";
+                                                       $tags_str .= "&hellip;";
                                                }
                                        }
 
                                        $tags_str = preg_replace("/, $/", "", $tags_str);
                                        $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
 
-                                       $all_tags_div = "<span class='cdmAllTagsCtr'>...<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
+                                       $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
 
                                        $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
 
                        print "</div>";
                }
 
-               return $topmost_article_ids;
+               return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
        }
 
 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
                return $url_path;
        }
 
+       function clear_feed_articles($link, $id) {
+               $result = db_query($link, "DELETE FROM ttrss_user_entries
+                       WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
+
+               $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
+                       (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
+       }
+
+        function add_feed_url() {
+               $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
+               $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
+               return $url_path;
+        }
+
+       function encrypt_password($pass, $login = '') {
+               if ($login) {
+                       return "SHA1X:" . sha1("$login:$pass");
+               } else {
+                       return "SHA1:" . sha1($pass);
+               }
+       }
+
 ?>