]> git.wh0rd.org - tt-rss.git/blobdiff - functions.php
properly handle on-the-fly adding of labels
[tt-rss.git] / functions.php
index 8b9c742e275b35cbaf425869752acbdc276856d3..f9de0622fe3a07cc7e38e210c6de6c9a15306519 100644 (file)
@@ -1,5 +1,7 @@
 <?php
 
+       date_default_timezone_set('UTC');
+
        if ($_REQUEST["debug"]) {
                define('DEFAULT_ERROR_LEVEL', E_ALL);
        }
                return $rv;
        }
 
-       function smart_date_time($timestamp) {
-               if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
+       function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
+                                       $no_smart_dt = false) {
+
+               if (!$owner_uid) $owner_uid = $_SESSION['uid'];
+               if (!$timestamp) $timestamp = '1970-01-01 0:00';
+
+               $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
+
+               try {
+                       $user_tz = new DateTimeZone($user_tz_string);
+               } catch (Exception $e) {
+                       $user_tz = new DateTimeZone('UTC');
+               }
+
+               # We store date in UTC internally
+               $dt = new DateTime($timestamp, new DateTimeZone('UTC'));
+               $user_timestamp = $dt->format('U') + $user_tz->getOffset($dt);
+
+               if (!$no_smart_dt && get_pref($link, 'HEADLINES_SMART_DATE', $owner_uid)) {
+                       return smart_date_time($link, $user_timestamp, 
+                               $user_tz->getOffset($dt), $owner_uid);
+               } else {
+                       if ($long)
+                               $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
+                       else
+                               $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
+
+                       return date($format, $user_timestamp);
+               }
+       }
+
+       function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
+               if (!$owner_uid) $owner_uid = $_SESSION['uid'];
+
+               if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
                        return date("G:i", $timestamp);
-               } else if (date("Y", $timestamp) == date("Y")) {
-                       return date("M d, G:i", $timestamp);
+               } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
+                       $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
+                       return date($format, $timestamp);
                } else {
-                       return date("Y/m/d, G:i", $timestamp);
+                       $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
+                       return date($format, $timestamp);
                }
        }
 
                $result = db_query($link, $query);
                $fctrs_modified = false;
 
-               $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
-
                while ($line = db_fetch_assoc($result)) {
                
                        $id = $line["id"];
                        $count = $line["count"];
                        $last_error = htmlspecialchars($line["last_error"]);
 
-                       if (get_pref($link, 'HEADLINES_SMART_DATE')) {
-                               $last_updated = smart_date_time(strtotime($line["last_updated"]));
-                       } else {
-                               $last_updated = date($short_date, strtotime($line["last_updated"]));
-                       }                               
+                       $last_updated = make_local_datetime($link, $line['last_updated'], false);
 
                        $has_img = feed_has_icon($id);
 
                return $ret_arr;
        }
 
-       function get_script_dt_add() {
-               return time();
-       }
-
        function get_pgsql_version($link) {
                $result = db_query($link, "SELECT version() AS version");
                $version = split(" ", db_fetch_result($result, 0, "version"));
                print "</rpc-reply>";
        }
 
