]> git.wh0rd.org - tt-rss.git/blobdiff - functions.php
make storeInitParam actually work (move back to cookies)
[tt-rss.git] / functions.php
index afe3e4cd2ff418a32a5b7deaac4ad4744c46bca3..05ac12dd304b044a3eaeff8f98246a647ed9750e 100644 (file)
@@ -6,7 +6,28 @@
                define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
        } */
 
+       require_once "accept-to-gettext.php";
+       require_once "gettext/gettext.inc";
+
        require_once 'config.php';
+
+       function startup_gettext() {
+
+               # Get locale from Accept-Language header
+               $lang = al2gt(array("en_US", "ru_RU"), "text/html");
+
+               if ($lang) {
+                       _setlocale(LC_MESSAGES, $lang);
+                       _bindtextdomain("messages", "locale");
+                       _textdomain("messages");
+                       _bind_textdomain_codeset("messages", "UTF-8");
+               }
+       }
+
+       if (ENABLE_TRANSLATIONS == true) { 
+               startup_gettext();
+       }
+
        require_once 'db-prefs.php';
        require_once 'compat.php';
        require_once 'errors.php';
        require_once "magpierss/rss_fetch.inc";
        require_once 'magpierss/rss_utils.inc';
 
+       function _debug($msg) {
+               $ts = strftime("%H:%M:%S", time());
+               print "[$ts] $msg\n";
+       }
+
        function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
 
                $rows = -1;
@@ -69,7 +95,7 @@
                }
 
                if ($debug) {
-                       print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
+                       _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
                }
        }
 
 
                        if ($fp) {
                                curl_setopt($ch, CURLOPT_FILE, $fp);
+                               curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
+                               curl_setopt($ch, CURLOPT_TIMEOUT, 45);
                                curl_exec($ch);
                                curl_close($ch);
                                fclose($fp);                                    
                        return;                 
                }
 
+               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                       _debug("update_rss_feed: start");
+               }
+
                $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
                        FROM ttrss_feeds WHERE id = '$feed'");
 
 
                }
 
-               error_reporting(0);
+               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                       _debug("update_rss_feed: fetching...");
+               }
+
+               if (!defined('DAEMON_EXTENDED_DEBUG')) {
+                       error_reporting(0);
+               }
+
                $rss = fetch_rss($fetch_url);
-               error_reporting (DEFAULT_ERROR_LEVEL);
-               
+
+               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                       _debug("update_rss_feed: fetch done, parsing...");
+               } else {
+                       error_reporting (DEFAULT_ERROR_LEVEL);
+               }
+
                $feed = db_escape_string($feed);
 
                if ($rss) {
-                       
+
+                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               _debug("update_rss_feed: processing feed data...");
+                       }
+
 //                     db_query($link, "BEGIN");
 
                        $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
                        $owner_uid = db_fetch_result($result, 0, "owner_uid");
 
                        if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
+                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       _debug("update_rss_feed: checking favicon...");
+                               }
                                check_feed_favicon($rss->channel["link"], $feed, $link);
                        }
 
                                db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
                        }
 
+                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               _debug("update_rss_feed: loading filters...");
+                       }
 
                        $filters = array();
 
                        $result = db_query($link, "SELECT reg_exp,
                                ttrss_filter_types.name AS name,
                                ttrss_filter_actions.name AS action,
+                               inverse,
                                action_param
                                FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
                                        enabled = true AND
                                        owner_uid = $owner_uid AND
                                        ttrss_filter_types.id = filter_type AND
                                        ttrss_filter_actions.id = action_id AND
-                               (feed_id IS NULL OR feed_id = '$feed')");
+                               (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
 
                        while ($line = db_fetch_assoc($result)) {
                                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["inverse"] = sql_bool_to_bool($line["inverse"]);
                        
                                array_push($filters[$line["name"]], $filter);
                        }
                                return; // WTF?
                        }
 
+                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                               _debug("update_rss_feed: processing articles...");
+                       }
+
                        foreach ($iterator as $item) {
 
                                $entry_guid = $item["id"];
-       
+
                                if (!$entry_guid) $entry_guid = $item["guid"];
                                if (!$entry_guid) $entry_guid = $item["link"];
                                if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
 
+                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       _debug("update_rss_feed: guid $entry_guid");
+                               }
+
                                if (!$entry_guid) continue;
 
                                $entry_timestamp = "";
                                if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
                                if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
                                
