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_last_error_content = false; // curl only for the time being
14 $fetch_curl_used = false;
15 $suppress_debugging = false;
17 mb_internal_encoding("UTF-8");
18 date_default_timezone_set('UTC');
19 if (defined('E_DEPRECATED')) {
20 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
22 error_reporting(E_ALL & ~E_NOTICE);
25 require_once 'config.php';
28 * Define a constant if not already defined
30 * @param string $name The constant name.
31 * @param mixed $value The constant value.
33 * @return boolean True if defined successfully or not.
35 function define_default($name, $value) {
36 defined($name) or define($name, $value);
39 ///// Some defaults that you can override in config.php //////
41 define_default('FEED_FETCH_TIMEOUT', 45);
42 // How may seconds to wait for response when requesting feed from a site
43 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
44 // How may seconds to wait for response when requesting feed from a
45 // site when that feed wasn't cached before
46 define_default('FILE_FETCH_TIMEOUT', 45);
47 // Default timeout when fetching files from remote sites
48 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
49 // How many seconds to wait for initial response from website when
50 // fetching files from remote sites
52 if (DB_TYPE == "pgsql") {
53 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
55 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
59 * Return available translations names.
62 * @return array A array of available translations.
64 function get_translations() {
66 "auto" => "Detect automatically",
67 "ar_SA" => "العربيّة (Arabic)",
72 "el_GR" => "Ελληνικά",
73 "es_ES" => "Español (España)",
76 "fr_FR" => "Français",
77 "hu_HU" => "Magyar (Hungarian)",
78 "it_IT" => "Italiano",
79 "ja_JP" => "日本語 (Japanese)",
80 "lv_LV" => "Latviešu",
81 "nb_NO" => "Norwegian bokmål",
85 "pt_BR" => "Portuguese/Brazil",
86 "pt_PT" => "Portuguese/Portugal",
87 "zh_CN" => "Simplified Chinese",
88 "zh_TW" => "Traditional Chinese",
96 require_once "lib/accept-to-gettext.php";
97 require_once "lib/gettext/gettext.inc";
99 require_once "lib/languagedetect/LanguageDetect.php";
101 function startup_gettext() {
103 # Get locale from Accept-Language header
104 $lang = al2gt(array_keys(get_translations()), "text/html");
106 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
107 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
110 if ($_SESSION["uid"] && get_schema_version() >= 120) {
111 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
113 if ($pref_lang && $pref_lang != 'auto') {
119 if (defined('LC_MESSAGES')) {
120 _setlocale(LC_MESSAGES, $lang);
121 } else if (defined('LC_ALL')) {
122 _setlocale(LC_ALL, $lang);
125 _bindtextdomain("messages", "locale");
127 _textdomain("messages");
128 _bind_textdomain_codeset("messages", "UTF-8");
132 require_once 'db-prefs.php';
133 require_once 'version.php';
134 require_once 'ccache.php';
135 require_once 'labels.php';
137 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
138 ini_set('user_agent', SELF_USER_AGENT);
140 require_once 'lib/pubsubhubbub/publisher.php';
142 $schema_version = false;
144 function _debug_suppress($suppress) {
145 global $suppress_debugging;
147 $suppress_debugging = $suppress;
151 * Print a timestamped debug message.
153 * @param string $msg The debug message.
156 function _debug($msg, $show = true) {
157 global $suppress_debugging;
159 //echo "[$suppress_debugging] $msg $show\n";
161 if ($suppress_debugging) return false;
163 $ts = strftime("%H:%M:%S", time());
164 if (function_exists('posix_getpid')) {
165 $ts = "$ts/" . posix_getpid();
168 if ($show && !(defined('QUIET') && QUIET)) {
169 print "[$ts] $msg\n";
172 if (defined('LOGFILE')) {
173 $fp = fopen(LOGFILE, 'a+');
178 if (function_exists("flock")) {
181 // try to lock logfile for writing
182 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
193 fputs($fp, "[$ts] $msg\n");
195 if (function_exists("flock")) {
206 * Purge a feed old posts.
208 * @param mixed $link A database connection.
209 * @param mixed $feed_id The id of the purged feed.
210 * @param mixed $purge_interval Olderness of purged posts.
211 * @param boolean $debug Set to True to enable the debug. False by default.
215 function purge_feed($feed_id, $purge_interval, $debug = false) {
217 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
222 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
226 if (db_num_rows($result) == 1) {
227 $owner_uid = db_fetch_result($result, 0, "owner_uid");
230 if ($purge_interval == -1 || !$purge_interval) {
232 ccache_update($feed_id, $owner_uid);
237 if (!$owner_uid) return;
239 if (FORCE_ARTICLE_PURGE == 0) {
240 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
243 $purge_unread = true;
244 $purge_interval = FORCE_ARTICLE_PURGE;
247 if (!$purge_unread) $query_limit = " unread = false AND ";
249 if (DB_TYPE == "pgsql") {
250 $pg_version = get_pgsql_version();
252 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
254 $result = db_query("DELETE FROM ttrss_user_entries WHERE
255 ttrss_entries.id = ref_id AND
257 feed_id = '$feed_id' AND
259 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
263 $result = db_query("DELETE FROM ttrss_user_entries
265 WHERE ttrss_entries.id = ref_id AND
267 feed_id = '$feed_id' AND
269 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
274 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
275 marked = false AND feed_id = '$feed_id' AND
276 (SELECT date_updated FROM ttrss_entries WHERE
277 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
279 $result = db_query("DELETE FROM ttrss_user_entries
280 USING ttrss_user_entries, ttrss_entries
281 WHERE ttrss_entries.id = ref_id AND
283 feed_id = '$feed_id' AND
285 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
288 $rows = db_affected_rows($result);
290 ccache_update($feed_id, $owner_uid);
293 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
297 } // function purge_feed
299 function feed_purge_interval($feed_id) {
301 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
302 WHERE id = '$feed_id'");
304 if (db_num_rows($result) == 1) {
305 $purge_interval = db_fetch_result($result, 0, "purge_interval");
306 $owner_uid = db_fetch_result($result, 0, "owner_uid");
308 if ($purge_interval == 0) $purge_interval = get_pref(
309 'PURGE_OLD_DAYS', $owner_uid);
311 return $purge_interval;
318 function purge_orphans($do_output = false) {
320 // purge orphaned posts in main content table
321 $result = db_query("DELETE FROM ttrss_entries WHERE
322 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
325 $rows = db_affected_rows($result);
326 _debug("Purged $rows orphaned posts.");
330 function get_feed_update_interval($feed_id) {
331 $result = db_query("SELECT owner_uid, update_interval FROM
332 ttrss_feeds WHERE id = '$feed_id'");
334 if (db_num_rows($result) == 1) {
335 $update_interval = db_fetch_result($result, 0, "update_interval");
336 $owner_uid = db_fetch_result($result, 0, "owner_uid");
338 if ($update_interval != 0) {
339 return $update_interval;
341 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
349 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0, $useragent = false) {
351 global $fetch_last_error;
352 global $fetch_last_error_code;
353 global $fetch_last_error_content;
354 global $fetch_last_content_type;
355 global $fetch_curl_used;
357 $url = ltrim($url, ' ');
358 $url = str_replace(' ', '%20', $url);
360 if (!defined('NO_CURL') && function_exists('curl_init')) {
362 $fetch_curl_used = true;
364 if (ini_get("safe_mode") || ini_get("open_basedir") || defined("FORCE_GETURL")) {
365 $new_url = geturl($url);
367 // geturl has already populated $fetch_last_error
370 $ch = curl_init($new_url);
372 $ch = curl_init($url);
375 if ($timestamp && !$post_query) {
376 curl_setopt($ch, CURLOPT_HTTPHEADER,
377 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
380 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
381 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
382 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode") && !ini_get("open_basedir"));
383 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
384 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
385 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
386 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
387 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
388 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
390 curl_setopt($ch, CURLOPT_ENCODING, "");
391 //curl_setopt($ch, CURLOPT_REFERER, $url);
393 if (!ini_get("safe_mode") && !ini_get("open_basedir")) {
394 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
397 if (defined('_CURL_HTTP_PROXY')) {
398 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
402 curl_setopt($ch, CURLOPT_POST, true);
403 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
406 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
407 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
411 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
413 $contents = @curl_exec($ch);
415 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
416 curl_setopt($ch, CURLOPT_ENCODING, 'none');
417 $contents = @curl_exec($ch);
420 if ($contents === false) {
421 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
426 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
427 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
429 $fetch_last_error_code = $http_code;
431 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
432 if (curl_errno($ch) != 0) {
433 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
435 $fetch_last_error = "HTTP Code: $http_code";
437 $fetch_last_error_content = $contents;
447 $fetch_curl_used = false;
449 if ($login && $pass){
450 $url_parts = array();
452 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
454 $pass = urlencode($pass);
456 if ($url_parts[1] && $url_parts[2]) {
457 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
461 if (!$post_query && $timestamp) {
462 $context = stream_context_create(array(
465 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
471 $old_error = error_get_last();
473 $data = @file_get_contents($url, false, $context);
475 $fetch_last_content_type = false; // reset if no type was sent from server
476 if (isset($http_response_header) && is_array($http_response_header)) {
477 foreach ($http_response_header as $h) {
478 if (substr(strtolower($h), 0, 13) == 'content-type:') {
479 $fetch_last_content_type = substr($h, 14);
480 // don't abort here b/c there might be more than one
481 // e.g. if we were being redirected -- last one is the right one
484 if (substr(strtolower($h), 0, 7) == 'http/1.') {
485 $fetch_last_error_code = (int) substr($h, 9, 3);
491 $error = error_get_last();
493 if ($error['message'] != $old_error['message']) {
494 $fetch_last_error = $error["message"];
496 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
505 * Try to determine the favicon URL for a feed.
506 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
507 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
509 * @param string $url A feed or page URL
511 * @return mixed The favicon URL, or false if none was found.
513 function get_favicon_url($url) {
515 $favicon_url = false;
517 if ($html = @fetch_file_contents($url)) {
519 libxml_use_internal_errors(true);
521 $doc = new DOMDocument();
522 $doc->loadHTML($html);
523 $xpath = new DOMXPath($doc);
525 $base = $xpath->query('/html/head/base');
526 foreach ($base as $b) {
527 $url = $b->getAttribute("href");
531 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
532 if (count($entries) > 0) {
533 foreach ($entries as $entry) {
534 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
541 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
544 } // function get_favicon_url
546 function check_feed_favicon($site_url, $feed) {
547 # print "FAVICON [$site_url]: $favicon_url\n";
549 $icon_file = ICONS_DIR . "/$feed.ico";
551 if (!file_exists($icon_file)) {
552 $favicon_url = get_favicon_url($site_url);
555 // Limiting to "image" type misses those served with text/plain
556 $contents = fetch_file_contents($favicon_url); // , "image");
559 // Crude image type matching.
560 // Patterns gleaned from the file(1) source code.
561 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
562 // 0 string \000\000\001\000 MS Windows icon resource
563 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
565 elseif (preg_match('/^GIF8/', $contents)) {
566 // 0 string GIF8 GIF image data
567 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
569 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
570 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
571 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
573 elseif (preg_match('/^\xff\xd8/', $contents)) {
574 // 0 beshort 0xffd8 JPEG image data
575 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
578 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
584 $fp = @fopen($icon_file, "w");
587 fwrite($fp, $contents);
589 chmod($icon_file, 0644);
597 function print_select($id, $default, $values, $attributes = "") {
598 print "<select name=\"$id\" id=\"$id\" $attributes>";
599 foreach ($values as $v) {
601 $sel = "selected=\"1\"";
607 print "<option value=\"$v\" $sel>$v</option>";
612 function print_select_hash($id, $default, $values, $attributes = "") {
613 print "<select name=\"$id\" id='$id' $attributes>";
614 foreach (array_keys($values) as $v) {
616 $sel = 'selected="selected"';
622 print "<option $sel value=\"$v\">".$values[$v]."</option>";
628 function print_radio($id, $default, $true_is, $values, $attributes = "") {
629 foreach ($values as $v) {
636 if ($v == $true_is) {
637 $sel .= " value=\"1\"";
639 $sel .= " value=\"0\"";
642 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
643 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
648 function initialize_user_prefs($uid, $profile = false) {
650 $uid = db_escape_string($uid);
654 $profile_qpart = "AND profile IS NULL";
656 $profile_qpart = "AND profile = '$profile'";
659 if (get_schema_version() < 63) $profile_qpart = "";
663 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
665 $u_result = db_query("SELECT pref_name
666 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
668 $active_prefs = array();
670 while ($line = db_fetch_assoc($u_result)) {
671 array_push($active_prefs, $line["pref_name"]);
674 while ($line = db_fetch_assoc($result)) {
675 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
676 // print "adding " . $line["pref_name"] . "<br>";
678 $line["def_value"] = db_escape_string($line["def_value"]);
679 $line["pref_name"] = db_escape_string($line["pref_name"]);
681 if (get_schema_version() < 63) {
682 db_query("INSERT INTO ttrss_user_prefs
683 (owner_uid,pref_name,value) VALUES
684 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
687 db_query("INSERT INTO ttrss_user_prefs
688 (owner_uid,pref_name,value, profile) VALUES
689 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
699 function get_ssl_certificate_id() {
700 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
701 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
702 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
703 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
704 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
706 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
707 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
708 $_SERVER["SSL_CLIENT_V_START"] .
709 $_SERVER["SSL_CLIENT_V_END"] .
710 $_SERVER["SSL_CLIENT_S_DN"]);
715 function authenticate_user($login, $password, $check_only = false) {
717 if (!SINGLE_USER_MODE) {
720 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
722 $user_id = (int) $plugin->authenticate($login, $password);
725 $_SESSION["auth_module"] = strtolower(get_class($plugin));
730 if ($user_id && !$check_only) {
733 $_SESSION["uid"] = $user_id;
734 $_SESSION["version"] = VERSION_STATIC;
736 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
737 WHERE id = '$user_id'");
739 $_SESSION["name"] = db_fetch_result($result, 0, "login");
740 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
741 $_SESSION["csrf_token"] = uniqid(rand(), true);
743 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
746 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
747 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
748 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
750 $_SESSION["last_version_check"] = time();
752 initialize_user_prefs($_SESSION["uid"]);
761 $_SESSION["uid"] = 1;
762 $_SESSION["name"] = "admin";
763 $_SESSION["access_level"] = 10;
765 $_SESSION["hide_hello"] = true;
766 $_SESSION["hide_logout"] = true;
768 $_SESSION["auth_module"] = false;
770 if (!$_SESSION["csrf_token"]) {
771 $_SESSION["csrf_token"] = uniqid(rand(), true);
774 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
776 initialize_user_prefs($_SESSION["uid"]);
782 function make_password($length = 8) {
785 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
789 while ($i < $length) {
790 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
792 if (!strstr($password, $char)) {
800 // this is called after user is created to initialize default feeds, labels
803 // user preferences are checked on every login, not here
805 function initialize_user($uid) {
807 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
808 values ('$uid', 'Tiny Tiny RSS: New Releases',
809 'http://tt-rss.org/releases.rss')");
811 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
812 values ('$uid', 'Tiny Tiny RSS: Forum',
813 'http://tt-rss.org/forum/rss.php')");
816 function logout_user() {
818 if (isset($_COOKIE[session_name()])) {
819 setcookie(session_name(), '', time()-42000, '/');
823 function validate_csrf($csrf_token) {
824 return $csrf_token == $_SESSION['csrf_token'];
827 function load_user_plugins($owner_uid) {
828 if ($owner_uid && SCHEMA_VERSION >= 100) {
829 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
831 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
833 if (get_schema_version() > 100) {
834 PluginHost::getInstance()->load_data();
839 function login_sequence() {
840 if (SINGLE_USER_MODE) {
842 authenticate_user("admin", null);
844 load_user_plugins($_SESSION["uid"]);
846 if (!validate_session()) $_SESSION["uid"] = false;
848 if (!$_SESSION["uid"]) {
850 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
851 $_SESSION["ref_schema_version"] = get_schema_version(true);
853 authenticate_user(null, null, true);
856 if (!$_SESSION["uid"]) {
858 setcookie(session_name(), '', time()-42000, '/');
865 /* bump login timestamp */
866 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
868 $_SESSION["last_login_update"] = time();
871 if ($_SESSION["uid"]) {
873 load_user_plugins($_SESSION["uid"]);
877 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
878 $_SESSION["uid"] . " AND
879 (SELECT COUNT(id) FROM ttrss_feeds WHERE
880 ttrss_feeds.id = feed_id) = 0");
882 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
883 $_SESSION["uid"] . " AND
884 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
885 ttrss_feed_categories.id = feed_id) = 0");
892 function truncate_string($str, $max_len, $suffix = '…') {
893 if (mb_strlen($str, "utf-8") > $max_len) {
894 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
900 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
903 $source_tz = new DateTimeZone($source_tz);
904 } catch (Exception $e) {
905 $source_tz = new DateTimeZone('UTC');
909 $dest_tz = new DateTimeZone($dest_tz);
910 } catch (Exception $e) {
911 $dest_tz = new DateTimeZone('UTC');
914 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
915 return $dt->format('U') + $dest_tz->getOffset($dt);
918 function make_local_datetime($timestamp, $long, $owner_uid = false,
919 $no_smart_dt = false) {
921 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
922 if (!$timestamp) $timestamp = '1970-01-01 0:00';
927 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
929 $timestamp = substr($timestamp, 0, 19);
931 # We store date in UTC internally
932 $dt = new DateTime($timestamp, $utc_tz);
934 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
936 if ($user_tz_string != 'Automatic') {
939 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
940 } catch (Exception $e) {
944 $tz_offset = $user_tz->getOffset($dt);
946 $tz_offset = (int) -$_SESSION["clientTzOffset"];
949 $user_timestamp = $dt->format('U') + $tz_offset;
952 return smart_date_time($user_timestamp,
953 $tz_offset, $owner_uid);
956 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
958 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
960 return date($format, $user_timestamp);
964 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false) {
965 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
967 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
968 return date("G:i", $timestamp);
969 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
970 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
971 return date($format, $timestamp);
973 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
974 return date($format, $timestamp);
978 function sql_bool_to_bool($s) {
979 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
986 function bool_to_sql_bool($s) {
994 // Session caching removed due to causing wrong redirects to upgrade
995 // script when get_schema_version() is called on an obsolete session
996 // created on a previous schema version.
997 function get_schema_version($nocache = false) {
998 global $schema_version;
1000 if (!$schema_version && !$nocache) {
1001 $result = db_query("SELECT schema_version FROM ttrss_version");
1002 $version = db_fetch_result($result, 0, "schema_version");
1003 $schema_version = $version;
1006 return $schema_version;
1010 function sanity_check() {
1011 require_once 'errors.php';
1015 $schema_version = get_schema_version(true);
1017 if ($schema_version != SCHEMA_VERSION) {
1021 if (DB_TYPE == "mysql") {
1022 $result = db_query("SELECT true", false);
1023 if (db_num_rows($result) != 1) {
1028 if (db_escape_string("testTEST") != "testTEST") {
1032 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1035 function file_is_locked($filename) {
1036 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1037 if (function_exists('flock')) {
1038 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1040 if (flock($fp, LOCK_EX | LOCK_NB)) {
1041 flock($fp, LOCK_UN);
1051 return true; // consider the file always locked and skip the test
1058 function make_lockfile($filename) {
1059 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1061 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1062 $stat_h = fstat($fp);
1063 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1065 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1066 if ($stat_h["ino"] != $stat_f["ino"] ||
1067 $stat_h["dev"] != $stat_f["dev"]) {
1073 if (function_exists('posix_getpid')) {
1074 fwrite($fp, posix_getpid() . "\n");
1082 function make_stampfile($filename) {
1083 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1085 if (flock($fp, LOCK_EX | LOCK_NB)) {
1086 fwrite($fp, time() . "\n");
1087 flock($fp, LOCK_UN);
1095 function sql_random_function() {
1096 if (DB_TYPE == "mysql") {
1103 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1105 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1107 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1109 // Todo: all this interval stuff needs some generic generator function
1111 $date_qpart = "false";
1115 if (DB_TYPE == "pgsql") {
1116 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1118 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1122 if (DB_TYPE == "pgsql") {
1123 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1125 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1129 if (DB_TYPE == "pgsql") {
1130 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1132 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1136 $date_qpart = "true";
1139 if (is_numeric($feed)) {
1145 $children = getChildCategories($feed, $owner_uid);
1146 array_push($children, $feed);
1148 $children = join(",", $children);
1150 $cat_qpart = "cat_id IN ($children)";
1152 $cat_qpart = "cat_id IS NULL";
1155 db_query("UPDATE ttrss_user_entries
1156 SET unread = false, last_read = NOW() WHERE ref_id IN
1158 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1159 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1160 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1162 } else if ($feed == -2) {
1164 db_query("UPDATE ttrss_user_entries
1165 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1166 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1167 AND unread = true AND owner_uid = $owner_uid");
1170 } else if ($feed > 0) {
1172 db_query("UPDATE ttrss_user_entries
1173 SET unread = false, last_read = NOW() WHERE ref_id IN
1175 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1176 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1178 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
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 marked = true AND $date_qpart) as tmp)");
1189 db_query("UPDATE ttrss_user_entries
1190 SET unread = false, last_read = NOW() WHERE ref_id IN
1192 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1193 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1198 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1200 if (DB_TYPE == "pgsql") {
1201 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1203 $match_part = "date_entered > DATE_SUB(NOW(),
1204 INTERVAL $intl HOUR) ";
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 score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1215 db_query("UPDATE ttrss_user_entries
1216 SET unread = false, last_read = NOW() WHERE ref_id IN
1218 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1219 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1222 } else if ($feed < LABEL_BASE_INDEX) { // label
1224 $label_id = feed_to_label_id($feed);
1226 db_query("UPDATE ttrss_user_entries
1227 SET unread = false, last_read = NOW() WHERE ref_id IN
1229 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1230 AND label_id = '$label_id' AND ref_id = article_id
1231 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1235 ccache_update($feed, $owner_uid, $cat_view);
1238 db_query("UPDATE ttrss_user_entries
1239 SET unread = false, last_read = NOW() WHERE ref_id IN
1241 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1242 AND post_int_id = int_id AND tag_name = '$feed'
1243 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1248 function getAllCounters() {
1249 $data = getGlobalCounters();
1251 $data = array_merge($data, getVirtCounters());
1252 $data = array_merge($data, getLabelCounters());
1253 $data = array_merge($data, getFeedCounters());
1254 $data = array_merge($data, getCategoryCounters());
1259 function getCategoryTitle($cat_id) {
1261 if ($cat_id == -1) {
1262 return __("Special");
1263 } else if ($cat_id == -2) {
1264 return __("Labels");
1267 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1270 if (db_num_rows($result) == 1) {
1271 return db_fetch_result($result, 0, "title");
1273 return __("Uncategorized");
1279 function getCategoryCounters() {
1282 /* Labels category */
1284 $cv = array("id" => -2, "kind" => "cat",
1285 "counter" => getCategoryUnread(-2));
1287 array_push($ret_arr, $cv);
1289 $result = db_query("SELECT id AS cat_id, value AS unread,
1290 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1291 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1292 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1293 WHERE ttrss_cat_counters_cache.feed_id = id AND
1294 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1295 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1297 while ($line = db_fetch_assoc($result)) {
1298 $line["cat_id"] = (int) $line["cat_id"];
1300 if ($line["num_children"] > 0) {
1301 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1306 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1307 "counter" => $line["unread"] + $child_counter);
1309 array_push($ret_arr, $cv);
1312 /* Special case: NULL category doesn't actually exist in the DB */
1314 $cv = array("id" => 0, "kind" => "cat",
1315 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1317 array_push($ret_arr, $cv);
1322 // only accepts real cats (>= 0)
1323 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1324 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1326 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1327 AND owner_uid = $owner_uid");
1331 while ($line = db_fetch_assoc($result)) {
1332 $unread += getCategoryUnread($line["id"], $owner_uid);
1333 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1339 function getCategoryUnread($cat, $owner_uid = false) {
1341 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1346 $cat_query = "cat_id = '$cat'";
1348 $cat_query = "cat_id IS NULL";
1351 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1352 AND owner_uid = " . $owner_uid);
1354 $cat_feeds = array();
1355 while ($line = db_fetch_assoc($result)) {
1356 array_push($cat_feeds, "feed_id = " . $line["id"]);
1359 if (count($cat_feeds) == 0) return 0;
1361 $match_part = implode(" OR ", $cat_feeds);
1363 $result = db_query("SELECT COUNT(int_id) AS unread
1364 FROM ttrss_user_entries
1365 WHERE unread = true AND ($match_part)
1366 AND owner_uid = " . $owner_uid);
1370 # this needs to be rewritten
1371 while ($line = db_fetch_assoc($result)) {
1372 $unread += $line["unread"];
1376 } else if ($cat == -1) {
1377 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1378 } else if ($cat == -2) {
1380 $result = db_query("
1381 SELECT COUNT(unread) AS unread FROM
1382 ttrss_user_entries, ttrss_user_labels2
1383 WHERE article_id = ref_id AND unread = true
1384 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1386 $unread = db_fetch_result($result, 0, "unread");
1393 function getFeedUnread($feed, $is_cat = false) {
1394 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1397 function getLabelUnread($label_id, $owner_uid = false) {
1398 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1400 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1401 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1403 if (db_num_rows($result) != 0) {
1404 return db_fetch_result($result, 0, "unread");
1410 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1411 $owner_uid = false) {
1413 $n_feed = (int) $feed;
1414 $need_entries = false;
1416 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1419 $unread_qpart = "unread = true";
1421 $unread_qpart = "true";
1425 return getCategoryUnread($n_feed, $owner_uid);
1426 } else if ($n_feed == -6) {
1428 } else if ($feed != "0" && $n_feed == 0) {
1430 $feed = db_escape_string($feed);
1432 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1433 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1434 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1435 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1436 return db_fetch_result($result, 0, "count");
1438 } else if ($n_feed == -1) {
1439 $match_part = "marked = true";
1440 } else if ($n_feed == -2) {
1441 $match_part = "published = true";
1442 } else if ($n_feed == -3) {
1443 $match_part = "unread = true AND score >= 0";
1445 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1447 if (DB_TYPE == "pgsql") {
1448 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1450 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1453 $need_entries = true;
1455 } else if ($n_feed == -4) {
1456 $match_part = "true";
1457 } else if ($n_feed >= 0) {
1460 $match_part = "feed_id = '$n_feed'";
1462 $match_part = "feed_id IS NULL";
1465 } else if ($feed < LABEL_BASE_INDEX) {
1467 $label_id = feed_to_label_id($feed);
1469 return getLabelUnread($label_id, $owner_uid);
1475 if ($need_entries) {
1476 $from_qpart = "ttrss_user_entries,ttrss_entries";
1477 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1479 $from_qpart = "ttrss_user_entries";
1483 $query = "SELECT count(int_id) AS unread
1484 FROM $from_qpart WHERE
1485 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1487 //echo "[$feed/$query]\n";
1489 $result = db_query($query);
1493 $result = db_query("SELECT COUNT(post_int_id) AS unread
1494 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1495 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1496 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1499 $unread = db_fetch_result($result, 0, "unread");
1504 function getGlobalUnread($user_id = false) {
1507 $user_id = $_SESSION["uid"];
1510 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1511 WHERE owner_uid = '$user_id' AND feed_id > 0");
1513 $c_id = db_fetch_result($result, 0, "c_id");
1518 function getGlobalCounters($global_unread = -1) {
1521 if ($global_unread == -1) {
1522 $global_unread = getGlobalUnread();
1525 $cv = array("id" => "global-unread",
1526 "counter" => (int) $global_unread);
1528 array_push($ret_arr, $cv);
1530 $result = db_query("SELECT COUNT(id) AS fn FROM
1531 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1533 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1535 $cv = array("id" => "subscribed-feeds",
1536 "counter" => (int) $subscribed_feeds);
1538 array_push($ret_arr, $cv);
1543 function getVirtCounters() {
1547 for ($i = 0; $i >= -4; $i--) {
1549 $count = getFeedUnread($i);
1551 if ($i == 0 || $i == -1 || $i == -2)
1552 $auxctr = getFeedArticles($i, false);
1556 $cv = array("id" => $i,
1557 "counter" => (int) $count,
1558 "auxcounter" => $auxctr);
1560 // if (get_pref('EXTENDED_FEEDLIST'))
1561 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1563 array_push($ret_arr, $cv);
1566 $feeds = PluginHost::getInstance()->get_feeds(-1);
1568 if (is_array($feeds)) {
1569 foreach ($feeds as $feed) {
1570 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1571 "counter" => $feed['sender']->get_unread($feed['id']));
1573 if (method_exists($feed['sender'], 'get_total'))
1574 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1576 array_push($ret_arr, $cv);
1583 function getLabelCounters($descriptions = false) {
1587 $owner_uid = $_SESSION["uid"];
1589 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1590 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1591 (ttrss_labels2.id = label_id)
1592 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1593 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1594 ttrss_labels2.caption");
1596 while ($line = db_fetch_assoc($result)) {
1598 $id = label_to_feed_id($line["id"]);
1600 $cv = array("id" => $id,
1601 "counter" => (int) $line["unread"],
1602 "auxcounter" => (int) $line["total"]);
1605 $cv["description"] = $line["caption"];
1607 array_push($ret_arr, $cv);
1613 function getFeedCounters($active_feed = false) {
1617 $query = "SELECT ttrss_feeds.id,
1619 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1620 last_error, value AS count
1621 FROM ttrss_feeds, ttrss_counters_cache
1622 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1623 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1624 AND ttrss_counters_cache.feed_id = id";
1626 $result = db_query($query);
1628 while ($line = db_fetch_assoc($result)) {
1631 $count = $line["count"];
1632 $last_error = htmlspecialchars($line["last_error"]);
1634 $last_updated = make_local_datetime($line['last_updated'], false);
1636 $has_img = feed_has_icon($id);
1638 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1641 $cv = array("id" => $id,
1642 "updated" => $last_updated,
1643 "counter" => (int) $count,
1644 "has_img" => (int) $has_img);
1647 $cv["error"] = $last_error;
1649 // if (get_pref('EXTENDED_FEEDLIST'))
1650 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1652 if ($active_feed && $id == $active_feed)
1653 $cv["title"] = truncate_string($line["title"], 30);
1655 array_push($ret_arr, $cv);
1662 function get_pgsql_version() {
1663 $result = db_query("SELECT version() AS version");
1664 $version = explode(" ", db_fetch_result($result, 0, "version"));
1669 * @return array (code => Status code, message => error message if available)
1671 * 0 - OK, Feed already exists
1672 * 1 - OK, Feed added
1674 * 3 - URL content is HTML, no feeds available
1675 * 4 - URL content is HTML which contains multiple feeds.
1676 * Here you should call extractfeedurls in rpc-backend
1677 * to get all possible feeds.
1678 * 5 - Couldn't download the URL content.
1679 * 6 - Content is an invalid XML.
1681 function subscribe_to_feed($url, $cat_id = 0,
1682 $auth_login = '', $auth_pass = '') {
1684 global $fetch_last_error;
1686 require_once "include/rssfuncs.php";
1688 $url = fix_url($url);
1690 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1692 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1695 return array("code" => 5, "message" => $fetch_last_error);
1698 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1699 $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1702 if (is_html($contents)) {
1703 $feedUrls = get_feeds_from_html($url, $contents);
1705 if (count($feedUrls) == 0) {
1706 return array("code" => 3);
1707 } else if (count($feedUrls) > 1) {
1708 return array("code" => 4, "feeds" => $feedUrls);
1710 //use feed url as new URL
1711 $url = key($feedUrls);
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 == -1) {
1969 return __("Starred articles");
1970 } else if ($id == -2) {
1971 return __("Published articles");
1972 } else if ($id == -3) {
1973 return __("Fresh articles");
1974 } else if ($id == -4) {
1975 return __("All articles");
1976 } else if ($id === 0 || $id === "0") {
1977 return __("Archived articles");
1978 } else if ($id == -6) {
1979 return __("Recently read");
1980 } else if ($id < LABEL_BASE_INDEX) {
1981 $label_id = feed_to_label_id($id);
1982 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1983 if (db_num_rows($result) == 1) {
1984 return db_fetch_result($result, 0, "caption");
1986 return "Unknown label ($label_id)";
1989 } else if (is_numeric($id) && $id > 0) {
1990 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
1991 if (db_num_rows($result) == 1) {
1992 return db_fetch_result($result, 0, "title");
1994 return "Unknown feed ($id)";
2001 // TODO: less dumb splitting
2002 require_once "functions2.php";