+       /**
+        * Subscribes the user to the given feed
+        *
+        * @param resource $link       Database connection
+        * @param string   $url        Feed URL to subscribe to
+        * @param integer  $cat_id     Category ID the feed shall be added to
+        * @param string   $auth_login (optional) Feed username
+        * @param string   $auth_pass  (optional) Feed password
+        *
+        * @return integer Status code:
+        *                 0 - OK, Feed already exists
+        *                 1 - OK, Feed added
+        *                 2 - Invalid URL
+        *                 3 - URL content is HTML, not a feed
+        */
        function subscribe_to_feed($link, $url, $cat_id = 0, 
                        $auth_login = '', $auth_pass = '') {
 
-               $parts = parse_url($url);
-
+               $url = fix_url($url);
                if (!validate_feed_url($url)) return 2;
 
-               if ($parts['scheme'] == 'feed') $parts['scheme'] = 'http';
-
-               $url = make_url_from_parts($parts);
-
                if ($cat_id == "0" || !$cat_id) {
                        $cat_qpart = "NULL";
                } else {
                        WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
        
                if (db_num_rows($result) == 0) {
+                       if (url_is_html($url)) {
+                               $feedUrls = get_feeds_from_html($url);
+                               if (count($feedUrls) != 1) {
+                                       return 3;
+                               }
+                               //use feed url as new URL
+                               $url = key($feedUrls);
+                       }
                        
                        $result = db_query($link,
                                "INSERT INTO ttrss_feeds 
 
                while ($line = db_fetch_assoc($result)) {
                        if ($line["id"] == $default_id) {
-                               $is_selected = "selected";
+                               $is_selected = "selected=\"1\"";
                        } else {
                                $is_selected = "";
                        }
        function print_feed_cat_select($link, $id, $default_id = "", 
                $attributes = "", $include_all_cats = true) {
                
-               print "<select id=\"$id\" name=\"$id\" $attributes>";
+               print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
 
                if ($include_all_cats) {
                        print "<option value=\"0\">".__('Uncategorized')."</option>";
 
                while ($line = db_fetch_assoc($result)) {
                        if ($line["id"] == $default_id) {
-                               $is_selected = "selected";
+                               $is_selected = "selected=\"1\"";
                        } else {
                                $is_selected = "";
                        }
                                $line["id"], htmlspecialchars($line["title"]));
                }
 
+               print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
+
                print "</select>";
        }
        
                                print "<author>" . htmlspecialchars($line["author"]) . "</author>";
                        }
  
-                       print "<title>" . 
-                               htmlspecialchars($line["title"]) . "</title>";
+                       print "<title><![CDATA[" . 
+                               htmlspecialchars($line["title"]) . "]]></title>";
   
                        print "<description><![CDATA[";
 
                                                print "Marking affected articles as read...\n";
                                                catchupArticlesById($link, $affected_ids, 0, $line["id"]);
                                        }
-
-                                       db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
-                                                       WHERE id = " . $line["id"]);
                                } else {
                                        print "No headlines\n";
                                }
+
+                               db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
+                                       WHERE id = " . $line["id"]);
                        }
                }
 
 
                        array_push($affected_ids, $line["ref_id"]);
 
-                       $updated = smart_date_time(strtotime($line["last_updated"]));
+                       $updated = make_local_datetime($link, $line['last_updated'], false,
+                               $user_id);
 
                        $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
                        $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
 
                                $sel_inv_link = "javascript:invertHeadlineSelection()";
 
-                               $tog_unread_link = "javascript:selectionToggleUnread(true)";
-                               $tog_marked_link = "javascript:selectionToggleMarked(true)";
-                               $tog_published_link = "javascript:selectionTogglePublished(true)";
+                               $tog_unread_link = "javascript:selectionToggleUnread()";
+                               $tog_marked_link = "javascript:selectionToggleMarked()";
+                               $tog_published_link = "javascript:selectionTogglePublished()";
 
                        }
 
                                $search_q = "";
                        }
 
-                       $rss_link = "backend.php?op=rss&id=$feed_id&is_cat=$is_cat&view-mode=$view_mode$search_q";
+                       // Adaptive doesn't really make any sense for generated feeds
+                       // All Articles is the default, so no need to insert it either
+                       if ($view_mode == "adaptive" || $view_mode == "all_articles") 
+                               $view_mode = "";
+                       else
+                               $view_mode = "&view-mode=$view_mode";
+
+                       $rss_link = htmlspecialchars(get_self_url_prefix() . 
+                               "/backend.php?op=rss&id=$feed_id&is_cat=$is_cat$view_mode$search_q");
+
+                       #print "
+                       #       <a target=\"_blank\"
+                       #               title=\"".__("View as RSS feed")."\"
+                       #               href=\"$rss_link\">
+                       #               <img class=\"noborder\" src=\"images/feed-icon-12x12.png\"></a>";
 
                        print "
-                               <a target=\"_blank\"
+                               <a href=\"#\"
                                        title=\"".__("View as RSS feed")."\"
-                                       href=\"$rss_link\">
-                                       <img class=\"noborder\" src=\"images/feed-icon-12x12.png\"></a>";
+                                       onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
+                                       <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
 
                        print "</div>";
 
                        print_labels_headlines_dropdown($link, $feed_id);
 
                        print "<li class=\"insensitive\">".__('Feed:')."</li>";
-                       print "<li onclick=\"window.open('$rss_link')\">&nbsp;&nbsp;".__('View as RSS')."</li>";
+                       print "<li onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">&nbsp;&nbsp;".__('View as RSS')."</li>";
 
                        print "</ul>";
 
                        $total_unread = 0;
 
                        $category = "";
