2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 126);
5 define('LABEL_BASE_INDEX', -1024);
6 define('PLUGIN_FEED_BASE_INDEX', -128);
8 define('COOKIE_LIFETIME_LONG', 86400*365);
10 $fetch_last_error = false;
11 $fetch_last_error_code = false;
12 $fetch_last_content_type = false;
13 $fetch_curl_used = false;
14 $suppress_debugging = false;
16 mb_internal_encoding("UTF-8");
17 date_default_timezone_set('UTC');
18 if (defined('E_DEPRECATED')) {
19 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
21 error_reporting(E_ALL & ~E_NOTICE);
24 require_once 'config.php';
27 * Define a constant if not already defined
29 * @param string $name The constant name.
30 * @param mixed $value The constant value.
32 * @return boolean True if defined successfully or not.
34 function define_default($name, $value) {
35 defined($name) or define($name, $value);
38 ///// Some defaults that you can override in config.php //////
40 define_default('FEED_FETCH_TIMEOUT', 45);
41 // How may seconds to wait for response when requesting feed from a site
42 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
43 // How may seconds to wait for response when requesting feed from a
44 // site when that feed wasn't cached before
45 define_default('FILE_FETCH_TIMEOUT', 45);
46 // Default timeout when fetching files from remote sites
47 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
48 // How many seconds to wait for initial response from website when
49 // fetching files from remote sites
51 if (DB_TYPE == "pgsql") {
52 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
54 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
58 * Return available translations names.
61 * @return array A array of available translations.
63 function get_translations() {
65 "auto" => "Detect automatically",
70 "el_GR" => "Ελληνικά",
71 "es_ES" => "Español (España)",
74 "fr_FR" => "Français",
75 "hu_HU" => "Magyar (Hungarian)",
76 "it_IT" => "Italiano",
77 "ja_JP" => "日本語 (Japanese)",
78 "lv_LV" => "Latviešu",
79 "nb_NO" => "Norwegian bokmål",
83 "pt_BR" => "Portuguese/Brazil",
84 "pt_PT" => "Portuguese/Portugal",
85 "zh_CN" => "Simplified Chinese",
86 "zh_TW" => "Traditional Chinese",
94 require_once "lib/accept-to-gettext.php";
95 require_once "lib/gettext/gettext.inc";
97 require_once "lib/languagedetect/LanguageDetect.php";
99 function startup_gettext() {
101 # Get locale from Accept-Language header
102 $lang = al2gt(array_keys(get_translations()), "text/html");
104 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
105 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
108 if ($_SESSION["uid"] && get_schema_version() >= 120) {
109 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
111 if ($pref_lang && $pref_lang != 'auto') {
117 if (defined('LC_MESSAGES')) {
118 _setlocale(LC_MESSAGES, $lang);
119 } else if (defined('LC_ALL')) {
120 _setlocale(LC_ALL, $lang);
123 _bindtextdomain("messages", "locale");
125 _textdomain("messages");
126 _bind_textdomain_codeset("messages", "UTF-8");
130 require_once 'db-prefs.php';
131 require_once 'version.php';
132 require_once 'ccache.php';
133 require_once 'labels.php';
135 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
136 ini_set('user_agent', SELF_USER_AGENT);
138 require_once 'lib/pubsubhubbub/publisher.php';
140 $schema_version = false;
142 function _debug_suppress($suppress) {
143 global $suppress_debugging;
145 $suppress_debugging = $suppress;
149 * Print a timestamped debug message.
151 * @param string $msg The debug message.
154 function _debug($msg, $show = true) {
155 global $suppress_debugging;
157 //echo "[$suppress_debugging] $msg $show\n";
159 if ($suppress_debugging) return false;
161 $ts = strftime("%H:%M:%S", time());
162 if (function_exists('posix_getpid')) {
163 $ts = "$ts/" . posix_getpid();
166 if ($show && !(defined('QUIET') && QUIET)) {
167 print "[$ts] $msg\n";
170 if (defined('LOGFILE')) {
171 $fp = fopen(LOGFILE, 'a+');
176 if (function_exists("flock")) {
179 // try to lock logfile for writing
180 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
191 fputs($fp, "[$ts] $msg\n");
193 if (function_exists("flock")) {
204 * Purge a feed old posts.
206 * @param mixed $link A database connection.
207 * @param mixed $feed_id The id of the purged feed.
208 * @param mixed $purge_interval Olderness of purged posts.
209 * @param boolean $debug Set to True to enable the debug. False by default.
213 function purge_feed($feed_id, $purge_interval, $debug = false) {
215 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
220 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
224 if (db_num_rows($result) == 1) {
225 $owner_uid = db_fetch_result($result, 0, "owner_uid");
228 if ($purge_interval == -1 || !$purge_interval) {
230 ccache_update($feed_id, $owner_uid);
235 if (!$owner_uid) return;
237 if (FORCE_ARTICLE_PURGE == 0) {
238 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
241 $purge_unread = true;
242 $purge_interval = FORCE_ARTICLE_PURGE;
245 if (!$purge_unread) $query_limit = " unread = false AND ";
247 if (DB_TYPE == "pgsql") {
248 $pg_version = get_pgsql_version();
250 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
252 $result = db_query("DELETE FROM ttrss_user_entries WHERE
253 ttrss_entries.id = ref_id AND
255 feed_id = '$feed_id' AND
257 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
261 $result = db_query("DELETE FROM ttrss_user_entries
263 WHERE ttrss_entries.id = ref_id AND
265 feed_id = '$feed_id' AND
267 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
272 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
273 marked = false AND feed_id = '$feed_id' AND
274 (SELECT date_updated FROM ttrss_entries WHERE
275 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
277 $result = db_query("DELETE FROM ttrss_user_entries
278 USING ttrss_user_entries, ttrss_entries
279 WHERE ttrss_entries.id = ref_id AND
281 feed_id = '$feed_id' AND
283 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
286 $rows = db_affected_rows($result);
288 ccache_update($feed_id, $owner_uid);
291 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
295 } // function purge_feed
297 function feed_purge_interval($feed_id) {
299 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
300 WHERE id = '$feed_id'");
302 if (db_num_rows($result) == 1) {
303 $purge_interval = db_fetch_result($result, 0, "purge_interval");
304 $owner_uid = db_fetch_result($result, 0, "owner_uid");
306 if ($purge_interval == 0) $purge_interval = get_pref(
307 'PURGE_OLD_DAYS', $owner_uid);
309 return $purge_interval;
316 function purge_orphans($do_output = false) {
318 // purge orphaned posts in main content table
319 $result = db_query("DELETE FROM ttrss_entries WHERE
320 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
323 $rows = db_affected_rows($result);
324 _debug("Purged $rows orphaned posts.");
328 function get_feed_update_interval($feed_id) {
329 $result = db_query("SELECT owner_uid, update_interval FROM
330 ttrss_feeds WHERE id = '$feed_id'");
332 if (db_num_rows($result) == 1) {
333 $update_interval = db_fetch_result($result, 0, "update_interval");
334 $owner_uid = db_fetch_result($result, 0, "owner_uid");
336 if ($update_interval != 0) {
337 return $update_interval;
339 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
347 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0, $useragent = false) {
349 global $fetch_last_error;
350 global $fetch_last_error_code;
351 global $fetch_last_content_type;
352 global $fetch_curl_used;
354 $url = str_replace(' ', '%20', $url);
356 if (!defined('NO_CURL') && function_exists('curl_init')) {
358 $fetch_curl_used = true;
360 if (ini_get("safe_mode") || ini_get("open_basedir")) {
361 $new_url = geturl($url);
363 // geturl has already populated $fetch_last_error
366 $ch = curl_init($new_url);
368 $ch = curl_init($url);
371 if ($timestamp && !$post_query) {
372 curl_setopt($ch, CURLOPT_HTTPHEADER,
373 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
376 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
377 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
378 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode") && !ini_get("open_basedir"));
379 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
380 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
381 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
382 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
383 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
384 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
386 curl_setopt($ch, CURLOPT_ENCODING, "");
387 //curl_setopt($ch, CURLOPT_REFERER, $url);
389 if (!ini_get("safe_mode") && !ini_get("open_basedir")) {
390 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
393 if (defined('_CURL_HTTP_PROXY')) {
394 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
398 curl_setopt($ch, CURLOPT_POST, true);
399 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
402 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
403 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
407 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
409 $contents = @curl_exec($ch);
411 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
412 curl_setopt($ch, CURLOPT_ENCODING, 'none');
413 $contents = @curl_exec($ch);
416 if ($contents === false) {
417 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
422 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
423 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
425 $fetch_last_error_code = $http_code;
427 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
428 if (curl_errno($ch) != 0) {
429 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
431 $fetch_last_error = "HTTP Code: $http_code";
442 $fetch_curl_used = false;
444 if ($login && $pass){
445 $url_parts = array();
447 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
449 $pass = urlencode($pass);
451 if ($url_parts[1] && $url_parts[2]) {
452 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
456 if (!$post_query && $timestamp) {
457 $context = stream_context_create(array(
460 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
466 $old_error = error_get_last();
468 $data = @file_get_contents($url, false, $context);
470 $fetch_last_content_type = false; // reset if no type was sent from server
471 if (isset($http_response_header) && is_array($http_response_header)) {
472 foreach ($http_response_header as $h) {
473 if (substr(strtolower($h), 0, 13) == 'content-type:') {
474 $fetch_last_content_type = substr($h, 14);
475 // don't abort here b/c there might be more than one
476 // e.g. if we were being redirected -- last one is the right one
479 if (substr(strtolower($h), 0, 7) == 'http/1.') {
480 $fetch_last_error_code = (int) substr($h, 9, 3);
486 $error = error_get_last();
488 if ($error['message'] != $old_error['message']) {
489 $fetch_last_error = $error["message"];
491 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
500 * Try to determine the favicon URL for a feed.
501 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
502 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
504 * @param string $url A feed or page URL
506 * @return mixed The favicon URL, or false if none was found.
508 function get_favicon_url($url) {
510 $favicon_url = false;
512 if ($html = @fetch_file_contents($url)) {
514 libxml_use_internal_errors(true);
516 $doc = new DOMDocument();
517 $doc->loadHTML($html);
518 $xpath = new DOMXPath($doc);
520 $base = $xpath->query('/html/head/base');
521 foreach ($base as $b) {
522 $url = $b->getAttribute("href");
526 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
527 if (count($entries) > 0) {
528 foreach ($entries as $entry) {
529 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
536 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
539 } // function get_favicon_url
541 function check_feed_favicon($site_url, $feed) {
542 # print "FAVICON [$site_url]: $favicon_url\n";
544 $icon_file = ICONS_DIR . "/$feed.ico";
546 if (!file_exists($icon_file)) {
547 $favicon_url = get_favicon_url($site_url);
550 // Limiting to "image" type misses those served with text/plain
551 $contents = fetch_file_contents($favicon_url); // , "image");
554 // Crude image type matching.
555 // Patterns gleaned from the file(1) source code.
556 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
557 // 0 string \000\000\001\000 MS Windows icon resource
558 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
560 elseif (preg_match('/^GIF8/', $contents)) {
561 // 0 string GIF8 GIF image data
562 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
564 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
565 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
566 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
568 elseif (preg_match('/^\xff\xd8/', $contents)) {
569 // 0 beshort 0xffd8 JPEG image data
570 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
573 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
579 $fp = @fopen($icon_file, "w");
582 fwrite($fp, $contents);
584 chmod($icon_file, 0644);
592 function print_select($id, $default, $values, $attributes = "") {
593 print "<select name=\"$id\" id=\"$id\" $attributes>";
594 foreach ($values as $v) {
596 $sel = "selected=\"1\"";
602 print "<option value=\"$v\" $sel>$v</option>";
607 function print_select_hash($id, $default, $values, $attributes = "") {
608 print "<select name=\"$id\" id='$id' $attributes>";
609 foreach (array_keys($values) as $v) {
611 $sel = 'selected="selected"';
617 print "<option $sel value=\"$v\">".$values[$v]."</option>";
623 function print_radio($id, $default, $true_is, $values, $attributes = "") {
624 foreach ($values as $v) {
631 if ($v == $true_is) {
632 $sel .= " value=\"1\"";
634 $sel .= " value=\"0\"";
637 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
638 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
643 function initialize_user_prefs($uid, $profile = false) {
645 $uid = db_escape_string($uid);
649 $profile_qpart = "AND profile IS NULL";
651 $profile_qpart = "AND profile = '$profile'";
654 if (get_schema_version() < 63) $profile_qpart = "";
658 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
660 $u_result = db_query("SELECT pref_name
661 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
663 $active_prefs = array();
665 while ($line = db_fetch_assoc($u_result)) {
666 array_push($active_prefs, $line["pref_name"]);
669 while ($line = db_fetch_assoc($result)) {
670 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
671 // print "adding " . $line["pref_name"] . "<br>";
673 $line["def_value"] = db_escape_string($line["def_value"]);
674 $line["pref_name"] = db_escape_string($line["pref_name"]);
676 if (get_schema_version() < 63) {
677 db_query("INSERT INTO ttrss_user_prefs
678 (owner_uid,pref_name,value) VALUES
679 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
682 db_query("INSERT INTO ttrss_user_prefs
683 (owner_uid,pref_name,value, profile) VALUES
684 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
694 function get_ssl_certificate_id() {
695 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
696 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
697 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
698 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
699 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
701 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
702 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
703 $_SERVER["SSL_CLIENT_V_START"] .
704 $_SERVER["SSL_CLIENT_V_END"] .
705 $_SERVER["SSL_CLIENT_S_DN"]);
710 function authenticate_user($login, $password, $check_only = false) {
712 if (!SINGLE_USER_MODE) {
715 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
717 $user_id = (int) $plugin->authenticate($login, $password);
720 $_SESSION["auth_module"] = strtolower(get_class($plugin));
725 if ($user_id && !$check_only) {
728 $_SESSION["uid"] = $user_id;
729 $_SESSION["version"] = VERSION_STATIC;
731 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
732 WHERE id = '$user_id'");
734 $_SESSION["name"] = db_fetch_result($result, 0, "login");
735 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
736 $_SESSION["csrf_token"] = uniqid(rand(), true);
738 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
741 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
742 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
743 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
745 $_SESSION["last_version_check"] = time();
747 initialize_user_prefs($_SESSION["uid"]);
756 $_SESSION["uid"] = 1;
757 $_SESSION["name"] = "admin";
758 $_SESSION["access_level"] = 10;
760 $_SESSION["hide_hello"] = true;
761 $_SESSION["hide_logout"] = true;
763 $_SESSION["auth_module"] = false;
765 if (!$_SESSION["csrf_token"]) {
766 $_SESSION["csrf_token"] = uniqid(rand(), true);
769 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
771 initialize_user_prefs($_SESSION["uid"]);
777 function make_password($length = 8) {
780 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
784 while ($i < $length) {
785 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
787 if (!strstr($password, $char)) {
795 // this is called after user is created to initialize default feeds, labels
798 // user preferences are checked on every login, not here
800 function initialize_user($uid) {
802 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
803 values ('$uid', 'Tiny Tiny RSS: New Releases',
804 'http://tt-rss.org/releases.rss')");
806 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
807 values ('$uid', 'Tiny Tiny RSS: Forum',
808 'http://tt-rss.org/forum/rss.php')");
811 function logout_user() {
813 if (isset($_COOKIE[session_name()])) {
814 setcookie(session_name(), '', time()-42000, '/');
818 function validate_csrf($csrf_token) {
819 return $csrf_token == $_SESSION['csrf_token'];
822 function load_user_plugins($owner_uid) {
823 if ($owner_uid && SCHEMA_VERSION >= 100) {
824 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
826 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
828 if (get_schema_version() > 100) {
829 PluginHost::getInstance()->load_data();
834 function login_sequence() {
835 if (SINGLE_USER_MODE) {
837 authenticate_user("admin", null);
839 load_user_plugins($_SESSION["uid"]);
841 if (!validate_session()) $_SESSION["uid"] = false;
843 if (!$_SESSION["uid"]) {
845 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
846 $_SESSION["ref_schema_version"] = get_schema_version(true);
848 authenticate_user(null, null, true);
851 if (!$_SESSION["uid"]) {
853 setcookie(session_name(), '', time()-42000, '/');
860 /* bump login timestamp */
861 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
863 $_SESSION["last_login_update"] = time();
866 if ($_SESSION["uid"]) {
868 load_user_plugins($_SESSION["uid"]);
872 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
873 $_SESSION["uid"] . " AND
874 (SELECT COUNT(id) FROM ttrss_feeds WHERE
875 ttrss_feeds.id = feed_id) = 0");
877 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
878 $_SESSION["uid"] . " AND
879 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
880 ttrss_feed_categories.id = feed_id) = 0");
887 function truncate_string($str, $max_len, $suffix = '…') {
888 if (mb_strlen($str, "utf-8") > $max_len) {
889 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
895 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
898 $source_tz = new DateTimeZone($source_tz);
899 } catch (Exception $e) {
900 $source_tz = new DateTimeZone('UTC');
904 $dest_tz = new DateTimeZone($dest_tz);
905 } catch (Exception $e) {
906 $dest_tz = new DateTimeZone('UTC');
909 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
910 return $dt->format('U') + $dest_tz->getOffset($dt);
913 function make_local_datetime($timestamp, $long, $owner_uid = false,
914 $no_smart_dt = false) {
916 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
917 if (!$timestamp) $timestamp = '1970-01-01 0:00';
922 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
924 $timestamp = substr($timestamp, 0, 19);
926 # We store date in UTC internally
927 $dt = new DateTime($timestamp, $utc_tz);
929 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
931 if ($user_tz_string != 'Automatic') {
934 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
935 } catch (Exception $e) {
939 $tz_offset = $user_tz->getOffset($dt);
941 $tz_offset = (int) -$_SESSION["clientTzOffset"];
944 $user_timestamp = $dt->format('U') + $tz_offset;
947 return smart_date_time($user_timestamp,
948 $tz_offset, $owner_uid);
951 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
953 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
955 return date($format, $user_timestamp);
959 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false) {
960 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
962 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
963 return date("G:i", $timestamp);
964 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
965 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
966 return date($format, $timestamp);
968 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
969 return date($format, $timestamp);
973 function sql_bool_to_bool($s) {
974 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
981 function bool_to_sql_bool($s) {
989 // Session caching removed due to causing wrong redirects to upgrade
990 // script when get_schema_version() is called on an obsolete session
991 // created on a previous schema version.
992 function get_schema_version($nocache = false) {
993 global $schema_version;
995 if (!$schema_version && !$nocache) {
996 $result = db_query("SELECT schema_version FROM ttrss_version");
997 $version = db_fetch_result($result, 0, "schema_version");
998 $schema_version = $version;
1001 return $schema_version;
1005 function sanity_check() {
1006 require_once 'errors.php';
1010 $schema_version = get_schema_version(true);
1012 if ($schema_version != SCHEMA_VERSION) {
1016 if (DB_TYPE == "mysql") {
1017 $result = db_query("SELECT true", false);
1018 if (db_num_rows($result) != 1) {
1023 if (db_escape_string("testTEST") != "testTEST") {
1027 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1030 function file_is_locked($filename) {
1031 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1032 if (function_exists('flock')) {
1033 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1035 if (flock($fp, LOCK_EX | LOCK_NB)) {
1036 flock($fp, LOCK_UN);
1046 return true; // consider the file always locked and skip the test
1053 function make_lockfile($filename) {
1054 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1056 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1057 $stat_h = fstat($fp);
1058 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1060 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1061 if ($stat_h["ino"] != $stat_f["ino"] ||
1062 $stat_h["dev"] != $stat_f["dev"]) {
1068 if (function_exists('posix_getpid')) {
1069 fwrite($fp, posix_getpid() . "\n");
1077 function make_stampfile($filename) {
1078 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1080 if (flock($fp, LOCK_EX | LOCK_NB)) {
1081 fwrite($fp, time() . "\n");
1082 flock($fp, LOCK_UN);
1090 function sql_random_function() {
1091 if (DB_TYPE == "mysql") {
1098 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1100 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1102 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1104 // Todo: all this interval stuff needs some generic generator function
1106 $date_qpart = "false";
1110 if (DB_TYPE == "pgsql") {
1111 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1113 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1117 if (DB_TYPE == "pgsql") {
1118 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1120 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1124 if (DB_TYPE == "pgsql") {
1125 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1127 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1131 $date_qpart = "true";
1134 if (is_numeric($feed)) {
1140 $children = getChildCategories($feed, $owner_uid);
1141 array_push($children, $feed);
1143 $children = join(",", $children);
1145 $cat_qpart = "cat_id IN ($children)";
1147 $cat_qpart = "cat_id IS NULL";
1150 db_query("UPDATE ttrss_user_entries
1151 SET unread = false, last_read = NOW() WHERE ref_id IN
1153 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1154 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1155 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1157 } else if ($feed == -2) {
1159 db_query("UPDATE ttrss_user_entries
1160 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1161 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1162 AND unread = true AND owner_uid = $owner_uid");
1165 } else if ($feed > 0) {
1167 db_query("UPDATE ttrss_user_entries
1168 SET unread = false, last_read = NOW() WHERE ref_id IN
1170 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1171 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1173 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1176 db_query("UPDATE ttrss_user_entries
1177 SET unread = false, last_read = NOW() WHERE ref_id IN
1179 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1180 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1184 db_query("UPDATE ttrss_user_entries
1185 SET unread = false, last_read = NOW() WHERE ref_id IN
1187 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1188 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1193 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1195 if (DB_TYPE == "pgsql") {
1196 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1198 $match_part = "date_entered > DATE_SUB(NOW(),
1199 INTERVAL $intl HOUR) ";
1202 db_query("UPDATE ttrss_user_entries
1203 SET unread = false, last_read = NOW() WHERE ref_id IN
1205 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1206 AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1210 db_query("UPDATE ttrss_user_entries
1211 SET unread = false, last_read = NOW() WHERE ref_id IN
1213 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1214 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1217 } else if ($feed < LABEL_BASE_INDEX) { // label
1219 $label_id = feed_to_label_id($feed);
1221 db_query("UPDATE ttrss_user_entries
1222 SET unread = false, last_read = NOW() WHERE ref_id IN
1224 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1225 AND label_id = '$label_id' AND ref_id = article_id
1226 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1230 ccache_update($feed, $owner_uid, $cat_view);
1233 db_query("UPDATE ttrss_user_entries
1234 SET unread = false, last_read = NOW() WHERE ref_id IN
1236 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1237 AND post_int_id = int_id AND tag_name = '$feed'
1238 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1243 function getAllCounters() {
1244 $data = getGlobalCounters();
1246 $data = array_merge($data, getVirtCounters());
1247 $data = array_merge($data, getLabelCounters());
1248 $data = array_merge($data, getFeedCounters());
1249 $data = array_merge($data, getCategoryCounters());
1254 function getCategoryTitle($cat_id) {
1256 if ($cat_id == -1) {
1257 return __("Special");
1258 } else if ($cat_id == -2) {
1259 return __("Labels");
1262 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1265 if (db_num_rows($result) == 1) {
1266 return db_fetch_result($result, 0, "title");
1268 return __("Uncategorized");
1274 function getCategoryCounters() {
1277 /* Labels category */
1279 $cv = array("id" => -2, "kind" => "cat",
1280 "counter" => getCategoryUnread(-2));
1282 array_push($ret_arr, $cv);
1284 $result = db_query("SELECT id AS cat_id, value AS unread,
1285 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1286 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1287 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1288 WHERE ttrss_cat_counters_cache.feed_id = id AND
1289 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1290 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1292 while ($line = db_fetch_assoc($result)) {
1293 $line["cat_id"] = (int) $line["cat_id"];
1295 if ($line["num_children"] > 0) {
1296 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1301 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1302 "counter" => $line["unread"] + $child_counter);
1304 array_push($ret_arr, $cv);
1307 /* Special case: NULL category doesn't actually exist in the DB */
1309 $cv = array("id" => 0, "kind" => "cat",
1310 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1312 array_push($ret_arr, $cv);
1317 // only accepts real cats (>= 0)
1318 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1319 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1321 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1322 AND owner_uid = $owner_uid");
1326 while ($line = db_fetch_assoc($result)) {
1327 $unread += getCategoryUnread($line["id"], $owner_uid);
1328 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1334 function getCategoryUnread($cat, $owner_uid = false) {
1336 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1341 $cat_query = "cat_id = '$cat'";
1343 $cat_query = "cat_id IS NULL";
1346 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1347 AND owner_uid = " . $owner_uid);
1349 $cat_feeds = array();
1350 while ($line = db_fetch_assoc($result)) {
1351 array_push($cat_feeds, "feed_id = " . $line["id"]);
1354 if (count($cat_feeds) == 0) return 0;
1356 $match_part = implode(" OR ", $cat_feeds);
1358 $result = db_query("SELECT COUNT(int_id) AS unread
1359 FROM ttrss_user_entries
1360 WHERE unread = true AND ($match_part)
1361 AND owner_uid = " . $owner_uid);
1365 # this needs to be rewritten
1366 while ($line = db_fetch_assoc($result)) {
1367 $unread += $line["unread"];
1371 } else if ($cat == -1) {
1372 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1373 } else if ($cat == -2) {
1375 $result = db_query("
1376 SELECT COUNT(unread) AS unread FROM
1377 ttrss_user_entries, ttrss_user_labels2
1378 WHERE article_id = ref_id AND unread = true
1379 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1381 $unread = db_fetch_result($result, 0, "unread");
1388 function getFeedUnread($feed, $is_cat = false) {
1389 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1392 function getLabelUnread($label_id, $owner_uid = false) {
1393 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1395 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1396 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1398 if (db_num_rows($result) != 0) {
1399 return db_fetch_result($result, 0, "unread");
1405 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1406 $owner_uid = false) {
1408 $n_feed = (int) $feed;
1409 $need_entries = false;
1411 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1414 $unread_qpart = "unread = true";
1416 $unread_qpart = "true";
1420 return getCategoryUnread($n_feed, $owner_uid);
1421 } else if ($n_feed == -6) {
1423 } else if ($feed != "0" && $n_feed == 0) {
1425 $feed = db_escape_string($feed);
1427 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1428 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1429 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1430 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1431 return db_fetch_result($result, 0, "count");
1433 } else if ($n_feed == -1) {
1434 $match_part = "marked = true";
1435 } else if ($n_feed == -2) {
1436 $match_part = "published = true";
1437 } else if ($n_feed == -3) {
1438 $match_part = "unread = true AND score >= 0";
1440 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1442 if (DB_TYPE == "pgsql") {
1443 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1445 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1448 $need_entries = true;
1450 } else if ($n_feed == -4) {
1451 $match_part = "true";
1452 } else if ($n_feed >= 0) {
1455 $match_part = "feed_id = '$n_feed'";
1457 $match_part = "feed_id IS NULL";
1460 } else if ($feed < LABEL_BASE_INDEX) {
1462 $label_id = feed_to_label_id($feed);
1464 return getLabelUnread($label_id, $owner_uid);
1470 if ($need_entries) {
1471 $from_qpart = "ttrss_user_entries,ttrss_entries";
1472 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1474 $from_qpart = "ttrss_user_entries";
1478 $query = "SELECT count(int_id) AS unread
1479 FROM $from_qpart WHERE
1480 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1482 //echo "[$feed/$query]\n";
1484 $result = db_query($query);
1488 $result = db_query("SELECT COUNT(post_int_id) AS unread
1489 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1490 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1491 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1494 $unread = db_fetch_result($result, 0, "unread");
1499 function getGlobalUnread($user_id = false) {
1502 $user_id = $_SESSION["uid"];
1505 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1506 WHERE owner_uid = '$user_id' AND feed_id > 0");
1508 $c_id = db_fetch_result($result, 0, "c_id");
1513 function getGlobalCounters($global_unread = -1) {
1516 if ($global_unread == -1) {
1517 $global_unread = getGlobalUnread();
1520 $cv = array("id" => "global-unread",
1521 "counter" => (int) $global_unread);
1523 array_push($ret_arr, $cv);
1525 $result = db_query("SELECT COUNT(id) AS fn FROM
1526 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1528 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1530 $cv = array("id" => "subscribed-feeds",
1531 "counter" => (int) $subscribed_feeds);
1533 array_push($ret_arr, $cv);
1538 function getVirtCounters() {
1542 for ($i = 0; $i >= -4; $i--) {
1544 $count = getFeedUnread($i);
1546 if ($i == 0 || $i == -1 || $i == -2)
1547 $auxctr = getFeedArticles($i, false);
1551 $cv = array("id" => $i,
1552 "counter" => (int) $count,
1553 "auxcounter" => $auxctr);
1555 // if (get_pref('EXTENDED_FEEDLIST'))
1556 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1558 array_push($ret_arr, $cv);
1561 $feeds = PluginHost::getInstance()->get_feeds(-1);
1563 if (is_array($feeds)) {
1564 foreach ($feeds as $feed) {
1565 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1566 "counter" => $feed['sender']->get_unread($feed['id']));
1568 if (method_exists($feed['sender'], 'get_total'))
1569 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1571 array_push($ret_arr, $cv);
1578 function getLabelCounters($descriptions = false) {
1582 $owner_uid = $_SESSION["uid"];
1584 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1585 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1586 (ttrss_labels2.id = label_id)
1587 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1588 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1589 ttrss_labels2.caption");
1591 while ($line = db_fetch_assoc($result)) {
1593 $id = label_to_feed_id($line["id"]);
1595 $cv = array("id" => $id,
1596 "counter" => (int) $line["unread"],
1597 "auxcounter" => (int) $line["total"]);
1600 $cv["description"] = $line["caption"];
1602 array_push($ret_arr, $cv);
1608 function getFeedCounters($active_feed = false) {
1612 $query = "SELECT ttrss_feeds.id,
1614 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1615 last_error, value AS count
1616 FROM ttrss_feeds, ttrss_counters_cache
1617 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1618 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1619 AND ttrss_counters_cache.feed_id = id";
1621 $result = db_query($query);
1623 while ($line = db_fetch_assoc($result)) {
1626 $count = $line["count"];
1627 $last_error = htmlspecialchars($line["last_error"]);
1629 $last_updated = make_local_datetime($line['last_updated'], false);
1631 $has_img = feed_has_icon($id);
1633 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1636 $cv = array("id" => $id,
1637 "updated" => $last_updated,
1638 "counter" => (int) $count,
1639 "has_img" => (int) $has_img);
1642 $cv["error"] = $last_error;
1644 // if (get_pref('EXTENDED_FEEDLIST'))
1645 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1647 if ($active_feed && $id == $active_feed)
1648 $cv["title"] = truncate_string($line["title"], 30);
1650 array_push($ret_arr, $cv);
1657 function get_pgsql_version() {
1658 $result = db_query("SELECT version() AS version");
1659 $version = explode(" ", db_fetch_result($result, 0, "version"));
1664 * @return array (code => Status code, message => error message if available)
1666 * 0 - OK, Feed already exists
1667 * 1 - OK, Feed added
1669 * 3 - URL content is HTML, no feeds available
1670 * 4 - URL content is HTML which contains multiple feeds.
1671 * Here you should call extractfeedurls in rpc-backend
1672 * to get all possible feeds.
1673 * 5 - Couldn't download the URL content.
1674 * 6 - Content is an invalid XML.
1676 function subscribe_to_feed($url, $cat_id = 0,
1677 $auth_login = '', $auth_pass = '') {
1679 global $fetch_last_error;
1681 require_once "include/rssfuncs.php";
1683 $url = fix_url($url);
1685 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1687 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1690 return array("code" => 5, "message" => $fetch_last_error);
1693 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1694 $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1697 if (is_html($contents)) {
1698 $feedUrls = get_feeds_from_html($url, $contents);
1700 if (count($feedUrls) == 0) {
1701 return array("code" => 3);
1702 } else if (count($feedUrls) > 1) {
1703 return array("code" => 4, "feeds" => $feedUrls);
1705 //use feed url as new URL
1706 $url = key($feedUrls);
1709 /* libxml_use_internal_errors(true);
1710 $doc = new DOMDocument();
1711 $doc->loadXML($contents);
1712 $error = libxml_get_last_error();
1713 libxml_clear_errors();
1716 $error_message = format_libxml_error($error);
1718 return array("code" => 6, "message" => $error_message);
1721 if ($cat_id == "0" || !$cat_id) {
1722 $cat_qpart = "NULL";
1724 $cat_qpart = "'$cat_id'";
1728 "SELECT id FROM ttrss_feeds
1729 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1731 if (strlen(FEED_CRYPT_KEY) > 0) {
1732 require_once "crypt.php";
1733 $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1734 $auth_pass_encrypted = 'true';
1736 $auth_pass_encrypted = 'false';
1739 $auth_pass = db_escape_string($auth_pass);
1741 if (db_num_rows($result) == 0) {
1743 "INSERT INTO ttrss_feeds
1744 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1745 VALUES ('".$_SESSION["uid"]."', '$url',
1746 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1749 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1750 AND owner_uid = " . $_SESSION["uid"]);
1752 $feed_id = db_fetch_result($result, 0, "id");
1755 update_rss_feed($feed_id, true);
1758 return array("code" => 1);
1760 return array("code" => 0);
1764 function print_feed_select($id, $default_id = "",
1765 $attributes = "", $include_all_feeds = true,
1766 $root_id = false, $nest_level = 0) {
1769 print "<select id=\"$id\" name=\"$id\" $attributes>";
1770 if ($include_all_feeds) {
1771 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1772 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1776 if (get_pref('ENABLE_FEED_CATS')) {
1779 $parent_qpart = "parent_cat = '$root_id'";
1781 $parent_qpart = "parent_cat IS NULL";
1783 $result = db_query("SELECT id,title,
1784 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1785 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1786 FROM ttrss_feed_categories
1787 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1789 while ($line = db_fetch_assoc($result)) {
1791 for ($i = 0; $i < $nest_level; $i++)
1792 $line["title"] = " - " . $line["title"];
1794 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1796 printf("<option $is_selected value='CAT:%d'>%s</option>",
1797 $line["id"], htmlspecialchars($line["title"]));
1799 if ($line["num_children"] > 0)
1800 print_feed_select($id, $default_id, $attributes,
1801 $include_all_feeds, $line["id"], $nest_level+1);
1803 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1804 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1806 while ($fline = db_fetch_assoc($feed_result)) {
1807 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1809 $fline["title"] = " + " . $fline["title"];
1811 for ($i = 0; $i < $nest_level; $i++)
1812 $fline["title"] = " - " . $fline["title"];
1814 printf("<option $is_selected value='%d'>%s</option>",
1815 $fline["id"], htmlspecialchars($fline["title"]));
1820 $default_is_cat = ($default_id == "CAT:0");
1821 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1823 printf("<option $is_selected value='CAT:0'>%s</option>",
1824 __("Uncategorized"));
1826 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1827 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1829 while ($fline = db_fetch_assoc($feed_result)) {
1830 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1832 $fline["title"] = " + " . $fline["title"];
1834 for ($i = 0; $i < $nest_level; $i++)
1835 $fline["title"] = " - " . $fline["title"];
1837 printf("<option $is_selected value='%d'>%s</option>",
1838 $fline["id"], htmlspecialchars($fline["title"]));
1843 $result = db_query("SELECT id,title FROM ttrss_feeds
1844 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1846 while ($line = db_fetch_assoc($result)) {
1848 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1850 printf("<option $is_selected value='%d'>%s</option>",
1851 $line["id"], htmlspecialchars($line["title"]));
1860 function print_feed_cat_select($id, $default_id,
1861 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1864 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1868 $parent_qpart = "parent_cat = '$root_id'";
1870 $parent_qpart = "parent_cat IS NULL";
1872 $result = db_query("SELECT id,title,
1873 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1874 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1875 FROM ttrss_feed_categories
1876 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1878 while ($line = db_fetch_assoc($result)) {
1879 if ($line["id"] == $default_id) {
1880 $is_selected = "selected=\"1\"";
1885 for ($i = 0; $i < $nest_level; $i++)
1886 $line["title"] = " - " . $line["title"];
1889 printf("<option $is_selected value='%d'>%s</option>",
1890 $line["id"], htmlspecialchars($line["title"]));
1892 if ($line["num_children"] > 0)
1893 print_feed_cat_select($id, $default_id, $attributes,
1894 $include_all_cats, $line["id"], $nest_level+1);
1898 if ($include_all_cats) {
1899 if (db_num_rows($result) > 0) {
1900 print "<option disabled=\"1\">--------</option>";
1903 if ($default_id == 0) {
1904 $is_selected = "selected=\"1\"";
1909 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1915 function checkbox_to_sql_bool($val) {
1916 return ($val == "on") ? "true" : "false";
1919 function getFeedCatTitle($id) {
1921 return __("Special");
1922 } else if ($id < LABEL_BASE_INDEX) {
1923 return __("Labels");
1924 } else if ($id > 0) {
1925 $result = db_query("SELECT ttrss_feed_categories.title
1926 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1927 cat_id = ttrss_feed_categories.id");
1928 if (db_num_rows($result) == 1) {
1929 return db_fetch_result($result, 0, "title");
1931 return __("Uncategorized");
1934 return "getFeedCatTitle($id) failed";
1939 function getFeedIcon($id) {
1942 return "images/archive.png";
1945 return "images/star.png";
1948 return "images/feed.png";
1951 return "images/fresh.png";
1954 return "images/folder.png";
1957 return "images/time.png";
1960 if ($id < LABEL_BASE_INDEX) {
1961 return "images/label.png";
1963 if (file_exists(ICONS_DIR . "/$id.ico"))
1964 return ICONS_URL . "/$id.ico";
1972 function getFeedTitle($id, $cat = false) {
1974 return getCategoryTitle($id);
1975 } else if ($id == -1) {
1976 return __("Starred articles");
1977 } else if ($id == -2) {
1978 return __("Published articles");
1979 } else if ($id == -3) {
1980 return __("Fresh articles");
1981 } else if ($id == -4) {
1982 return __("All articles");
1983 } else if ($id === 0 || $id === "0") {
1984 return __("Archived articles");
1985 } else if ($id == -6) {
1986 return __("Recently read");
1987 } else if ($id < LABEL_BASE_INDEX) {
1988 $label_id = feed_to_label_id($id);
1989 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1990 if (db_num_rows($result) == 1) {
1991 return db_fetch_result($result, 0, "caption");
1993 return "Unknown label ($label_id)";
1996 } else if (is_numeric($id) && $id > 0) {
1997 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
1998 if (db_num_rows($result) == 1) {
1999 return db_fetch_result($result, 0, "title");
2001 return "Unknown feed ($id)";
2008 // TODO: less dumb splitting
2009 require_once "functions2.php";