]> git.wh0rd.org Git - tt-rss.git/blob - include/functions.php
fix various issues reported by static analysis
[tt-rss.git] / include / functions.php
1 <?php
2         define('EXPECTED_CONFIG_VERSION', 26);
3         define('SCHEMA_VERSION', 130);
4
5         define('LABEL_BASE_INDEX', -1024);
6         define('PLUGIN_FEED_BASE_INDEX', -128);
7
8         define('COOKIE_LIFETIME_LONG', 86400*365);
9
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;
16
17         libxml_disable_entity_loader(true);
18
19         // separate test because this is included before sanity checks
20         if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
21
22         date_default_timezone_set('UTC');
23         if (defined('E_DEPRECATED')) {
24                 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
25         } else {
26                 error_reporting(E_ALL & ~E_NOTICE);
27         }
28
29         require_once 'config.php';
30
31         /**
32          * Define a constant if not already defined
33          *
34          * @param string $name The constant name.
35          * @param mixed $value The constant value.
36          * @access public
37          * @return boolean True if defined successfully or not.
38          */
39         function define_default($name, $value) {
40                 defined($name) or define($name, $value);
41         }
42
43         ///// Some defaults that you can override in config.php //////
44
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
55
56         if (DB_TYPE == "pgsql") {
57                 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
58         } else {
59                 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
60         }
61
62         /**
63          * Return available translations names.
64          *
65          * @access public
66          * @return array A array of available translations.
67          */
68         function get_translations() {
69                 $tr = array(
70                                         "auto"  => "Detect automatically",
71                                         "ar_SA" => "العربيّة (Arabic)",
72                                         "bg_BG" => "Bulgarian",
73                                         "da_DA" => "Dansk",
74                                         "ca_CA" => "Català",
75                                         "cs_CZ" => "Česky",
76                                         "en_US" => "English",
77                                         "el_GR" => "Ελληνικά",
78                                         "es_ES" => "Español (España)",
79                                         "es_LA" => "Español",
80                                         "de_DE" => "Deutsch",
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",
87                                         "nl_NL" => "Dutch",
88                                         "pl_PL" => "Polski",
89                                         "ru_RU" => "Русский",
90                                         "pt_BR" => "Portuguese/Brazil",
91                                         "pt_PT" => "Portuguese/Portugal",
92                                         "zh_CN" => "Simplified Chinese",
93                                         "zh_TW" => "Traditional Chinese",
94                                         "sv_SE" => "Svenska",
95                                         "fi_FI" => "Suomi",
96                                         "tr_TR" => "Türkçe");
97
98                 return $tr;
99         }
100
101         require_once "lib/accept-to-gettext.php";
102         require_once "lib/gettext/gettext.inc";
103
104         function startup_gettext() {
105
106                 # Get locale from Accept-Language header
107                 $lang = al2gt(array_keys(get_translations()), "text/html");
108
109                 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
110                         $lang = _TRANSLATION_OVERRIDE_DEFAULT;
111                 }
112
113                 if ($_SESSION["uid"] && get_schema_version() >= 120) {
114                         $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
115
116                         if ($pref_lang && $pref_lang != 'auto') {
117                                 $lang = $pref_lang;
118                         }
119                 }
120
121                 if ($lang) {
122                         if (defined('LC_MESSAGES')) {
123                                 _setlocale(LC_MESSAGES, $lang);
124                         } else if (defined('LC_ALL')) {
125                                 _setlocale(LC_ALL, $lang);
126                         }
127
128                         _bindtextdomain("messages", "locale");
129
130                         _textdomain("messages");
131                         _bind_textdomain_codeset("messages", "UTF-8");
132                 }
133         }
134
135         require_once 'db-prefs.php';
136         require_once 'version.php';
137         require_once 'ccache.php';
138         require_once 'labels.php';
139
140         define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
141         ini_set('user_agent', SELF_USER_AGENT);
142
143         require_once 'lib/pubsubhubbub/Publisher.php';
144
145         $schema_version = false;
146
147         function _debug_suppress($suppress) {
148                 global $suppress_debugging;
149
150                 $suppress_debugging = $suppress;
151         }
152
153         /**
154          * Print a timestamped debug message.
155          *
156          * @param string $msg The debug message.
157          * @return void
158          */
159         function _debug($msg, $show = true) {
160                 global $suppress_debugging;
161
162                 //echo "[$suppress_debugging] $msg $show\n";
163
164                 if ($suppress_debugging) return false;
165
166                 $ts = strftime("%H:%M:%S", time());
167                 if (function_exists('posix_getpid')) {
168                         $ts = "$ts/" . posix_getpid();
169                 }
170
171                 if ($show && !(defined('QUIET') && QUIET)) {
172                         print "[$ts] $msg\n";
173                 }
174
175                 if (defined('LOGFILE'))  {
176                         $fp = fopen(LOGFILE, 'a+');
177
178                         if ($fp) {
179                                 $locked = false;
180
181                                 if (function_exists("flock")) {
182                                         $tries = 0;
183
184                                         // try to lock logfile for writing
185                                         while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
186                                                 sleep(1);
187                                                 ++$tries;
188                                         }
189
190                                         if (!$locked) {
191                                                 fclose($fp);
192                                                 return;
193                                         }
194                                 }
195
196                                 fputs($fp, "[$ts] $msg\n");
197
198                                 if (function_exists("flock")) {
199                                         flock($fp, LOCK_UN);
200                                 }
201
202                                 fclose($fp);
203                         }
204                 }
205
206         } // function _debug
207
208         /**
209          * Purge a feed old posts.
210          *
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.
215          * @access public
216          * @return void
217          */
218         function purge_feed($feed_id, $purge_interval, $debug = false) {
219
220                 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
221
222                 $rows = -1;
223
224                 $result = db_query(
225                         "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
226
227                 $owner_uid = false;
228
229                 if (db_num_rows($result) == 1) {
230                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
231                 }
232
233                 if ($purge_interval == -1 || !$purge_interval) {
234                         if ($owner_uid) {
235                                 ccache_update($feed_id, $owner_uid);
236                         }
237                         return;
238                 }
239
240                 if (!$owner_uid) return;
241
242                 if (FORCE_ARTICLE_PURGE == 0) {
243                         $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
244                                 $owner_uid, false);
245                 } else {
246                         $purge_unread = true;
247                         $purge_interval = FORCE_ARTICLE_PURGE;
248                 }
249
250                 if (!$purge_unread) $query_limit = " unread = false AND ";
251
252                 if (DB_TYPE == "pgsql") {
253                         $result = db_query("DELETE FROM ttrss_user_entries
254                                 USING ttrss_entries
255                                 WHERE ttrss_entries.id = ref_id AND
256                                 marked = false AND
257                                 feed_id = '$feed_id' AND
258                                 $query_limit
259                                 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
260
261                 } else {
262
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)"); */
267
268                         $result = db_query("DELETE FROM ttrss_user_entries
269                                 USING ttrss_user_entries, ttrss_entries
270                                 WHERE ttrss_entries.id = ref_id AND
271                                 marked = false AND
272                                 feed_id = '$feed_id' AND
273                                 $query_limit
274                                 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
275                 }
276
277                 $rows = db_affected_rows($result);
278
279                 ccache_update($feed_id, $owner_uid);
280
281                 if ($debug) {
282                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
283                 }
284
285                 return $rows;
286         } // function purge_feed
287
288         function feed_purge_interval($feed_id) {
289
290                 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
291                         WHERE id = '$feed_id'");
292
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");
296
297                         if ($purge_interval == 0) $purge_interval = get_pref(
298                                 'PURGE_OLD_DAYS', $owner_uid);
299
300                         return $purge_interval;
301
302                 } else {
303                         return -1;
304                 }
305         }
306
307         function purge_orphans($do_output = false) {
308
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)");
312
313                 if ($do_output) {
314                         $rows = db_affected_rows($result);
315                         _debug("Purged $rows orphaned posts.");
316                 }
317         }
318
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'");
322
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");
326
327                         if ($update_interval != 0) {
328                                 return $update_interval;
329                         } else {
330                                 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
331                         }
332
333                 } else {
334                         return -1;
335                 }
336         }
337
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*/) {
341
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;
347
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;
353
354                 if (!is_array($options)) {
355
356                         // falling back on compatibility shim
357                         $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
358                         $tmp = [];
359
360                         for ($i = 0; $i < func_num_args(); $i++) {
361                                 $tmp[$option_names[$i]] = func_get_arg($i);
362                         }
363
364                         $options = $tmp;
365
366                         /*$options = array(
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)
375                         ); */
376                 }
377
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;
387
388                 $url = ltrim($url, ' ');
389                 $url = str_replace(' ', '%20', $url);
390
391                 if (strpos($url, "//") === 0)
392                         $url = 'http:' . $url;
393
394                 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
395
396                         $fetch_curl_used = true;
397
398                         $ch = curl_init($url);
399
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)));
403                         }
404
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 :
413                                 SELF_USER_AGENT);
414                         curl_setopt($ch, CURLOPT_ENCODING, "");
415                         //curl_setopt($ch, CURLOPT_REFERER, $url);
416
417                         if (!ini_get("open_basedir")) {
418                                 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
419                         }
420
421                         if (defined('_CURL_HTTP_PROXY')) {
422                                 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
423                         }
424
425                         if ($post_query) {
426                                 curl_setopt($ch, CURLOPT_POST, true);
427                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
428                         }
429
430                         if ($login && $pass)
431                                 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
432
433                         $contents = @curl_exec($ch);
434
435                         if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
436                                 curl_setopt($ch, CURLOPT_ENCODING, 'none');
437                                 $contents = @curl_exec($ch);
438                         }
439
440                         if ($contents === false) {
441                                 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
442                                 curl_close($ch);
443                                 return false;
444                         }
445
446                         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
447                         $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
448
449                         $fetch_last_error_code = $http_code;
450
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);
454                                 } else {
455                                         $fetch_last_error = "HTTP Code: $http_code";
456                                 }
457                                 $fetch_last_error_content = $contents;
458                                 curl_close($ch);
459                                 return false;
460                         }
461
462                         curl_close($ch);
463
464                         return $contents;
465                 } else {
466
467                         $fetch_curl_used = false;
468
469                         if ($login && $pass){
470                                 $url_parts = array();
471
472                                 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
473
474                                 $pass = urlencode($pass);
475
476                                 if ($url_parts[1] && $url_parts[2]) {
477                                         $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
478                                 }
479                         }
480
481                         // TODO: should this support POST requests or not? idk
482
483                         if (!$post_query && $timestamp) {
484                                  $context = stream_context_create(array(
485                                           'http' => array(
486                                                         'method' => 'GET',
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)
491                                           )));
492                         } else {
493                                  $context = stream_context_create(array(
494                                           'http' => array(
495                                                         'method' => 'GET',
496                                                     'ignore_errors' => true,
497                                                     'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
498                                                         'protocol_version'=> 1.1
499                                           )));
500                         }
501
502                         $old_error = error_get_last();
503
504                         $data = @file_get_contents($url, false, $context);
505
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
512                                         }
513
514                                         if (substr(strtolower($h), 0, 7) == 'http/1.') {
515                                                 $fetch_last_error_code = (int) substr($h, 9, 3);
516                                         }
517                                 }
518                         }
519
520                         if ($fetch_last_error_code != 200) {
521                                 $error = error_get_last();
522
523                                 if ($error['message'] != $old_error['message']) {
524                                         $fetch_last_error = $error["message"];
525                                 } else {
526                                         $fetch_last_error = "HTTP Code: $fetch_last_error_code";
527                                 }
528
529                                 $fetch_last_error_content = $data;
530
531                                 return false;
532                         }
533                         return $data;
534                 }
535
536         }
537
538         /**
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
542          *
543          * @param string $url A feed or page URL
544          * @access public
545          * @return mixed The favicon URL, or false if none was found.
546          */
547         function get_favicon_url($url) {
548
549                 $favicon_url = false;
550
551                 if ($html = @fetch_file_contents($url)) {
552
553                         libxml_use_internal_errors(true);
554
555                         $doc = new DOMDocument();
556                         $doc->loadHTML($html);
557                         $xpath = new DOMXPath($doc);
558
559                         $base = $xpath->query('/html/head/base');
560                         foreach ($base as $b) {
561                                 $url = $b->getAttribute("href");
562                                 break;
563                         }
564
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"));
569                                         break;
570                                 }
571                         }
572                 }
573
574                 if (!$favicon_url)
575                         $favicon_url = rewrite_relative_url($url, "/favicon.ico");
576
577                 return $favicon_url;
578         } // function get_favicon_url
579
580         function check_feed_favicon($site_url, $feed) {
581 #               print "FAVICON [$site_url]: $favicon_url\n";
582
583                 $icon_file = ICONS_DIR . "/$feed.ico";
584
585                 if (!file_exists($icon_file)) {
586                         $favicon_url = get_favicon_url($site_url);
587
588                         if ($favicon_url) {
589                                 // Limiting to "image" type misses those served with text/plain
590                                 $contents = fetch_file_contents($favicon_url); // , "image");
591
592                                 if ($contents) {
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");
598                                         }
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");
602                                         }
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");
606                                         }
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");
610                                         }
611                                         else {
612                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
613                                                 $contents = "";
614                                         }
615                                 }
616
617                                 if ($contents) {
618                                         $fp = @fopen($icon_file, "w");
619
620                                         if ($fp) {
621                                                 fwrite($fp, $contents);
622                                                 fclose($fp);
623                                                 chmod($icon_file, 0644);
624                                         }
625                                 }
626                         }
627             return $icon_file;
628                 }
629         }
630
631         function print_select($id, $default, $values, $attributes = "", $name = "") {
632                 if (!$name) $name = $id;
633
634                 print "<select name=\"$name\" id=\"$id\" $attributes>";
635                 foreach ($values as $v) {
636                         if ($v == $default)
637                                 $sel = "selected=\"1\"";
638                          else
639                                 $sel = "";
640
641                         $v = trim($v);
642
643                         print "<option value=\"$v\" $sel>$v</option>";
644                 }
645                 print "</select>";
646         }
647
648         function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
649                 if (!$name) $name = $id;
650
651                 print "<select name=\"$name\" id='$id' $attributes>";
652                 foreach (array_keys($values) as $v) {
653                         if ($v == $default)
654                                 $sel = 'selected="selected"';
655                          else
656                                 $sel = "";
657
658                         $v = trim($v);
659
660                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
661                 }
662
663                 print "</select>";
664         }
665
666         function print_hidden($name, $value) {
667                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"$name\" value=\"$value\">";
668         }
669
670         function print_checkbox($id, $checked, $value = "", $attributes = "") {
671                 $checked_str = $checked ? "checked" : "";
672                 $value_str = $value ? "value=\"$value\"" : "";
673
674                 print "<input dojoType=\"dijit.form.CheckBox\" id=\"$id\" $value_str $checked_str $attributes name=\"$id\">";
675         }
676
677         function print_button($type, $value, $attributes = "") {
678                 print "<p><button dojoType=\"dijit.form.Button\" $attributes type=\"$type\">$value</button>";
679         }
680
681         function print_radio($id, $default, $true_is, $values, $attributes = "") {
682                 foreach ($values as $v) {
683
684                         if ($v == $default)
685                                 $sel = "checked";
686                          else
687                                 $sel = "";
688
689                         if ($v == $true_is) {
690                                 $sel .= " value=\"1\"";
691                         } else {
692                                 $sel .= " value=\"0\"";
693                         }
694
695                         print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
696                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
697
698                 }
699         }
700
701         function initialize_user_prefs($uid, $profile = false) {
702
703                 $uid = db_escape_string($uid);
704
705                 if (!$profile) {
706                         $profile = "NULL";
707                         $profile_qpart = "AND profile IS NULL";
708                 } else {
709                         $profile_qpart = "AND profile = '$profile'";
710                 }
711
712                 if (get_schema_version() < 63) $profile_qpart = "";
713
714                 db_query("BEGIN");
715
716                 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
717
718                 $u_result = db_query("SELECT pref_name
719                         FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
720
721                 $active_prefs = array();
722
723                 while ($line = db_fetch_assoc($u_result)) {
724                         array_push($active_prefs, $line["pref_name"]);
725                 }
726
727                 while ($line = db_fetch_assoc($result)) {
728                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
729 //                              print "adding " . $line["pref_name"] . "<br>";
730
731                                 $line["def_value"] = db_escape_string($line["def_value"]);
732                                 $line["pref_name"] = db_escape_string($line["pref_name"]);
733
734                                 if (get_schema_version() < 63) {
735                                         db_query("INSERT INTO ttrss_user_prefs
736                                                 (owner_uid,pref_name,value) VALUES
737                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
738
739                                 } else {
740                                         db_query("INSERT INTO ttrss_user_prefs
741                                                 (owner_uid,pref_name,value, profile) VALUES
742                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
743                                 }
744
745                         }
746                 }
747
748                 db_query("COMMIT");
749
750         }
751
752         function get_ssl_certificate_id() {
753                 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
754                         return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
755                                 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
756                                 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
757                                 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
758                 }
759                 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
760                         return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
761                                 $_SERVER["SSL_CLIENT_V_START"] .
762                                 $_SERVER["SSL_CLIENT_V_END"] .
763                                 $_SERVER["SSL_CLIENT_S_DN"]);
764                 }
765                 return "";
766         }
767
768         function authenticate_user($login, $password, $check_only = false) {
769
770                 if (!SINGLE_USER_MODE) {
771                         $user_id = false;
772
773                         foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
774
775                                 $user_id = (int) $plugin->authenticate($login, $password);
776
777                                 if ($user_id) {
778                                         $_SESSION["auth_module"] = strtolower(get_class($plugin));
779                                         break;
780                                 }
781                         }
782
783                         if ($user_id && !$check_only) {
784                                 @session_start();
785
786                                 $_SESSION["uid"] = $user_id;
787                                 $_SESSION["version"] = VERSION_STATIC;
788
789                                 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
790                                         WHERE id = '$user_id'");
791
792                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
793                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
794                                 $_SESSION["csrf_token"] = uniqid_short();
795
796                                 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
797                                         $_SESSION["uid"]);
798
799                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
800                                 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
801                                 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
802
803                                 $_SESSION["last_version_check"] = time();
804
805                                 initialize_user_prefs($_SESSION["uid"]);
806
807                                 return true;
808                         }
809
810                         return false;
811
812                 } else {
813
814                         $_SESSION["uid"] = 1;
815                         $_SESSION["name"] = "admin";
816                         $_SESSION["access_level"] = 10;
817
818                         $_SESSION["hide_hello"] = true;
819                         $_SESSION["hide_logout"] = true;
820
821                         $_SESSION["auth_module"] = false;
822
823                         if (!$_SESSION["csrf_token"]) {
824                                 $_SESSION["csrf_token"] = uniqid_short();
825                         }
826
827                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
828
829                         initialize_user_prefs($_SESSION["uid"]);
830
831                         return true;
832                 }
833         }
834
835         function make_password($length = 8) {
836
837                 $password = "";
838                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
839
840         $i = 0;
841
842                 while ($i < $length) {
843                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
844
845                         if (!strstr($password, $char)) {
846                                 $password .= $char;
847                                 $i++;
848                         }
849                 }
850                 return $password;
851         }
852
853         // this is called after user is created to initialize default feeds, labels
854         // or whatever else
855
856         // user preferences are checked on every login, not here
857
858         function initialize_user($uid) {
859
860                 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
861                         values ('$uid', 'Tiny Tiny RSS: Forum',
862                                 'http://tt-rss.org/forum/rss.php')");
863         }
864
865         function logout_user() {
866                 session_destroy();
867                 if (isset($_COOKIE[session_name()])) {
868                    setcookie(session_name(), '', time()-42000, '/');
869                 }
870         }
871
872         function validate_csrf($csrf_token) {
873                 return $csrf_token == $_SESSION['csrf_token'];
874         }
875
876         function load_user_plugins($owner_uid, $pluginhost = false) {
877
878                 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
879
880                 if ($owner_uid && SCHEMA_VERSION >= 100) {
881                         $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
882
883                         $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
884
885                         if (get_schema_version() > 100) {
886                                 $pluginhost->load_data();
887                         }
888                 }
889         }
890
891         function login_sequence() {
892                 if (SINGLE_USER_MODE) {
893                         @session_start();
894                         authenticate_user("admin", null);
895                         startup_gettext();
896                         load_user_plugins($_SESSION["uid"]);
897                 } else {
898                         if (!validate_session()) $_SESSION["uid"] = false;
899
900                         if (!$_SESSION["uid"]) {
901
902                                 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
903                                     $_SESSION["ref_schema_version"] = get_schema_version(true);
904                                 } else {
905                                          authenticate_user(null, null, true);
906                                 }
907
908                                 if (!$_SESSION["uid"]) {
909                                         @session_destroy();
910                                         setcookie(session_name(), '', time()-42000, '/');
911
912                                         render_login_form();
913                                         exit;
914                                 }
915
916                         } else {
917                                 /* bump login timestamp */
918                                 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
919                                         $_SESSION["uid"]);
920                                 $_SESSION["last_login_update"] = time();
921                         }
922
923                         if ($_SESSION["uid"]) {
924                                 startup_gettext();
925                                 load_user_plugins($_SESSION["uid"]);
926
927                                 /* cleanup ccache */
928
929                                 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
930                                         $_SESSION["uid"] . " AND
931                                                 (SELECT COUNT(id) FROM ttrss_feeds WHERE
932                                                         ttrss_feeds.id = feed_id) = 0");
933
934                                 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
935                                         $_SESSION["uid"] . " AND
936                                                 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
937                                                         ttrss_feed_categories.id = feed_id) = 0");
938
939                         }
940
941                 }
942         }
943
944         function truncate_string($str, $max_len, $suffix = '&hellip;') {
945                 if (mb_strlen($str, "utf-8") > $max_len) {
946                         return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
947                 } else {
948                         return $str;
949                 }
950         }
951
952         // is not utf8 clean
953         function truncate_middle($str, $max_len, $suffix = '&hellip;') {
954                 if (strlen($str) > $max_len) {
955                         return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
956                 } else {
957                         return $str;
958                 }
959         }
960
961         function convert_timestamp($timestamp, $source_tz, $dest_tz) {
962
963                 try {
964                         $source_tz = new DateTimeZone($source_tz);
965                 } catch (Exception $e) {
966                         $source_tz = new DateTimeZone('UTC');
967                 }
968
969                 try {
970                         $dest_tz = new DateTimeZone($dest_tz);
971                 } catch (Exception $e) {
972                         $dest_tz = new DateTimeZone('UTC');
973                 }
974
975                 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
976                 return $dt->format('U') + $dest_tz->getOffset($dt);
977         }
978
979         function make_local_datetime($timestamp, $long, $owner_uid = false,
980                                         $no_smart_dt = false, $eta_min = false) {
981
982                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
983                 if (!$timestamp) $timestamp = '1970-01-01 0:00';
984
985                 global $utc_tz;
986                 global $user_tz;
987
988                 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
989
990                 $timestamp = substr($timestamp, 0, 19);
991
992                 # We store date in UTC internally
993                 $dt = new DateTime($timestamp, $utc_tz);
994
995                 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
996
997                 if ($user_tz_string != 'Automatic') {
998
999                         try {
1000                                 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
1001                         } catch (Exception $e) {
1002                                 $user_tz = $utc_tz;
1003                         }
1004
1005                         $tz_offset = $user_tz->getOffset($dt);
1006                 } else {
1007                         $tz_offset = (int) -$_SESSION["clientTzOffset"];
1008                 }
1009
1010                 $user_timestamp = $dt->format('U') + $tz_offset;
1011
1012                 if (!$no_smart_dt) {
1013                         return smart_date_time($user_timestamp,
1014                                 $tz_offset, $owner_uid, $eta_min);
1015                 } else {
1016                         if ($long)
1017                                 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1018                         else
1019                                 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1020
1021                         return date($format, $user_timestamp);
1022                 }
1023         }
1024
1025         function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
1026                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1027
1028                 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
1029                         return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
1030                 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
1031                         return date("G:i", $timestamp);
1032                 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
1033                         $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1034                         return date($format, $timestamp);
1035                 } else {
1036                         $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1037                         return date($format, $timestamp);
1038                 }
1039         }
1040
1041         function sql_bool_to_bool($s) {
1042                 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
1043                         return true;
1044                 } else {
1045                         return false;
1046                 }
1047         }
1048
1049         function bool_to_sql_bool($s) {
1050                 if ($s) {
1051                         return "true";
1052                 } else {
1053                         return "false";
1054                 }
1055         }
1056
1057         // Session caching removed due to causing wrong redirects to upgrade
1058         // script when get_schema_version() is called on an obsolete session
1059         // created on a previous schema version.
1060         function get_schema_version($nocache = false) {
1061                 global $schema_version;
1062
1063                 if (!$schema_version && !$nocache) {
1064                         $result = db_query("SELECT schema_version FROM ttrss_version");
1065                         $version = db_fetch_result($result, 0, "schema_version");
1066                         $schema_version = $version;
1067                         return $version;
1068                 } else {
1069                         return $schema_version;
1070                 }
1071         }
1072
1073         function sanity_check() {
1074                 require_once 'errors.php';
1075                 global $ERRORS;
1076
1077                 $error_code = 0;
1078                 $schema_version = get_schema_version(true);
1079
1080                 if ($schema_version != SCHEMA_VERSION) {
1081                         $error_code = 5;
1082                 }
1083
1084                 if (DB_TYPE == "mysql") {
1085                         $result = db_query("SELECT true", false);
1086                         if (db_num_rows($result) != 1) {
1087                                 $error_code = 10;
1088                         }
1089                 }
1090
1091                 if (db_escape_string("testTEST") != "testTEST") {
1092                         $error_code = 12;
1093                 }
1094
1095                 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1096         }
1097
1098         function file_is_locked($filename) {
1099                 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1100                         if (function_exists('flock')) {
1101                                 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1102                                 if ($fp) {
1103                                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1104                                                 flock($fp, LOCK_UN);
1105                                                 fclose($fp);
1106                                                 return false;
1107                                         }
1108                                         fclose($fp);
1109                                         return true;
1110                                 } else {
1111                                         return false;
1112                                 }
1113                         }
1114                         return true; // consider the file always locked and skip the test
1115                 } else {
1116                         return false;
1117                 }
1118         }
1119
1120
1121         function make_lockfile($filename) {
1122                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1123
1124                 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1125                         $stat_h = fstat($fp);
1126                         $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1127
1128                         if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1129                                 if ($stat_h["ino"] != $stat_f["ino"] ||
1130                                                 $stat_h["dev"] != $stat_f["dev"]) {
1131
1132                                         return false;
1133                                 }
1134                         }
1135
1136                         if (function_exists('posix_getpid')) {
1137                                 fwrite($fp, posix_getpid() . "\n");
1138                         }
1139                         return $fp;
1140                 } else {
1141                         return false;
1142                 }
1143         }
1144
1145         function make_stampfile($filename) {
1146                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1147
1148                 if (flock($fp, LOCK_EX | LOCK_NB)) {
1149                         fwrite($fp, time() . "\n");
1150                         flock($fp, LOCK_UN);
1151                         fclose($fp);
1152                         return true;
1153                 } else {
1154                         return false;
1155                 }
1156         }
1157
1158         function sql_random_function() {
1159                 if (DB_TYPE == "mysql") {
1160                         return "RAND()";
1161                 } else {
1162                         return "RANDOM()";
1163                 }
1164         }
1165
1166         function catchup_feed($feed, $cat_view, $owner_uid = false, $mode = 'all', $search = false) {
1167
1168                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1169
1170                 // Todo: all this interval stuff needs some generic generator function
1171
1172                 $date_qpart = "false";
1173                 $search_qpart = is_array($search) && $search[0] ? search_to_sql($search[0], $search[1])[0] : 'true';
1174
1175                 switch ($mode) {
1176                 case "1day":
1177                         if (DB_TYPE == "pgsql") {
1178                                 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1179                         } else {
1180                                 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1181                         }
1182                         break;
1183                 case "1week":
1184                         if (DB_TYPE == "pgsql") {
1185                                 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1186                         } else {
1187                                 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1188                         }
1189                         break;
1190                 case "2week":
1191                         if (DB_TYPE == "pgsql") {
1192                                 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1193                         } else {
1194                                 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1195                         }
1196                         break;
1197                 default:
1198                         $date_qpart = "true";
1199                 }
1200
1201                 if (is_numeric($feed)) {
1202                         if ($cat_view) {
1203
1204                                 if ($feed >= 0) {
1205
1206                                         if ($feed > 0) {
1207                                                 $children = getChildCategories($feed, $owner_uid);
1208                                                 array_push($children, $feed);
1209
1210                                                 $children = join(",", $children);
1211
1212                                                 $cat_qpart = "cat_id IN ($children)";
1213                                         } else {
1214                                                 $cat_qpart = "cat_id IS NULL";
1215                                         }
1216
1217                                         db_query("UPDATE ttrss_user_entries
1218                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1219                                                         (SELECT id FROM
1220                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1221                                                                         AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1222                                                                                 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart AND $search_qpart) as tmp)");
1223
1224                                 } else if ($feed == -2) {
1225
1226                                         db_query("UPDATE ttrss_user_entries
1227                                                 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1228                                                         FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart AND $search_qpart) > 0
1229                                                         AND unread = true AND owner_uid = $owner_uid");
1230                                 }
1231
1232                         } else if ($feed > 0) {
1233
1234                                 db_query("UPDATE ttrss_user_entries
1235                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1236                                                 (SELECT id FROM
1237                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1238                                                                 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart AND $search_qpart) as tmp)");
1239
1240                         } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1241
1242                                 if ($feed == -1) {
1243                                         db_query("UPDATE ttrss_user_entries
1244                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1245                                                         (SELECT id FROM
1246                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1247                                                                         AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart AND $search_qpart) as tmp)");
1248                                 }
1249
1250                                 if ($feed == -2) {
1251                                         db_query("UPDATE ttrss_user_entries
1252                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1253                                                         (SELECT id FROM
1254                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1255                                                                         AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart AND $search_qpart) as tmp)");
1256                                 }
1257
1258                                 if ($feed == -3) {
1259
1260                                         $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1261
1262                                         if (DB_TYPE == "pgsql") {
1263                                                 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1264                                         } else {
1265                                                 $match_part = "date_entered > DATE_SUB(NOW(),
1266                                                         INTERVAL $intl HOUR) ";
1267                                         }
1268
1269                                         db_query("UPDATE ttrss_user_entries
1270                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1271                                                         (SELECT id FROM
1272                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1273                                                                         AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part AND $search_qpart) as tmp)");
1274                                 }
1275
1276                                 if ($feed == -4) {
1277                                         db_query("UPDATE ttrss_user_entries
1278                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1279                                                         (SELECT id FROM
1280                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1281                                                                         AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1282                                 }
1283
1284                         } else if ($feed < LABEL_BASE_INDEX) { // label
1285
1286                                 $label_id = feed_to_label_id($feed);
1287
1288                                 db_query("UPDATE ttrss_user_entries
1289                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1290                                                 (SELECT id FROM
1291                                                         (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1292                                                                 AND label_id = '$label_id' AND ref_id = article_id
1293                                                                 AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1294
1295                         }
1296
1297                         ccache_update($feed, $owner_uid, $cat_view);
1298
1299                 } else { // tag
1300                         db_query("UPDATE ttrss_user_entries
1301                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1302                                         (SELECT id FROM
1303                                                 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1304                                                         AND post_int_id = int_id AND tag_name = '$feed'
1305                                                         AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1306
1307                 }
1308         }
1309
1310         function getAllCounters() {
1311                 $data = getGlobalCounters();
1312
1313                 $data = array_merge($data, getVirtCounters());
1314                 $data = array_merge($data, getLabelCounters());
1315                 $data = array_merge($data, getFeedCounters());
1316                 $data = array_merge($data, getCategoryCounters());
1317
1318                 return $data;
1319         }
1320
1321         function getCategoryTitle($cat_id) {
1322
1323                 if ($cat_id == -1) {
1324                         return __("Special");
1325                 } else if ($cat_id == -2) {
1326                         return __("Labels");
1327                 } else {
1328
1329                         $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1330                                 id = '$cat_id'");
1331
1332                         if (db_num_rows($result) == 1) {
1333                                 return db_fetch_result($result, 0, "title");
1334                         } else {
1335                                 return __("Uncategorized");
1336                         }
1337                 }
1338         }
1339
1340
1341         function getCategoryCounters() {
1342                 $ret_arr = array();
1343
1344                 /* Labels category */
1345
1346                 $cv = array("id" => -2, "kind" => "cat",
1347                         "counter" => getCategoryUnread(-2));
1348
1349                 array_push($ret_arr, $cv);
1350
1351                 $result = db_query("SELECT id AS cat_id, value AS unread,
1352                         (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1353                                 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1354                         FROM ttrss_feed_categories, ttrss_cat_counters_cache
1355                         WHERE ttrss_cat_counters_cache.feed_id = id AND
1356                         ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1357                         ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1358
1359                 while ($line = db_fetch_assoc($result)) {
1360                         $line["cat_id"] = (int) $line["cat_id"];
1361
1362                         if ($line["num_children"] > 0) {
1363                                 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1364                         } else {
1365                                 $child_counter = 0;
1366                         }
1367
1368                         $cv = array("id" => $line["cat_id"], "kind" => "cat",
1369                                 "counter" => $line["unread"] + $child_counter);
1370
1371                         array_push($ret_arr, $cv);
1372                 }
1373
1374                 /* Special case: NULL category doesn't actually exist in the DB */
1375
1376                 $cv = array("id" => 0, "kind" => "cat",
1377                         "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1378
1379                 array_push($ret_arr, $cv);
1380
1381                 return $ret_arr;
1382         }
1383
1384         // only accepts real cats (>= 0)
1385         function getCategoryChildrenUnread($cat, $owner_uid = false) {
1386                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1387
1388                 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1389                                 AND owner_uid = $owner_uid");
1390
1391                 $unread = 0;
1392
1393                 while ($line = db_fetch_assoc($result)) {
1394                         $unread += getCategoryUnread($line["id"], $owner_uid);
1395                         $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1396                 }
1397
1398                 return $unread;
1399         }
1400
1401         function getCategoryUnread($cat, $owner_uid = false) {
1402
1403                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1404
1405                 if ($cat >= 0) {
1406
1407                         if ($cat != 0) {
1408                                 $cat_query = "cat_id = '$cat'";
1409                         } else {
1410                                 $cat_query = "cat_id IS NULL";
1411                         }
1412
1413                         $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1414                                         AND owner_uid = " . $owner_uid);
1415
1416                         $cat_feeds = array();
1417                         while ($line = db_fetch_assoc($result)) {
1418                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
1419                         }
1420
1421                         if (count($cat_feeds) == 0) return 0;
1422
1423                         $match_part = implode(" OR ", $cat_feeds);
1424
1425                         $result = db_query("SELECT COUNT(int_id) AS unread
1426                                 FROM ttrss_user_entries
1427                                 WHERE   unread = true AND ($match_part)
1428                                 AND owner_uid = " . $owner_uid);
1429
1430                         $unread = 0;
1431
1432                         # this needs to be rewritten
1433                         while ($line = db_fetch_assoc($result)) {
1434                                 $unread += $line["unread"];
1435                         }
1436
1437                         return $unread;
1438                 } else if ($cat == -1) {
1439                         return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1440                 } else if ($cat == -2) {
1441
1442                         $result = db_query("
1443                                 SELECT COUNT(unread) AS unread FROM
1444                                         ttrss_user_entries, ttrss_user_labels2
1445                                 WHERE article_id = ref_id AND unread = true
1446                                         AND ttrss_user_entries.owner_uid = '$owner_uid'");
1447
1448                         $unread = db_fetch_result($result, 0, "unread");
1449
1450                         return $unread;
1451
1452                 }
1453         }
1454
1455         function getFeedUnread($feed, $is_cat = false) {
1456                 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1457         }
1458
1459         function getLabelUnread($label_id, $owner_uid = false) {
1460                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1461
1462                 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1463                         WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1464
1465                 if (db_num_rows($result) != 0) {
1466                         return db_fetch_result($result, 0, "unread");
1467                 } else {
1468                         return 0;
1469                 }
1470         }
1471
1472         function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1473                 $owner_uid = false) {
1474
1475                 $n_feed = (int) $feed;
1476                 $need_entries = false;
1477
1478                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1479
1480                 if ($unread_only) {
1481                         $unread_qpart = "unread = true";
1482                 } else {
1483                         $unread_qpart = "true";
1484                 }
1485
1486                 if ($is_cat) {
1487                         return getCategoryUnread($n_feed, $owner_uid);
1488                 } else if ($n_feed == -6) {
1489                         return 0;
1490                 } else if ($feed != "0" && $n_feed == 0) {
1491
1492                         $feed = db_escape_string($feed);
1493
1494                         $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1495                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1496                                         AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1497                                 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1498                         return db_fetch_result($result, 0, "count");
1499
1500                 } else if ($n_feed == -1) {
1501                         $match_part = "marked = true";
1502                 } else if ($n_feed == -2) {
1503                         $match_part = "published = true";
1504                 } else if ($n_feed == -3) {
1505                         $match_part = "unread = true AND score >= 0";
1506
1507                         $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1508
1509                         if (DB_TYPE == "pgsql") {
1510                                 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1511                         } else {
1512                                 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1513                         }
1514
1515                         $need_entries = true;
1516
1517                 } else if ($n_feed == -4) {
1518                         $match_part = "true";
1519                 } else if ($n_feed >= 0) {
1520
1521                         if ($n_feed != 0) {
1522                                 $match_part = "feed_id = '$n_feed'";
1523                         } else {
1524                                 $match_part = "feed_id IS NULL";
1525                         }
1526
1527                 } else if ($feed < LABEL_BASE_INDEX) {
1528
1529                         $label_id = feed_to_label_id($feed);
1530
1531                         return getLabelUnread($label_id, $owner_uid);
1532
1533                 }
1534
1535                 if ($match_part) {
1536
1537                         if ($need_entries) {
1538                                 $from_qpart = "ttrss_user_entries,ttrss_entries";
1539                                 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1540                         } else {
1541                                 $from_qpart = "ttrss_user_entries";
1542                                 $from_where = "";
1543                         }
1544
1545                         $query = "SELECT count(int_id) AS unread
1546                                 FROM $from_qpart WHERE
1547                                 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1548
1549                         //echo "[$feed/$query]\n";
1550
1551                         $result = db_query($query);
1552
1553                 } else {
1554
1555                         $result = db_query("SELECT COUNT(post_int_id) AS unread
1556                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1557                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1558                                 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1559                 }
1560
1561                 $unread = db_fetch_result($result, 0, "unread");
1562
1563                 return $unread;
1564         }
1565
1566         function getGlobalUnread($user_id = false) {
1567
1568                 if (!$user_id) {
1569                         $user_id = $_SESSION["uid"];
1570                 }
1571
1572                 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1573                         WHERE owner_uid = '$user_id' AND feed_id > 0");
1574
1575                 $c_id = db_fetch_result($result, 0, "c_id");
1576
1577                 return $c_id;
1578         }
1579
1580         function getGlobalCounters($global_unread = -1) {
1581                 $ret_arr = array();
1582
1583                 if ($global_unread == -1) {
1584                         $global_unread = getGlobalUnread();
1585                 }
1586
1587                 $cv = array("id" => "global-unread",
1588                         "counter" => (int) $global_unread);
1589
1590                 array_push($ret_arr, $cv);
1591
1592                 $result = db_query("SELECT COUNT(id) AS fn FROM
1593                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1594
1595                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1596
1597                 $cv = array("id" => "subscribed-feeds",
1598                         "counter" => (int) $subscribed_feeds);
1599
1600                 array_push($ret_arr, $cv);
1601
1602                 return $ret_arr;
1603         }
1604
1605         function getVirtCounters() {
1606
1607                 $ret_arr = array();
1608
1609                 for ($i = 0; $i >= -4; $i--) {
1610
1611                         $count = getFeedUnread($i);
1612
1613                         if ($i == 0 || $i == -1 || $i == -2)
1614                                 $auxctr = getFeedArticles($i, false);
1615                         else
1616                                 $auxctr = 0;
1617
1618                         $cv = array("id" => $i,
1619                                 "counter" => (int) $count,
1620                                 "auxcounter" => (int) $auxctr);
1621
1622 //                      if (get_pref('EXTENDED_FEEDLIST'))
1623 //                              $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1624
1625                         array_push($ret_arr, $cv);
1626                 }
1627
1628                 $feeds = PluginHost::getInstance()->get_feeds(-1);
1629
1630                 if (is_array($feeds)) {
1631                         foreach ($feeds as $feed) {
1632                                 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1633                                         "counter" => $feed['sender']->get_unread($feed['id']));
1634
1635                                 if (method_exists($feed['sender'], 'get_total'))
1636                                         $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1637
1638                                 array_push($ret_arr, $cv);
1639                         }
1640                 }
1641
1642                 return $ret_arr;
1643         }
1644
1645         function getLabelCounters($descriptions = false) {
1646
1647                 $ret_arr = array();
1648
1649                 $owner_uid = $_SESSION["uid"];
1650
1651                 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1652                         FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1653                                 (ttrss_labels2.id = label_id)
1654                                 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1655                                 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1656                                 GROUP BY ttrss_labels2.id,
1657                                         ttrss_labels2.caption");
1658
1659                 while ($line = db_fetch_assoc($result)) {
1660
1661                         $id = label_to_feed_id($line["id"]);
1662
1663                         $cv = array("id" => $id,
1664                                 "counter" => (int) $line["unread"],
1665                                 "auxcounter" => (int) $line["total"]);
1666
1667                         if ($descriptions)
1668                                 $cv["description"] = $line["caption"];
1669
1670                         array_push($ret_arr, $cv);
1671                 }
1672
1673                 return $ret_arr;
1674         }
1675
1676         function getFeedCounters($active_feed = false) {
1677
1678                 $ret_arr = array();
1679
1680                 $query = "SELECT ttrss_feeds.id,
1681                                 ttrss_feeds.title,
1682                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1683                                 last_error, value AS count
1684                         FROM ttrss_feeds, ttrss_counters_cache
1685                         WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1686                                 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1687                                 AND ttrss_counters_cache.feed_id = id";
1688
1689                 $result = db_query($query);
1690
1691                 while ($line = db_fetch_assoc($result)) {
1692
1693                         $id = $line["id"];
1694                         $count = $line["count"];
1695                         $last_error = htmlspecialchars($line["last_error"]);
1696
1697                         $last_updated = make_local_datetime($line['last_updated'], false);
1698
1699                         $has_img = feed_has_icon($id);
1700
1701                         if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1702                                 $last_updated = '';
1703
1704                         $cv = array("id" => $id,
1705                                 "updated" => $last_updated,
1706                                 "counter" => (int) $count,
1707                                 "has_img" => (int) $has_img);
1708
1709                         if ($last_error)
1710                                 $cv["error"] = $last_error;
1711
1712 //                      if (get_pref('EXTENDED_FEEDLIST'))
1713 //                              $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1714
1715                         if ($active_feed && $id == $active_feed)
1716                                 $cv["title"] = truncate_string($line["title"], 30);
1717
1718                         array_push($ret_arr, $cv);
1719
1720                 }
1721
1722                 return $ret_arr;
1723         }
1724
1725         function get_pgsql_version() {
1726                 $result = db_query("SELECT version() AS version");
1727                 $version = explode(" ", db_fetch_result($result, 0, "version"));
1728                 return $version[1];
1729         }
1730
1731         /**
1732          * @return array (code => Status code, message => error message if available)
1733          *
1734          *                 0 - OK, Feed already exists
1735          *                 1 - OK, Feed added
1736          *                 2 - Invalid URL
1737          *                 3 - URL content is HTML, no feeds available
1738          *                 4 - URL content is HTML which contains multiple feeds.
1739          *                     Here you should call extractfeedurls in rpc-backend
1740          *                     to get all possible feeds.
1741          *                 5 - Couldn't download the URL content.
1742          *                 6 - Content is an invalid XML.
1743          */
1744         function subscribe_to_feed($url, $cat_id = 0,
1745                         $auth_login = '', $auth_pass = '') {
1746
1747                 global $fetch_last_error;
1748                 global $fetch_last_error_content;
1749
1750                 require_once "include/rssfuncs.php";
1751
1752                 $url = fix_url($url);
1753
1754                 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1755
1756                 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1757
1758                 if (!$contents) {
1759                         if (preg_match("/cloudflare\.com/", $fetch_last_error_content)) {
1760                                 $fetch_last_error .= " (feed behind Cloudflare)";
1761                         }
1762
1763                         return array("code" => 5, "message" => $fetch_last_error);
1764                 }
1765
1766                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1767                         $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1768                 }
1769
1770                 if (is_html($contents)) {
1771                         $feedUrls = get_feeds_from_html($url, $contents);
1772
1773                         if (count($feedUrls) == 0) {
1774                                 return array("code" => 3);
1775                         } else if (count($feedUrls) > 1) {
1776                                 return array("code" => 4, "feeds" => $feedUrls);
1777                         }
1778                         //use feed url as new URL
1779                         $url = key($feedUrls);
1780                 }
1781
1782                 if ($cat_id == "0" || !$cat_id) {
1783                         $cat_qpart = "NULL";
1784                 } else {
1785                         $cat_qpart = "'$cat_id'";
1786                 }
1787
1788                 $result = db_query(
1789                         "SELECT id FROM ttrss_feeds
1790                         WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1791
1792                 $auth_pass_encrypted = 'false';
1793                 $auth_pass = db_escape_string($auth_pass);
1794
1795                 if (db_num_rows($result) == 0) {
1796                         $result = db_query(
1797                                 "INSERT INTO ttrss_feeds
1798                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1799                                 VALUES ('".$_SESSION["uid"]."', '$url',
1800                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1801
1802                         $result = db_query(
1803                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1804                                         AND owner_uid = " . $_SESSION["uid"]);
1805
1806                         $feed_id = db_fetch_result($result, 0, "id");
1807
1808                         if ($feed_id) {
1809                                 set_basic_feed_info($feed_id);
1810                         }
1811
1812                         return array("code" => 1, "feed_id" => (int) $feed_id);
1813                 } else {
1814                         return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
1815                 }
1816         }
1817
1818         function print_feed_select($id, $default_id = "",
1819                 $attributes = "", $include_all_feeds = true,
1820                 $root_id = false, $nest_level = 0) {
1821
1822                 if (!$root_id) {
1823                         print "<select id=\"$id\" name=\"$id\" $attributes>";
1824                         if ($include_all_feeds) {
1825                                 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1826                                 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1827                         }
1828                 }
1829
1830                 if (get_pref('ENABLE_FEED_CATS')) {
1831
1832                         if ($root_id)
1833                                 $parent_qpart = "parent_cat = '$root_id'";
1834                         else
1835                                 $parent_qpart = "parent_cat IS NULL";
1836
1837                         $result = db_query("SELECT id,title,
1838                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1839                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1840                                 FROM ttrss_feed_categories
1841                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1842
1843                         while ($line = db_fetch_assoc($result)) {
1844
1845                                 for ($i = 0; $i < $nest_level; $i++)
1846                                         $line["title"] = " - " . $line["title"];
1847
1848                                 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1849
1850                                 printf("<option $is_selected value='CAT:%d'>%s</option>",
1851                                         $line["id"], htmlspecialchars($line["title"]));
1852
1853                                 if ($line["num_children"] > 0)
1854                                         print_feed_select($id, $default_id, $attributes,
1855                                                 $include_all_feeds, $line["id"], $nest_level+1);
1856
1857                                 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1858                                         WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1859
1860                                 while ($fline = db_fetch_assoc($feed_result)) {
1861                                         $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1862
1863                                         $fline["title"] = " + " . $fline["title"];
1864
1865                                         for ($i = 0; $i < $nest_level; $i++)
1866                                                 $fline["title"] = " - " . $fline["title"];
1867
1868                                         printf("<option $is_selected value='%d'>%s</option>",
1869                                                 $fline["id"], htmlspecialchars($fline["title"]));
1870                                 }
1871                         }
1872
1873                         if (!$root_id) {
1874                                 $default_is_cat = ($default_id == "CAT:0");
1875                                 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1876
1877                                 printf("<option $is_selected value='CAT:0'>%s</option>",
1878                                         __("Uncategorized"));
1879
1880                                 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1881                                         WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1882
1883                                 while ($fline = db_fetch_assoc($feed_result)) {
1884                                         $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1885
1886                                         $fline["title"] = " + " . $fline["title"];
1887
1888                                         for ($i = 0; $i < $nest_level; $i++)
1889                                                 $fline["title"] = " - " . $fline["title"];
1890
1891                                         printf("<option $is_selected value='%d'>%s</option>",
1892                                                 $fline["id"], htmlspecialchars($fline["title"]));
1893                                 }
1894                         }
1895
1896                 } else {
1897                         $result = db_query("SELECT id,title FROM ttrss_feeds
1898                                 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1899
1900                         while ($line = db_fetch_assoc($result)) {
1901
1902                                 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1903
1904                                 printf("<option $is_selected value='%d'>%s</option>",
1905                                         $line["id"], htmlspecialchars($line["title"]));
1906                         }
1907                 }
1908
1909                 if (!$root_id) {
1910                         print "</select>";
1911                 }
1912         }
1913
1914         function print_feed_cat_select($id, $default_id,
1915                 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1916
1917                         if (!$root_id) {
1918                                         print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" $attributes>";
1919                         }
1920
1921                         if ($root_id)
1922                                 $parent_qpart = "parent_cat = '$root_id'";
1923                         else
1924                                 $parent_qpart = "parent_cat IS NULL";
1925
1926                         $result = db_query("SELECT id,title,
1927                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1928                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1929                                 FROM ttrss_feed_categories
1930                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1931
1932                         while ($line = db_fetch_assoc($result)) {
1933                                 if ($line["id"] == $default_id) {
1934                                         $is_selected = "selected=\"1\"";
1935                                 } else {
1936                                         $is_selected = "";
1937                                 }
1938
1939                                 for ($i = 0; $i < $nest_level; $i++)
1940                                         $line["title"] = " - " . $line["title"];
1941
1942                                 if ($line["title"])
1943                                         printf("<option $is_selected value='%d'>%s</option>",
1944                                                 $line["id"], htmlspecialchars($line["title"]));
1945
1946                                 if ($line["num_children"] > 0)
1947                                         print_feed_cat_select($id, $default_id, $attributes,
1948                                                 $include_all_cats, $line["id"], $nest_level+1);
1949                         }
1950
1951                         if (!$root_id) {
1952                                 if ($include_all_cats) {
1953                                         if (db_num_rows($result) > 0) {
1954                                                 print "<option disabled=\"1\">--------</option>";
1955                                         }
1956
1957                                         if ($default_id == 0) {
1958                                                 $is_selected = "selected=\"1\"";
1959                                         } else {
1960                                                 $is_selected = "";
1961                                         }
1962
1963                                         print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1964                                 }
1965                                 print "</select>";
1966                         }
1967                 }
1968
1969         function checkbox_to_sql_bool($val) {
1970                 return ($val == "on") ? "true" : "false";
1971         }
1972
1973         function getFeedCatTitle($id) {
1974                 if ($id == -1) {
1975                         return __("Special");
1976                 } else if ($id < LABEL_BASE_INDEX) {
1977                         return __("Labels");
1978                 } else if ($id > 0) {
1979                         $result = db_query("SELECT ttrss_feed_categories.title
1980                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1981                                         cat_id = ttrss_feed_categories.id");
1982                         if (db_num_rows($result) == 1) {
1983                                 return db_fetch_result($result, 0, "title");
1984                         } else {
1985                                 return __("Uncategorized");
1986                         }
1987                 } else {
1988                         return "getFeedCatTitle($id) failed";
1989                 }
1990
1991         }
1992
1993         function getFeedIcon($id) {
1994                 switch ($id) {
1995                 case 0:
1996                         return "images/archive.png";
1997                         break;
1998                 case -1:
1999                         return "images/star.png";
2000                         break;
2001                 case -2:
2002                         return "images/feed.png";
2003                         break;
2004                 case -3:
2005                         return "images/fresh.png";
2006                         break;
2007                 case -4:
2008                         return "images/folder.png";
2009                         break;
2010                 case -6:
2011                         return "images/time.png";
2012                         break;
2013                 default:
2014                         if ($id < LABEL_BASE_INDEX) {
2015                                 return "images/label.png";
2016                         } else {
2017                                 if (file_exists(ICONS_DIR . "/$id.ico"))
2018                                         return ICONS_URL . "/$id.ico";
2019                         }
2020                         break;
2021                 }
2022
2023                 return false;
2024         }
2025
2026         function getFeedTitle($id, $cat = false) {
2027                 if ($cat) {
2028                         return getCategoryTitle($id);
2029                 } else if ($id == -1) {
2030                         return __("Starred articles");
2031                 } else if ($id == -2) {
2032                         return __("Published articles");
2033                 } else if ($id == -3) {
2034                         return __("Fresh articles");
2035                 } else if ($id == -4) {
2036                         return __("All articles");
2037                 } else if ($id === 0 || $id === "0") {
2038                         return __("Archived articles");
2039                 } else if ($id == -6) {
2040                         return __("Recently read");
2041                 } else if ($id < LABEL_BASE_INDEX) {
2042                         $label_id = feed_to_label_id($id);
2043                         $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2044                         if (db_num_rows($result) == 1) {
2045                                 return db_fetch_result($result, 0, "caption");
2046                         } else {
2047                                 return "Unknown label ($label_id)";
2048                         }
2049
2050                 } else if (is_numeric($id) && $id > 0) {
2051                         $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
2052                         if (db_num_rows($result) == 1) {
2053                                 return db_fetch_result($result, 0, "title");
2054                         } else {
2055                                 return "Unknown feed ($id)";
2056                         }
2057                 } else {
2058                         return $id;
2059                 }
2060         }
2061
2062         function uniqid_short() {
2063                 return uniqid(base_convert(rand(), 10, 36));
2064         }
2065
2066         // TODO: less dumb splitting
2067         require_once "functions2.php";