2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 125);
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",
71 "fr_FR" => "Français",
72 "hu_HU" => "Magyar (Hungarian)",
73 "it_IT" => "Italiano",
74 "ja_JP" => "日本語 (Japanese)",
75 "lv_LV" => "Latviešu",
76 "nb_NO" => "Norwegian bokmål",
80 "pt_BR" => "Portuguese/Brazil",
81 "pt_PT" => "Portuguese/Portugal",
82 "zh_CN" => "Simplified Chinese",
83 "zh_TW" => "Traditional Chinese",
91 require_once "lib/accept-to-gettext.php";
92 require_once "lib/gettext/gettext.inc";
94 require_once "lib/languagedetect/LanguageDetect.php";
96 function startup_gettext() {
98 # Get locale from Accept-Language header
99 $lang = al2gt(array_keys(get_translations()), "text/html");
101 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
102 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
105 if ($_SESSION["uid"] && get_schema_version() >= 120) {
106 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
108 if ($pref_lang && $pref_lang != 'auto') {
114 if (defined('LC_MESSAGES')) {
115 _setlocale(LC_MESSAGES, $lang);
116 } else if (defined('LC_ALL')) {
117 _setlocale(LC_ALL, $lang);
120 _bindtextdomain("messages", "locale");
122 _textdomain("messages");
123 _bind_textdomain_codeset("messages", "UTF-8");
127 require_once 'db-prefs.php';
128 require_once 'version.php';
129 require_once 'ccache.php';
130 require_once 'labels.php';
132 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
133 ini_set('user_agent', SELF_USER_AGENT);
135 require_once 'lib/pubsubhubbub/publisher.php';
137 $schema_version = false;
139 function _debug_suppress($suppress) {
140 global $suppress_debugging;
142 $suppress_debugging = $suppress;
146 * Print a timestamped debug message.
148 * @param string $msg The debug message.
151 function _debug($msg, $show = true) {
152 global $suppress_debugging;
154 //echo "[$suppress_debugging] $msg $show\n";
156 if ($suppress_debugging) return false;
158 $ts = strftime("%H:%M:%S", time());
159 if (function_exists('posix_getpid')) {
160 $ts = "$ts/" . posix_getpid();
163 if ($show && !(defined('QUIET') && QUIET)) {
164 print "[$ts] $msg\n";
167 if (defined('LOGFILE')) {
168 $fp = fopen(LOGFILE, 'a+');
173 if (function_exists("flock")) {
176 // try to lock logfile for writing
177 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
188 fputs($fp, "[$ts] $msg\n");
190 if (function_exists("flock")) {
201 * Purge a feed old posts.
203 * @param mixed $link A database connection.
204 * @param mixed $feed_id The id of the purged feed.
205 * @param mixed $purge_interval Olderness of purged posts.
206 * @param boolean $debug Set to True to enable the debug. False by default.
210 function purge_feed($feed_id, $purge_interval, $debug = false) {
212 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
217 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
221 if (db_num_rows($result) == 1) {
222 $owner_uid = db_fetch_result($result, 0, "owner_uid");
225 if ($purge_interval == -1 || !$purge_interval) {
227 ccache_update($feed_id, $owner_uid);
232 if (!$owner_uid) return;
234 if (FORCE_ARTICLE_PURGE == 0) {
235 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
238 $purge_unread = true;
239 $purge_interval = FORCE_ARTICLE_PURGE;
242 if (!$purge_unread) $query_limit = " unread = false AND ";
244 if (DB_TYPE == "pgsql") {
245 $pg_version = get_pgsql_version();
247 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
249 $result = db_query("DELETE FROM ttrss_user_entries WHERE
250 ttrss_entries.id = ref_id AND
252 feed_id = '$feed_id' AND
254 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
258 $result = db_query("DELETE FROM ttrss_user_entries
260 WHERE ttrss_entries.id = ref_id AND
262 feed_id = '$feed_id' AND
264 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
269 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
270 marked = false AND feed_id = '$feed_id' AND
271 (SELECT date_updated FROM ttrss_entries WHERE
272 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
274 $result = db_query("DELETE FROM ttrss_user_entries
275 USING ttrss_user_entries, ttrss_entries
276 WHERE ttrss_entries.id = ref_id AND
278 feed_id = '$feed_id' AND
280 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
283 $rows = db_affected_rows($result);
285 ccache_update($feed_id, $owner_uid);
288 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
292 } // function purge_feed
294 function feed_purge_interval($feed_id) {
296 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
297 WHERE id = '$feed_id'");
299 if (db_num_rows($result) == 1) {
300 $purge_interval = db_fetch_result($result, 0, "purge_interval");
301 $owner_uid = db_fetch_result($result, 0, "owner_uid");
303 if ($purge_interval == 0) $purge_interval = get_pref(
304 'PURGE_OLD_DAYS', $owner_uid);
306 return $purge_interval;
313 function purge_orphans($do_output = false) {
315 // purge orphaned posts in main content table
316 $result = db_query("DELETE FROM ttrss_entries WHERE
317 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
320 $rows = db_affected_rows($result);
321 _debug("Purged $rows orphaned posts.");
325 function get_feed_update_interval($feed_id) {
326 $result = db_query("SELECT owner_uid, update_interval FROM
327 ttrss_feeds WHERE id = '$feed_id'");
329 if (db_num_rows($result) == 1) {
330 $update_interval = db_fetch_result($result, 0, "update_interval");
331 $owner_uid = db_fetch_result($result, 0, "owner_uid");
333 if ($update_interval != 0) {
334 return $update_interval;
336 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
344 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0, $useragent = false) {
346 global $fetch_last_error;
347 global $fetch_last_error_code;
348 global $fetch_last_content_type;
349 global $fetch_curl_used;
351 $url = str_replace(' ', '%20', $url);
353 if (!defined('NO_CURL') && function_exists('curl_init')) {
355 $fetch_curl_used = true;
357 if (ini_get("safe_mode") || ini_get("open_basedir")) {
358 $new_url = geturl($url);
360 // geturl has already populated $fetch_last_error
363 $ch = curl_init($new_url);
365 $ch = curl_init($url);
368 if ($timestamp && !$post_query) {
369 curl_setopt($ch, CURLOPT_HTTPHEADER,
370 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
373 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
374 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
375 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode") && !ini_get("open_basedir"));
376 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
377 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
378 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
379 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
380 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
381 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
383 curl_setopt($ch, CURLOPT_ENCODING, "");
384 //curl_setopt($ch, CURLOPT_REFERER, $url);
386 if (!ini_get("safe_mode") && !ini_get("open_basedir")) {
387 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
390 if (defined('_CURL_HTTP_PROXY')) {
391 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
395 curl_setopt($ch, CURLOPT_POST, true);
396 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
399 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
400 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
404 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
406 $contents = @curl_exec($ch);
408 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
409 curl_setopt($ch, CURLOPT_ENCODING, 'none');
410 $contents = @curl_exec($ch);
413 if ($contents === false) {
414 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
419 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
420 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
422 $fetch_last_error_code = $http_code;
424 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
425 if (curl_errno($ch) != 0) {
426 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
428 $fetch_last_error = "HTTP Code: $http_code";
439 $fetch_curl_used = false;
441 if ($login && $pass){
442 $url_parts = array();
444 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
446 $pass = urlencode($pass);
448 if ($url_parts[1] && $url_parts[2]) {
449 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
453 if (!$post_query && $timestamp) {
454 $context = stream_context_create(array(
457 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
463 $old_error = error_get_last();
465 $data = @file_get_contents($url, false, $context);
467 $fetch_last_content_type = false; // reset if no type was sent from server
468 if (isset($http_response_header) && is_array($http_response_header)) {
469 foreach ($http_response_header as $h) {
470 if (substr(strtolower($h), 0, 13) == 'content-type:') {
471 $fetch_last_content_type = substr($h, 14);
472 // don't abort here b/c there might be more than one
473 // e.g. if we were being redirected -- last one is the right one
476 if (substr(strtolower($h), 0, 7) == 'http/1.') {
477 $fetch_last_error_code = (int) substr($h, 9, 3);
483 $error = error_get_last();
485 if ($error['message'] != $old_error['message']) {
486 $fetch_last_error = $error["message"];
488 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
497 * Try to determine the favicon URL for a feed.
498 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
499 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
501 * @param string $url A feed or page URL
503 * @return mixed The favicon URL, or false if none was found.
505 function get_favicon_url($url) {
507 $favicon_url = false;
509 if ($html = @fetch_file_contents($url)) {
511 libxml_use_internal_errors(true);
513 $doc = new DOMDocument();
514 $doc->loadHTML($html);
515 $xpath = new DOMXPath($doc);
517 $base = $xpath->query('/html/head/base');
518 foreach ($base as $b) {
519 $url = $b->getAttribute("href");
523 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
524 if (count($entries) > 0) {
525 foreach ($entries as $entry) {
526 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
533 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
536 } // function get_favicon_url
538 function check_feed_favicon($site_url, $feed) {
539 # print "FAVICON [$site_url]: $favicon_url\n";
541 $icon_file = ICONS_DIR . "/$feed.ico";
543 if (!file_exists($icon_file)) {
544 $favicon_url = get_favicon_url($site_url);
547 // Limiting to "image" type misses those served with text/plain
548 $contents = fetch_file_contents($favicon_url); // , "image");
551 // Crude image type matching.
552 // Patterns gleaned from the file(1) source code.
553 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
554 // 0 string \000\000\001\000 MS Windows icon resource
555 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
557 elseif (preg_match('/^GIF8/', $contents)) {
558 // 0 string GIF8 GIF image data
559 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
561 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
562 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
563 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
565 elseif (preg_match('/^\xff\xd8/', $contents)) {
566 // 0 beshort 0xffd8 JPEG image data
567 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
570 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
576 $fp = @fopen($icon_file, "w");
579 fwrite($fp, $contents);
581 chmod($icon_file, 0644);
589 function print_select($id, $default, $values, $attributes = "") {
590 print "<select name=\"$id\" id=\"$id\" $attributes>";
591 foreach ($values as $v) {
593 $sel = "selected=\"1\"";
599 print "<option value=\"$v\" $sel>$v</option>";
604 function print_select_hash($id, $default, $values, $attributes = "") {
605 print "<select name=\"$id\" id='$id' $attributes>";
606 foreach (array_keys($values) as $v) {
608 $sel = 'selected="selected"';
614 print "<option $sel value=\"$v\">".$values[$v]."</option>";
620 function print_radio($id, $default, $true_is, $values, $attributes = "") {
621 foreach ($values as $v) {
628 if ($v == $true_is) {
629 $sel .= " value=\"1\"";
631 $sel .= " value=\"0\"";
634 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
635 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
640 function initialize_user_prefs($uid, $profile = false) {
642 $uid = db_escape_string($uid);
646 $profile_qpart = "AND profile IS NULL";
648 $profile_qpart = "AND profile = '$profile'";
651 if (get_schema_version() < 63) $profile_qpart = "";
655 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
657 $u_result = db_query("SELECT pref_name
658 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
660 $active_prefs = array();
662 while ($line = db_fetch_assoc($u_result)) {
663 array_push($active_prefs, $line["pref_name"]);
666 while ($line = db_fetch_assoc($result)) {
667 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
668 // print "adding " . $line["pref_name"] . "<br>";
670 $line["def_value"] = db_escape_string($line["def_value"]);
671 $line["pref_name"] = db_escape_string($line["pref_name"]);
673 if (get_schema_version() < 63) {
674 db_query("INSERT INTO ttrss_user_prefs
675 (owner_uid,pref_name,value) VALUES
676 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
679 db_query("INSERT INTO ttrss_user_prefs
680 (owner_uid,pref_name,value, profile) VALUES
681 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
691 function get_ssl_certificate_id() {
692 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
693 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
694 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
695 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
696 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
698 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
699 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
700 $_SERVER["SSL_CLIENT_V_START"] .
701 $_SERVER["SSL_CLIENT_V_END"] .
702 $_SERVER["SSL_CLIENT_S_DN"]);
707 function authenticate_user($login, $password, $check_only = false) {
709 if (!SINGLE_USER_MODE) {
712 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
714 $user_id = (int) $plugin->authenticate($login, $password);
717 $_SESSION["auth_module"] = strtolower(get_class($plugin));
722 if ($user_id && !$check_only) {
725 $_SESSION["uid"] = $user_id;
726 $_SESSION["version"] = VERSION_STATIC;
728 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
729 WHERE id = '$user_id'");
731 $_SESSION["name"] = db_fetch_result($result, 0, "login");
732 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
733 $_SESSION["csrf_token"] = uniqid(rand(), true);
735 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
738 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
739 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
740 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
742 $_SESSION["last_version_check"] = time();
744 initialize_user_prefs($_SESSION["uid"]);
753 $_SESSION["uid"] = 1;
754 $_SESSION["name"] = "admin";
755 $_SESSION["access_level"] = 10;
757 $_SESSION["hide_hello"] = true;
758 $_SESSION["hide_logout"] = true;
760 $_SESSION["auth_module"] = false;
762 if (!$_SESSION["csrf_token"]) {
763 $_SESSION["csrf_token"] = uniqid(rand(), true);
766 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
768 initialize_user_prefs($_SESSION["uid"]);
774 function make_password($length = 8) {
777 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
781 while ($i < $length) {
782 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
784 if (!strstr($password, $char)) {
792 // this is called after user is created to initialize default feeds, labels
795 // user preferences are checked on every login, not here
797 function initialize_user($uid) {
799 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
800 values ('$uid', 'Tiny Tiny RSS: New Releases',
801 'http://tt-rss.org/releases.rss')");
803 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
804 values ('$uid', 'Tiny Tiny RSS: Forum',
805 'http://tt-rss.org/forum/rss.php')");
808 function logout_user() {
810 if (isset($_COOKIE[session_name()])) {
811 setcookie(session_name(), '', time()-42000, '/');
815 function validate_csrf($csrf_token) {
816 return $csrf_token == $_SESSION['csrf_token'];
819 function load_user_plugins($owner_uid) {
820 if ($owner_uid && SCHEMA_VERSION >= 100) {
821 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
823 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
825 if (get_schema_version() > 100) {
826 PluginHost::getInstance()->load_data();
831 function login_sequence() {
832 if (SINGLE_USER_MODE) {
834 authenticate_user("admin", null);
836 load_user_plugins($_SESSION["uid"]);
838 if (!validate_session()) $_SESSION["uid"] = false;
840 if (!$_SESSION["uid"]) {
842 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
843 $_SESSION["ref_schema_version"] = get_schema_version(true);
845 authenticate_user(null, null, true);
848 if (!$_SESSION["uid"]) {
850 setcookie(session_name(), '', time()-42000, '/');
857 /* bump login timestamp */
858 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
860 $_SESSION["last_login_update"] = time();
863 if ($_SESSION["uid"]) {
865 load_user_plugins($_SESSION["uid"]);
869 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
870 $_SESSION["uid"] . " AND
871 (SELECT COUNT(id) FROM ttrss_feeds WHERE
872 ttrss_feeds.id = feed_id) = 0");
874 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
875 $_SESSION["uid"] . " AND
876 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
877 ttrss_feed_categories.id = feed_id) = 0");
884 function truncate_string($str, $max_len, $suffix = '…') {
885 if (mb_strlen($str, "utf-8") > $max_len) {
886 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
892 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
895 $source_tz = new DateTimeZone($source_tz);
896 } catch (Exception $e) {
897 $source_tz = new DateTimeZone('UTC');
901 $dest_tz = new DateTimeZone($dest_tz);
902 } catch (Exception $e) {
903 $dest_tz = new DateTimeZone('UTC');
906 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
907 return $dt->format('U') + $dest_tz->getOffset($dt);
910 function make_local_datetime($timestamp, $long, $owner_uid = false,
911 $no_smart_dt = false) {
913 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
914 if (!$timestamp) $timestamp = '1970-01-01 0:00';
919 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
921 $timestamp = substr($timestamp, 0, 19);
923 # We store date in UTC internally
924 $dt = new DateTime($timestamp, $utc_tz);
926 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
928 if ($user_tz_string != 'Automatic') {
931 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
932 } catch (Exception $e) {
936 $tz_offset = $user_tz->getOffset($dt);
938 $tz_offset = (int) -$_SESSION["clientTzOffset"];
941 $user_timestamp = $dt->format('U') + $tz_offset;
944 return smart_date_time($user_timestamp,
945 $tz_offset, $owner_uid);
948 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
950 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
952 return date($format, $user_timestamp);
956 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false) {
957 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
959 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
960 return date("G:i", $timestamp);
961 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
962 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
963 return date($format, $timestamp);
965 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
966 return date($format, $timestamp);
970 function sql_bool_to_bool($s) {
971 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
978 function bool_to_sql_bool($s) {
986 // Session caching removed due to causing wrong redirects to upgrade
987 // script when get_schema_version() is called on an obsolete session
988 // created on a previous schema version.
989 function get_schema_version($nocache = false) {
990 global $schema_version;
992 if (!$schema_version && !$nocache) {
993 $result = db_query("SELECT schema_version FROM ttrss_version");
994 $version = db_fetch_result($result, 0, "schema_version");
995 $schema_version = $version;
998 return $schema_version;
1002 function sanity_check() {
1003 require_once 'errors.php';
1007 $schema_version = get_schema_version(true);
1009 if ($schema_version != SCHEMA_VERSION) {
1013 if (DB_TYPE == "mysql") {
1014 $result = db_query("SELECT true", false);
1015 if (db_num_rows($result) != 1) {
1020 if (db_escape_string("testTEST") != "testTEST") {
1024 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1027 function file_is_locked($filename) {
1028 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1029 if (function_exists('flock')) {
1030 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1032 if (flock($fp, LOCK_EX | LOCK_NB)) {
1033 flock($fp, LOCK_UN);
1043 return true; // consider the file always locked and skip the test
1050 function make_lockfile($filename) {
1051 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1053 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1054 $stat_h = fstat($fp);
1055 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1057 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1058 if ($stat_h["ino"] != $stat_f["ino"] ||
1059 $stat_h["dev"] != $stat_f["dev"]) {
1065 if (function_exists('posix_getpid')) {
1066 fwrite($fp, posix_getpid() . "\n");
1074 function make_stampfile($filename) {
1075 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1077 if (flock($fp, LOCK_EX | LOCK_NB)) {
1078 fwrite($fp, time() . "\n");
1079 flock($fp, LOCK_UN);
1087 function sql_random_function() {
1088 if (DB_TYPE == "mysql") {
1095 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1097 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1099 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1101 // Todo: all this interval stuff needs some generic generator function
1103 $date_qpart = "false";
1107 if (DB_TYPE == "pgsql") {
1108 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1110 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1114 if (DB_TYPE == "pgsql") {
1115 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1117 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1121 if (DB_TYPE == "pgsql") {
1122 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1124 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1128 $date_qpart = "true";
1131 if (is_numeric($feed)) {
1137 $children = getChildCategories($feed, $owner_uid);
1138 array_push($children, $feed);
1140 $children = join(",", $children);
1142 $cat_qpart = "cat_id IN ($children)";
1144 $cat_qpart = "cat_id IS NULL";
1147 db_query("UPDATE ttrss_user_entries
1148 SET unread = false, last_read = NOW() WHERE ref_id IN
1150 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1151 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1152 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1154 } else if ($feed == -2) {
1156 db_query("UPDATE ttrss_user_entries
1157 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1158 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1159 AND unread = true AND owner_uid = $owner_uid");
1162 } else if ($feed > 0) {
1164 db_query("UPDATE ttrss_user_entries
1165 SET unread = false, last_read = NOW() WHERE ref_id IN
1167 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1168 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1170 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1173 db_query("UPDATE ttrss_user_entries
1174 SET unread = false, last_read = NOW() WHERE ref_id IN
1176 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1177 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1181 db_query("UPDATE ttrss_user_entries
1182 SET unread = false, last_read = NOW() WHERE ref_id IN
1184 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1185 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1190 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1192 if (DB_TYPE == "pgsql") {
1193 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1195 $match_part = "date_entered > DATE_SUB(NOW(),
1196 INTERVAL $intl HOUR) ";
1199 db_query("UPDATE ttrss_user_entries
1200 SET unread = false, last_read = NOW() WHERE ref_id IN
1202 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1203 AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $match_part) as tmp)");
1207 db_query("UPDATE ttrss_user_entries
1208 SET unread = false, last_read = NOW() WHERE ref_id IN
1210 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1211 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1214 } else if ($feed < LABEL_BASE_INDEX) { // label
1216 $label_id = feed_to_label_id($feed);
1218 db_query("UPDATE ttrss_user_entries
1219 SET unread = false, last_read = NOW() WHERE ref_id IN
1221 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1222 AND label_id = '$label_id' AND ref_id = article_id
1223 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1227 ccache_update($feed, $owner_uid, $cat_view);
1230 db_query("UPDATE ttrss_user_entries
1231 SET unread = false, last_read = NOW() WHERE ref_id IN
1233 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1234 AND post_int_id = int_id AND tag_name = '$feed'
1235 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1240 function getAllCounters() {
1241 $data = getGlobalCounters();
1243 $data = array_merge($data, getVirtCounters());
1244 $data = array_merge($data, getLabelCounters());
1245 $data = array_merge($data, getFeedCounters());
1246 $data = array_merge($data, getCategoryCounters());
1251 function getCategoryTitle($cat_id) {
1253 if ($cat_id == -1) {
1254 return __("Special");
1255 } else if ($cat_id == -2) {
1256 return __("Labels");
1259 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1262 if (db_num_rows($result) == 1) {
1263 return db_fetch_result($result, 0, "title");
1265 return __("Uncategorized");
1271 function getCategoryCounters() {
1274 /* Labels category */
1276 $cv = array("id" => -2, "kind" => "cat",
1277 "counter" => getCategoryUnread(-2));
1279 array_push($ret_arr, $cv);
1281 $result = db_query("SELECT id AS cat_id, value AS unread,
1282 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1283 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1284 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1285 WHERE ttrss_cat_counters_cache.feed_id = id AND
1286 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1287 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1289 while ($line = db_fetch_assoc($result)) {
1290 $line["cat_id"] = (int) $line["cat_id"];
1292 if ($line["num_children"] > 0) {
1293 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1298 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1299 "counter" => $line["unread"] + $child_counter);
1301 array_push($ret_arr, $cv);
1304 /* Special case: NULL category doesn't actually exist in the DB */
1306 $cv = array("id" => 0, "kind" => "cat",
1307 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1309 array_push($ret_arr, $cv);
1314 // only accepts real cats (>= 0)
1315 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1316 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1318 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1319 AND owner_uid = $owner_uid");
1323 while ($line = db_fetch_assoc($result)) {
1324 $unread += getCategoryUnread($line["id"], $owner_uid);
1325 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1331 function getCategoryUnread($cat, $owner_uid = false) {
1333 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1338 $cat_query = "cat_id = '$cat'";
1340 $cat_query = "cat_id IS NULL";
1343 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1344 AND owner_uid = " . $owner_uid);
1346 $cat_feeds = array();
1347 while ($line = db_fetch_assoc($result)) {
1348 array_push($cat_feeds, "feed_id = " . $line["id"]);
1351 if (count($cat_feeds) == 0) return 0;
1353 $match_part = implode(" OR ", $cat_feeds);
1355 $result = db_query("SELECT COUNT(int_id) AS unread
1356 FROM ttrss_user_entries
1357 WHERE unread = true AND ($match_part)
1358 AND owner_uid = " . $owner_uid);
1362 # this needs to be rewritten
1363 while ($line = db_fetch_assoc($result)) {
1364 $unread += $line["unread"];
1368 } else if ($cat == -1) {
1369 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1370 } else if ($cat == -2) {
1372 $result = db_query("
1373 SELECT COUNT(unread) AS unread FROM
1374 ttrss_user_entries, ttrss_user_labels2
1375 WHERE article_id = ref_id AND unread = true
1376 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1378 $unread = db_fetch_result($result, 0, "unread");
1385 function getFeedUnread($feed, $is_cat = false) {
1386 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1389 function getLabelUnread($label_id, $owner_uid = false) {
1390 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1392 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1393 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1395 if (db_num_rows($result) != 0) {
1396 return db_fetch_result($result, 0, "unread");
1402 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1403 $owner_uid = false) {
1405 $n_feed = (int) $feed;
1406 $need_entries = false;
1408 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1411 $unread_qpart = "unread = true";
1413 $unread_qpart = "true";
1417 return getCategoryUnread($n_feed, $owner_uid);
1418 } else if ($n_feed == -6) {
1420 } else if ($feed != "0" && $n_feed == 0) {
1422 $feed = db_escape_string($feed);
1424 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1425 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1426 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1427 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1428 return db_fetch_result($result, 0, "count");
1430 } else if ($n_feed == -1) {
1431 $match_part = "marked = true";
1432 } else if ($n_feed == -2) {
1433 $match_part = "published = true";
1434 } else if ($n_feed == -3) {
1435 $match_part = "unread = true AND score >= 0";
1437 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1439 if (DB_TYPE == "pgsql") {
1440 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1442 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1445 $need_entries = true;
1447 } else if ($n_feed == -4) {
1448 $match_part = "true";
1449 } else if ($n_feed >= 0) {
1452 $match_part = "feed_id = '$n_feed'";
1454 $match_part = "feed_id IS NULL";
1457 } else if ($feed < LABEL_BASE_INDEX) {
1459 $label_id = feed_to_label_id($feed);
1461 return getLabelUnread($label_id, $owner_uid);
1467 if ($need_entries) {
1468 $from_qpart = "ttrss_user_entries,ttrss_entries";
1469 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1471 $from_qpart = "ttrss_user_entries";
1475 $query = "SELECT count(int_id) AS unread
1476 FROM $from_qpart WHERE
1477 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1479 //echo "[$feed/$query]\n";
1481 $result = db_query($query);
1485 $result = db_query("SELECT COUNT(post_int_id) AS unread
1486 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1487 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1488 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1491 $unread = db_fetch_result($result, 0, "unread");
1496 function getGlobalUnread($user_id = false) {
1499 $user_id = $_SESSION["uid"];
1502 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1503 WHERE owner_uid = '$user_id' AND feed_id > 0");
1505 $c_id = db_fetch_result($result, 0, "c_id");
1510 function getGlobalCounters($global_unread = -1) {
1513 if ($global_unread == -1) {
1514 $global_unread = getGlobalUnread();
1517 $cv = array("id" => "global-unread",
1518 "counter" => (int) $global_unread);
1520 array_push($ret_arr, $cv);
1522 $result = db_query("SELECT COUNT(id) AS fn FROM
1523 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1525 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1527 $cv = array("id" => "subscribed-feeds",
1528 "counter" => (int) $subscribed_feeds);
1530 array_push($ret_arr, $cv);
1535 function getVirtCounters() {
1539 for ($i = 0; $i >= -4; $i--) {
1541 $count = getFeedUnread($i);
1543 if ($i == 0 || $i == -1 || $i == -2)
1544 $auxctr = getFeedArticles($i, false);
1548 $cv = array("id" => $i,
1549 "counter" => (int) $count,
1550 "auxcounter" => $auxctr);
1552 // if (get_pref('EXTENDED_FEEDLIST'))
1553 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1555 array_push($ret_arr, $cv);
1558 $feeds = PluginHost::getInstance()->get_feeds(-1);
1560 if (is_array($feeds)) {
1561 foreach ($feeds as $feed) {
1562 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1563 "counter" => $feed['sender']->get_unread($feed['id']));
1565 if (method_exists($feed['sender'], 'get_total'))
1566 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1568 array_push($ret_arr, $cv);
1575 function getLabelCounters($descriptions = false) {
1579 $owner_uid = $_SESSION["uid"];
1581 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1582 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1583 (ttrss_labels2.id = label_id)
1584 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1585 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1586 ttrss_labels2.caption");
1588 while ($line = db_fetch_assoc($result)) {
1590 $id = label_to_feed_id($line["id"]);
1592 $cv = array("id" => $id,
1593 "counter" => (int) $line["unread"],
1594 "auxcounter" => (int) $line["total"]);
1597 $cv["description"] = $line["caption"];
1599 array_push($ret_arr, $cv);
1605 function getFeedCounters($active_feed = false) {
1609 $query = "SELECT ttrss_feeds.id,
1611 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1612 last_error, value AS count
1613 FROM ttrss_feeds, ttrss_counters_cache
1614 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1615 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1616 AND ttrss_counters_cache.feed_id = id";
1618 $result = db_query($query);
1620 while ($line = db_fetch_assoc($result)) {
1623 $count = $line["count"];
1624 $last_error = htmlspecialchars($line["last_error"]);
1626 $last_updated = make_local_datetime($line['last_updated'], false);
1628 $has_img = feed_has_icon($id);
1630 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1633 $cv = array("id" => $id,
1634 "updated" => $last_updated,
1635 "counter" => (int) $count,
1636 "has_img" => (int) $has_img);
1639 $cv["error"] = $last_error;
1641 // if (get_pref('EXTENDED_FEEDLIST'))
1642 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1644 if ($active_feed && $id == $active_feed)
1645 $cv["title"] = truncate_string($line["title"], 30);
1647 array_push($ret_arr, $cv);
1654 function get_pgsql_version() {
1655 $result = db_query("SELECT version() AS version");
1656 $version = explode(" ", db_fetch_result($result, 0, "version"));
1661 * @return array (code => Status code, message => error message if available)
1663 * 0 - OK, Feed already exists
1664 * 1 - OK, Feed added
1666 * 3 - URL content is HTML, no feeds available
1667 * 4 - URL content is HTML which contains multiple feeds.
1668 * Here you should call extractfeedurls in rpc-backend
1669 * to get all possible feeds.
1670 * 5 - Couldn't download the URL content.
1671 * 6 - Content is an invalid XML.
1673 function subscribe_to_feed($url, $cat_id = 0,
1674 $auth_login = '', $auth_pass = '') {
1676 global $fetch_last_error;
1678 require_once "include/rssfuncs.php";
1680 $url = fix_url($url);
1682 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1684 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1687 return array("code" => 5, "message" => $fetch_last_error);
1690 if (is_html($contents)) {
1691 $feedUrls = get_feeds_from_html($url, $contents);
1693 if (count($feedUrls) == 0) {
1694 return array("code" => 3);
1695 } else if (count($feedUrls) > 1) {
1696 return array("code" => 4, "feeds" => $feedUrls);
1698 //use feed url as new URL
1699 $url = key($feedUrls);
1702 /* libxml_use_internal_errors(true);
1703 $doc = new DOMDocument();
1704 $doc->loadXML($contents);
1705 $error = libxml_get_last_error();
1706 libxml_clear_errors();
1709 $error_message = format_libxml_error($error);
1711 return array("code" => 6, "message" => $error_message);
1714 if ($cat_id == "0" || !$cat_id) {
1715 $cat_qpart = "NULL";
1717 $cat_qpart = "'$cat_id'";
1721 "SELECT id FROM ttrss_feeds
1722 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1724 if (strlen(FEED_CRYPT_KEY) > 0) {
1725 require_once "crypt.php";
1726 $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1727 $auth_pass_encrypted = 'true';
1729 $auth_pass_encrypted = 'false';
1732 $auth_pass = db_escape_string($auth_pass);
1734 if (db_num_rows($result) == 0) {
1736 "INSERT INTO ttrss_feeds
1737 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1738 VALUES ('".$_SESSION["uid"]."', '$url',
1739 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1742 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1743 AND owner_uid = " . $_SESSION["uid"]);
1745 $feed_id = db_fetch_result($result, 0, "id");
1748 update_rss_feed($feed_id, true);
1751 return array("code" => 1);
1753 return array("code" => 0);
1757 function print_feed_select($id, $default_id = "",
1758 $attributes = "", $include_all_feeds = true,
1759 $root_id = false, $nest_level = 0) {
1762 print "<select id=\"$id\" name=\"$id\" $attributes>";
1763 if ($include_all_feeds) {
1764 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1765 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1769 if (get_pref('ENABLE_FEED_CATS')) {
1772 $parent_qpart = "parent_cat = '$root_id'";
1774 $parent_qpart = "parent_cat IS NULL";
1776 $result = db_query("SELECT id,title,
1777 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1778 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1779 FROM ttrss_feed_categories
1780 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1782 while ($line = db_fetch_assoc($result)) {
1784 for ($i = 0; $i < $nest_level; $i++)
1785 $line["title"] = " - " . $line["title"];
1787 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1789 printf("<option $is_selected value='CAT:%d'>%s</option>",
1790 $line["id"], htmlspecialchars($line["title"]));
1792 if ($line["num_children"] > 0)
1793 print_feed_select($id, $default_id, $attributes,
1794 $include_all_feeds, $line["id"], $nest_level+1);
1796 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1797 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1799 while ($fline = db_fetch_assoc($feed_result)) {
1800 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1802 $fline["title"] = " + " . $fline["title"];
1804 for ($i = 0; $i < $nest_level; $i++)
1805 $fline["title"] = " - " . $fline["title"];
1807 printf("<option $is_selected value='%d'>%s</option>",
1808 $fline["id"], htmlspecialchars($fline["title"]));
1813 $default_is_cat = ($default_id == "CAT:0");
1814 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1816 printf("<option $is_selected value='CAT:0'>%s</option>",
1817 __("Uncategorized"));
1819 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1820 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1822 while ($fline = db_fetch_assoc($feed_result)) {
1823 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1825 $fline["title"] = " + " . $fline["title"];
1827 for ($i = 0; $i < $nest_level; $i++)
1828 $fline["title"] = " - " . $fline["title"];
1830 printf("<option $is_selected value='%d'>%s</option>",
1831 $fline["id"], htmlspecialchars($fline["title"]));
1836 $result = db_query("SELECT id,title FROM ttrss_feeds
1837 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1839 while ($line = db_fetch_assoc($result)) {
1841 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1843 printf("<option $is_selected value='%d'>%s</option>",
1844 $line["id"], htmlspecialchars($line["title"]));
1853 function print_feed_cat_select($id, $default_id,
1854 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1857 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1861 $parent_qpart = "parent_cat = '$root_id'";
1863 $parent_qpart = "parent_cat IS NULL";
1865 $result = db_query("SELECT id,title,
1866 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1867 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1868 FROM ttrss_feed_categories
1869 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1871 while ($line = db_fetch_assoc($result)) {
1872 if ($line["id"] == $default_id) {
1873 $is_selected = "selected=\"1\"";
1878 for ($i = 0; $i < $nest_level; $i++)
1879 $line["title"] = " - " . $line["title"];
1882 printf("<option $is_selected value='%d'>%s</option>",
1883 $line["id"], htmlspecialchars($line["title"]));
1885 if ($line["num_children"] > 0)
1886 print_feed_cat_select($id, $default_id, $attributes,
1887 $include_all_cats, $line["id"], $nest_level+1);
1891 if ($include_all_cats) {
1892 if (db_num_rows($result) > 0) {
1893 print "<option disabled=\"1\">--------</option>";
1896 if ($default_id == 0) {
1897 $is_selected = "selected=\"1\"";
1902 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1908 function checkbox_to_sql_bool($val) {
1909 return ($val == "on") ? "true" : "false";
1912 function getFeedCatTitle($id) {
1914 return __("Special");
1915 } else if ($id < LABEL_BASE_INDEX) {
1916 return __("Labels");
1917 } else if ($id > 0) {
1918 $result = db_query("SELECT ttrss_feed_categories.title
1919 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1920 cat_id = ttrss_feed_categories.id");
1921 if (db_num_rows($result) == 1) {
1922 return db_fetch_result($result, 0, "title");
1924 return __("Uncategorized");
1927 return "getFeedCatTitle($id) failed";
1932 function getFeedIcon($id) {
1935 return "images/archive.png";
1938 return "images/star.png";
1941 return "images/feed.png";
1944 return "images/fresh.png";
1947 return "images/folder.png";
1950 return "images/time.png";
1953 if ($id < LABEL_BASE_INDEX) {
1954 return "images/label.png";
1956 if (file_exists(ICONS_DIR . "/$id.ico"))
1957 return ICONS_URL . "/$id.ico";
1965 function getFeedTitle($id, $cat = false) {
1967 return getCategoryTitle($id);
1968 } else if ($id == 0) {
1969 return __("All feeds");
1970 } else if ($id == -1) {
1971 return __("Starred articles");
1972 } else if ($id == -2) {
1973 return __("Published articles");
1974 } else if ($id == -3) {
1975 return __("Fresh articles");
1976 } else if ($id == -4) {
1977 return __("All articles");
1978 } else if ($id === 0 || $id === "0") {
1979 return __("Archived articles");
1980 } else if ($id == -6) {
1981 return __("Recently read");
1982 } else if ($id < LABEL_BASE_INDEX) {
1983 $label_id = feed_to_label_id($id);
1984 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1985 if (db_num_rows($result) == 1) {
1986 return db_fetch_result($result, 0, "caption");
1988 return "Unknown label ($label_id)";
1991 } else if (is_numeric($id) && $id > 0) {
1992 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
1993 if (db_num_rows($result) == 1) {
1994 return db_fetch_result($result, 0, "title");
1996 return "Unknown feed ($id)";
2003 // TODO: less dumb splitting
2004 require_once "functions2.php";