-
-                       $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
        
                        while ($line = db_fetch_assoc($result)) {
                        
        
                                $subop = $_REQUEST["subop"];
 
-                               if (get_pref($link, 'HEADLINES_SMART_DATE')) {
-                                       $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
-                               } else {
-                                       $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
-                               }
+                               $last_updated = make_local_datetime($link, $line['last_updated_noms'], 
+                                       false);
 
                                $rtl_content = sql_bool_to_bool($line["rtl_content"]);
 
                                $entry_author = __(" - ") . $entry_author;
                        }
 
-                       $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT')
-                               strtotime($line["updated"]));
-               
+                       $parsed_updated = make_local_datetime($link, $line["updated"], true
+                               false, true);
+
                        print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
 
                        if ($line["link"]) {
                        $rtl_content = false;
                }
 
-               $script_dt_add = get_script_dt_add();
-
                /// START /////////////////////////////////////////////////////////////////////////////////
 
                @$search = db_escape_string($_REQUEST["query"]);
 
                $vgroup_last_feed = $vgr_last_feed;
 
-               if ($feed == -2) {
+/*             if ($feed == -2) {
                        $feed_site_url = article_publish_url($link);
-               }
+               } */
 
                /// STOP //////////////////////////////////////////////////////////////////////////////////
 
 #                              $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
 #                                      $line["title"] . "</a>";
 
-                               if (get_pref($link, 'HEADLINES_SMART_DATE')) {
-                                       $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
-                               } else {
-                                       $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
-                                       $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
-                               }                               
+                               $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);        
 
                                if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
                                        $content_preview = truncate_string(strip_tags($line["content_preview"]), 
                return $tag;
        }
 