-                               if ($entry_timestamp == "") {
+                               if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
                                        $entry_timestamp = time();
                                        $no_orig_date = 'true';
                                } else {
                                $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
 
                                if ($item['author']) {
-                                       if (!$entry_author) {
-                                               $entry_author = db_escape_string(strip_tags($item['author']['name']));
-                                       }
 
-                                       if (!$entry_author) {
-                                               $entry_author = db_escape_string(strip_tags($item['author']['email']));
+                                       if (is_array($item['author'])) {
+
+                                               if (!$entry_author) {
+                                                       $entry_author = db_escape_string(strip_tags($item['author']['name']));
+                                               }
+
+                                               if (!$entry_author) {
+                                                       $entry_author = db_escape_string(strip_tags($item['author']['email']));
+                                               }
                                        }
 
                                        if (!$entry_author) {
 
                                if (!$num_comments) $num_comments = 0;
 
-                               $dc_subject = $item['dc']['subject'];
+/*                             $dc_subject = $item['dc']['subject'];
 
                                $subject_tags = false;
 
                                        $subject_tags = $dc_subject;
                                } else if ($dc_subject) {
                                        $subject_tags = array($dc_subject);
-                               }
+                               } */
 
                                # sanitize content
                                
                                $entry_content = sanitize_rss($entry_content);
 
+                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
+                               }
+
                                db_query($link, "BEGIN");
 
                                if (db_num_rows($result) == 0) {
 
+                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                               _debug("update_rss_feed: base guid not found");
+                                       }
+
                                        // base post entry does not exist, create it
 
                                        $result = db_query($link,
 
                                if (db_num_rows($result) == 1) {
 
+                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                               _debug("update_rss_feed: base guid found, checking for user record");
+                                       }
+
                                        // this will be used below in update handler
                                        $orig_content_hash = db_fetch_result($result, 0, "content_hash");
                                        $orig_title = db_fetch_result($result, 0, "title");
 
 //                                     error_reporting(0);
 
-                                       $tuple = get_filter_name($entry_title, $entry_content
-                                               $entry_link, $filters);
+                                       $article_filters = get_article_filters($filters, $entry_title
+                                                       $entry_content, $entry_link);
 
-                                       $filter_name = $tuple[0];
-                                       $filter_param = $tuple[1];
+                                       if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                               _debug("update_rss_feed: article filters: ");
+                                               if (count($article_filters) != 0) {
+                                                       print_r($article_filters);
+                                               }
+                                       }
 
-                                       if ($filter_name == "filter") {
+                                       if (find_article_filter($article_filters, "filter")) {
                                                continue;
                                        }
 
                                                "SELECT ref_id FROM ttrss_user_entries WHERE
                                                        ref_id = '$ref_id' AND owner_uid = '$owner_uid'
                                                        $dupcheck_qpart");
-                                                       
+
                                        // okay it doesn't exist - create user entry
                                        if (db_num_rows($result) == 0) {
 
-                                               if ($filter_name != 'catchup') {
+                                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                                       _debug("update_rss_feed: user record not found, creating...");
+                                               }
+
+                                               if (!find_article_filter($article_filters, 'catchup')) {
                                                        $unread = 'true';
                                                        $last_read_qpart = 'NULL';
                                                } else {
                                                        $last_read_qpart = 'NOW()';
                                                }                                               
 
-                                               if ($filter_name == 'mark') {
+                                               if (find_article_filter($article_filters, 'mark')) {
                                                        $marked = 'true';
                                                } else {
                                                        $marked = 'false';
                                        // linking to this post as updated                                      
                                        if ($post_needs_update) {
 
+                                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                                       _debug("update_rss_feed: post $entry_guid needs update...");
+                                               }
+
 //                                             print "<!-- post $orig_title needs update : $post_needs_update -->";
 
                                                db_query($link, "UPDATE ttrss_entries 
 
                                db_query($link, "COMMIT");
 
+                               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                                       _debug("update_rss_feed: looking for tags...");
+                               }
+
                                /* taaaags */
                                // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
 
 
                                # check for manual tags
 
-                               if ($filter_name == "tag") {
+                               $tag_filter = find_article_filter($article_filters, "tag"); 
+
+                               if ($tag_filter) {
 
-                                       $manual_tags = trim_array(split(",", $filter_param));
+                                       $manual_tags = trim_array(split(",", $tag_filter[1]));
 
-                                       foreach ($manual_tags as $tag) {                                        
+                                       foreach ($manual_tags as $tag) {
                                                if (tag_is_valid($tag)) {
                                                        array_push($entry_tags, $tag);
                                                }
                                        }
                                }
 
-                               if ($subject_tags) {
+/*                             if ($subject_tags) {
                                        foreach ($subject_tags as $tag) {
                                                if (tag_is_valid($tag)) {
                                                        array_push($entry_tags, $tag);
                                                }
                                        }
-                               }
+                               } */
 
                                if (count($entry_tags) > 0) {
                                
                                                $entry_int_id = db_fetch_result($result, 0, "int_id");
                                                
                                                foreach ($entry_tags as $tag) {
-                                                       $tag = db_escape_string(strtolower($tag));
+                                                       $tag = db_escape_string(mb_strtolower(strip_tags($tag)));
 
                                                        $tag = str_replace("+", " ", $tag);     
                                                        $tag = str_replace("technorati tag: ", "", $tag);
-       
+
+                                                       if (!tag_is_valid($tag)) continue;
+                                                       
                                                        $result = db_query($link, "SELECT id FROM ttrss_tags            
                                                                WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
                                                                owner_uid = '$owner_uid' LIMIT 1");
                                        last_updated = NOW() WHERE id = '$feed'");
                }
 
+               if (defined('DAEMON_EXTENDED_DEBUG')) {
+                       _debug("update_rss_feed: done");
+               }
+
        }
 
        function print_select($id, $default, $values, $attributes = "") {
                print "</select>";
        }
 
-       function get_filter_name($title, $content, $link, $filters) {
+       function get_article_filters($filters, $title, $content, $link) {
+               $matches = array();
 
                if ($filters["title"]) {
                        foreach ($filters["title"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];                  
-                               if (preg_match("/$reg_exp/i", $title)) {
-                                       return array($filter["action"], $filter["action_param"]);
-                               }
-                       }
-               }
-
-               if ($filters["content"]) {
-                       foreach ($filters["content"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];                  
-                               if (preg_match("/$reg_exp/i", $content)) {
-                                       return array($filter["action"], $filter["action_param"]);
-                               }               
-                       }
-               }
-
-               if ($filters["both"]) {
-                       foreach ($filters["both"] as $filter) {                 
                                $reg_exp = $filter["reg_exp"];          
-                               if (preg_match("/$reg_exp/i", $title) || 
-                                       preg_match("/$reg_exp/i", $content)) {
-                                               return array($filter["action"], $filter["action_param"]);
-                               }
-                       }
-               }
-
-               if ($filters["link"]) {
-                       $reg_exp = $filter["reg_exp"];
-                       foreach ($filters["link"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];
-                               if (preg_match("/$reg_exp/i", $link)) {
-                                       return array($filter["action"], $filter["action_param"]);
-                               }
-                       }
-               }
-
-               return false;
-       }
-
-       function get_filter_matches($title, $content, $link, $filters) {
-
-               $matches = array();
+                               $inverse = $filter["inverse"];  
+                               if ((!$inverse && preg_match("/$reg_exp/i", $title)) || 
+                                               ($inverse && !preg_match("/$reg_exp/i", $title))) {
 
-               if ($filters["title"]) {
-                       foreach ($filters["title"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];                  
-                               if (preg_match("/$reg_exp/i", $title)) {
                                        array_push($matches, array($filter["action"], $filter["action_param"]));
                                }
                        }
 
                if ($filters["content"]) {
                        foreach ($filters["content"] as $filter) {
-                               $reg_exp = $filter["reg_exp"];                  
-                               if (preg_match("/$reg_exp/i", $content)) {
+                               $reg_exp = $filter["reg_exp"];
+                               $inverse = $filter["inverse"];
+
+                               if ((!$inverse && preg_match("/$reg_exp/i", $content)) || 
+                                               ($inverse && !preg_match("/$reg_exp/i", $content))) {
+
                                        array_push($matches, array($filter["action"], $filter["action_param"]));
                                }               
                        }
                if ($filters["both"]) {
                        foreach ($filters["both"] as $filter) {                 
                                $reg_exp = $filter["reg_exp"];          
-                               if (preg_match("/$reg_exp/i", $title) || 
-                                       preg_match("/$reg_exp/i", $content)) {
+                               $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"]));
+                                       }
+                               } else {
+                                       if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
+                                               array_push($matches, array($filter["action"], $filter["action_param"]));
+                                       }
                                }
                        }
                }
                        $reg_exp = $filter["reg_exp"];
                        foreach ($filters["link"] as $filter) {
                                $reg_exp = $filter["reg_exp"];
-                               if (preg_match("/$reg_exp/i", $link)) {
+                               $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"]));
                                }
                        }
                return $matches;
        }
 
+       function find_article_filter($filters, $filter_name) {
+               foreach ($filters as $f) {
+                       if ($f[0] == $filter_name) {
+                               return $f;
+                       };
+               }
+               return false;
+       }
+
        function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
                $rtl_content = false, $last_updated = false, $last_error = false) {
 
                }
 
                $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" 
-                       href=\"#\" onclick=\"javascript:viewfeed('$feed_id', '', false);\">$feed_title</a>";
+                       href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
 
                print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
                if (get_pref($link, 'ENABLE_FEED_ICONS')) {
                        values ('$uid', 'Tiny Tiny RSS: New Releases',
                        'http://tt-rss.spb.ru/releases.rss')");
 
+               db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
+                       values ('$uid', 'Tiny Tiny RSS: Forum',
+                       'http://tt-rss.spb.ru/forum/rss.php')");
        }
 
        function logout_user() {
                return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
        }
 
-       function get_login_redirect() {
-               $server = $_SERVER["SERVER_NAME"];
-
-               if (ENABLE_LOGIN_SSL) {
-                       $protocol = "https";
-               } else {
-                       $protocol = "http";
-               }               
-
-               $url_path = get_script_urlpath();
-
-               $redirect_uri = "$protocol://$server$url_path/login.php";
-
-               return $redirect_uri;
-       }
-
        function validate_session($link) {
                if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
                        if ($_SESSION["ip_address"]) {
                                if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
+                                       $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
                                        return false;
                                }
                        }
                }
-               return true;
-       }
 
-       function basic_nosid_redirect_check() {
-               if (!SINGLE_USER_MODE) {
-                       if (!$_COOKIE[get_session_cookie_name()]) {
-                               $redirect_uri = get_login_redirect();
-                               $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
-                               header("Location: $redirect_uri?rt=$return_to");
-                               exit;
+/*             if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
+
+                       //print_r($_SESSION);
+
+                       if (time() > $_SESSION["cookie_lifetime"]) {
+                               return false;
                        }
-               }
+               } */
+
+               return true;
        }
 
-       function login_sequence($link) {
+       function login_sequence($link, $mobile = false) {
                if (!SINGLE_USER_MODE) {
 
                        if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
                                }
                        }
 
-                       if (!validate_session($link)) {
-                               logout_user();
-                               $redirect_uri = get_login_redirect();
-                               $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
-                               header("Location: $redirect_uri?rt=$return_to");
-                               exit;
-                       }
+                       $login_action = $_POST["login_action"];
+
+                       # try to authenticate user if called from login form                    
+                       if ($login_action == "do_login") {
+                               $login = $_POST["login"];
+                               $password = $_POST["password"];
+                               $remember_me = $_POST["remember_me"];
+
+                               if (authenticate_user($link, $login, $password)) {
+                                       $_POST["password"] = "";
 
-                       if (!USE_HTTP_AUTH) {
-                               if (!$_SESSION["uid"]) {
-                                       $redirect_uri = get_login_redirect();
-                                       $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
-                                       header("Location: $redirect_uri?rt=$return_to");
+                                       header("Location: " . $_SERVER["REQUEST_URI"]);
                                        exit;
+
+                                       return;
+                               } else {
+                                       $_SESSION["login_error_msg"] = "Incorrect username or password";
                                }
-                       } else {
-                               if (!$_SESSION["uid"]) {
-                                       if (!$_SERVER["PHP_AUTH_USER"]) {
+                       }
 
-                                               header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
-                                               header('HTTP/1.0 401 Unauthorized');
-                                               exit;
-                                               
-                                       } else {
-                                               $auth_result = authenticate_user($link, 
-                                                       $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
+//                     print session_id();
+//                     print_r($_SESSION);
 
-                                               if (!$auth_result) {
-                                                       header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
-                                                       header('HTTP/1.0 401 Unauthorized');
-                                                       exit;
-                                               }
-                                       }
-                               }                               
+                       if (!$_SESSION["uid"] || !validate_session($link)) {
+                               render_login_form($link, $mobile);
+                               exit;
                        }
+
+
                } else {
                        return authenticate_user($link, "admin", null);
                }
                        return false;
                } else {
                        return true;
-               } 
+               }
        }
 
        function file_is_locked($filename) {
        }
 
        function get_script_dt_add() {
-               if (strpos(VERSION, "99") === false) {
+               if (strpos(VERSION, ".99") === false) {
                        return VERSION;
                } else {
                        return time();
 
        function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
 
+               # check for feed:http://url
                $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
 
+               # check for feed://URL
+               if (strpos($feed_link, "//") === 0) {
+                       $feed_link = "http:$feed_link";
+               }
+
                if ($feed_link == "") return;
 
                if ($cat_id == "0" || !$cat_id) {
                print "<select id=\"$id\" name=\"$id\" $attributes>";
 
                if ($include_all_cats) {
-                       print "<option value=\"0\">"._('Uncategorized')."</option>";
+                       print "<option value=\"0\">".__('Uncategorized')."</option>";
                }
 
                $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
 
        function getFeedCatTitle($link, $id) {
                if ($id == -1) {
-                       return _("Special");
+                       return __("Special");
                } else if ($id < -10) {
-                       return _("Labels");
+                       return __("Labels");
                } else if ($id > 0) {
                        $result = db_query($link, "SELECT ttrss_feed_categories.title 
                                FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
                        if (db_num_rows($result) == 1) {
                                return db_fetch_result($result, 0, "title");
                        } else {
-                               return _("Uncategorized");
+                               return __("Uncategorized");
                        }
                } else {
                        return "getFeedCatTitle($id) failed";
 
        function getFeedTitle($link, $id) {
                if ($id == -1) {
-                       return _("Starred articles");
+                       return __("Starred articles");
                } else if ($id < -10) {
                        $label_id = -10 - $id;
                        $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
                print "<param key=\"confirm_feed_catchup\" value=\"" . 
                        sprintf("%d", get_pref($link, "CONFIRM_FEED_CATCHUP")) . "\"/>";
 
+               print "<param key=\"cdm_auto_catchup\" value=\"" . 
+                       sprintf("%d", get_pref($link, "CDM_AUTO_CATCHUP")) . "\"/>";
+
+               print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
+
+               print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
+
                print "</init-params>";
        }
 
                        print "<param key=\"daemon_is_running\" value=\"".
                                sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
                }
+               if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
+                       
+                       if ($_SESSION["last_version_check"] + 600 < time()) {
+                               $new_version_details = check_for_update($link);
+
+                               print "<param key=\"new_version_available\" value=\"".
+                                       sprintf("%d", $new_version_details != ""). "\"/>";
+
+                               $_SESSION["last_version_check"] = time();
+                       }
+               }
+
                print "</runtime-info>";
        }
 
                return $search_query_part;
        }
 
-       function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false) {
+       function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
+
                        if ($search) {
                        
                                $search_query_part = getSearchSql($search, $match_on);
                        $feed_title = "";
 
                        if ($search && $search_mode == "all_feeds") {
-                               $feed_title = _("Global search results")." ($search)";
+                               $feed_title = __("Global search results")." ($search)";
                        } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
-                               $feed_title = _("Tag search results")." ($search, $feed)";
+                               $feed_title = __("Tag search results")." ($search, $feed)";
                        } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
                                $feed_title = $feed;
                        } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
                                                        WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
                                                $feed_title = db_fetch_result($result, 0, "title");
                                        } else {
-                                               $feed_title = _("Uncategorized");
+                                               $feed_title = __("Uncategorized");
                                        }
 
                                        if ($search) {
-                                               $feed_title = _("Category search results")." ($search, $feed_title)";
+                                               $feed_title = __("Category search results")." ($search, $feed_title)";
                                        }
 
                                } else {
                                        $last_error = db_fetch_result($result, 0, "last_error");
 
                                        if ($search) {
-                                               $feed_title = _("Feed search results") . " ($search, $feed_title)";
+                                               $feed_title = __("Feed search results") . " ($search, $feed_title)";
                                        }
                                }
        
                        } else if ($feed == -1) {
-                               $feed_title = _("Starred articles");
+                               $feed_title = __("Starred articles");
                        } else if ($feed < -10) {
                                $label_id = -$feed - 11;
                                $result = db_query($link, "SELECT description FROM ttrss_labels
                                $feed_title = db_fetch_result($result, 0, "description");
 
                                if ($search) {
-                                       $feed_title = _("Label search results") . " ($search, $feed_title)";
+                                       $feed_title = __("Label search results") . " ($search, $feed_title)";
                                }
                        } else {
                                $feed_title = "?";
                                }
        
                                $content_query_part = "content as content_preview,";
-                               
+
+                               if ($limit_query_part) {
+                                       $offset_query_part = "OFFSET $offset";
+                               }
+
                                $query = "SELECT 
                                                guid,
                                                ttrss_entries.id,ttrss_entries.title,
                                        $search_query_part
                                        $view_query_part
                                        $query_strategy_part ORDER BY $order_by
-                                       $limit_query_part";
+                                       $limit_query_part $offset_query_part";
                                        
                                $result = db_query($link, $query);
        
        }
 
        function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
-               $tmp =  _("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";        
+               $tmp =  __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";       
                $tmp .= "=======================================================\n\n";
 
                if (DB_TYPE == "pgsql") {
                }
 
                $tmp .= "--- \n";
-               $tmp .= _("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") . 
+               $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") . 
                        DIGEST_HOSTNAME . "\n".
-                       _("To unsubscribe, visit your configuration options or contact instance owner.\n");
+                       __("To unsubscribe, visit your configuration options or contact instance owner.\n");
                        
 
                return array($tmp, $headlines_count);
        }
 
-       function check_for_update($link) {
+       function check_for_update($link, $brief_fmt = true) {
                $releases_feed = "http://tt-rss.spb.ru/releases.rss";
 
                if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
                        $content = sanitize_rss($latest_item["description"]);
 
                        if (version_compare(VERSION, $latest_version) == -1) {
-                               return "<div class=\"notice\"><a href=\"javascript:showBlockElement('milestoneDetails')\">      
-                                       New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
-                                       <div id=\"milestoneDetails\">$content</div></div>";
+                               if ($brief_fmt) {
+                                       return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">      
+                                               New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
+                                               <div id=\"milestoneDetails\">$content</div>");
+                               } else {
+                                       return "New version of Tiny-Tiny RSS ($latest_version) is available:
+                                               <div class='milestoneDetails'>$content</div>
+                                               Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
+                                               download and update information.";      
+                               }
+
                        }                       
                }
        }
        function print_headline_subtoolbar($link, $feed_site_url, $feed_title, 
                        $bottom = false, $rtl_content = false, $feed_id = 0,
                        $is_cat = false, $search = false, $match_on = false,
-                       $search_mode = false) {
+                       $search_mode = false, $offset = 0, $limit = 0) {
+
+                       $user_page_offset = $offset + 1;
 
                        if (!$bottom) {
                                $class = "headlinesSubToolbar";
                                $rtl_cpart = "";
                        }
 
+                       $page_prev_link = "javascript:viewFeedGoPage(-1)";
+                       $page_next_link = "javascript:viewFeedGoPage(1)";
+                       $page_first_link = "javascript:viewFeedGoPage(0)";
+
+                       $catchup_page_link = "javascript:catchupPage()";
+                       $catchup_feed_link = "javascript:catchupCurrentFeed()";
+
                        if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
 
-                               print "<td class=\"headlineActions$rtl_cpart\">".
-                                       _('Select:')."
-                                                               <a href=\"javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)\">All</a>,
-                                                               <a href=\"javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)\">Unread</a>,
-                                                               <a href=\"javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)\">None</a>
-                                               &nbsp;&nbsp;".
-                                               _('Toggle:')." <a href=\"javascript:selectionToggleUnread()\">Unread</a>,
-                                                       <a href=\"javascript:selectionToggleMarked()\">Starred</a>
-                                               &nbsp;&nbsp;".
-                                               _('Mark as read:')."
-                                                       <a href=\"#\" onclick=\"catchupPage()\">Page</a>,
-                                                       <a href=\"#\" onclick=\"catchupCurrentFeed()\">Feed</a>";
-                               print "</td>";
-
-                               if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
-                                       print "<td class=\"headlineActions$rtl_cpart\">
-                                               <a href=\"javascript:labelFromSearch('$search', '$search_mode',
-                                                               '$match_on', '$feed_id', '$is_cat');\">
-                                                       "._('Convert this search to label')."</a></td>";
-                               }
+                               $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
+                               $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
+                               $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
+
+                               $tog_unread_link = "javascript:selectionToggleUnread()";
+                               $tog_marked_link = "javascript:selectionToggleMarked()";
+
+                       } else {
+
+                               $sel_all_link = "javascript:cdmSelectArticles('all')";
+                               $sel_unread_link = "javascript:cdmSelectArticles('unread')";
+                               $sel_none_link = "javascript:cdmSelectArticles('none')";
+
+                               $tog_unread_link = "javascript:selectionToggleUnread(true)";
+                               $tog_marked_link = "javascript:selectionToggleMarked(true)";
+
+                       }
+
+                       if (!strstr($_SESSION["client.userAgent"], "MSIE")) {
+
+                               print "<td class=\"headlineActions$rtl_cpart\">
+                                       <ul class=\"headlineDropdownMenu\">
+                                       <li class=\"top2\">
+                                       ".__('Select:')."
+                                               <a href=\"$sel_all_link\">".__('All')."</a>,
+                                               <a href=\"$sel_unread_link\">".__('Unread')."</a>,
+                                               <a href=\"$sel_none_link\">".__('None')."</a></li>
+                                       <li class=\"vsep\">&nbsp;</li>
+                                       <li class=\"top\">Selection<ul>
+                                               <li onclick=\"$tog_unread_link\">".__('Toggle unread')."</li>
+                                               <li onclick=\"$tog_marked_link\">".__('Toggle starred')."</li></ul></li>
+                                       <li class=\"vsep\">&nbsp;</li>
+                                       <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
+                                               <li onclick=\"$catchup_page_link\">".__('This page')."</li>
+                                               <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
+                                       <li class=\"vsep\">&nbsp;</li>";
+
+                                       if ($limit != 0) {
+                                               print "
+                                               <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
+                                                       <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
+                                                       <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
+                                                       </ul>";
+                                       }
+
+                                       print " 
+                                       </td>"; 
 
                        } else {
+                       // old style subtoolbar:
 
                                print "<td class=\"headlineActions$rtl_cpart\">".
-                                       _('Select:')."
-                                                               <a href=\"javascript:cdmSelectArticles('all')\">"._('All')."</a>,
-                                                               <a href=\"javascript:cdmSelectArticles('unread')\">"._('Unread')."</a>,
-                                                               <a href=\"javascript:cdmSelectArticles('none')\">"._('None')."</a>
+                                       __('Select:')."
+                                                               <a href=\"$sel_all_link\">".__('All')."</a>,
+                                                               <a href=\"$sel_unread_link\">".__('Unread')."</a>,
+                                                               <a href=\"$sel_none_link\">".__('None')."</a>
                                                &nbsp;&nbsp;".
-                                               _('Toggle:')." <a href=\"javascript:selectionToggleUnread(true)\">"._('Unread')."</a>,
-                                                       <a href=\"javascript:selectionToggleMarked(true)\">"._('Starred')."</a>
+                                               __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
+                                                       <a href=\"$tog_marked_link\">".__('Starred')."</a>
                                                &nbsp;&nbsp;".
-                                               _('Mark as read:').
-                                                       "<a href=\"#\" onclick=\"catchupPage()\">"._('Page')."</a>,
-                                                       <a href=\"#\" onclick=\"catchupCurrentFeed()\">"._('Feed')."</a>";
-                       
-                               print "</td>";
+                                               __('Mark as read:')."
+                                                       <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
+                                                       <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
+                               print "</td>";  
 
                        }
 
+                       if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
+                               print "<td class=\"headlineActions$rtl_cpart\">
+                                       <a href=\"javascript:labelFromSearch('$search', '$search_mode',
+                                                       '$match_on', '$feed_id', '$is_cat');\">
+                                               ".__('Convert to Label')."</a></td>";
+                       }
+
                        print "<td class=\"headlineTitle$rtl_cpart\">";
                
                        if ($feed_site_url) {
                                $search_q = "&q=$search&m=$match_on&smode=$search_mode";
                        }
 
+                       if ($user_page_offset > 1) {
+                               print " [$user_page_offset] ";
+                       }
+
                        if (!$bottom) {
-                               print "&nbsp;
+                               print "
                                        <a target=\"_new\" 
                                                href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
                                                <img class=\"noborder\" 
-                                                       alt=\"Generated feed\" src=\"images/feed-icon-12x12.png\">
+                                                       alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
                                        </a>";
                        }
                                
                /* virtual feeds */
 
                if (get_pref($link, 'ENABLE_FEED_CATS')) {
-                       print "<li class=\"feedCat\">"._('Special')."</li>";
+                       print "<li class=\"feedCat\">".__('Special')."</li>";
                        print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
                }
 
 
                if ($num_starred > 0) $class .= "Unread";
 
-               printFeedEntry(-1, $class, _("Starred articles"), $num_starred, 
+               printFeedEntry(-1, $class, __("Starred articles"), $num_starred, 
                        "images/mark_set.png", $link);
 
                if (get_pref($link, 'ENABLE_FEED_CATS')) {
                
                                if (db_num_rows($result) > 0) {
                                        if (get_pref($link, 'ENABLE_FEED_CATS')) {
-                                               print "<li class=\"feedCat\">"._('Labels')."</li>";
+                                               print "<li class=\"feedCat\">".__('Labels')."</li>";
                                                print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
                                        } else {
                                                print "<li><hr></li>";
                                $tmp_category = $line["category"];
 
                                if (!$tmp_category) {
-                                       $tmp_category = _("Uncategorized");
+                                       $tmp_category = __("Uncategorized");
                                }
                                
        //                      $class = ($lnum % 2) ? "even" : "odd";
                                        $collapsed = $line["collapsed"];
 
                                        // workaround for NULL category
-                                       if ($category == _("Uncategorized")) {
+                                       if ($category == __("Uncategorized")) {
                                                if ($_COOKIE["ttrss_vf_uclps"] == 1) {
                                                        $collapsed = "t";
                                                }
                                        $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
 
                                        print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
-                                               <a id=\"FCATN-$cat_id\" href=\"#\"onclick=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
+                                               <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
                                                        <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
                                                        <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\" 
                                                        class=\"$catctr_class\">($cat_unread)</span> $ellipsis
                                }
        
                                printFeedEntry($feed_id, $class, $feed, $unread, 
-                                       "icons/$feed_id.ico", $link, $rtl_content, 
+                                       ICONS_DIR."/$feed_id.ico", $link, $rtl_content, 
                                        $last_updated, $line["last_error"]);
        
                                ++$lnum;
                        }
 
                        if (db_num_rows($result) == 0) {
-                               print "<li>"._('No feeds to display.')."</li>";
+                               print "<li>".__('No feeds to display.')."</li>";
                        }
 
                } else {
                        ORDER BY tag_name"); */
 
                        if (get_pref($link, 'ENABLE_FEED_CATS')) {
-                               print "<li class=\"feedCat\">"._('Tags')."</li>";
+                               print "<li class=\"feedCat\">".__('Tags')."</li>";
                                print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
                        }
 
 
                $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
                        ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
-                               ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."') ORDER BY tag_name");
+                               ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
 
                $tags = array();        
        
        }
 
        function tag_is_valid($tag) {
-               return ($tag !='' && !preg_match("/^[0-9]*$/", $tag));
+               if ($tag == '') return false;
+               if (preg_match("/^[0-9]*$/", $tag)) return false;
+
+               $tag = iconv("utf-8", "utf-8", $tag);
+               if (!$tag) return false;
+
+               return true;
+       }
+
+       function render_login_form($link, $mobile = false) {
+               if (!$mobile) {
+                       require_once "login_form.php";
+               } else {
+                       require_once "mobile/login_form.php";
+               }
+       }
+
+       // from http://developer.apple.com/internet/safari/faq.html
+       function no_cache_incantation() {
+               header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
+               header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
+               header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
+               header("Cache-Control: post-check=0, pre-check=0", false);
+               header("Pragma: no-cache"); // HTTP/1.0
+       }
+
+       function format_warning($msg, $id = "") {
+               return "<div class=\"warning\" id=\"$id\"> 
+                       <img src=\"images/sign_excl.png\">$msg</div>";
+       }
+
+       function format_notice($msg) {
+               return "<div class=\"notice\"> 
+                       <img src=\"images/sign_info.png\">$msg</div>";
+       }
+
+       function print_notice($msg) {
+               return print format_notice($msg);
+       }
+
+       function print_warning($msg) {
+               return print format_warning($msg);
+       }
+
+       function T_sprintf() {
+               $args = func_get_args();
+               return vsprintf(__(array_shift($args)), $args);
        }
 
 ?>