]> git.wh0rd.org - tt-rss.git/blobdiff - include/functions.php
implement multiple rule/action filters
[tt-rss.git] / include / functions.php
index aaca70dae5c7ba9e76ce9f798ad2f8d3471a6eac..ac0276fc7607b180ece39b616d8d9d1af1d675ba 100644 (file)
@@ -1,4 +1,20 @@
 <?php
+       define('EXPECTED_CONFIG_VERSION', 26);
+       define('SCHEMA_VERSION', 96);
+
+       $fetch_last_error = false;
+
+       function __autoload($class) {
+               $class_file = str_replace("_", "/", strtolower(basename($class)));
+
+               $file = dirname(__FILE__)."/../classes/$class_file.php";
+
+               if (file_exists($file)) {
+                       require $file;
+               }
+       }
+
+       mb_internal_encoding("UTF-8");
        date_default_timezone_set('UTC');
        if (defined('E_DEPRECATED')) {
                error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
 
        startup_gettext();
 
-       if (defined('MEMCACHE_SERVER')) {
-               $memcache = new Memcache;
-               $memcache->connect(MEMCACHE_SERVER, 11211);
-       }
-
        require_once 'db-prefs.php';
        require_once 'version.php';
 
         * @return void
         */
        function _debug($msg) {
+               if (defined('QUIET') && QUIET) {
+                       return;
+               }
                $ts = strftime("%H:%M:%S", time());
                if (function_exists('posix_getpid')) {
                        $ts = "$ts/" . posix_getpid();
                $login = urlencode($login);
                $pass = urlencode($pass);
 
+               global $fetch_last_error;
+
                if (function_exists('curl_init') && !ini_get("open_basedir")) {
                        $ch = curl_init($url);
 
                        $contents = @curl_exec($ch);
 
                        if ($contents === false) {
+                               $fetch_last_error = curl_error($ch);
                                curl_close($ch);
                                return false;
                        }
                                }
                        }
 
-                       return @file_get_contents($url);
+                       $data = @file_get_contents($url);
+
+                       if (!$data && function_exists('error_get_last')) {
+                               $error = error_get_last();
+                               $fetch_last_error = $error["message"];
+                       }
+                       return $data;
                }
 
        }
                        $favicon_url = get_favicon_url($site_url);
 
                        if ($favicon_url) {
-                               $contents = fetch_file_contents($favicon_url, "image");
+                               // Limiting to "image" type misses those served with text/plain
+                               $contents = fetch_file_contents($favicon_url); // , "image");
+
+                               if ($contents) {
+                                       // Crude image type matching.
+                                       // Patterns gleaned from the file(1) source code.
+                                       if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
+                                               // 0       string  \000\000\001\000        MS Windows icon resource
+                                               //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
+                                       }
+                                       elseif (preg_match('/^GIF8/', $contents)) {
+                                               // 0       string          GIF8            GIF image data
+                                               //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
+                                       }
+                                       elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
+                                               // 0       string          \x89PNG\x0d\x0a\x1a\x0a         PNG image data
+                                               //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
+                                       }
+                                       elseif (preg_match('/^\xff\xd8/', $contents)) {
+                                               // 0       beshort         0xffd8          JPEG image data
+                                               //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
+                                       }
+                                       else {
+                                               //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
+                                               $contents = "";
+                                       }
+                               }
 
                                if ($contents) {
                                        $fp = @fopen($icon_file, "w");
        function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
                $matches = array();
 
-               if ($filters["title"]) {
-                       foreach ($filters["title"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
-                               if ((!$inverse && @preg_match("/$reg_exp/i", $title)) ||
-                                               ($inverse && !@preg_match("/$reg_exp/i", $title))) {
+               foreach ($filters as $filter) {
+                       $match_any_rule = $filter["match_any_rule"];
+                       $filter_match = false;
 
-                                       array_push($matches, array($filter["action"], $filter["action_param"]));
-                               }
-                       }
-               }
+                       foreach ($filter["rules"] as $rule) {
+                               $match = false;
+                               $reg_exp = $rule["reg_exp"];
 
-               if ($filters["content"]) {
-                       foreach ($filters["content"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
+                               if (!$reg_exp)
+                                       continue;
 
-                               if ((!$inverse && @preg_match("/$reg_exp/i", $content)) ||
-                                               ($inverse && !@preg_match("/$reg_exp/i", $content))) {
-
-                                       array_push($matches, array($filter["action"], $filter["action_param"]));
+                               switch ($rule["type"]) {
+                               case "title":
+                                       $match = @preg_match("/$reg_exp/i", $title);
+                                       break;
+                               case "content":
+                                       $match = @preg_match("/$reg_exp/i", $content);
+                                       break;
+                               case "both":
+                                       $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $title));
+                                       break;
+                               case "link":
+                                       $match = @preg_match("/$reg_exp/i", $link);
+                                       break;
+                               case "author":
+                                       $match = @preg_match("/$reg_exp/i", $author);
+                                       break;
+                               case "tag":
+                                       $tag_string = join(",", $tags);
+                                       $match = @preg_match("/$reg_exp/i", $tag_string);
+                                       break;
                                }
-                       }
-               }
 
-               if ($filters["both"]) {
-                       foreach ($filters["both"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
-
-                               if ($inverse) {
-                                       if (!@preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
-                                               array_push($matches, array($filter["action"], $filter["action_param"]));
+                               if ($match_any_rule) {
+                                       if ($match) {
+                                               $filter_match = true;
+                                               break;
                                        }
                                } else {
-                                       if (@preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
-                                               array_push($matches, array($filter["action"], $filter["action_param"]));
+                                       $filter_match = $match;
+                                       if (!$match) {
+                                               break;
                                        }
                                }
                        }
-               }
-
-               if ($filters["link"]) {
-                       $reg_exp = $filter["reg_exp"];
-                       foreach ($filters["link"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
-
-                               if ((!$inverse && @preg_match("/$reg_exp/i", $link)) ||
-                                               ($inverse && !@preg_match("/$reg_exp/i", $link))) {
-
-                                       array_push($matches, array($filter["action"], $filter["action_param"]));
-                               }
-                       }
-               }
-
-               if ($filters["date"]) {
-                       $reg_exp = $filter["reg_exp"];
-                       foreach ($filters["date"] as $filter) {
-                               $date_modifier = $filter["filter_param"];
-                               $inverse = $filter["inverse"];
-                               $check_timestamp = strtotime($filter["reg_exp"]);
 
-                               # no-op when timestamp doesn't parse to prevent misfires
-
-                               if ($check_timestamp) {
-                                       $match_ok = false;
-
-                                       if ($date_modifier == "before" && $timestamp < $check_timestamp ||
-                                               $date_modifier == "after" && $timestamp > $check_timestamp) {
-                                                       $match_ok = true;
-                                       }
-
-                                       if ($inverse) $match_ok = !$match_ok;
-
-                                       if ($match_ok) {
-                                               array_push($matches, array($filter["action"], $filter["action_param"]));
-                                       }
+                       if ($filter_match) {
+                               foreach ($filter["actions"] AS $action) {
+                                       array_push($matches, $action);
                                }
                        }
                }
 
-               if ($filters["author"]) {
-                       foreach ($filters["author"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
-                               if ((!$inverse && @preg_match("/$reg_exp/i", $author)) ||
-                                               ($inverse && !@preg_match("/$reg_exp/i", $author))) {
-
-                                       array_push($matches, array($filter["action"], $filter["action_param"]));
-                               }
-                       }
-               }
-
-               if ($filters["tag"]) {
-
-                       $tag_string = join(",", $tags);
-
-                       foreach ($filters["tag"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               $inverse = $filter["inverse"];
-
-                               if ((!$inverse && @preg_match("/$reg_exp/i", $tag_string)) ||
-                                               ($inverse && !@preg_match("/$reg_exp/i", $tag_string))) {
-
-                                       array_push($matches, array($filter["action"], $filter["action_param"]));
-                               }
-                       }
-               }
-
-
                return $matches;
        }
 
        function find_article_filter($filters, $filter_name) {
                foreach ($filters as $f) {
-                       if ($f[0] == $filter_name) {
+                       if ($f["type"] == $filter_name) {
                                return $f;
                        };
                }
                return false;
        }
 
+       function find_article_filters($filters, $filter_name) {
+               $results = array();
+
+               foreach ($filters as $f) {
+                       if ($f["type"] == $filter_name) {
+                               array_push($results, $f);
+                       };
+               }
+               return $results;
+       }
+
        function calculate_article_score($filters) {
                $score = 0;
 
                foreach ($filters as $f) {
-                       if ($f[0] == "score") {
-                               $score += $f[1];
+                       if ($f["type"] == "score") {
+                               $score += $f["param"];
                        };
                }
                return $score;
 
        function assign_article_to_labels($link, $id, $filters, $owner_uid) {
                foreach ($filters as $f) {
-                       if ($f[0] == "label") {
-                               label_add_article($link, $id, $f[1], $owner_uid);
+                       if ($f["type"] == "label") {
+                               label_add_article($link, $id, $f["param"], $owner_uid);
                        };
                }
        }
                return "";
        }
 
-       function get_login_by_ssl_certificate($link) {
-
-               $cert_serial = db_escape_string(get_ssl_certificate_id());
-
-               if ($cert_serial) {
-                       $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
-                               WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
-                               owner_uid = ttrss_users.id");
-
-                       if (db_num_rows($result) != 0) {
-                               return db_escape_string(db_fetch_result($result, 0, "login"));
-                       }
-               }
-
-               return "";
-       }
-
-       function get_remote_user($link) {
-
-               if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH) {
-                       return db_escape_string($_SERVER["REMOTE_USER"]);
-               }
-
-               return db_escape_string(get_login_by_ssl_certificate($link));
-       }
-
-       function get_remote_fakepass($link) {
-               if (get_remote_user($link))
-                       return "******";
-               else
-                       return "";
-       }
-
-       function authenticate_user($link, $login, $password, $force_auth = false) {
+       function authenticate_user($link, $login, $password, $check_only = false) {
 
                if (!SINGLE_USER_MODE) {
 
-                       $pwd_hash1 = encrypt_password($password);
-                       $pwd_hash2 = encrypt_password($password, $login);
-                       $login = db_escape_string($login);
-
-                       $remote_user = get_remote_user($link);
-
-                       if ($remote_user && $remote_user == $login && $login != "admin") {
-
-                               $login = $remote_user;
-
-                               $query = "SELECT id,login,access_level,pwd_hash
-                   FROM ttrss_users WHERE
-                                       login = '$login'";
+                       $user_id = false;
+                       $modules = explode(",", AUTH_MODULES);
 
-                               if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
-                                               && $_SERVER["REMOTE_USER"]) {
-                                       $result = db_query($link, $query);
+                       foreach ($modules as $module) {
+                               $module_class = "auth_$module";
+                               if (class_exists($module_class)) {
+                                       $authenticator = new $module_class($link);
 
-                                       // First login ?
-                                       if (db_num_rows($result) == 0) {
-                                               $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
-                                               $pwd_hash = encrypt_password($password, $salt, true);
+                                       $user_id = (int) $authenticator->authenticate($login, $password);
 
-                                               $query2 = "INSERT INTO ttrss_users
-                                                               (login,access_level,last_login,created,pwd_hash,salt)
-                                                               VALUES ('$login', 0, null, NOW(), '$pwd_hash','$salt')";
-                                               db_query($link, $query2);
-                                       }
-                               }
-
-                       } else if (get_schema_version($link) > 87) {
-                               $result = db_query($link, "SELECT salt FROM ttrss_users WHERE
-                                       login = '$login'");
-
-                               if (db_num_rows($result) != 1) {
-                                       return false;
-                               }
-
-                               $salt = db_fetch_result($result, 0, "salt");
-
-                               if ($salt == "") {
-
-                                       $query = "SELECT id,login,access_level,pwd_hash
-                           FROM ttrss_users WHERE
-                                               login = '$login' AND (pwd_hash = '$pwd_hash1' OR
-                                               pwd_hash = '$pwd_hash2')";
-
-                                       // verify and upgrade password to new salt base
-
-                                       $result = db_query($link, $query);
-
-                                       if (db_num_rows($result) == 1) {
-                                               // upgrade password to MODE2
-
-                                               $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
-                                               $pwd_hash = encrypt_password($password, $salt, true);
-
-                                               db_query($link, "UPDATE ttrss_users SET
-                                                       pwd_hash = '$pwd_hash', salt = '$salt' WHERE login = '$login'");
-
-                                               $query = "SELECT id,login,access_level,pwd_hash
-                                   FROM ttrss_users WHERE
-                                                       login = '$login' AND pwd_hash = '$pwd_hash'";
-
-                                       } else {
-                                               return false;
+                                       if ($user_id) {
+                                               $_SESSION["auth_module"] = $module;
+                                               break;
                                        }
 
                                } else {
-
-                                       $pwd_hash = encrypt_password($password, $salt, true);
-
-                                       $query = "SELECT id,login,access_level,pwd_hash
-                                FROM ttrss_users WHERE
-                                               login = '$login' AND pwd_hash = '$pwd_hash'";
-
+                                       print T_sprintf("Fatal: authentication module %s not found.", $module);
+                                       die;
                                }
-                       } else {
-                               $query = "SELECT id,login,access_level,pwd_hash
-                        FROM ttrss_users WHERE
-                                       login = '$login' AND (pwd_hash = '$pwd_hash1' OR
-                                               pwd_hash = '$pwd_hash2')";
                        }
 
-                       $result = db_query($link, $query);
+                       if ($user_id && !$check_only) {
+                               $_SESSION["uid"] = $user_id;
+
+                               $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
+                                       WHERE id = '$user_id'");
 
-                       if (db_num_rows($result) == 1) {
-                               $_SESSION["uid"] = db_fetch_result($result, 0, "id");
                                $_SESSION["name"] = db_fetch_result($result, 0, "login");
                                $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
                                $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
                                db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
                                        $_SESSION["uid"]);
 
-
-                               // LemonLDAP can send user informations via HTTP HEADER
-                               if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER){
-                                       // update user name
-                                       $fullname = $_SERVER['HTTP_USER_NAME'] ? $_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
-                                       if ($fullname){
-                                               $fullname = db_escape_string($fullname);
-                                               db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
-                                                       $_SESSION["uid"]);
-                                       }
-                                       // update user mail
-                                       $email = $_SERVER['HTTP_USER_MAIL'] ? $_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
-                                       if ($email){
-                                               $email = db_escape_string($email);
-                                               db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
-                                                       $_SESSION["uid"]);
-                                       }
-                               }
-
                                $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
                                $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
 
 
                        $_SESSION["uid"] = 1;
                        $_SESSION["name"] = "admin";
+                       $_SESSION["access_level"] = 10;
+
+                       $_SESSION["hide_hello"] = true;
+                       $_SESSION["hide_logout"] = true;
+
+                       $_SESSION["auth_module"] = false;
+
+                       if (!$_SESSION["csrf_token"]) {
+                               $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
+                       }
 
                        $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
 
 
                        if (!$_SESSION["uid"] || !validate_session($link)) {
 
-                               if (get_remote_user($link) && AUTO_LOGIN) {
-                                   authenticate_user($link, get_remote_user($link), null);
+                               if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
                                    $_SESSION["ref_schema_version"] = get_schema_version($link, true);
                                } else {
+                                        authenticate_user($link, null, null, true);
                                    render_login_form($link, $mobile);
-                                   //header("Location: login.php");
                                    exit;
                                }
                        } else {
                }
        }
 
-       function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
+       function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
 
                        if (!$owner_uid) $owner_uid = $_SESSION['uid'];
 
                        //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
 
+                       $ref_check_qpart = ($max_id &&
+                               !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
+
                        if (is_numeric($feed)) {
                                if ($cat_view) {
 
 
                                                        db_query($link, "UPDATE ttrss_user_entries
                                                                SET unread = false,last_read = NOW()
-                                                               WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
+                                                               WHERE feed_id = '$tmp_feed'
+                                                               AND $ref_check_qpart
+                                                               AND owner_uid = $owner_uid");
                                                }
                                        } else if ($feed == -2) {
 
                                                db_query($link, "UPDATE ttrss_user_entries
                                                        SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
                                                                FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
-                                                       AND unread = true AND owner_uid = $owner_uid");
+                                                               AND $ref_check_qpart
+                                                               AND unread = true AND owner_uid = $owner_uid");
                                        }
 
                                } else if ($feed > 0) {
 
                                        db_query($link, "UPDATE ttrss_user_entries
                                                        SET unread = false,last_read = NOW()
-                                                       WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
+                                                       WHERE feed_id = '$feed'
+                                                       AND $ref_check_qpart
+                                                       AND owner_uid = $owner_uid");
 
                                } else if ($feed < 0 && $feed > -10) { // special, like starred
 
                                        if ($feed == -1) {
                                                db_query($link, "UPDATE ttrss_user_entries
                                                        SET unread = false,last_read = NOW()
-                                                       WHERE marked = true AND owner_uid = $owner_uid");
+                                                       WHERE marked = true
+                                                       AND $ref_check_qpart
+                                                       AND owner_uid = $owner_uid");
                                        }
 
                                        if ($feed == -2) {
                                                db_query($link, "UPDATE ttrss_user_entries
                                                        SET unread = false,last_read = NOW()
-                                                       WHERE published = true AND owner_uid = $owner_uid");
+                                                       WHERE published = true
+                                                       AND $ref_check_qpart
+                                                       AND owner_uid = $owner_uid");
                                        }
 
                                        if ($feed == -3) {
                                        if ($feed == -4) {
                                                db_query($link, "UPDATE ttrss_user_entries
                                                        SET unread = false,last_read = NOW()
-                                                       WHERE owner_uid = $owner_uid");
+                                                       WHERE $ref_check_qpart AND owner_uid = $owner_uid");
                                        }
 
                                } else if ($feed < -10) { // label
                                        db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
                                                SET unread = false, last_read = NOW()
                                                        WHERE label_id = '$label_id' AND unread = true
+                                                       AND $ref_check_qpart
                                                        AND owner_uid = '$owner_uid' AND ref_id = article_id");
 
                                }
                                while ($line = db_fetch_assoc($result)) {
                                        db_query($link, "UPDATE ttrss_user_entries SET
                                                unread = false, last_read = NOW()
-                                               WHERE int_id = " . $line["post_int_id"]);
+                                               WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
                                }
                                db_query($link, "COMMIT");
                        }
 
                array_push($ret_arr, $cv);
 
-               $age_qpart = getMaxAgeSubquery();
-
-               $result = db_query($link, "SELECT id AS cat_id, value AS unread
+               $result = db_query($link, "SELECT id AS cat_id, value AS unread,
+                       (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
+                               WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
                        FROM ttrss_feed_categories, ttrss_cat_counters_cache
                        WHERE ttrss_cat_counters_cache.feed_id = id AND
+                       ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
                        ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
 
                while ($line = db_fetch_assoc($result)) {
                        $line["cat_id"] = (int) $line["cat_id"];
 
+                       if ($line["num_children"] > 0) {
+                               $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
+                       } else {
+                               $child_counter = 0;
+                       }
+
                        $cv = array("id" => $line["cat_id"], "kind" => "cat",
+                               "child_counter" => $child_counter,
                                "counter" => $line["unread"]);
 
                        array_push($ret_arr, $cv);
                return $ret_arr;
        }
 
+       // only accepts real cats (>= 0)
+       function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
+               if (!$owner_uid) $owner_uid = $_SESSION["uid"];
+
+               $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
+                               AND owner_uid = $owner_uid");
+
+               $unread = 0;
+
+               while ($line = db_fetch_assoc($result)) {
+                       $unread += getCategoryUnread($link, $line["id"], $owner_uid);
+                       $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
+               }
+
+               return $unread;
+       }
+
        function getCategoryUnread($link, $cat, $owner_uid = false) {
 
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
                                $cat_query = "cat_id IS NULL";
                        }
 
-                       $age_qpart = getMaxAgeSubquery();
-
                        $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
                                        AND owner_uid = " . $owner_uid);
 
                        $match_part = implode(" OR ", $cat_feeds);
 
                        $result = db_query($link, "SELECT COUNT(int_id) AS unread
-                               FROM ttrss_user_entries,ttrss_entries
-                               WHERE   unread = true AND ($match_part) AND id = ref_id
-                               AND $age_qpart AND owner_uid = " . $owner_uid);
+                               FROM ttrss_user_entries
+                               WHERE   unread = true AND ($match_part)
+                               AND owner_uid = " . $owner_uid);
 
                        $unread = 0;
 
 
                        $result = db_query($link, "
                                SELECT COUNT(unread) AS unread FROM
-                                       ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
-                               WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
-                                       ttrss_labels2.owner_uid = '$owner_uid'
-                                       AND unread = true AND feed_id = ttrss_feeds.id
+                                       ttrss_user_entries, ttrss_user_labels2
+                               WHERE article_id = ref_id AND unread = true
                                        AND ttrss_user_entries.owner_uid = '$owner_uid'");
 
                        $unread = db_fetch_result($result, 0, "unread");
                }
        }
 
-       function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
-               if (DB_TYPE == "pgsql") {
-                       return "ttrss_entries.date_updated >
-                               NOW() - INTERVAL '$days days'";
-               } else {
-                       return "ttrss_entries.date_updated >
-                               DATE_SUB(NOW(), INTERVAL $days DAY)";
-               }
-       }
-
        function getFeedUnread($link, $feed, $is_cat = false) {
                return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
        }
        function getLabelUnread($link, $label_id, $owner_uid = false) {
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
-               $result = db_query($link, "
-                       SELECT COUNT(unread) AS unread FROM
-                               ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
-                       WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
-                               ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
-                               AND unread = true AND feed_id = ttrss_feeds.id
-                               AND ttrss_user_entries.owner_uid = '$owner_uid'");
+               $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
+                       WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
 
                if (db_num_rows($result) != 0) {
                        return db_fetch_result($result, 0, "unread");
                $owner_uid = false) {
 
                $n_feed = (int) $feed;
+               $need_entries = false;
 
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
                        $unread_qpart = "true";
                }
 
-               $age_qpart = getMaxAgeSubquery();
-
                if ($is_cat) {
                        return getCategoryUnread($link, $n_feed, $owner_uid);
-               } if ($feed != "0" && $n_feed == 0) {
+               } else if ($n_feed == -6) {
+                       return 0;
+               } else if ($feed != "0" && $n_feed == 0) {
 
                        $feed = db_escape_string($feed);
 
                        $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
                                FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
-                                       AND ref_id = id AND $age_qpart
-                                       AND $unread_qpart)) AS count FROM ttrss_tags
+                                       AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
                                WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
                        return db_fetch_result($result, 0, "count");
 
                        } else {
                                $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
                        }
+
+                       $need_entries = true;
+
                } else if ($n_feed == -4) {
                        $match_part = "true";
                } else if ($n_feed >= 0) {
 
                if ($match_part) {
 
-                       if ($n_feed != 0) {
-                               $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
-                               $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
-                       } else {
+                       if ($need_entries) {
                                $from_qpart = "ttrss_user_entries,ttrss_entries";
-                               $feeds_qpart = '';
+                               $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
+                       } else {
+                               $from_qpart = "ttrss_user_entries";
                        }
 
                        $query = "SELECT count(int_id) AS unread
                                FROM $from_qpart WHERE
-                               ttrss_user_entries.ref_id = ttrss_entries.id AND
-                               $age_qpart AND
-                               $feeds_qpart
-                               $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
+                               $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
+
+                       //echo "[$feed/$query]\n";
 
                        $result = db_query($link, $query);
 
                        $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
                                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_qpart AND $age_qpart AND
-                                       ttrss_tags.owner_uid = " . $owner_uid);
+                               AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
                }
 
                $unread = db_fetch_result($result, 0, "unread");
 
                $ret_arr = array();
 
-               $age_qpart = getMaxAgeSubquery();
-
                $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(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
+                               AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
                                WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
                                ORDER BY count DESC LIMIT 55");
 
 
                $ret_arr = array();
 
-               $age_qpart = getMaxAgeSubquery();
-
                $owner_uid = $_SESSION["uid"];
 
                $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
 
                $ret_arr = array();
 
-               $age_qpart = getMaxAgeSubquery();
-
                $query = "SELECT ttrss_feeds.id,
                                ttrss_feeds.title,
                                ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
                                last_error, value AS count
                        FROM ttrss_feeds, ttrss_counters_cache
                        WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
+                               AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
                                AND ttrss_counters_cache.feed_id = id";
 
                $result = db_query($link, $query);
        }
 
        /**
-        * @return integer Status code:
+        * @return array (code => Status code, message => error message if available)
+        *
         *                 0 - OK, Feed already exists
         *                 1 - OK, Feed added
         *                 2 - Invalid URL
        function subscribe_to_feed($link, $url, $cat_id = 0,
                        $auth_login = '', $auth_pass = '', $need_auth = false) {
 
+               global $fetch_last_error;
+
                require_once "include/rssfuncs.php";
 
                $url = fix_url($url);
 
-               if (!$url || !validate_feed_url($url)) return 2;
+               if (!$url || !validate_feed_url($url)) return array("code" => 2);
 
                $update_method = 0;
 
                $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
 
                if (!$need_auth || !$has_oauth || strpos($url, '://api.twitter.com') === false) {
-                       if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
+                       if (!fetch_file_contents($url, false, $auth_login, $auth_pass))
+                               return array("code" => 5, "message" => $fetch_last_error);
 
                        if (url_is_html($url, $auth_login, $auth_pass)) {
                                $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
                                if (count($feedUrls) == 0) {
-                                       return 3;
+                                       return array("code" => 3);
                                } else if (count($feedUrls) > 1) {
-                                       return 4;
+                                       return array("code" => 4);
                                }
                                //use feed url as new URL
                                $url = key($feedUrls);
 
                        } else {
                                if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
-                                       return 5;
+                                       return array("code" => 5);
 
                                $update_method = 3;
                        }
                                update_rss_feed($link, $feed_id, true);
                        }
 
-                       return 1;
+                       return array("code" => 1);
                } else {
-                       return 0;
+                       return array("code" => 0);
                }
        }
 
        function print_feed_select($link, $id, $default_id = "",
-               $attributes = "", $include_all_feeds = true) {
+               $attributes = "", $include_all_feeds = true,
+               $root_id = false, $nest_level = 0) {
 
-               print "<select id=\"$id\" name=\"$id\" $attributes>";
-               if ($include_all_feeds) {
-                       print "<option value=\"0\">".__('All feeds')."</option>";
+               if (!$root_id) {
+                       print "<select id=\"$id\" name=\"$id\" $attributes>";
+                       if ($include_all_feeds) {
+                               $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
+                               print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
+                       }
                }
 
-               $result = db_query($link, "SELECT id,title FROM ttrss_feeds
-                       WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
+               if (get_pref($link, 'ENABLE_FEED_CATS')) {
 
-               if (db_num_rows($result) > 0 && $include_all_feeds) {
-                       print "<option disabled>--------</option>";
-               }
+                       if ($root_id)
+                               $parent_qpart = "parent_cat = '$root_id'";
+                       else
+                               $parent_qpart = "parent_cat IS NULL";
 
-               while ($line = db_fetch_assoc($result)) {
-                       if ($line["id"] == $default_id) {
-                               $is_selected = "selected=\"1\"";
-                       } else {
-                               $is_selected = "";
-                       }
+                       $result = db_query($link, "SELECT id,title,
+                               (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
+                                       c2.parent_cat = ttrss_feed_categories.id) AS num_children
+                               FROM ttrss_feed_categories
+                               WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
 
-                       $title = truncate_string(htmlspecialchars($line["title"]), 40);
+                       while ($line = db_fetch_assoc($result)) {
 
-                       printf("<option $is_selected value='%d'>%s</option>",
-                               $line["id"], $title);
-               }
+                               for ($i = 0; $i < $nest_level; $i++)
+                                       $line["title"] = " - " . $line["title"];
 
-               print "</select>";
-       }
+                               $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
 
-       function print_feed_cat_select($link, $id, $default_id = "",
-               $attributes = "", $include_all_cats = true) {
+                               printf("<option $is_selected value='CAT:%d'>%s</option>",
+                                       $line["id"], htmlspecialchars($line["title"]));
 
-               print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
+                               if ($line["num_children"] > 0)
+                                       print_feed_select($link, $id, $default_id, $attributes,
+                                               $include_all_feeds, $line["id"], $nest_level+1);
 
-               if ($include_all_cats) {
-                       print "<option value=\"0\">".__('Uncategorized')."</option>";
-               }
+                               $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
+                                       WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
 
-               $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
-                       WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
+                               while ($fline = db_fetch_assoc($feed_result)) {
+                                       $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
 
-               if (db_num_rows($result) > 0 && $include_all_cats) {
-                       print "<option disabled=\"1\">--------</option>";
-               }
+                                       $fline["title"] = " + " . $fline["title"];
 
-               while ($line = db_fetch_assoc($result)) {
-                       if ($line["id"] == $default_id) {
-                               $is_selected = "selected=\"1\"";
-                       } else {
-                               $is_selected = "";
+                                       for ($i = 0; $i < $nest_level; $i++)
+                                               $fline["title"] = " - " . $fline["title"];
+
+                                       printf("<option $is_selected value='%d'>%s</option>",
+                                               $fline["id"], htmlspecialchars($fline["title"]));
+                               }
+                       }
+
+                       if (!$root_id) {
+                               $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
+
+                               printf("<option $is_selected value='CAT:0'>%s</option>",
+                                       __("Uncategorized"));
+
+                               $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
+                                       WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
+
+                               while ($fline = db_fetch_assoc($feed_result)) {
+                                       $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
+
+                                       $fline["title"] = " + " . $fline["title"];
+
+                                       for ($i = 0; $i < $nest_level; $i++)
+                                               $fline["title"] = " - " . $fline["title"];
+
+                                       printf("<option $is_selected value='%d'>%s</option>",
+                                               $fline["id"], htmlspecialchars($fline["title"]));
+                               }
                        }
 
-                       if ($line["title"])
+               } else {
+                       $result = db_query($link, "SELECT id,title FROM ttrss_feeds
+                               WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
+
+                       while ($line = db_fetch_assoc($result)) {
+
+                               $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
+
                                printf("<option $is_selected value='%d'>%s</option>",
                                        $line["id"], htmlspecialchars($line["title"]));
+                       }
                }
 
-#              print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
-
-               print "</select>";
+               if (!$root_id) {
+                       print "</select>";
+               }
        }
 
+       function print_feed_cat_select($link, $id, $default_id,
+               $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
+
+                       if (!$root_id) {
+                                       print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
+                       }
+
+                       if ($root_id)
+                               $parent_qpart = "parent_cat = '$root_id'";
+                       else
+                               $parent_qpart = "parent_cat IS NULL";
+
+                       $result = db_query($link, "SELECT id,title,
+                               (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
+                                       c2.parent_cat = ttrss_feed_categories.id) AS num_children
+                               FROM ttrss_feed_categories
+                               WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
+
+                       while ($line = db_fetch_assoc($result)) {
+                               if ($line["id"] == $default_id) {
+                                       $is_selected = "selected=\"1\"";
+                               } else {
+                                       $is_selected = "";
+                               }
+
+                               for ($i = 0; $i < $nest_level; $i++)
+                                       $line["title"] = " - " . $line["title"];
+
+                               if ($line["title"])
+                                       printf("<option $is_selected value='%d'>%s</option>",
+                                               $line["id"], htmlspecialchars($line["title"]));
+
+                               if ($line["num_children"] > 0)
+                                       print_feed_cat_select($link, $id, $default_id, $attributes,
+                                               $include_all_cats, $line["id"], $nest_level+1);
+                       }
+
+                       if (!$root_id) {
+                               if ($include_all_cats) {
+                                       if (db_num_rows($result) > 0) {
+                                               print "<option disabled=\"1\">--------</option>";
+                                       }
+
+                                       if ($default_id == 0) {
+                                               $is_selected = "selected=\"1\"";
+                                       } else {
+                                               $is_selected = "";
+                                       }
+
+                                       print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
+                               }
+                               print "</select>";
+                       }
+               }
+
        function checkbox_to_sql_bool($val) {
                return ($val == "on") ? "true" : "false";
        }
                case -4:
                        return "images/tag.png";
                        break;
+               case -6:
+                       return "images/recently_read.png";
+                       break;
                default:
                        if ($id < -10) {
                                return "images/label.png";
                        return __("All articles");
                } else if ($id === 0 || $id === "0") {
                        return __("Archived articles");
+               } else if ($id == -6) {
+                       return __("Recently read");
                } else if ($id < -10) {
                        $label_id = -$id - 11;
                        $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
 
                $params["icons_url"] = ICONS_URL;
                $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
+               $params["default_include_children"] = get_pref($link, "_DEFAULT_INCLUDE_CHILDREN");
                $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
                $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
                $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
                                $data['new_version_available'] = (int) ($new_version_details != false);
 
                                $_SESSION["last_version_check"] = time();
+                               $_SESSION["version_data"] = $new_version_details;
                }
 
                return $data;
                return $search_query_part;
        }
 
+       function getChildCategories($link, $cat, $owner_uid) {
+               $rv = array();
+
+               $result = db_query($link, "SELECT id FROM ttrss_feed_categories
+                       WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
+
+               while ($line = db_fetch_assoc($result)) {
+                       array_push($rv, $line["id"]);
+                       $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
+               }
+
+               return $rv;
+       }
 
-       function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
+       function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false) {
 
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
                                        $view_query_part = " ";
                                } else if ($feed != -1) {
                                        $unread = getFeedUnread($link, $feed, $cat_view);
+
+                                       if ($cat_view && $feed > 0 && $include_children)
+                                               $unread += getCategoryChildrenUnread($link, $feed);
+
                                        if ($unread > 0) {
                                                $view_query_part = " unread = true AND ";
                                        }
                                if ($cat_view) {
 
                                        if ($feed > 0) {
-                                               $query_strategy_part = "cat_id = '$feed'";
+                                               if ($include_children) {
+                                                       # sub-cats
+                                                       $subcats = getChildCategories($link, $feed, $owner_uid);
+
+                                                       if (count($subcats) == 0) {
+                                                               $query_strategy_part = "cat_id = '$feed'";
+                                                       } else {
+                                                               array_push($subcats, $feed);
+                                                               $query_strategy_part = "cat_id IN (".
+                                                                       implode(",", $subcats).")";
+                                                       }
+                                               } else {
+                                                       $query_strategy_part = "cat_id = '$feed'";
+                                               }
+
                                        } else {
                                                $query_strategy_part = "cat_id IS NULL";
                                        }
                        } else if ($feed == 0 && !$cat_view) { // archive virtual feed
                                $query_strategy_part = "feed_id IS NULL";
                        } else if ($feed == 0 && $cat_view) { // uncategorized
-                               $query_strategy_part = "cat_id IS NULL";
+                               $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
                                $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
                        } else if ($feed == -1) { // starred virtual feed
                                $query_strategy_part = "marked = true";
                                                ttrss_user_labels2.article_id = ref_id";
 
                                }
-
+                       } else if ($feed == -6) { // recently read
+                               $query_strategy_part = "unread = false AND last_read IS NOT NULL";
+                               $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
+                               $override_order = "last_read DESC";
                        } else if ($feed == -3) { // fresh virtual feed
                                $query_strategy_part = "unread = true AND score >= 0";
 
 
                $node = $doc->getElementsByTagName('body')->item(0);
 
-               return $doc->saveXML($node);
+               return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
        }
 
        /**
 
                                        $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
 
+                                       global $tz_offset;
+
+                                       // reset tz_offset global to prevent tz cache clash between users
+                                       $tz_offset = -1;
+
                                        $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
                                        $digest = $tuple[0];
                                        $headlines_count = $tuple[1];
                $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'));
+               $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
+               $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
 
-               $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
-               $tpl_t->setVariable('CUR_TIME', date('G:i'));
+               $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
+               $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
+
+               $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
+               $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
 
                $affected_ids = array();
 
 
                $result = db_query($link, "SELECT ttrss_entries.title,
                                ttrss_feeds.title AS feed_title,
-                               ttrss_feed_categories.title AS cat_title,
+                               COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
                                date_updated,
                                ttrss_user_entries.ref_id,
                                link,
                        } */
 
                        if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
-                               if (!$line['cat_title']) $line['cat_title'] = __("Uncategorized");
-
                                $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
                        }
 
 
        function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
 
-               global $memcache;
-
                $a_id = db_escape_string($id);
 
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
                $obj_id = md5("TAGS:$owner_uid:$id");
                $tags = array();
 
-               if ($memcache && $obj = $memcache->get($obj_id)) {
-                       $tags = $obj;
-               } else {
-                       /* check cache first */
-
-                       if ($tag_cache === false) {
-                               $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
-                                       WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
+               /* check cache first */
 
-                               $tag_cache = db_fetch_result($result, 0, "tag_cache");
-                       }
+               if ($tag_cache === false) {
+                       $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
+                               WHERE ref_id = '$id' AND owner_uid = $owner_uid");
 
-                       if ($tag_cache) {
-                               $tags = explode(",", $tag_cache);
-                       } else {
+                       $tag_cache = db_fetch_result($result, 0, "tag_cache");
+               }
 
-                               /* do it the hard way */
+               if ($tag_cache) {
+                       $tags = explode(",", $tag_cache);
+               } else {
 
-                               $tmp_result = db_query($link, $query);
+                       /* do it the hard way */
 
-                               while ($tmp_line = db_fetch_assoc($tmp_result)) {
-                                       array_push($tags, $tmp_line["tag_name"]);
-                               }
+                       $tmp_result = db_query($link, $query);
 
-                               /* update the cache */
+                       while ($tmp_line = db_fetch_assoc($tmp_result)) {
+                               array_push($tags, $tmp_line["tag_name"]);
+                       }
 
-                               $tags_str = db_escape_string(join(",", $tags));
+                       /* update the cache */
 
-                               db_query($link, "UPDATE ttrss_user_entries
-                                       SET tag_cache = '$tags_str' WHERE ref_id = '$id'
-                                       AND owner_uid = " . $_SESSION["uid"]);
-                       }
+                       $tags_str = db_escape_string(join(",", $tags));
 
-                       if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
+                       db_query($link, "UPDATE ttrss_user_entries
+                               SET tag_cache = '$tags_str' WHERE ref_id = '$id'
+                               AND owner_uid = $owner_uid");
                }
 
                return $tags;
                return $entry;
        }
 
-       function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
+       function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
+               if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
                $rv = array();
 
                //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
 
                $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
-                       WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
+                       WHERE id = '$feed_id' AND owner_uid = $owner_uid");
 
                if (db_num_rows($result) == 1) {
                        $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
                if ($mark_as_read) {
                        $result = db_query($link, "UPDATE ttrss_user_entries
                                SET unread = false,last_read = NOW()
-                               WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
+                               WHERE ref_id = '$id' AND owner_uid = $owner_uid");
 
-                       ccache_update($link, $feed_id, $_SESSION["uid"]);
+                       ccache_update($link, $feed_id, $owner_uid);
                }
 
                $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
                        orig_feed_id,
                        note
                        FROM ttrss_entries,ttrss_user_entries
-                       WHERE   id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
+                       WHERE   id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
 
                if ($result) {
 
                                        </head><body>";
                        }
 
+                       $title_escaped = db_escape_string($line['title']);
+
                        $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
                                truncate_string(strip_tags($line['title']), 15) . "</div>";
 
+                       $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
+                               strip_tags($line['title']) . "</div>";
+
                        $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
 
                        $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
                        }
 
                        $parsed_updated = make_local_datetime($link, $line["updated"], true,
-                               false, true);
+                               $owner_uid, true);
 
                        $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
 
                        if ($line["link"]) {
-                               $rv['content'] .= "<div clear='both'><a target='_blank'
+                               $rv['content'] .= "<div class='postTitle' clear='both'><a target='_blank'
                                        title=\"".htmlspecialchars($line['title'])."\"
                                        href=\"" .
                                        $line["link"] . "\">" .
                                        truncate_string($line["title"], 100) .
                                        "<span class='author'>$entry_author</span></a></div>";
                        } else {
-                               $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
+                               $rv['content'] .= "<div class='postTitle' clear='both'>" . $line["title"] . "$entry_author</div>";
                        }
 
                        $tag_cache = $line["tag_cache"];
 
                        if (!$tag_cache)
-                               $tags = get_article_tags($link, $id);
+                               $tags = get_article_tags($link, $id, $owner_uid);
                        else
                                $tags = explode(",", $tag_cache);
 
 
                        if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
 
-                       $rv['content'] .= "<div style='float : right'>
+                       $rv['content'] .= "<div class='postTags' style='float : right'>
                                <img src='".theme_image($link, 'images/tag.png')."'
                                class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
 
                                $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS);
 
                                foreach ($button_plugins as $p) {
-                                       $pclass = trim("${p}_button");
+                                       $pclass = trim("button_${p}");
 
                                        if (class_exists($pclass)) {
                                                $plugin = new $pclass($link);
 
                        $rv['content'] .= "<div class=\"postContent\">";
 
-                       $article_content = sanitize($link, $line["content"], false, false,
+                       // N-grams
+
+                       if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
+
+                               $ngram_result = db_query($link, "SELECT id,title FROM
+                                               ttrss_entries,ttrss_user_entries
+                                       WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
+                                               AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
+                                               AND title != '$title_escaped'
+                                               AND owner_uid = $owner_uid");
+
+                               if (db_num_rows($ngram_result) > 0) {
+                                       $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
+                                               "<span>" . __('Related')."</span>";
+                                       $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
+
+                                       while ($nline = db_fetch_assoc($ngram_result)) {
+                                               $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
+                                                       dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
+
+                                       }
+                                       $rv['content'] .= "</div></div><br/";
+                               }
+                       }
+
+                       $article_content = sanitize($link, $line["content"], false, $owner_uid,
                                $feed_site_url);
 
                        $rv['content'] .= $article_content;
                return $text;
        }
 
-       function load_filters($link, $feed, $owner_uid, $action_id = false) {
+       function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
                $filters = array();
 
-               global $memcache;
+               $cat_id = getFeedCategory($link, $feed_id);
+
+               $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
+                       owner_uid = $owner_uid AND enabled = true");
+
+               while ($line = db_fetch_assoc($result)) {
+                       $filter_id = $line["id"];
 
-               $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
+                       $result2 = db_query($link, "SELECT
+                               r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
+                               FROM ttrss_filters2_rules AS r,
+                               ttrss_filter_types AS t
+                               WHERE
+                                       (cat_id IS NULL OR cat_id = '$cat_id') AND
+                                       (feed_id IS NULL OR feed_id = '$feed_id') AND
+                                       filter_type = t.id AND filter_id = '$filter_id'");
 
-               if ($memcache && $obj = $memcache->get($obj_id)) {
+                       $rules = array();
+                       $actions = array();
 
-                       return $obj;
+                       while ($rule_line = db_fetch_assoc($result2)) {
+#                              print_r($rule_line);
 
-               } else {
+                               $rule = array();
+                               $rule["reg_exp"] = $rule_line["reg_exp"];
+                               $rule["type"] = $rule_line["type_name"];
 
-                       if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
-
-                       $result = db_query($link, "SELECT reg_exp,
-                               ttrss_filter_types.name AS name,
-                               ttrss_filter_actions.name AS action,
-                               inverse,
-                               action_param,
-                               filter_param
-                               FROM ttrss_filters
-                                       LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
-                                       ttrss_filter_types,ttrss_filter_actions
+                               array_push($rules, $rule);
+                       }
+
+                       $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
+                               FROM ttrss_filters2_actions AS a,
+                               ttrss_filter_actions AS t
                                WHERE
-                                       enabled = true AND
-                                       $ftype_query_part
-                                       ttrss_filters.owner_uid = $owner_uid AND
-                                       ttrss_filter_types.id = filter_type AND
-                                       ttrss_filter_actions.id = action_id AND
-                                       ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
-                                       (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
-                                               ttrss_filters.cat_id IS NULL) OR
-                                       (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
-                               ORDER BY reg_exp");
+                                       action_id = t.id AND filter_id = '$filter_id'");
 
-                       while ($line = db_fetch_assoc($result)) {
+                       while ($action_line = db_fetch_assoc($result2)) {
+#                              print_r($action_line);
 
-                               if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
-                                       $filter["reg_exp"] = $line["reg_exp"];
-                                       $filter["action"] = $line["action"];
-                                       $filter["action_param"] = $line["action_param"];
-                                       $filter["filter_param"] = $line["filter_param"];
-                                       $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
+                               $action = array();
+                               $action["type"] = $action_line["type_name"];
+                               $action["param"] = $action_line["action_param"];
+
+                               array_push($actions, $action);
+                       }
 
-                                       array_push($filters[$line["name"]], $filter);
-                               }
 
-                       if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
+                       $filter = array();
+                       $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
+                       $filter["rules"] = $rules;
+                       $filter["actions"] = $actions;
 
-                       return $filters;
+                       if (count($rules) > 0 && count($actions) > 0) {
+                               array_push($filters, $filter);
+                       }
                }
+
+               return $filters;
        }
 
        function get_score_pic($score) {
        }
 
        function get_article_labels($link, $id) {
-               global $memcache;
-
-               $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
-
                $rv = array();
 
-               if ($memcache && $obj = $memcache->get($obj_id)) {
-                       return $obj;
-               } else {
-
-                       $result = db_query($link, "SELECT label_cache FROM
-                               ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
-                               $_SESSION["uid"]);
 
-                       $label_cache = db_fetch_result($result, 0, "label_cache");
+               $result = db_query($link, "SELECT label_cache FROM
+                       ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
+                       $_SESSION["uid"]);
 
-                       if ($label_cache) {
+               $label_cache = db_fetch_result($result, 0, "label_cache");
 
-                               $label_cache = json_decode($label_cache, true);
+               if ($label_cache) {
 
-                               if ($label_cache["no-labels"] == 1)
-                                       return $rv;
-                               else
-                                       return $label_cache;
-                       }
+                       $label_cache = json_decode($label_cache, true);
 
-                       $result = db_query($link,
-                               "SELECT DISTINCT label_id,caption,fg_color,bg_color
-                                       FROM ttrss_labels2, ttrss_user_labels2
-                               WHERE id = label_id
-                                       AND article_id = '$id'
-                                       AND owner_uid = ".$_SESSION["uid"] . "
-                               ORDER BY caption");
+                       if ($label_cache["no-labels"] == 1)
+                               return $rv;
+                       else
+                               return $label_cache;
+               }
 
-                       while ($line = db_fetch_assoc($result)) {
-                               $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
-                                       $line["bg_color"]);
-                               array_push($rv, $rk);
-                       }
-                       if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
+               $result = db_query($link,
+                       "SELECT DISTINCT label_id,caption,fg_color,bg_color
+                               FROM ttrss_labels2, ttrss_user_labels2
+                       WHERE id = label_id
+                               AND article_id = '$id'
+                               AND owner_uid = ".$_SESSION["uid"] . "
+                       ORDER BY caption");
 
-                       if (count($rv) > 0)
-                               label_update_cache($link, $id, $rv);
-                       else
-                               label_update_cache($link, $id, array("no-labels" => 1));
+               while ($line = db_fetch_assoc($result)) {
+                       $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
+                               $line["bg_color"]);
+                       array_push($rv, $rk);
                }
 
+               if (count($rv) > 0)
+                       label_update_cache($link, $id, $rv);
+               else
+                       label_update_cache($link, $id, array("no-labels" => 1));
+
                return $rv;
        }
 
 
        function label_add_article($link, $id, $label, $owner_uid) {
 
-               global $memcache;
-
-               if ($memcache) {
-                       $obj_id = md5("LABELS:$id:$owner_uid");
-                       $memcache->delete($obj_id);
-               }
-
                $label_id = label_find_id($link, $label, $owner_uid);
 
                if (!$label_id) return;
        }
 
        function label_remove($link, $id, $owner_uid) {
-               global $memcache;
-
                if (!$owner_uid) $owner_uid = $_SESSION["uid"];
 
-               if ($memcache) {
-                       $obj_id = md5("LABELS:$id:$owner_uid");
-                       $memcache->delete($obj_id);
-               }
-
                db_query($link, "BEGIN");
 
                $result = db_query($link, "SELECT caption FROM ttrss_labels2
                }
        }
 
-       function add_feed_category($link, $feed_cat) {
+       function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
+               if ($parent_cat_id) {
+                       $parent_qpart = "parent_cat = '$parent_cat_id'";
+                       $parent_insert = "'$parent_cat_id'";
+               } else {
+                       $parent_qpart = "parent_cat IS NULL";
+                       $parent_insert = "NULL";
+               }
+
+               $result = db_query($link,
+                       "SELECT id FROM ttrss_feed_categories
+                       WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
+
+               if (db_num_rows($result) == 0) {
+                       return false;
+               } else {
+                       return db_fetch_result($result, 0, "id");
+               }
+       }
+
+       function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
 
                if (!$feed_cat) return false;
 
                db_query($link, "BEGIN");
 
+               if ($parent_cat_id) {
+                       $parent_qpart = "parent_cat = '$parent_cat_id'";
+                       $parent_insert = "'$parent_cat_id'";
+               } else {
+                       $parent_qpart = "parent_cat IS NULL";
+                       $parent_insert = "NULL";
+               }
+
                $result = db_query($link,
                        "SELECT id FROM ttrss_feed_categories
-                       WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
+                       WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
 
                if (db_num_rows($result) == 0) {
 
                        $result = db_query($link,
-                               "INSERT INTO ttrss_feed_categories (owner_uid,title)
-                               VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
+                               "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
+                               VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
 
                        db_query($link, "COMMIT");
 
 
        function get_article_enclosures($link, $id) {
 
-               global $memcache;
-
                $query = "SELECT * FROM ttrss_enclosures
                        WHERE post_id = '$id' AND content_url != ''";
 
-               $obj_id = md5("ENCLOSURES:$id");
-
                $rv = array();
 
-               if ($memcache && $obj = $memcache->get($obj_id)) {
-                       $rv = $obj;
-               } else {
-                       $result = db_query($link, $query);
+               $result = db_query($link, $query);
 
-                       if (db_num_rows($result) > 0) {
-                               while ($line = db_fetch_assoc($result)) {
-                                       array_push($rv, $line);
-                               }
-                               if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
+               if (db_num_rows($result) > 0) {
+                       while ($line = db_fetch_assoc($result)) {
+                               array_push($rv, $line);
                        }
                }
 
 
                        if ($cat_id == -4 || $cat_id == -3) {
                                $result = db_query($link, "SELECT
-                                       id, feed_url, cat_id, title, ".
+                                       id, feed_url, cat_id, title, order_id, ".
                                                SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
                                                FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
                                                " ORDER BY cat_id, title " . $limit_qpart);
                                        $cat_qpart = "cat_id IS NULL";
 
                                $result = db_query($link, "SELECT
-                                       id, feed_url, cat_id, title, ".
+                                       id, feed_url, cat_id, title, order_id, ".
                                                SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
                                                FROM ttrss_feeds WHERE
                                                $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
                                                        "unread" => (int)$unread,
                                                        "has_icon" => $has_icon,
                                                        "cat_id" => (int)$line["cat_id"],
-                                                       "last_updated" => strtotime($line["last_updated"])
+                                                       "last_updated" => strtotime($line["last_updated"]),
+                                                       "order_id" => (int) $line["order_id"],
                                                );
 
                                        array_push($feeds, $row);
 
                                $headline_row["labels"] = $labels;
 
+                               $headline_row["feed_title"] = $line["feed_title"];
+
                                array_push($headlines, $headline_row);
                        }
 
 
                                if (!$ctype) $ctype = __("unknown type");
 
-#                              $filename = substr($url, strrpos($url, "/")+1);
+                               $filename = substr($url, strrpos($url, "/")+1);
 
-                               $entry = format_inline_player($link, $url, $ctype);
+#                              $player = format_inline_player($link, $url, $ctype);
 
 #                              $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
 #                                      $filename . " (" . $ctype . ")" . "</a>";
 
+                               $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
+                                       dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
+
                                array_push($entries_html, $entry);
 
                                $entry = array();
                                array_push($entries, $entry);
                        }
 
-                       $rv .= "<div class=\"postEnclosures\">";
-
                        if (!get_pref($link, "STRIP_IMAGES")) {
                                if ($always_display_enclosures ||
                                                        !preg_match("/<img/i", $article_content)) {
                                                                $rv .= "<p><img
                                                                alt=\"".htmlspecialchars($entry["filename"])."\"
                                                                src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
+
                                                }
                                        }
                                }
                        }
 
-                       if (count($entries) == 1) {
-                               $rv .= __("Attachment:") . " ";
-                       } else {
-                               $rv .= __("Attachments:") . " ";
-                       }
+                       $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
+                               "<span>" . __('Attachments')."</span>";
+                       $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
 
-                       $rv .= join(", ", $entries_html);
+                       foreach ($entries_html as $entry) { $rv .= $entry; };
 
-                       $rv .= "</div>";
+                       $rv .= "</div></div>";
                }
 
                return $rv;
         * @return string Absolute URL
         */
        function rewrite_relative_url($url, $rel_url) {
-               if (strpos($rel_url, "://") !== false) {
+               if (strpos($rel_url, "magnet:") === 0) {
+                       return $rel_url;
+               } else if (strpos($rel_url, "://") !== false) {
+                       return $rel_url;
+               } else if (strpos($rel_url, "//") === 0) {
+                       # protocol-relative URL (rare but they exist)
                        return $rel_url;
                } else if (strpos($rel_url, "/") === 0)
                {
 
                $node = $doc->getElementsByTagName('body')->item(0);
 
-               return $doc->saveXML($node);
+               // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
+               if ($node)
+                       return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
+               else
+                       return $html;
        }
 
        function filter_to_sql($filter) {
                $query = "";
 
-               if (DB_TYPE == "pgsql")
-                       $reg_qpart = "~";
-               else
-                       $reg_qpart = "REGEXP";
+               $regexp_valid = preg_match('/' . $filter['reg_exp'] . '/',
+                       $filter['reg_exp']) !== FALSE;
 
-               switch ($filter["type"]) {
-                       case "title":
-                               $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "')";
-                               break;
-                       case "content":
-                               $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "')";
-                               break;
-                       case "both":
-                               $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "') OR LOWER(" .
-                                       "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
-                               break;
-                       case "tag":
-                               $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "')";
-                               break;
-                       case "link":
-                               $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "')";
-                               break;
-                       case "date":
+               if ($regexp_valid) {
 
-                               if ($filter["filter_param"] == "before")
-                                       $cmp_qpart = "<";
-                               else
-                                       $cmp_qpart = ">=";
+                       if (DB_TYPE == "pgsql")
+                               $reg_qpart = "~";
+                       else
+                               $reg_qpart = "REGEXP";
 
-                               $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
-                               $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
-                               break;
-                       case "author":
-                               $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
-                                       $filter['reg_exp'] . "')";
-                               break;
-               }
+                       switch ($filter["type"]) {
+                               case "title":
+                                       $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "')";
+                                       break;
+                               case "content":
+                                       $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "')";
+                                       break;
+                               case "both":
+                                       $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "') OR LOWER(" .
+                                               "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
+                                       break;
+                               case "tag":
+                                       $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "')";
+                                       break;
+                               case "link":
+                                       $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "')";
+                                       break;
+                               case "date":
 
-               if ($filter["inverse"])
-                       $query = "NOT ($query)";
+                                       if ($filter["filter_param"] == "before")
+                                               $cmp_qpart = "<";
+                                       else
+                                               $cmp_qpart = ">=";
 
-               if ($query) {
-                       if (DB_TYPE == "pgsql") {
-                               $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
-                       } else {
-                               $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
+                                       $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
+                                       $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
+                                       break;
+                               case "author":
+                                       $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
+                                               $filter['reg_exp'] . "')";
+                                       break;
                        }
-                       $query .= " AND ";
-               }
 
+                       if ($filter["inverse"])
+                               $query = "NOT ($query)";
+
+                       if ($query) {
+                               if (DB_TYPE == "pgsql") {
+                                       $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
+                               } else {
+                                       $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
+                               }
+                               $query .= " AND ";
+                       }
 
-               return $query;
+                       return $query;
+               } else {
+                       return false;
+               }
        }
 
        // Status codes:
                        return $output;
                }
        }
+
+       function read_stdin() {
+               $fp = fopen("php://stdin", "r");
+
+               if ($fp) {
+                       $line = trim(fgets($fp));
+                       fclose($fp);
+                       return $line;
+               }
+
+               return null;
+       }
+
+       function tmpdirname($path, $prefix) {
+               // Use PHP's tmpfile function to create a temporary
+               // directory name. Delete the file and keep the name.
+               $tempname = tempnam($path,$prefix);
+               if (!$tempname)
+                       return false;
+
+               if (!unlink($tempname))
+                       return false;
+
+       return $tempname;
+       }
+
+       function getFeedCategory($link, $feed) {
+               $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
+                       WHERE id = '$feed'");
+
+               if (db_num_rows($result) > 0) {
+                       return db_fetch_result($result, 0, "cat_id");
+               } else {
+                       return false;
+               }
+
+       }
+
 ?>