-       function generate_publish_key() {
-               return sha1(uniqid(rand(), true));
-       }
-
-       function article_publish_url($link) {
+       function get_self_url_prefix() {
 
                $url_path = "";
-               
-
+       
                if ($_SERVER['HTTPS'] != "on") {
                        $url_path = "http://";
                } else {
                }
 
                $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
-               $url_path .= "/backend.php?op=publish&key=" . 
-                       get_pref($link, "_PREFS_PUBLISH_KEY", $_SESSION["uid"]);
 
                return $url_path;
-       }
-        function opml_publish_url($link){
-               $url_path = "";
-               
 
-               if ($_SERVER['HTTPS'] != "on") {
-                       $url_path = "http://";
-               } else {
-                       $url_path = "https://";
-               }
+       }
+       function opml_publish_url($link){
 
-               $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
+               $url_path = get_self_url_prefix();
                $url_path .= "/opml.php?op=publish&key=" . 
-                       get_pref($link, "_PREFS_PUBLISH_KEY", $_SESSION["uid"]);
+                       get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
 
                return $url_path;
        }
                        pg_query($link, "set client_encoding = 'UTF-8'");
                        pg_set_client_encoding("UNICODE");
                        pg_query($link, "set datestyle = 'ISO, european'");
+                       pg_query($link, "set TIME ZONE 0");
                } else {
+                       db_query($link, "SET time_zone = '+0:0'");
+
                        if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
                                db_query($link, "SET NAMES " . MYSQL_CHARSET);
        //                      db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
 
                if (db_affected_rows($link, $result) != 0 && $caption) {
 
+                       /* Remove access key for the label */
+
+                       $ext_id = -11 - $id;
+
+                       db_query($link, "DELETE FROM ttrss_access_keys WHERE
+                               feed_id = '$ext_id' AND owner_uid = $owner_uid");
+
                        /* Disable filters that reference label being removed */
        
                        db_query($link, "UPDATE ttrss_filters SET
                                orig_feed_id = '$id' WHERE feed_id = '$id' AND 
                                        marked = true AND owner_uid = $owner_uid");
 
+                       /* Remove access key for the feed */
+
+                       db_query($link, "DELETE FROM ttrss_access_keys WHERE
+                               feed_id = '$id' AND owner_uid = $owner_uid");
+
                        /* remove the feed */
 
                        db_query($link, "DELETE FROM ttrss_feeds 
                }
        }
 
+       function add_feed_category($link, $feed_cat) {
+               db_query($link, "BEGIN");
+
+               $result = db_query($link,
+                       "SELECT id FROM ttrss_feed_categories
+                       WHERE 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')");
+
+                       db_query($link, "COMMIT");
+
+                       return true;
+               }
+
+               return false;
+       }                       
+
        function remove_feed_category($link, $id, $owner_uid) {
 
                db_query($link, "DELETE FROM ttrss_feed_categories
                return $url;
        }
 
+       /**
+        * Fixes incomplete URLs by prepending "http://".
+        * Also replaces feed:// with http://, and
+        * prepends a trailing slash if the url is a domain name only.
+        *
+        * @param string $url Possibly incomplete URL
+        *
+        * @return string Fixed URL.
+        */
+       function fix_url($url) {
+               if (strpos($url, '://') === false) {
+                       $url = 'http://' . $url;
+               } else if (substr($url, 0, 5) == 'feed:') {
+                       $url = 'http:' . substr($url, 5);
+               }
+
+               //prepend slash if the URL has no slash in it
+               // "http://www.example" -> "http://www.example/"
+               if (strpos($url, '/', 7) === false) {
+                       $url .= '/';
+               }
+               return $url;
+       }
+
        function validate_feed_url($url) {
                $parts = parse_url($url);
 
                        WHERE owner_uid = " . $_SESSION['uid']);
 
                $last_updated = db_fetch_result($result, 0, "last_updated");
-
-               if (get_pref($link, 'HEADLINES_SMART_DATE')) {
-                       $last_updated = smart_date_time(strtotime($last_updated));
-               } else {
-                       $last_updated = date($short_date, strtotime($last_updated));
-               }                               
+               $last_updated = make_local_datetime($link, $last_updated, false);
 
                printf(__("Feeds last updated at %s"), $last_updated);
 
                if (!in_array($email, $_SESSION['stored_emails']))
                        array_push($_SESSION['stored_emails'], $email);
        }
+
+       function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
+               if (!$owner_uid) $owner_uid = $_SESSION["uid"];
+
+               $sql_is_cat = bool_to_sql_bool($is_cat);
+
+               $result = db_query($link, "SELECT access_key FROM ttrss_access_keys 
+                       WHERE feed_id = '$feed_id'      AND is_cat = $sql_is_cat 
+                       AND owner_uid = " . $owner_uid);
+
+               if (db_num_rows($result) == 1) {
+                       $key = db_escape_string(sha1(uniqid(rand(), true)));
+
+                       db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
+                               WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat 
+                               AND owner_uid = " . $owner_uid);
+
+                       return $key;
+
+               } else {
+                       return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
+               }
+       }
+
+       function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
+
+               if (!$owner_uid) $owner_uid = $_SESSION["uid"];
+
+               $sql_is_cat = bool_to_sql_bool($is_cat);
+
+               $result = db_query($link, "SELECT access_key FROM ttrss_access_keys 
+                       WHERE feed_id = '$feed_id'      AND is_cat = $sql_is_cat 
+                       AND owner_uid = " . $owner_uid);
+
+               if (db_num_rows($result) == 1) {
+                       return db_fetch_result($result, 0, "access_key");
+               } else {
+                       $key = db_escape_string(sha1(uniqid(rand(), true)));
+
+                       $result = db_query($link, "INSERT INTO ttrss_access_keys 
+                               (access_key, feed_id, is_cat, owner_uid)
+                               VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
+
+                       return $key;
+               }
+               return false;
+       }
+
+       /**
+        * Extracts RSS/Atom feed URLs from the given HTML URL.
+        *
+        * @param string $url HTML page URL
+        *
+        * @return array Array of feeds. Key is the full URL, value the title
+        */
+       function get_feeds_from_html($url)
+       {
+               $url     = fix_url($url);
+               $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
+
+               $doc = new DOMDocument();
+               $doc->loadHTMLFile($url);
+               $xpath = new DOMXPath($doc);
+               $entries = $xpath->query('/html/head/link[@rel="alternate"]');
+               $feedUrls = array();
+               foreach ($entries as $entry) {
+                       if ($entry->hasAttribute('href')) {
+                               $title = $entry->getAttribute('title');
+                               if ($title == '') {
+                                       $title = $entry->getAttribute('type');
+                               }
+                               $feedUrl = $entry->getAttribute('href');
+                               if (strpos($feedUrl, '://') === false) {
+                                       //no protocol -> relative URL
+                                       $feedUrl = $baseUrl . $feedUrl;
+                               }
+                               $feedUrls[$feedUrl] = $title;
+                       }
+               }
+               return $feedUrls;
+       }
+
+       /**
+        * Checks if the content behind the given URL is a HTML file
+        *
+        * @param string $url URL to check
+        *
+        * @return boolean True if the URL contains HTML content
+        */
+       function url_is_html($url) {
+               $content = substr(fetch_file_contents($url, false), 0, 1000);
+               if (strpos($content, '<html>') === false
+                       && strpos($content, '<html ') === false
+               ) {
+                       return false;
+               }
+
+               return true;
+       }
 ?>