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 get_feed_update_interval($feed_id) {
309 $result = db_query("SELECT owner_uid, update_interval FROM
310 ttrss_feeds WHERE id = '$feed_id'");
312 if (db_num_rows($result) == 1) {
313 $update_interval = db_fetch_result($result, 0, "update_interval");
314 $owner_uid = db_fetch_result($result, 0, "owner_uid");
316 if ($update_interval != 0) {
317 return $update_interval;
319 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
327 // TODO: multiple-argument way is deprecated, first parameter is a hash now
328 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
329 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
331 global $fetch_last_error;
332 global $fetch_last_error_code;
333 global $fetch_last_error_content;
334 global $fetch_last_content_type;
335 global $fetch_curl_used;
337 $fetch_last_error = false;
338 $fetch_last_error_code = -1;
339 $fetch_last_error_content = "";
340 $fetch_last_content_type = "";
341 $fetch_curl_used = false;
343 if (!is_array($options)) {
345 // falling back on compatibility shim
346 $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
349 for ($i = 0; $i < func_num_args(); $i++
) {
350 $tmp[$option_names[$i]] = func_get_arg($i);
356 "url" => func_get_arg(0),
357 "type" => @func_get_arg(1),
358 "login" => @func_get_arg(2),
359 "pass" => @func_get_arg(3),
360 "post_query" => @func_get_arg(4),
361 "timeout" => @func_get_arg(5),
362 "timestamp" => @func_get_arg(6),
363 "useragent" => @func_get_arg(7)
367 $url = $options["url"];
368 $type = isset($options["type"]) ?
$options["type"] : false;
369 $login = isset($options["login"]) ?
$options["login"] : false;
370 $pass = isset($options["pass"]) ?
$options["pass"] : false;
371 $post_query = isset($options["post_query"]) ?
$options["post_query"] : false;
372 $timeout = isset($options["timeout"]) ?
$options["timeout"] : false;
373 $timestamp = isset($options["timestamp"]) ?
$options["timestamp"] : 0;
374 $useragent = isset($options["useragent"]) ?
$options["useragent"] : false;
375 $followlocation = isset($options["followlocation"]) ?
$options["followlocation"] : true;
377 $url = ltrim($url, ' ');
378 $url = str_replace(' ', '%20', $url);
380 if (strpos($url, "//") === 0)
381 $url = 'http:' . $url;
383 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
385 $fetch_curl_used = true;
387 $ch = curl_init($url);
389 if ($timestamp && !$post_query) {
390 curl_setopt($ch, CURLOPT_HTTPHEADER
,
391 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
394 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $timeout ?
$timeout : FILE_FETCH_CONNECT_TIMEOUT
);
395 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout ?
$timeout : FILE_FETCH_TIMEOUT
);
396 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir") && $followlocation);
397 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
398 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
399 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
400 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
401 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent ?
$useragent :
403 curl_setopt($ch, CURLOPT_ENCODING
, "");
404 //curl_setopt($ch, CURLOPT_REFERER, $url);
406 if (!ini_get("open_basedir")) {
407 curl_setopt($ch, CURLOPT_COOKIEJAR
, "/dev/null");
410 if (defined('_CURL_HTTP_PROXY')) {
411 curl_setopt($ch, CURLOPT_PROXY
, _CURL_HTTP_PROXY
);
415 curl_setopt($ch, CURLOPT_POST
, true);
416 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
420 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
422 $contents = @curl_exec
($ch);
424 if (curl_errno($ch) === 23 ||
curl_errno($ch) === 61) {
425 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
426 $contents = @curl_exec
($ch);
429 if ($contents === false) {
430 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
435 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
436 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
438 $fetch_last_error_code = $http_code;
440 if ($http_code != 200 ||
$type && strpos($fetch_last_content_type, "$type") === false) {
441 if (curl_errno($ch) != 0) {
442 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
444 $fetch_last_error = "HTTP Code: $http_code";
446 $fetch_last_error_content = $contents;
456 $fetch_curl_used = false;
458 if ($login && $pass){
459 $url_parts = array();
461 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
463 $pass = urlencode($pass);
465 if ($url_parts[1] && $url_parts[2]) {
466 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
470 // TODO: should this support POST requests or not? idk
472 if (!$post_query && $timestamp) {
473 $context = stream_context_create(array(
476 'ignore_errors' => true,
477 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
478 'protocol_version'=> 1.1,
479 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
482 $context = stream_context_create(array(
485 'ignore_errors' => true,
486 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
487 'protocol_version'=> 1.1
491 $old_error = error_get_last();
493 $data = @file_get_contents
($url, false, $context);
495 if (isset($http_response_header) && is_array($http_response_header)) {
496 foreach ($http_response_header as $h) {
497 if (substr(strtolower($h), 0, 13) == 'content-type:') {
498 $fetch_last_content_type = substr($h, 14);
499 // don't abort here b/c there might be more than one
500 // e.g. if we were being redirected -- last one is the right one
503 if (substr(strtolower($h), 0, 7) == 'http/1.') {
504 $fetch_last_error_code = (int) substr($h, 9, 3);
509 if ($fetch_last_error_code != 200) {
510 $error = error_get_last();
512 if ($error['message'] != $old_error['message']) {
513 $fetch_last_error = $error["message"];
515 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
518 $fetch_last_error_content = $data;
528 * Try to determine the favicon URL for a feed.
529 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
530 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
532 * @param string $url A feed or page URL
534 * @return mixed The favicon URL, or false if none was found.
536 function get_favicon_url($url) {
538 $favicon_url = false;
540 if ($html = @fetch_file_contents
($url)) {
542 libxml_use_internal_errors(true);
544 $doc = new DOMDocument();
545 $doc->loadHTML($html);
546 $xpath = new DOMXPath($doc);
548 $base = $xpath->query('/html/head/base');
549 foreach ($base as $b) {
550 $url = $b->getAttribute("href");
554 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
555 if (count($entries) > 0) {
556 foreach ($entries as $entry) {
557 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
564 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
567 } // function get_favicon_url
569 function initialize_user_prefs($uid, $profile = false) {
571 $uid = db_escape_string($uid);
575 $profile_qpart = "AND profile IS NULL";
577 $profile_qpart = "AND profile = '$profile'";
580 if (get_schema_version() < 63) $profile_qpart = "";
584 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
586 $u_result = db_query("SELECT pref_name
587 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
589 $active_prefs = array();
591 while ($line = db_fetch_assoc($u_result)) {
592 array_push($active_prefs, $line["pref_name"]);
595 while ($line = db_fetch_assoc($result)) {
596 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
597 // print "adding " . $line["pref_name"] . "<br>";
599 $line["def_value"] = db_escape_string($line["def_value"]);
600 $line["pref_name"] = db_escape_string($line["pref_name"]);
602 if (get_schema_version() < 63) {
603 db_query("INSERT INTO ttrss_user_prefs
604 (owner_uid,pref_name,value) VALUES
605 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
608 db_query("INSERT INTO ttrss_user_prefs
609 (owner_uid,pref_name,value, profile) VALUES
610 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
620 function get_ssl_certificate_id() {
621 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
622 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
623 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
624 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
625 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
627 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
628 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
629 $_SERVER["SSL_CLIENT_V_START"] .
630 $_SERVER["SSL_CLIENT_V_END"] .
631 $_SERVER["SSL_CLIENT_S_DN"]);
636 function authenticate_user($login, $password, $check_only = false) {
638 if (!SINGLE_USER_MODE
) {
641 foreach (PluginHost
::getInstance()->get_hooks(PluginHost
::HOOK_AUTH_USER
) as $plugin) {
643 $user_id = (int) $plugin->authenticate($login, $password);
646 $_SESSION["auth_module"] = strtolower(get_class($plugin));
651 if ($user_id && !$check_only) {
654 $_SESSION["uid"] = $user_id;
655 $_SESSION["version"] = VERSION_STATIC
;
657 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
658 WHERE id = '$user_id'");
660 $_SESSION["name"] = db_fetch_result($result, 0, "login");
661 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
662 $_SESSION["csrf_token"] = uniqid_short();
664 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
667 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
668 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
669 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
671 $_SESSION["last_version_check"] = time();
673 initialize_user_prefs($_SESSION["uid"]);
682 $_SESSION["uid"] = 1;
683 $_SESSION["name"] = "admin";
684 $_SESSION["access_level"] = 10;
686 $_SESSION["hide_hello"] = true;
687 $_SESSION["hide_logout"] = true;
689 $_SESSION["auth_module"] = false;
691 if (!$_SESSION["csrf_token"]) {
692 $_SESSION["csrf_token"] = uniqid_short();
695 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
697 initialize_user_prefs($_SESSION["uid"]);
703 function make_password($length = 8) {
706 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
710 while ($i < $length) {
711 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
713 if (!strstr($password, $char)) {
721 // this is called after user is created to initialize default feeds, labels
724 // user preferences are checked on every login, not here
726 function initialize_user($uid) {
728 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
729 values ('$uid', 'Tiny Tiny RSS: Forum',
730 'http://tt-rss.org/forum/rss.php')");
733 function logout_user() {
735 if (isset($_COOKIE[session_name()])) {
736 setcookie(session_name(), '', time()-42000, '/');
740 function validate_csrf($csrf_token) {
741 return $csrf_token == $_SESSION['csrf_token'];
744 function load_user_plugins($owner_uid, $pluginhost = false) {
746 if (!$pluginhost) $pluginhost = PluginHost
::getInstance();
748 if ($owner_uid && SCHEMA_VERSION
>= 100) {
749 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
751 $pluginhost->load($plugins, PluginHost
::KIND_USER
, $owner_uid);
753 if (get_schema_version() > 100) {
754 $pluginhost->load_data();
759 function login_sequence() {
760 if (SINGLE_USER_MODE
) {
762 authenticate_user("admin", null);
764 load_user_plugins($_SESSION["uid"]);
766 if (!validate_session()) $_SESSION["uid"] = false;
768 if (!$_SESSION["uid"]) {
770 if (AUTH_AUTO_LOGIN
&& authenticate_user(null, null)) {
771 $_SESSION["ref_schema_version"] = get_schema_version(true);
773 authenticate_user(null, null, true);
776 if (!$_SESSION["uid"]) {
778 setcookie(session_name(), '', time()-42000, '/');
785 /* bump login timestamp */
786 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
788 $_SESSION["last_login_update"] = time();
791 if ($_SESSION["uid"]) {
793 load_user_plugins($_SESSION["uid"]);
797 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
798 $_SESSION["uid"] . " AND
799 (SELECT COUNT(id) FROM ttrss_feeds WHERE
800 ttrss_feeds.id = feed_id) = 0");
802 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
803 $_SESSION["uid"] . " AND
804 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
805 ttrss_feed_categories.id = feed_id) = 0");
812 function truncate_string($str, $max_len, $suffix = '…') {
813 if (mb_strlen($str, "utf-8") > $max_len) {
814 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
821 function truncate_middle($str, $max_len, $suffix = '…') {
822 if (strlen($str) > $max_len) {
823 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
829 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
832 $source_tz = new DateTimeZone($source_tz);
833 } catch (Exception
$e) {
834 $source_tz = new DateTimeZone('UTC');
838 $dest_tz = new DateTimeZone($dest_tz);
839 } catch (Exception
$e) {
840 $dest_tz = new DateTimeZone('UTC');
843 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
844 return $dt->format('U') +
$dest_tz->getOffset($dt);
847 function make_local_datetime($timestamp, $long, $owner_uid = false,
848 $no_smart_dt = false, $eta_min = false) {
850 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
851 if (!$timestamp) $timestamp = '1970-01-01 0:00';
856 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
858 $timestamp = substr($timestamp, 0, 19);
860 # We store date in UTC internally
861 $dt = new DateTime($timestamp, $utc_tz);
863 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
865 if ($user_tz_string != 'Automatic') {
868 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
869 } catch (Exception
$e) {
873 $tz_offset = $user_tz->getOffset($dt);
875 $tz_offset = (int) -$_SESSION["clientTzOffset"];
878 $user_timestamp = $dt->format('U') +
$tz_offset;
881 return smart_date_time($user_timestamp,
882 $tz_offset, $owner_uid, $eta_min);
885 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
887 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
889 return date($format, $user_timestamp);
893 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
894 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
896 if ($eta_min && time() +
$tz_offset - $timestamp < 3600) {
897 return T_sprintf("%d min", date("i", time() +
$tz_offset - $timestamp));
898 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
899 return date("G:i", $timestamp);
900 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
901 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
902 return date($format, $timestamp);
904 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
905 return date($format, $timestamp);
909 function sql_bool_to_bool($s) {
910 if ($s == "t" ||
$s == "1" ||
strtolower($s) == "true") {
917 function bool_to_sql_bool($s) {
925 // Session caching removed due to causing wrong redirects to upgrade
926 // script when get_schema_version() is called on an obsolete session
927 // created on a previous schema version.
928 function get_schema_version($nocache = false) {
929 global $schema_version;
931 if (!$schema_version && !$nocache) {
932 $result = db_query("SELECT schema_version FROM ttrss_version");
933 $version = db_fetch_result($result, 0, "schema_version");
934 $schema_version = $version;
937 return $schema_version;
941 function sanity_check() {
942 require_once 'errors.php';
946 $schema_version = get_schema_version(true);
948 if ($schema_version != SCHEMA_VERSION
) {
952 if (DB_TYPE
== "mysql") {
953 $result = db_query("SELECT true", false);
954 if (db_num_rows($result) != 1) {
959 if (db_escape_string("testTEST") != "testTEST") {
963 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
966 function file_is_locked($filename) {
967 if (file_exists(LOCK_DIRECTORY
. "/$filename")) {
968 if (function_exists('flock')) {
969 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
971 if (flock($fp, LOCK_EX | LOCK_NB
)) {
982 return true; // consider the file always locked and skip the test
989 function make_lockfile($filename) {
990 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
992 if ($fp && flock($fp, LOCK_EX | LOCK_NB
)) {
993 $stat_h = fstat($fp);
994 $stat_f = stat(LOCK_DIRECTORY
. "/$filename");
996 if (strtoupper(substr(PHP_OS
, 0, 3)) !== 'WIN') {
997 if ($stat_h["ino"] != $stat_f["ino"] ||
998 $stat_h["dev"] != $stat_f["dev"]) {
1004 if (function_exists('posix_getpid')) {
1005 fwrite($fp, posix_getpid() . "\n");
1013 function make_stampfile($filename) {
1014 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1016 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1017 fwrite($fp, time() . "\n");
1018 flock($fp, LOCK_UN
);
1026 function sql_random_function() {
1027 if (DB_TYPE
== "mysql") {
1034 function getAllCounters() {
1035 $data = getGlobalCounters();
1037 $data = array_merge($data, getVirtCounters());
1038 $data = array_merge($data, getLabelCounters());
1039 $data = array_merge($data, getFeedCounters());
1040 $data = array_merge($data, getCategoryCounters());
1045 function getCategoryCounters() {
1048 /* Labels category */
1050 $cv = array("id" => -2, "kind" => "cat",
1051 "counter" => Feeds
::getCategoryUnread(-2));
1053 array_push($ret_arr, $cv);
1055 $result = db_query("SELECT id AS cat_id, value AS unread,
1056 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1057 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1058 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1059 WHERE ttrss_cat_counters_cache.feed_id = id AND
1060 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1061 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1063 while ($line = db_fetch_assoc($result)) {
1064 $line["cat_id"] = (int) $line["cat_id"];
1066 if ($line["num_children"] > 0) {
1067 $child_counter = Feeds
::getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1072 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1073 "counter" => $line["unread"] +
$child_counter);
1075 array_push($ret_arr, $cv);
1078 /* Special case: NULL category doesn't actually exist in the DB */
1080 $cv = array("id" => 0, "kind" => "cat",
1081 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1083 array_push($ret_arr, $cv);
1088 function getFeedUnread($feed, $is_cat = false) {
1089 return Feeds
::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1092 function getGlobalCounters($global_unread = -1) {
1095 if ($global_unread == -1) {
1096 $global_unread = Feeds
::getGlobalUnread();
1099 $cv = array("id" => "global-unread",
1100 "counter" => (int) $global_unread);
1102 array_push($ret_arr, $cv);
1104 $result = db_query("SELECT COUNT(id) AS fn FROM
1105 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1107 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1109 $cv = array("id" => "subscribed-feeds",
1110 "counter" => (int) $subscribed_feeds);
1112 array_push($ret_arr, $cv);
1117 function getVirtCounters() {
1121 for ($i = 0; $i >= -4; $i--) {
1123 $count = getFeedUnread($i);
1125 if ($i == 0 ||
$i == -1 ||
$i == -2)
1126 $auxctr = Feeds
::getFeedArticles($i, false);
1130 $cv = array("id" => $i,
1131 "counter" => (int) $count,
1132 "auxcounter" => (int) $auxctr);
1134 // if (get_pref('EXTENDED_FEEDLIST'))
1135 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1137 array_push($ret_arr, $cv);
1140 $feeds = PluginHost
::getInstance()->get_feeds(-1);
1142 if (is_array($feeds)) {
1143 foreach ($feeds as $feed) {
1144 $cv = array("id" => PluginHost
::pfeed_to_feed_id($feed['id']),
1145 "counter" => $feed['sender']->get_unread($feed['id']));
1147 if (method_exists($feed['sender'], 'get_total'))
1148 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1150 array_push($ret_arr, $cv);
1157 function getLabelCounters($descriptions = false) {
1161 $owner_uid = $_SESSION["uid"];
1163 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1164 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1165 (ttrss_labels2.id = label_id)
1166 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1167 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1168 GROUP BY ttrss_labels2.id,
1169 ttrss_labels2.caption");
1171 while ($line = db_fetch_assoc($result)) {
1173 $id = label_to_feed_id($line["id"]);
1175 $cv = array("id" => $id,
1176 "counter" => (int) $line["unread"],
1177 "auxcounter" => (int) $line["total"]);
1180 $cv["description"] = $line["caption"];
1182 array_push($ret_arr, $cv);
1188 function getFeedCounters($active_feed = false) {
1192 $query = "SELECT ttrss_feeds.id,
1194 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1195 last_error, value AS count
1196 FROM ttrss_feeds, ttrss_counters_cache
1197 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1198 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1199 AND ttrss_counters_cache.feed_id = id";
1201 $result = db_query($query);
1203 while ($line = db_fetch_assoc($result)) {
1206 $count = $line["count"];
1207 $last_error = htmlspecialchars($line["last_error"]);
1209 $last_updated = make_local_datetime($line['last_updated'], false);
1211 $has_img = feed_has_icon($id);
1213 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1216 $cv = array("id" => $id,
1217 "updated" => $last_updated,
1218 "counter" => (int) $count,
1219 "has_img" => (int) $has_img);
1222 $cv["error"] = $last_error;
1224 // if (get_pref('EXTENDED_FEEDLIST'))
1225 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1227 if ($active_feed && $id == $active_feed)
1228 $cv["title"] = truncate_string($line["title"], 30);
1230 array_push($ret_arr, $cv);
1237 /*function get_pgsql_version() {
1238 $result = db_query("SELECT version() AS version");
1239 $version = explode(" ", db_fetch_result($result, 0, "version"));
1243 function checkbox_to_sql_bool($val) {
1244 return ($val == "on") ?
"true" : "false";
1247 /*function getFeedCatTitle($id) {
1249 return __("Special");
1250 } else if ($id < LABEL_BASE_INDEX) {
1251 return __("Labels");
1252 } else if ($id > 0) {
1253 $result = db_query("SELECT ttrss_feed_categories.title
1254 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1255 cat_id = ttrss_feed_categories.id");
1256 if (db_num_rows($result) == 1) {
1257 return db_fetch_result($result, 0, "title");
1259 return __("Uncategorized");
1262 return "getFeedCatTitle($id) failed";
1267 function uniqid_short() {
1268 return uniqid(base_convert(rand(), 10, 36));
1271 // TODO: less dumb splitting
1272 require_once "functions2.php";