2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 130);
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 libxml_disable_entity_loader(true);
19 // separate test because this is included before sanity checks
20 if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
22 date_default_timezone_set('UTC');
23 if (defined('E_DEPRECATED')) {
24 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
26 error_reporting(E_ALL
& ~E_NOTICE
);
29 require_once 'config.php';
32 * Define a constant if not already defined
34 * @param string $name The constant name.
35 * @param mixed $value The constant value.
37 * @return boolean True if defined successfully or not.
39 function define_default($name, $value) {
40 defined($name) or define($name, $value);
43 ///// Some defaults that you can override in config.php //////
45 define_default('FEED_FETCH_TIMEOUT', 45);
46 // How may seconds to wait for response when requesting feed from a site
47 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
48 // How may seconds to wait for response when requesting feed from a
49 // site when that feed wasn't cached before
50 define_default('FILE_FETCH_TIMEOUT', 45);
51 // Default timeout when fetching files from remote sites
52 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
53 // How many seconds to wait for initial response from website when
54 // fetching files from remote sites
56 if (DB_TYPE
== "pgsql") {
57 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
59 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
63 * Return available translations names.
66 * @return array A array of available translations.
68 function get_translations() {
70 "auto" => "Detect automatically",
71 "ar_SA" => "العربيّة (Arabic)",
72 "bg_BG" => "Bulgarian",
77 "el_GR" => "Ελληνικά",
78 "es_ES" => "Español (España)",
81 "fr_FR" => "Français",
82 "hu_HU" => "Magyar (Hungarian)",
83 "it_IT" => "Italiano",
84 "ja_JP" => "日本語 (Japanese)",
85 "lv_LV" => "Latviešu",
86 "nb_NO" => "Norwegian bokmål",
90 "pt_BR" => "Portuguese/Brazil",
91 "pt_PT" => "Portuguese/Portugal",
92 "zh_CN" => "Simplified Chinese",
93 "zh_TW" => "Traditional Chinese",
101 require_once "lib/accept-to-gettext.php";
102 require_once "lib/gettext/gettext.inc";
104 function startup_gettext() {
106 # Get locale from Accept-Language header
107 $lang = al2gt(array_keys(get_translations()), "text/html");
109 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
110 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
113 if ($_SESSION["uid"] && get_schema_version() >= 120) {
114 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
116 if ($pref_lang && $pref_lang != 'auto') {
122 if (defined('LC_MESSAGES')) {
123 _setlocale(LC_MESSAGES
, $lang);
124 } else if (defined('LC_ALL')) {
125 _setlocale(LC_ALL
, $lang);
128 _bindtextdomain("messages", "locale");
130 _textdomain("messages");
131 _bind_textdomain_codeset("messages", "UTF-8");
135 require_once 'db-prefs.php';
136 require_once 'version.php';
137 require_once 'ccache.php';
138 require_once 'labels.php';
139 require_once 'controls.php';
141 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
142 ini_set('user_agent', SELF_USER_AGENT
);
144 require_once 'lib/pubsubhubbub/Publisher.php';
146 $schema_version = false;
148 function _debug_suppress($suppress) {
149 global $suppress_debugging;
151 $suppress_debugging = $suppress;
155 * Print a timestamped debug message.
157 * @param string $msg The debug message.
160 function _debug($msg, $show = true) {
161 global $suppress_debugging;
163 //echo "[$suppress_debugging] $msg $show\n";
165 if ($suppress_debugging) return false;
167 $ts = strftime("%H:%M:%S", time());
168 if (function_exists('posix_getpid')) {
169 $ts = "$ts/" . posix_getpid();
172 if ($show && !(defined('QUIET') && QUIET
)) {
173 print "[$ts] $msg\n";
176 if (defined('LOGFILE')) {
177 $fp = fopen(LOGFILE
, 'a+');
182 if (function_exists("flock")) {
185 // try to lock logfile for writing
186 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB
)) {
197 fputs($fp, "[$ts] $msg\n");
199 if (function_exists("flock")) {
210 * Purge a feed old posts.
212 * @param mixed $link A database connection.
213 * @param mixed $feed_id The id of the purged feed.
214 * @param mixed $purge_interval Olderness of purged posts.
215 * @param boolean $debug Set to True to enable the debug. False by default.
219 function purge_feed($feed_id, $purge_interval, $debug = false) {
221 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
226 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
230 if (db_num_rows($result) == 1) {
231 $owner_uid = db_fetch_result($result, 0, "owner_uid");
234 if ($purge_interval == -1 ||
!$purge_interval) {
236 ccache_update($feed_id, $owner_uid);
241 if (!$owner_uid) return;
243 if (FORCE_ARTICLE_PURGE
== 0) {
244 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
247 $purge_unread = true;
248 $purge_interval = FORCE_ARTICLE_PURGE
;
251 if (!$purge_unread) $query_limit = " unread = false AND ";
253 if (DB_TYPE
== "pgsql") {
254 $result = db_query("DELETE FROM ttrss_user_entries
256 WHERE ttrss_entries.id = ref_id AND
258 feed_id = '$feed_id' AND
260 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
264 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
265 marked = false AND feed_id = '$feed_id' AND
266 (SELECT date_updated FROM ttrss_entries WHERE
267 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
269 $result = db_query("DELETE FROM ttrss_user_entries
270 USING ttrss_user_entries, ttrss_entries
271 WHERE ttrss_entries.id = ref_id AND
273 feed_id = '$feed_id' AND
275 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
278 $rows = db_affected_rows($result);
280 ccache_update($feed_id, $owner_uid);
283 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
287 } // function purge_feed
289 function feed_purge_interval($feed_id) {
291 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
292 WHERE id = '$feed_id'");
294 if (db_num_rows($result) == 1) {
295 $purge_interval = db_fetch_result($result, 0, "purge_interval");
296 $owner_uid = db_fetch_result($result, 0, "owner_uid");
298 if ($purge_interval == 0) $purge_interval = get_pref(
299 'PURGE_OLD_DAYS', $owner_uid);
301 return $purge_interval;
308 function purge_orphans($do_output = false) {
310 // purge orphaned posts in main content table
311 $result = db_query("DELETE FROM ttrss_entries WHERE
312 NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id)");
315 $rows = db_affected_rows($result);
316 _debug("Purged $rows orphaned posts.");
320 function get_feed_update_interval($feed_id) {
321 $result = db_query("SELECT owner_uid, update_interval FROM
322 ttrss_feeds WHERE id = '$feed_id'");
324 if (db_num_rows($result) == 1) {
325 $update_interval = db_fetch_result($result, 0, "update_interval");
326 $owner_uid = db_fetch_result($result, 0, "owner_uid");
328 if ($update_interval != 0) {
329 return $update_interval;
331 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
339 // TODO: multiple-argument way is deprecated, first parameter is a hash now
340 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
341 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
343 global $fetch_last_error;
344 global $fetch_last_error_code;
345 global $fetch_last_error_content;
346 global $fetch_last_content_type;
347 global $fetch_curl_used;
349 $fetch_last_error = false;
350 $fetch_last_error_code = -1;
351 $fetch_last_error_content = "";
352 $fetch_last_content_type = "";
353 $fetch_curl_used = false;
355 if (!is_array($options)) {
357 // falling back on compatibility shim
358 $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
361 for ($i = 0; $i < func_num_args(); $i++
) {
362 $tmp[$option_names[$i]] = func_get_arg($i);
368 "url" => func_get_arg(0),
369 "type" => @func_get_arg(1),
370 "login" => @func_get_arg(2),
371 "pass" => @func_get_arg(3),
372 "post_query" => @func_get_arg(4),
373 "timeout" => @func_get_arg(5),
374 "timestamp" => @func_get_arg(6),
375 "useragent" => @func_get_arg(7)
379 $url = $options["url"];
380 $type = isset($options["type"]) ?
$options["type"] : false;
381 $login = isset($options["login"]) ?
$options["login"] : false;
382 $pass = isset($options["pass"]) ?
$options["pass"] : false;
383 $post_query = isset($options["post_query"]) ?
$options["post_query"] : false;
384 $timeout = isset($options["timeout"]) ?
$options["timeout"] : false;
385 $timestamp = isset($options["timestamp"]) ?
$options["timestamp"] : 0;
386 $useragent = isset($options["useragent"]) ?
$options["useragent"] : false;
387 $followlocation = isset($options["followlocation"]) ?
$options["followlocation"] : true;
389 $url = ltrim($url, ' ');
390 $url = str_replace(' ', '%20', $url);
392 if (strpos($url, "//") === 0)
393 $url = 'http:' . $url;
395 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
397 $fetch_curl_used = true;
399 $ch = curl_init($url);
401 if ($timestamp && !$post_query) {
402 curl_setopt($ch, CURLOPT_HTTPHEADER
,
403 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
406 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $timeout ?
$timeout : FILE_FETCH_CONNECT_TIMEOUT
);
407 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout ?
$timeout : FILE_FETCH_TIMEOUT
);
408 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir") && $followlocation);
409 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
410 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
411 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
412 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
413 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent ?
$useragent :
415 curl_setopt($ch, CURLOPT_ENCODING
, "");
416 //curl_setopt($ch, CURLOPT_REFERER, $url);
418 if (!ini_get("open_basedir")) {
419 curl_setopt($ch, CURLOPT_COOKIEJAR
, "/dev/null");
422 if (defined('_CURL_HTTP_PROXY')) {
423 curl_setopt($ch, CURLOPT_PROXY
, _CURL_HTTP_PROXY
);
427 curl_setopt($ch, CURLOPT_POST
, true);
428 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
432 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
434 $contents = @curl_exec
($ch);
436 if (curl_errno($ch) === 23 ||
curl_errno($ch) === 61) {
437 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
438 $contents = @curl_exec
($ch);
441 if ($contents === false) {
442 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
447 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
448 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
450 $fetch_last_error_code = $http_code;
452 if ($http_code != 200 ||
$type && strpos($fetch_last_content_type, "$type") === false) {
453 if (curl_errno($ch) != 0) {
454 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
456 $fetch_last_error = "HTTP Code: $http_code";
458 $fetch_last_error_content = $contents;
468 $fetch_curl_used = false;
470 if ($login && $pass){
471 $url_parts = array();
473 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
475 $pass = urlencode($pass);
477 if ($url_parts[1] && $url_parts[2]) {
478 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
482 // TODO: should this support POST requests or not? idk
484 if (!$post_query && $timestamp) {
485 $context = stream_context_create(array(
488 'ignore_errors' => true,
489 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
490 'protocol_version'=> 1.1,
491 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
494 $context = stream_context_create(array(
497 'ignore_errors' => true,
498 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
499 'protocol_version'=> 1.1
503 $old_error = error_get_last();
505 $data = @file_get_contents
($url, false, $context);
507 if (isset($http_response_header) && is_array($http_response_header)) {
508 foreach ($http_response_header as $h) {
509 if (substr(strtolower($h), 0, 13) == 'content-type:') {
510 $fetch_last_content_type = substr($h, 14);
511 // don't abort here b/c there might be more than one
512 // e.g. if we were being redirected -- last one is the right one
515 if (substr(strtolower($h), 0, 7) == 'http/1.') {
516 $fetch_last_error_code = (int) substr($h, 9, 3);
521 if ($fetch_last_error_code != 200) {
522 $error = error_get_last();
524 if ($error['message'] != $old_error['message']) {
525 $fetch_last_error = $error["message"];
527 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
530 $fetch_last_error_content = $data;
540 * Try to determine the favicon URL for a feed.
541 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
542 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
544 * @param string $url A feed or page URL
546 * @return mixed The favicon URL, or false if none was found.
548 function get_favicon_url($url) {
550 $favicon_url = false;
552 if ($html = @fetch_file_contents
($url)) {
554 libxml_use_internal_errors(true);
556 $doc = new DOMDocument();
557 $doc->loadHTML($html);
558 $xpath = new DOMXPath($doc);
560 $base = $xpath->query('/html/head/base');
561 foreach ($base as $b) {
562 $url = $b->getAttribute("href");
566 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
567 if (count($entries) > 0) {
568 foreach ($entries as $entry) {
569 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
576 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
579 } // function get_favicon_url
581 function check_feed_favicon($site_url, $feed) {
582 # print "FAVICON [$site_url]: $favicon_url\n";
584 $icon_file = ICONS_DIR
. "/$feed.ico";
586 if (!file_exists($icon_file)) {
587 $favicon_url = get_favicon_url($site_url);
590 // Limiting to "image" type misses those served with text/plain
591 $contents = fetch_file_contents($favicon_url); // , "image");
594 // Crude image type matching.
595 // Patterns gleaned from the file(1) source code.
596 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
597 // 0 string \000\000\001\000 MS Windows icon resource
598 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
600 elseif (preg_match('/^GIF8/', $contents)) {
601 // 0 string GIF8 GIF image data
602 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
604 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
605 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
606 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
608 elseif (preg_match('/^\xff\xd8/', $contents)) {
609 // 0 beshort 0xffd8 JPEG image data
610 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
613 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
619 $fp = @fopen
($icon_file, "w");
622 fwrite($fp, $contents);
624 chmod($icon_file, 0644);
632 function initialize_user_prefs($uid, $profile = false) {
634 $uid = db_escape_string($uid);
638 $profile_qpart = "AND profile IS NULL";
640 $profile_qpart = "AND profile = '$profile'";
643 if (get_schema_version() < 63) $profile_qpart = "";
647 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
649 $u_result = db_query("SELECT pref_name
650 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
652 $active_prefs = array();
654 while ($line = db_fetch_assoc($u_result)) {
655 array_push($active_prefs, $line["pref_name"]);
658 while ($line = db_fetch_assoc($result)) {
659 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
660 // print "adding " . $line["pref_name"] . "<br>";
662 $line["def_value"] = db_escape_string($line["def_value"]);
663 $line["pref_name"] = db_escape_string($line["pref_name"]);
665 if (get_schema_version() < 63) {
666 db_query("INSERT INTO ttrss_user_prefs
667 (owner_uid,pref_name,value) VALUES
668 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
671 db_query("INSERT INTO ttrss_user_prefs
672 (owner_uid,pref_name,value, profile) VALUES
673 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
683 function get_ssl_certificate_id() {
684 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
685 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
686 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
687 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
688 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
690 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
691 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
692 $_SERVER["SSL_CLIENT_V_START"] .
693 $_SERVER["SSL_CLIENT_V_END"] .
694 $_SERVER["SSL_CLIENT_S_DN"]);
699 function authenticate_user($login, $password, $check_only = false) {
701 if (!SINGLE_USER_MODE
) {
704 foreach (PluginHost
::getInstance()->get_hooks(PluginHost
::HOOK_AUTH_USER
) as $plugin) {
706 $user_id = (int) $plugin->authenticate($login, $password);
709 $_SESSION["auth_module"] = strtolower(get_class($plugin));
714 if ($user_id && !$check_only) {
717 $_SESSION["uid"] = $user_id;
718 $_SESSION["version"] = VERSION_STATIC
;
720 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
721 WHERE id = '$user_id'");
723 $_SESSION["name"] = db_fetch_result($result, 0, "login");
724 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
725 $_SESSION["csrf_token"] = uniqid_short();
727 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
730 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
731 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
732 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
734 $_SESSION["last_version_check"] = time();
736 initialize_user_prefs($_SESSION["uid"]);
745 $_SESSION["uid"] = 1;
746 $_SESSION["name"] = "admin";
747 $_SESSION["access_level"] = 10;
749 $_SESSION["hide_hello"] = true;
750 $_SESSION["hide_logout"] = true;
752 $_SESSION["auth_module"] = false;
754 if (!$_SESSION["csrf_token"]) {
755 $_SESSION["csrf_token"] = uniqid_short();
758 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
760 initialize_user_prefs($_SESSION["uid"]);
766 function make_password($length = 8) {
769 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
773 while ($i < $length) {
774 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
776 if (!strstr($password, $char)) {
784 // this is called after user is created to initialize default feeds, labels
787 // user preferences are checked on every login, not here
789 function initialize_user($uid) {
791 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
792 values ('$uid', 'Tiny Tiny RSS: Forum',
793 'http://tt-rss.org/forum/rss.php')");
796 function logout_user() {
798 if (isset($_COOKIE[session_name()])) {
799 setcookie(session_name(), '', time()-42000, '/');
803 function validate_csrf($csrf_token) {
804 return $csrf_token == $_SESSION['csrf_token'];
807 function load_user_plugins($owner_uid, $pluginhost = false) {
809 if (!$pluginhost) $pluginhost = PluginHost
::getInstance();
811 if ($owner_uid && SCHEMA_VERSION
>= 100) {
812 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
814 $pluginhost->load($plugins, PluginHost
::KIND_USER
, $owner_uid);
816 if (get_schema_version() > 100) {
817 $pluginhost->load_data();
822 function login_sequence() {
823 if (SINGLE_USER_MODE
) {
825 authenticate_user("admin", null);
827 load_user_plugins($_SESSION["uid"]);
829 if (!validate_session()) $_SESSION["uid"] = false;
831 if (!$_SESSION["uid"]) {
833 if (AUTH_AUTO_LOGIN
&& authenticate_user(null, null)) {
834 $_SESSION["ref_schema_version"] = get_schema_version(true);
836 authenticate_user(null, null, true);
839 if (!$_SESSION["uid"]) {
841 setcookie(session_name(), '', time()-42000, '/');
848 /* bump login timestamp */
849 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
851 $_SESSION["last_login_update"] = time();
854 if ($_SESSION["uid"]) {
856 load_user_plugins($_SESSION["uid"]);
860 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
861 $_SESSION["uid"] . " AND
862 (SELECT COUNT(id) FROM ttrss_feeds WHERE
863 ttrss_feeds.id = feed_id) = 0");
865 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
866 $_SESSION["uid"] . " AND
867 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
868 ttrss_feed_categories.id = feed_id) = 0");
875 function truncate_string($str, $max_len, $suffix = '…') {
876 if (mb_strlen($str, "utf-8") > $max_len) {
877 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
884 function truncate_middle($str, $max_len, $suffix = '…') {
885 if (strlen($str) > $max_len) {
886 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
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, $eta_min = 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, $eta_min);
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, $eta_min = false) {
957 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
959 if ($eta_min && time() +
$tz_offset - $timestamp < 3600) {
960 return T_sprintf("%d min", date("i", time() +
$tz_offset - $timestamp));
961 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
962 return date("G:i", $timestamp);
963 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
964 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
965 return date($format, $timestamp);
967 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
968 return date($format, $timestamp);
972 function sql_bool_to_bool($s) {
973 if ($s == "t" ||
$s == "1" ||
strtolower($s) == "true") {
980 function bool_to_sql_bool($s) {
988 // Session caching removed due to causing wrong redirects to upgrade
989 // script when get_schema_version() is called on an obsolete session
990 // created on a previous schema version.
991 function get_schema_version($nocache = false) {
992 global $schema_version;
994 if (!$schema_version && !$nocache) {
995 $result = db_query("SELECT schema_version FROM ttrss_version");
996 $version = db_fetch_result($result, 0, "schema_version");
997 $schema_version = $version;
1000 return $schema_version;
1004 function sanity_check() {
1005 require_once 'errors.php';
1009 $schema_version = get_schema_version(true);
1011 if ($schema_version != SCHEMA_VERSION
) {
1015 if (DB_TYPE
== "mysql") {
1016 $result = db_query("SELECT true", false);
1017 if (db_num_rows($result) != 1) {
1022 if (db_escape_string("testTEST") != "testTEST") {
1026 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1029 function file_is_locked($filename) {
1030 if (file_exists(LOCK_DIRECTORY
. "/$filename")) {
1031 if (function_exists('flock')) {
1032 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1034 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1035 flock($fp, LOCK_UN
);
1045 return true; // consider the file always locked and skip the test
1052 function make_lockfile($filename) {
1053 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1055 if ($fp && flock($fp, LOCK_EX | LOCK_NB
)) {
1056 $stat_h = fstat($fp);
1057 $stat_f = stat(LOCK_DIRECTORY
. "/$filename");
1059 if (strtoupper(substr(PHP_OS
, 0, 3)) !== 'WIN') {
1060 if ($stat_h["ino"] != $stat_f["ino"] ||
1061 $stat_h["dev"] != $stat_f["dev"]) {
1067 if (function_exists('posix_getpid')) {
1068 fwrite($fp, posix_getpid() . "\n");
1076 function make_stampfile($filename) {
1077 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1079 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1080 fwrite($fp, time() . "\n");
1081 flock($fp, LOCK_UN
);
1089 function sql_random_function() {
1090 if (DB_TYPE
== "mysql") {
1097 function getAllCounters() {
1098 $data = getGlobalCounters();
1100 $data = array_merge($data, getVirtCounters());
1101 $data = array_merge($data, getLabelCounters());
1102 $data = array_merge($data, getFeedCounters());
1103 $data = array_merge($data, getCategoryCounters());
1108 function getCategoryTitle($cat_id) {
1110 if ($cat_id == -1) {
1111 return __("Special");
1112 } else if ($cat_id == -2) {
1113 return __("Labels");
1116 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1119 if (db_num_rows($result) == 1) {
1120 return db_fetch_result($result, 0, "title");
1122 return __("Uncategorized");
1128 function getCategoryCounters() {
1131 /* Labels category */
1133 $cv = array("id" => -2, "kind" => "cat",
1134 "counter" => Feeds
::getCategoryUnread(-2));
1136 array_push($ret_arr, $cv);
1138 $result = db_query("SELECT id AS cat_id, value AS unread,
1139 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1140 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1141 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1142 WHERE ttrss_cat_counters_cache.feed_id = id AND
1143 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1144 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1146 while ($line = db_fetch_assoc($result)) {
1147 $line["cat_id"] = (int) $line["cat_id"];
1149 if ($line["num_children"] > 0) {
1150 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1155 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1156 "counter" => $line["unread"] +
$child_counter);
1158 array_push($ret_arr, $cv);
1161 /* Special case: NULL category doesn't actually exist in the DB */
1163 $cv = array("id" => 0, "kind" => "cat",
1164 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1166 array_push($ret_arr, $cv);
1171 function getFeedUnread($feed, $is_cat = false) {
1172 return Feeds
::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1175 function getLabelUnread($label_id, $owner_uid = false) {
1176 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1178 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1179 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1181 if (db_num_rows($result) != 0) {
1182 return db_fetch_result($result, 0, "unread");
1188 function getGlobalUnread($user_id = false) {
1191 $user_id = $_SESSION["uid"];
1194 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1195 WHERE owner_uid = '$user_id' AND feed_id > 0");
1197 $c_id = db_fetch_result($result, 0, "c_id");
1202 function getGlobalCounters($global_unread = -1) {
1205 if ($global_unread == -1) {
1206 $global_unread = getGlobalUnread();
1209 $cv = array("id" => "global-unread",
1210 "counter" => (int) $global_unread);
1212 array_push($ret_arr, $cv);
1214 $result = db_query("SELECT COUNT(id) AS fn FROM
1215 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1217 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1219 $cv = array("id" => "subscribed-feeds",
1220 "counter" => (int) $subscribed_feeds);
1222 array_push($ret_arr, $cv);
1227 function getVirtCounters() {
1231 for ($i = 0; $i >= -4; $i--) {
1233 $count = getFeedUnread($i);
1235 if ($i == 0 ||
$i == -1 ||
$i == -2)
1236 $auxctr = Feeds
::getFeedArticles($i, false);
1240 $cv = array("id" => $i,
1241 "counter" => (int) $count,
1242 "auxcounter" => (int) $auxctr);
1244 // if (get_pref('EXTENDED_FEEDLIST'))
1245 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1247 array_push($ret_arr, $cv);
1250 $feeds = PluginHost
::getInstance()->get_feeds(-1);
1252 if (is_array($feeds)) {
1253 foreach ($feeds as $feed) {
1254 $cv = array("id" => PluginHost
::pfeed_to_feed_id($feed['id']),
1255 "counter" => $feed['sender']->get_unread($feed['id']));
1257 if (method_exists($feed['sender'], 'get_total'))
1258 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1260 array_push($ret_arr, $cv);
1267 function getLabelCounters($descriptions = false) {
1271 $owner_uid = $_SESSION["uid"];
1273 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1274 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1275 (ttrss_labels2.id = label_id)
1276 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1277 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1278 GROUP BY ttrss_labels2.id,
1279 ttrss_labels2.caption");
1281 while ($line = db_fetch_assoc($result)) {
1283 $id = label_to_feed_id($line["id"]);
1285 $cv = array("id" => $id,
1286 "counter" => (int) $line["unread"],
1287 "auxcounter" => (int) $line["total"]);
1290 $cv["description"] = $line["caption"];
1292 array_push($ret_arr, $cv);
1298 function getFeedCounters($active_feed = false) {
1302 $query = "SELECT ttrss_feeds.id,
1304 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1305 last_error, value AS count
1306 FROM ttrss_feeds, ttrss_counters_cache
1307 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1308 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1309 AND ttrss_counters_cache.feed_id = id";
1311 $result = db_query($query);
1313 while ($line = db_fetch_assoc($result)) {
1316 $count = $line["count"];
1317 $last_error = htmlspecialchars($line["last_error"]);
1319 $last_updated = make_local_datetime($line['last_updated'], false);
1321 $has_img = feed_has_icon($id);
1323 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1326 $cv = array("id" => $id,
1327 "updated" => $last_updated,
1328 "counter" => (int) $count,
1329 "has_img" => (int) $has_img);
1332 $cv["error"] = $last_error;
1334 // if (get_pref('EXTENDED_FEEDLIST'))
1335 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1337 if ($active_feed && $id == $active_feed)
1338 $cv["title"] = truncate_string($line["title"], 30);
1340 array_push($ret_arr, $cv);
1347 /*function get_pgsql_version() {
1348 $result = db_query("SELECT version() AS version");
1349 $version = explode(" ", db_fetch_result($result, 0, "version"));
1353 function checkbox_to_sql_bool($val) {
1354 return ($val == "on") ?
"true" : "false";
1357 /*function getFeedCatTitle($id) {
1359 return __("Special");
1360 } else if ($id < LABEL_BASE_INDEX) {
1361 return __("Labels");
1362 } else if ($id > 0) {
1363 $result = db_query("SELECT ttrss_feed_categories.title
1364 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1365 cat_id = ttrss_feed_categories.id");
1366 if (db_num_rows($result) == 1) {
1367 return db_fetch_result($result, 0, "title");
1369 return __("Uncategorized");
1372 return "getFeedCatTitle($id) failed";
1377 function uniqid_short() {
1378 return uniqid(base_convert(rand(), 10, 36));
1381 // TODO: less dumb splitting
1382 require_once "functions2.php";