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';
140 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
141 ini_set('user_agent', SELF_USER_AGENT
);
143 require_once 'lib/pubsubhubbub/Publisher.php';
145 $schema_version = false;
147 function _debug_suppress($suppress) {
148 global $suppress_debugging;
150 $suppress_debugging = $suppress;
154 * Print a timestamped debug message.
156 * @param string $msg The debug message.
159 function _debug($msg, $show = true) {
160 global $suppress_debugging;
162 //echo "[$suppress_debugging] $msg $show\n";
164 if ($suppress_debugging) return false;
166 $ts = strftime("%H:%M:%S", time());
167 if (function_exists('posix_getpid')) {
168 $ts = "$ts/" . posix_getpid();
171 if ($show && !(defined('QUIET') && QUIET
)) {
172 print "[$ts] $msg\n";
175 if (defined('LOGFILE')) {
176 $fp = fopen(LOGFILE
, 'a+');
181 if (function_exists("flock")) {
184 // try to lock logfile for writing
185 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB
)) {
196 fputs($fp, "[$ts] $msg\n");
198 if (function_exists("flock")) {
209 * Purge a feed old posts.
211 * @param mixed $link A database connection.
212 * @param mixed $feed_id The id of the purged feed.
213 * @param mixed $purge_interval Olderness of purged posts.
214 * @param boolean $debug Set to True to enable the debug. False by default.
218 function purge_feed($feed_id, $purge_interval, $debug = false) {
220 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
225 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
229 if (db_num_rows($result) == 1) {
230 $owner_uid = db_fetch_result($result, 0, "owner_uid");
233 if ($purge_interval == -1 ||
!$purge_interval) {
235 ccache_update($feed_id, $owner_uid);
240 if (!$owner_uid) return;
242 if (FORCE_ARTICLE_PURGE
== 0) {
243 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
246 $purge_unread = true;
247 $purge_interval = FORCE_ARTICLE_PURGE
;
250 if (!$purge_unread) $query_limit = " unread = false AND ";
252 if (DB_TYPE
== "pgsql") {
253 $result = db_query("DELETE FROM ttrss_user_entries
255 WHERE 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 WHERE
264 marked = false AND feed_id = '$feed_id' AND
265 (SELECT date_updated FROM ttrss_entries WHERE
266 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
268 $result = db_query("DELETE FROM ttrss_user_entries
269 USING ttrss_user_entries, ttrss_entries
270 WHERE ttrss_entries.id = ref_id AND
272 feed_id = '$feed_id' AND
274 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
277 $rows = db_affected_rows($result);
279 ccache_update($feed_id, $owner_uid);
282 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
286 } // function purge_feed
288 function feed_purge_interval($feed_id) {
290 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
291 WHERE id = '$feed_id'");
293 if (db_num_rows($result) == 1) {
294 $purge_interval = db_fetch_result($result, 0, "purge_interval");
295 $owner_uid = db_fetch_result($result, 0, "owner_uid");
297 if ($purge_interval == 0) $purge_interval = get_pref(
298 'PURGE_OLD_DAYS', $owner_uid);
300 return $purge_interval;
307 function purge_orphans($do_output = false) {
309 // purge orphaned posts in main content table
310 $result = db_query("DELETE FROM ttrss_entries WHERE
311 NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id)");
314 $rows = db_affected_rows($result);
315 _debug("Purged $rows orphaned posts.");
319 function get_feed_update_interval($feed_id) {
320 $result = db_query("SELECT owner_uid, update_interval FROM
321 ttrss_feeds WHERE id = '$feed_id'");
323 if (db_num_rows($result) == 1) {
324 $update_interval = db_fetch_result($result, 0, "update_interval");
325 $owner_uid = db_fetch_result($result, 0, "owner_uid");
327 if ($update_interval != 0) {
328 return $update_interval;
330 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
338 // TODO: multiple-argument way is deprecated, first parameter is a hash now
339 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
340 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
342 global $fetch_last_error;
343 global $fetch_last_error_code;
344 global $fetch_last_error_content;
345 global $fetch_last_content_type;
346 global $fetch_curl_used;
348 $fetch_last_error = false;
349 $fetch_last_error_code = -1;
350 $fetch_last_error_content = "";
351 $fetch_last_content_type = "";
352 $fetch_curl_used = false;
354 if (!is_array($options)) {
356 // falling back on compatibility shim
357 $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
360 for ($i = 0; $i < func_num_args(); $i++
) {
361 $tmp[$option_names[$i]] = func_get_arg($i);
367 "url" => func_get_arg(0),
368 "type" => @func_get_arg(1),
369 "login" => @func_get_arg(2),
370 "pass" => @func_get_arg(3),
371 "post_query" => @func_get_arg(4),
372 "timeout" => @func_get_arg(5),
373 "timestamp" => @func_get_arg(6),
374 "useragent" => @func_get_arg(7)
378 $url = $options["url"];
379 $type = isset($options["type"]) ?
$options["type"] : false;
380 $login = isset($options["login"]) ?
$options["login"] : false;
381 $pass = isset($options["pass"]) ?
$options["pass"] : false;
382 $post_query = isset($options["post_query"]) ?
$options["post_query"] : false;
383 $timeout = isset($options["timeout"]) ?
$options["timeout"] : false;
384 $timestamp = isset($options["timestamp"]) ?
$options["timestamp"] : 0;
385 $useragent = isset($options["useragent"]) ?
$options["useragent"] : false;
386 $followlocation = isset($options["followlocation"]) ?
$options["followlocation"] : true;
388 $url = ltrim($url, ' ');
389 $url = str_replace(' ', '%20', $url);
391 if (strpos($url, "//") === 0)
392 $url = 'http:' . $url;
394 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
396 $fetch_curl_used = true;
398 $ch = curl_init($url);
400 if ($timestamp && !$post_query) {
401 curl_setopt($ch, CURLOPT_HTTPHEADER
,
402 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
405 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $timeout ?
$timeout : FILE_FETCH_CONNECT_TIMEOUT
);
406 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout ?
$timeout : FILE_FETCH_TIMEOUT
);
407 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir") && $followlocation);
408 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
409 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
410 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
411 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
412 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent ?
$useragent :
414 curl_setopt($ch, CURLOPT_ENCODING
, "");
415 //curl_setopt($ch, CURLOPT_REFERER, $url);
417 if (!ini_get("open_basedir")) {
418 curl_setopt($ch, CURLOPT_COOKIEJAR
, "/dev/null");
421 if (defined('_CURL_HTTP_PROXY')) {
422 curl_setopt($ch, CURLOPT_PROXY
, _CURL_HTTP_PROXY
);
426 curl_setopt($ch, CURLOPT_POST
, true);
427 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
431 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
433 $contents = @curl_exec
($ch);
435 if (curl_errno($ch) === 23 ||
curl_errno($ch) === 61) {
436 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
437 $contents = @curl_exec
($ch);
440 if ($contents === false) {
441 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
446 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
447 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
449 $fetch_last_error_code = $http_code;
451 if ($http_code != 200 ||
$type && strpos($fetch_last_content_type, "$type") === false) {
452 if (curl_errno($ch) != 0) {
453 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
455 $fetch_last_error = "HTTP Code: $http_code";
457 $fetch_last_error_content = $contents;
467 $fetch_curl_used = false;
469 if ($login && $pass){
470 $url_parts = array();
472 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
474 $pass = urlencode($pass);
476 if ($url_parts[1] && $url_parts[2]) {
477 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
481 // TODO: should this support POST requests or not? idk
483 if (!$post_query && $timestamp) {
484 $context = stream_context_create(array(
487 'ignore_errors' => true,
488 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
489 'protocol_version'=> 1.1,
490 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
493 $context = stream_context_create(array(
496 'ignore_errors' => true,
497 'timeout' => $timeout ?
$timeout : FILE_FETCH_TIMEOUT
,
498 'protocol_version'=> 1.1
502 $old_error = error_get_last();
504 $data = @file_get_contents
($url, false, $context);
506 if (isset($http_response_header) && is_array($http_response_header)) {
507 foreach ($http_response_header as $h) {
508 if (substr(strtolower($h), 0, 13) == 'content-type:') {
509 $fetch_last_content_type = substr($h, 14);
510 // don't abort here b/c there might be more than one
511 // e.g. if we were being redirected -- last one is the right one
514 if (substr(strtolower($h), 0, 7) == 'http/1.') {
515 $fetch_last_error_code = (int) substr($h, 9, 3);
520 if ($fetch_last_error_code != 200) {
521 $error = error_get_last();
523 if ($error['message'] != $old_error['message']) {
524 $fetch_last_error = $error["message"];
526 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
529 $fetch_last_error_content = $data;
539 * Try to determine the favicon URL for a feed.
540 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
541 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
543 * @param string $url A feed or page URL
545 * @return mixed The favicon URL, or false if none was found.
547 function get_favicon_url($url) {
549 $favicon_url = false;
551 if ($html = @fetch_file_contents
($url)) {
553 libxml_use_internal_errors(true);
555 $doc = new DOMDocument();
556 $doc->loadHTML($html);
557 $xpath = new DOMXPath($doc);
559 $base = $xpath->query('/html/head/base');
560 foreach ($base as $b) {
561 $url = $b->getAttribute("href");
565 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
566 if (count($entries) > 0) {
567 foreach ($entries as $entry) {
568 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
575 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
578 } // function get_favicon_url
580 function check_feed_favicon($site_url, $feed) {
581 # print "FAVICON [$site_url]: $favicon_url\n";
583 $icon_file = ICONS_DIR
. "/$feed.ico";
585 if (!file_exists($icon_file)) {
586 $favicon_url = get_favicon_url($site_url);
589 // Limiting to "image" type misses those served with text/plain
590 $contents = fetch_file_contents($favicon_url); // , "image");
593 // Crude image type matching.
594 // Patterns gleaned from the file(1) source code.
595 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
596 // 0 string \000\000\001\000 MS Windows icon resource
597 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
599 elseif (preg_match('/^GIF8/', $contents)) {
600 // 0 string GIF8 GIF image data
601 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
603 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
604 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
605 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
607 elseif (preg_match('/^\xff\xd8/', $contents)) {
608 // 0 beshort 0xffd8 JPEG image data
609 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
612 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
618 $fp = @fopen
($icon_file, "w");
621 fwrite($fp, $contents);
623 chmod($icon_file, 0644);
631 function print_select($id, $default, $values, $attributes = "", $name = "") {
632 if (!$name) $name = $id;
634 print "<select name=\"$name\" id=\"$id\" $attributes>";
635 foreach ($values as $v) {
637 $sel = "selected=\"1\"";
643 print "<option value=\"$v\" $sel>$v</option>";
648 function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
649 if (!$name) $name = $id;
651 print "<select name=\"$name\" id='$id' $attributes>";
652 foreach (array_keys($values) as $v) {
654 $sel = 'selected="selected"';
660 print "<option $sel value=\"$v\">".$values[$v]."</option>";
666 function print_radio($id, $default, $true_is, $values, $attributes = "") {
667 foreach ($values as $v) {
674 if ($v == $true_is) {
675 $sel .= " value=\"1\"";
677 $sel .= " value=\"0\"";
680 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
681 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
686 function initialize_user_prefs($uid, $profile = false) {
688 $uid = db_escape_string($uid);
692 $profile_qpart = "AND profile IS NULL";
694 $profile_qpart = "AND profile = '$profile'";
697 if (get_schema_version() < 63) $profile_qpart = "";
701 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
703 $u_result = db_query("SELECT pref_name
704 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
706 $active_prefs = array();
708 while ($line = db_fetch_assoc($u_result)) {
709 array_push($active_prefs, $line["pref_name"]);
712 while ($line = db_fetch_assoc($result)) {
713 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
714 // print "adding " . $line["pref_name"] . "<br>";
716 $line["def_value"] = db_escape_string($line["def_value"]);
717 $line["pref_name"] = db_escape_string($line["pref_name"]);
719 if (get_schema_version() < 63) {
720 db_query("INSERT INTO ttrss_user_prefs
721 (owner_uid,pref_name,value) VALUES
722 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
725 db_query("INSERT INTO ttrss_user_prefs
726 (owner_uid,pref_name,value, profile) VALUES
727 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
737 function get_ssl_certificate_id() {
738 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
739 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
740 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
741 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
742 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
744 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
745 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
746 $_SERVER["SSL_CLIENT_V_START"] .
747 $_SERVER["SSL_CLIENT_V_END"] .
748 $_SERVER["SSL_CLIENT_S_DN"]);
753 function authenticate_user($login, $password, $check_only = false) {
755 if (!SINGLE_USER_MODE
) {
758 foreach (PluginHost
::getInstance()->get_hooks(PluginHost
::HOOK_AUTH_USER
) as $plugin) {
760 $user_id = (int) $plugin->authenticate($login, $password);
763 $_SESSION["auth_module"] = strtolower(get_class($plugin));
768 if ($user_id && !$check_only) {
771 $_SESSION["uid"] = $user_id;
772 $_SESSION["version"] = VERSION_STATIC
;
774 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
775 WHERE id = '$user_id'");
777 $_SESSION["name"] = db_fetch_result($result, 0, "login");
778 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
779 $_SESSION["csrf_token"] = uniqid_short();
781 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
784 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
785 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
786 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
788 $_SESSION["last_version_check"] = time();
790 initialize_user_prefs($_SESSION["uid"]);
799 $_SESSION["uid"] = 1;
800 $_SESSION["name"] = "admin";
801 $_SESSION["access_level"] = 10;
803 $_SESSION["hide_hello"] = true;
804 $_SESSION["hide_logout"] = true;
806 $_SESSION["auth_module"] = false;
808 if (!$_SESSION["csrf_token"]) {
809 $_SESSION["csrf_token"] = uniqid_short();
812 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
814 initialize_user_prefs($_SESSION["uid"]);
820 function make_password($length = 8) {
823 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
827 while ($i < $length) {
828 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
830 if (!strstr($password, $char)) {
838 // this is called after user is created to initialize default feeds, labels
841 // user preferences are checked on every login, not here
843 function initialize_user($uid) {
845 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
846 values ('$uid', 'Tiny Tiny RSS: Forum',
847 'http://tt-rss.org/forum/rss.php')");
850 function logout_user() {
852 if (isset($_COOKIE[session_name()])) {
853 setcookie(session_name(), '', time()-42000, '/');
857 function validate_csrf($csrf_token) {
858 return $csrf_token == $_SESSION['csrf_token'];
861 function load_user_plugins($owner_uid, $pluginhost = false) {
863 if (!$pluginhost) $pluginhost = PluginHost
::getInstance();
865 if ($owner_uid && SCHEMA_VERSION
>= 100) {
866 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
868 $pluginhost->load($plugins, PluginHost
::KIND_USER
, $owner_uid);
870 if (get_schema_version() > 100) {
871 $pluginhost->load_data();
876 function login_sequence() {
877 if (SINGLE_USER_MODE
) {
879 authenticate_user("admin", null);
881 load_user_plugins($_SESSION["uid"]);
883 if (!validate_session()) $_SESSION["uid"] = false;
885 if (!$_SESSION["uid"]) {
887 if (AUTH_AUTO_LOGIN
&& authenticate_user(null, null)) {
888 $_SESSION["ref_schema_version"] = get_schema_version(true);
890 authenticate_user(null, null, true);
893 if (!$_SESSION["uid"]) {
895 setcookie(session_name(), '', time()-42000, '/');
902 /* bump login timestamp */
903 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
905 $_SESSION["last_login_update"] = time();
908 if ($_SESSION["uid"]) {
910 load_user_plugins($_SESSION["uid"]);
914 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
915 $_SESSION["uid"] . " AND
916 (SELECT COUNT(id) FROM ttrss_feeds WHERE
917 ttrss_feeds.id = feed_id) = 0");
919 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
920 $_SESSION["uid"] . " AND
921 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
922 ttrss_feed_categories.id = feed_id) = 0");
929 function truncate_string($str, $max_len, $suffix = '…') {
930 if (mb_strlen($str, "utf-8") > $max_len) {
931 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
938 function truncate_middle($str, $max_len, $suffix = '…') {
939 if (strlen($str) > $max_len) {
940 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
946 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
949 $source_tz = new DateTimeZone($source_tz);
950 } catch (Exception
$e) {
951 $source_tz = new DateTimeZone('UTC');
955 $dest_tz = new DateTimeZone($dest_tz);
956 } catch (Exception
$e) {
957 $dest_tz = new DateTimeZone('UTC');
960 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
961 return $dt->format('U') +
$dest_tz->getOffset($dt);
964 function make_local_datetime($timestamp, $long, $owner_uid = false,
965 $no_smart_dt = false, $eta_min = false) {
967 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
968 if (!$timestamp) $timestamp = '1970-01-01 0:00';
973 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
975 $timestamp = substr($timestamp, 0, 19);
977 # We store date in UTC internally
978 $dt = new DateTime($timestamp, $utc_tz);
980 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
982 if ($user_tz_string != 'Automatic') {
985 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
986 } catch (Exception
$e) {
990 $tz_offset = $user_tz->getOffset($dt);
992 $tz_offset = (int) -$_SESSION["clientTzOffset"];
995 $user_timestamp = $dt->format('U') +
$tz_offset;
998 return smart_date_time($user_timestamp,
999 $tz_offset, $owner_uid, $eta_min);
1002 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1004 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1006 return date($format, $user_timestamp);
1010 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
1011 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1013 if ($eta_min && time() +
$tz_offset - $timestamp < 3600) {
1014 return T_sprintf("%d min", date("i", time() +
$tz_offset - $timestamp));
1015 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
1016 return date("G:i", $timestamp);
1017 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
1018 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1019 return date($format, $timestamp);
1021 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1022 return date($format, $timestamp);
1026 function sql_bool_to_bool($s) {
1027 if ($s == "t" ||
$s == "1" ||
strtolower($s) == "true") {
1034 function bool_to_sql_bool($s) {
1042 // Session caching removed due to causing wrong redirects to upgrade
1043 // script when get_schema_version() is called on an obsolete session
1044 // created on a previous schema version.
1045 function get_schema_version($nocache = false) {
1046 global $schema_version;
1048 if (!$schema_version && !$nocache) {
1049 $result = db_query("SELECT schema_version FROM ttrss_version");
1050 $version = db_fetch_result($result, 0, "schema_version");
1051 $schema_version = $version;
1054 return $schema_version;
1058 function sanity_check() {
1059 require_once 'errors.php';
1063 $schema_version = get_schema_version(true);
1065 if ($schema_version != SCHEMA_VERSION
) {
1069 if (DB_TYPE
== "mysql") {
1070 $result = db_query("SELECT true", false);
1071 if (db_num_rows($result) != 1) {
1076 if (db_escape_string("testTEST") != "testTEST") {
1080 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1083 function file_is_locked($filename) {
1084 if (file_exists(LOCK_DIRECTORY
. "/$filename")) {
1085 if (function_exists('flock')) {
1086 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1088 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1089 flock($fp, LOCK_UN
);
1099 return true; // consider the file always locked and skip the test
1106 function make_lockfile($filename) {
1107 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1109 if ($fp && flock($fp, LOCK_EX | LOCK_NB
)) {
1110 $stat_h = fstat($fp);
1111 $stat_f = stat(LOCK_DIRECTORY
. "/$filename");
1113 if (strtoupper(substr(PHP_OS
, 0, 3)) !== 'WIN') {
1114 if ($stat_h["ino"] != $stat_f["ino"] ||
1115 $stat_h["dev"] != $stat_f["dev"]) {
1121 if (function_exists('posix_getpid')) {
1122 fwrite($fp, posix_getpid() . "\n");
1130 function make_stampfile($filename) {
1131 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1133 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1134 fwrite($fp, time() . "\n");
1135 flock($fp, LOCK_UN
);
1143 function sql_random_function() {
1144 if (DB_TYPE
== "mysql") {
1151 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1153 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1155 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1157 // Todo: all this interval stuff needs some generic generator function
1159 $date_qpart = "false";
1163 if (DB_TYPE
== "pgsql") {
1164 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1166 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1170 if (DB_TYPE
== "pgsql") {
1171 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1173 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1177 if (DB_TYPE
== "pgsql") {
1178 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1180 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1184 $date_qpart = "true";
1187 if (is_numeric($feed)) {
1193 $children = getChildCategories($feed, $owner_uid);
1194 array_push($children, $feed);
1196 $children = join(",", $children);
1198 $cat_qpart = "cat_id IN ($children)";
1200 $cat_qpart = "cat_id IS NULL";
1203 db_query("UPDATE ttrss_user_entries
1204 SET unread = false, last_read = NOW() WHERE ref_id IN
1206 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1207 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1208 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1210 } else if ($feed == -2) {
1212 db_query("UPDATE ttrss_user_entries
1213 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1214 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1215 AND unread = true AND owner_uid = $owner_uid");
1218 } else if ($feed > 0) {
1220 db_query("UPDATE ttrss_user_entries
1221 SET unread = false, last_read = NOW() WHERE ref_id IN
1223 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1224 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1226 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX
) { // special, like starred
1229 db_query("UPDATE ttrss_user_entries
1230 SET unread = false, last_read = NOW() WHERE ref_id IN
1232 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1233 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1237 db_query("UPDATE ttrss_user_entries
1238 SET unread = false, last_read = NOW() WHERE ref_id IN
1240 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1241 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1246 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1248 if (DB_TYPE
== "pgsql") {
1249 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1251 $match_part = "date_entered > DATE_SUB(NOW(),
1252 INTERVAL $intl HOUR) ";
1255 db_query("UPDATE ttrss_user_entries
1256 SET unread = false, last_read = NOW() WHERE ref_id IN
1258 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1259 AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1263 db_query("UPDATE ttrss_user_entries
1264 SET unread = false, last_read = NOW() WHERE ref_id IN
1266 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1267 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1270 } else if ($feed < LABEL_BASE_INDEX
) { // label
1272 $label_id = feed_to_label_id($feed);
1274 db_query("UPDATE ttrss_user_entries
1275 SET unread = false, last_read = NOW() WHERE ref_id IN
1277 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1278 AND label_id = '$label_id' AND ref_id = article_id
1279 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1283 ccache_update($feed, $owner_uid, $cat_view);
1286 db_query("UPDATE ttrss_user_entries
1287 SET unread = false, last_read = NOW() WHERE ref_id IN
1289 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1290 AND post_int_id = int_id AND tag_name = '$feed'
1291 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1296 function getAllCounters() {
1297 $data = getGlobalCounters();
1299 $data = array_merge($data, getVirtCounters());
1300 $data = array_merge($data, getLabelCounters());
1301 $data = array_merge($data, getFeedCounters());
1302 $data = array_merge($data, getCategoryCounters());
1307 function getCategoryTitle($cat_id) {
1309 if ($cat_id == -1) {
1310 return __("Special");
1311 } else if ($cat_id == -2) {
1312 return __("Labels");
1315 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1318 if (db_num_rows($result) == 1) {
1319 return db_fetch_result($result, 0, "title");
1321 return __("Uncategorized");
1327 function getCategoryCounters() {
1330 /* Labels category */
1332 $cv = array("id" => -2, "kind" => "cat",
1333 "counter" => getCategoryUnread(-2));
1335 array_push($ret_arr, $cv);
1337 $result = db_query("SELECT id AS cat_id, value AS unread,
1338 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1339 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1340 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1341 WHERE ttrss_cat_counters_cache.feed_id = id AND
1342 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1343 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1345 while ($line = db_fetch_assoc($result)) {
1346 $line["cat_id"] = (int) $line["cat_id"];
1348 if ($line["num_children"] > 0) {
1349 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1354 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1355 "counter" => $line["unread"] +
$child_counter);
1357 array_push($ret_arr, $cv);
1360 /* Special case: NULL category doesn't actually exist in the DB */
1362 $cv = array("id" => 0, "kind" => "cat",
1363 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1365 array_push($ret_arr, $cv);
1370 // only accepts real cats (>= 0)
1371 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1372 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1374 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1375 AND owner_uid = $owner_uid");
1379 while ($line = db_fetch_assoc($result)) {
1380 $unread +
= getCategoryUnread($line["id"], $owner_uid);
1381 $unread +
= getCategoryChildrenUnread($line["id"], $owner_uid);
1387 function getCategoryUnread($cat, $owner_uid = false) {
1389 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1394 $cat_query = "cat_id = '$cat'";
1396 $cat_query = "cat_id IS NULL";
1399 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1400 AND owner_uid = " . $owner_uid);
1402 $cat_feeds = array();
1403 while ($line = db_fetch_assoc($result)) {
1404 array_push($cat_feeds, "feed_id = " . $line["id"]);
1407 if (count($cat_feeds) == 0) return 0;
1409 $match_part = implode(" OR ", $cat_feeds);
1411 $result = db_query("SELECT COUNT(int_id) AS unread
1412 FROM ttrss_user_entries
1413 WHERE unread = true AND ($match_part)
1414 AND owner_uid = " . $owner_uid);
1418 # this needs to be rewritten
1419 while ($line = db_fetch_assoc($result)) {
1420 $unread +
= $line["unread"];
1424 } else if ($cat == -1) {
1425 return getFeedUnread(-1) +
getFeedUnread(-2) +
getFeedUnread(-3) +
getFeedUnread(0);
1426 } else if ($cat == -2) {
1428 $result = db_query("
1429 SELECT COUNT(unread) AS unread FROM
1430 ttrss_user_entries, ttrss_user_labels2
1431 WHERE article_id = ref_id AND unread = true
1432 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1434 $unread = db_fetch_result($result, 0, "unread");
1441 function getFeedUnread($feed, $is_cat = false) {
1442 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1445 function getLabelUnread($label_id, $owner_uid = false) {
1446 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1448 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1449 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1451 if (db_num_rows($result) != 0) {
1452 return db_fetch_result($result, 0, "unread");
1458 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1459 $owner_uid = false) {
1461 $n_feed = (int) $feed;
1462 $need_entries = false;
1464 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1467 $unread_qpart = "unread = true";
1469 $unread_qpart = "true";
1473 return getCategoryUnread($n_feed, $owner_uid);
1474 } else if ($n_feed == -6) {
1476 } else if ($feed != "0" && $n_feed == 0) {
1478 $feed = db_escape_string($feed);
1480 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1481 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1482 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1483 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1484 return db_fetch_result($result, 0, "count");
1486 } else if ($n_feed == -1) {
1487 $match_part = "marked = true";
1488 } else if ($n_feed == -2) {
1489 $match_part = "published = true";
1490 } else if ($n_feed == -3) {
1491 $match_part = "unread = true AND score >= 0";
1493 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1495 if (DB_TYPE
== "pgsql") {
1496 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1498 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1501 $need_entries = true;
1503 } else if ($n_feed == -4) {
1504 $match_part = "true";
1505 } else if ($n_feed >= 0) {
1508 $match_part = "feed_id = '$n_feed'";
1510 $match_part = "feed_id IS NULL";
1513 } else if ($feed < LABEL_BASE_INDEX
) {
1515 $label_id = feed_to_label_id($feed);
1517 return getLabelUnread($label_id, $owner_uid);
1523 if ($need_entries) {
1524 $from_qpart = "ttrss_user_entries,ttrss_entries";
1525 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1527 $from_qpart = "ttrss_user_entries";
1531 $query = "SELECT count(int_id) AS unread
1532 FROM $from_qpart WHERE
1533 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1535 //echo "[$feed/$query]\n";
1537 $result = db_query($query);
1541 $result = db_query("SELECT COUNT(post_int_id) AS unread
1542 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1543 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1544 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1547 $unread = db_fetch_result($result, 0, "unread");
1552 function getGlobalUnread($user_id = false) {
1555 $user_id = $_SESSION["uid"];
1558 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1559 WHERE owner_uid = '$user_id' AND feed_id > 0");
1561 $c_id = db_fetch_result($result, 0, "c_id");
1566 function getGlobalCounters($global_unread = -1) {
1569 if ($global_unread == -1) {
1570 $global_unread = getGlobalUnread();
1573 $cv = array("id" => "global-unread",
1574 "counter" => (int) $global_unread);
1576 array_push($ret_arr, $cv);
1578 $result = db_query("SELECT COUNT(id) AS fn FROM
1579 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1581 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1583 $cv = array("id" => "subscribed-feeds",
1584 "counter" => (int) $subscribed_feeds);
1586 array_push($ret_arr, $cv);
1591 function getVirtCounters() {
1595 for ($i = 0; $i >= -4; $i--) {
1597 $count = getFeedUnread($i);
1599 if ($i == 0 ||
$i == -1 ||
$i == -2)
1600 $auxctr = getFeedArticles($i, false);
1604 $cv = array("id" => $i,
1605 "counter" => (int) $count,
1606 "auxcounter" => (int) $auxctr);
1608 // if (get_pref('EXTENDED_FEEDLIST'))
1609 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1611 array_push($ret_arr, $cv);
1614 $feeds = PluginHost
::getInstance()->get_feeds(-1);
1616 if (is_array($feeds)) {
1617 foreach ($feeds as $feed) {
1618 $cv = array("id" => PluginHost
::pfeed_to_feed_id($feed['id']),
1619 "counter" => $feed['sender']->get_unread($feed['id']));
1621 if (method_exists($feed['sender'], 'get_total'))
1622 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1624 array_push($ret_arr, $cv);
1631 function getLabelCounters($descriptions = false) {
1635 $owner_uid = $_SESSION["uid"];
1637 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1638 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1639 (ttrss_labels2.id = label_id)
1640 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1641 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1642 GROUP BY ttrss_labels2.id,
1643 ttrss_labels2.caption");
1645 while ($line = db_fetch_assoc($result)) {
1647 $id = label_to_feed_id($line["id"]);
1649 $cv = array("id" => $id,
1650 "counter" => (int) $line["unread"],
1651 "auxcounter" => (int) $line["total"]);
1654 $cv["description"] = $line["caption"];
1656 array_push($ret_arr, $cv);
1662 function getFeedCounters($active_feed = false) {
1666 $query = "SELECT ttrss_feeds.id,
1668 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1669 last_error, value AS count
1670 FROM ttrss_feeds, ttrss_counters_cache
1671 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1672 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1673 AND ttrss_counters_cache.feed_id = id";
1675 $result = db_query($query);
1677 while ($line = db_fetch_assoc($result)) {
1680 $count = $line["count"];
1681 $last_error = htmlspecialchars($line["last_error"]);
1683 $last_updated = make_local_datetime($line['last_updated'], false);
1685 $has_img = feed_has_icon($id);
1687 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1690 $cv = array("id" => $id,
1691 "updated" => $last_updated,
1692 "counter" => (int) $count,
1693 "has_img" => (int) $has_img);
1696 $cv["error"] = $last_error;
1698 // if (get_pref('EXTENDED_FEEDLIST'))
1699 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1701 if ($active_feed && $id == $active_feed)
1702 $cv["title"] = truncate_string($line["title"], 30);
1704 array_push($ret_arr, $cv);
1711 function get_pgsql_version() {
1712 $result = db_query("SELECT version() AS version");
1713 $version = explode(" ", db_fetch_result($result, 0, "version"));
1718 * @return array (code => Status code, message => error message if available)
1720 * 0 - OK, Feed already exists
1721 * 1 - OK, Feed added
1723 * 3 - URL content is HTML, no feeds available
1724 * 4 - URL content is HTML which contains multiple feeds.
1725 * Here you should call extractfeedurls in rpc-backend
1726 * to get all possible feeds.
1727 * 5 - Couldn't download the URL content.
1728 * 6 - Content is an invalid XML.
1730 function subscribe_to_feed($url, $cat_id = 0,
1731 $auth_login = '', $auth_pass = '') {
1733 global $fetch_last_error;
1734 global $fetch_last_error_content;
1735 global $fetch_last_error_code;
1737 require_once "include/rssfuncs.php";
1739 $url = fix_url($url);
1741 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1743 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1746 if (preg_match("/cloudflare\.com/", $fetch_last_error_content)) {
1747 $fetch_last_error .= " (feed behind Cloudflare)";
1750 return array("code" => 5, "message" => $fetch_last_error);
1753 foreach (PluginHost
::getInstance()->get_hooks(PluginHost
::HOOK_SUBSCRIBE_FEED
) as $plugin) {
1754 $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1757 if (is_html($contents)) {
1758 $feedUrls = get_feeds_from_html($url, $contents);
1760 if (count($feedUrls) == 0) {
1761 return array("code" => 3);
1762 } else if (count($feedUrls) > 1) {
1763 return array("code" => 4, "feeds" => $feedUrls);
1765 //use feed url as new URL
1766 $url = key($feedUrls);
1769 if ($cat_id == "0" ||
!$cat_id) {
1770 $cat_qpart = "NULL";
1772 $cat_qpart = "'$cat_id'";
1776 "SELECT id FROM ttrss_feeds
1777 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1779 $auth_pass_encrypted = 'false';
1780 $auth_pass = db_escape_string($auth_pass);
1782 if (db_num_rows($result) == 0) {
1784 "INSERT INTO ttrss_feeds
1785 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1786 VALUES ('".$_SESSION["uid"]."', '$url',
1787 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1790 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1791 AND owner_uid = " . $_SESSION["uid"]);
1793 $feed_id = db_fetch_result($result, 0, "id");
1796 set_basic_feed_info($feed_id);
1799 return array("code" => 1, "feed_id" => (int) $feed_id);
1801 return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
1805 function print_feed_select($id, $default_id = "",
1806 $attributes = "", $include_all_feeds = true,
1807 $root_id = false, $nest_level = 0) {
1810 print "<select id=\"$id\" name=\"$id\" $attributes>";
1811 if ($include_all_feeds) {
1812 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1813 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1817 if (get_pref('ENABLE_FEED_CATS')) {
1820 $parent_qpart = "parent_cat = '$root_id'";
1822 $parent_qpart = "parent_cat IS NULL";
1824 $result = db_query("SELECT id,title,
1825 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1826 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1827 FROM ttrss_feed_categories
1828 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1830 while ($line = db_fetch_assoc($result)) {
1832 for ($i = 0; $i < $nest_level; $i++
)
1833 $line["title"] = " - " . $line["title"];
1835 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1837 printf("<option $is_selected value='CAT:%d'>%s</option>",
1838 $line["id"], htmlspecialchars($line["title"]));
1840 if ($line["num_children"] > 0)
1841 print_feed_select($id, $default_id, $attributes,
1842 $include_all_feeds, $line["id"], $nest_level+
1);
1844 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1845 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1847 while ($fline = db_fetch_assoc($feed_result)) {
1848 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1850 $fline["title"] = " + " . $fline["title"];
1852 for ($i = 0; $i < $nest_level; $i++
)
1853 $fline["title"] = " - " . $fline["title"];
1855 printf("<option $is_selected value='%d'>%s</option>",
1856 $fline["id"], htmlspecialchars($fline["title"]));
1861 $default_is_cat = ($default_id == "CAT:0");
1862 $is_selected = $default_is_cat ?
"selected=\"1\"" : "";
1864 printf("<option $is_selected value='CAT:0'>%s</option>",
1865 __("Uncategorized"));
1867 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1868 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1870 while ($fline = db_fetch_assoc($feed_result)) {
1871 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1873 $fline["title"] = " + " . $fline["title"];
1875 for ($i = 0; $i < $nest_level; $i++
)
1876 $fline["title"] = " - " . $fline["title"];
1878 printf("<option $is_selected value='%d'>%s</option>",
1879 $fline["id"], htmlspecialchars($fline["title"]));
1884 $result = db_query("SELECT id,title FROM ttrss_feeds
1885 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1887 while ($line = db_fetch_assoc($result)) {
1889 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1891 printf("<option $is_selected value='%d'>%s</option>",
1892 $line["id"], htmlspecialchars($line["title"]));
1901 function print_feed_cat_select($id, $default_id,
1902 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1905 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1909 $parent_qpart = "parent_cat = '$root_id'";
1911 $parent_qpart = "parent_cat IS NULL";
1913 $result = db_query("SELECT id,title,
1914 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1915 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1916 FROM ttrss_feed_categories
1917 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1919 while ($line = db_fetch_assoc($result)) {
1920 if ($line["id"] == $default_id) {
1921 $is_selected = "selected=\"1\"";
1926 for ($i = 0; $i < $nest_level; $i++
)
1927 $line["title"] = " - " . $line["title"];
1930 printf("<option $is_selected value='%d'>%s</option>",
1931 $line["id"], htmlspecialchars($line["title"]));
1933 if ($line["num_children"] > 0)
1934 print_feed_cat_select($id, $default_id, $attributes,
1935 $include_all_cats, $line["id"], $nest_level+
1);
1939 if ($include_all_cats) {
1940 if (db_num_rows($result) > 0) {
1941 print "<option disabled=\"1\">--------</option>";
1944 if ($default_id == 0) {
1945 $is_selected = "selected=\"1\"";
1950 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1956 function checkbox_to_sql_bool($val) {
1957 return ($val == "on") ?
"true" : "false";
1960 function getFeedCatTitle($id) {
1962 return __("Special");
1963 } else if ($id < LABEL_BASE_INDEX
) {
1964 return __("Labels");
1965 } else if ($id > 0) {
1966 $result = db_query("SELECT ttrss_feed_categories.title
1967 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1968 cat_id = ttrss_feed_categories.id");
1969 if (db_num_rows($result) == 1) {
1970 return db_fetch_result($result, 0, "title");
1972 return __("Uncategorized");
1975 return "getFeedCatTitle($id) failed";
1980 function getFeedIcon($id) {
1983 return "images/archive.png";
1986 return "images/star.png";
1989 return "images/feed.png";
1992 return "images/fresh.png";
1995 return "images/folder.png";
1998 return "images/time.png";
2001 if ($id < LABEL_BASE_INDEX
) {
2002 return "images/label.png";
2004 if (file_exists(ICONS_DIR
. "/$id.ico"))
2005 return ICONS_URL
. "/$id.ico";
2013 function getFeedTitle($id, $cat = false) {
2015 return getCategoryTitle($id);
2016 } else if ($id == -1) {
2017 return __("Starred articles");
2018 } else if ($id == -2) {
2019 return __("Published articles");
2020 } else if ($id == -3) {
2021 return __("Fresh articles");
2022 } else if ($id == -4) {
2023 return __("All articles");
2024 } else if ($id === 0 ||
$id === "0") {
2025 return __("Archived articles");
2026 } else if ($id == -6) {
2027 return __("Recently read");
2028 } else if ($id < LABEL_BASE_INDEX
) {
2029 $label_id = feed_to_label_id($id);
2030 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2031 if (db_num_rows($result) == 1) {
2032 return db_fetch_result($result, 0, "caption");
2034 return "Unknown label ($label_id)";
2037 } else if (is_numeric($id) && $id > 0) {
2038 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
2039 if (db_num_rows($result) == 1) {
2040 return db_fetch_result($result, 0, "title");
2042 return "Unknown feed ($id)";
2049 function uniqid_short() {
2050 return uniqid(base_convert(rand(), 10, 36));
2053 // TODO: less dumb splitting
2054 require_once "functions2.php";