]> git.wh0rd.org Git - tt-rss.git/blob - include/functions.php
fetch_file_contents: set timeout when not using CURL
[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                 if (!is_array($options)) {
349
350                         // falling back on compatibility shim
351                         $options = array(
352                                         "url" => func_get_arg(0),
353                                         "type" => @func_get_arg(1),
354                                         "login" => @func_get_arg(2),
355                                         "pass" => @func_get_arg(3),
356                                         "post_query" => @func_get_arg(4),
357                                         "timeout" => @func_get_arg(5),
358                                         "timestamp" => @func_get_arg(6),
359                                         "useragent" => @func_get_arg(7)
360                         );
361                 }
362
363                 $url = $options["url"];
364                 $type = isset($options["type"]) ? $options["type"] : false;
365                 $login = isset($options["login"]) ? $options["login"] : false;
366                 $pass = isset($options["pass"]) ? $options["pass"] : false;
367                 $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
368                 $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
369                 $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
370                 $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
371
372                 $url = ltrim($url, ' ');
373                 $url = str_replace(' ', '%20', $url);
374
375                 if (strpos($url, "//") === 0)
376                         $url = 'http:' . $url;
377
378                 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
379
380                         $fetch_curl_used = true;
381
382                         $ch = curl_init($url);
383
384                         if ($timestamp && !$post_query) {
385                                 curl_setopt($ch, CURLOPT_HTTPHEADER,
386                                         array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
387                         }
388
389                         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
390                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
391                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
392                         curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
393                         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
394                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
395                         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
396                         curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
397                                 SELF_USER_AGENT);
398                         curl_setopt($ch, CURLOPT_ENCODING, "");
399                         //curl_setopt($ch, CURLOPT_REFERER, $url);
400
401                         if (!ini_get("open_basedir")) {
402                                 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
403                         }
404
405                         if (defined('_CURL_HTTP_PROXY')) {
406                                 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
407                         }
408
409                         if ($post_query) {
410                                 curl_setopt($ch, CURLOPT_POST, true);
411                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
412                         }
413
414                         if ($login && $pass)
415                                 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
416
417                         $contents = @curl_exec($ch);
418
419                         if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
420                                 curl_setopt($ch, CURLOPT_ENCODING, 'none');
421                                 $contents = @curl_exec($ch);
422                         }
423
424                         if ($contents === false) {
425                                 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
426                                 curl_close($ch);
427                                 return false;
428                         }
429
430                         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
431                         $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
432
433                         $fetch_last_error_code = $http_code;
434
435                         if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
436                                 if (curl_errno($ch) != 0) {
437                                         $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
438                                 } else {
439                                         $fetch_last_error = "HTTP Code: $http_code";
440                                 }
441                                 $fetch_last_error_content = $contents;
442                                 curl_close($ch);
443                                 return false;
444                         }
445
446                         curl_close($ch);
447
448                         return $contents;
449                 } else {
450
451                         $fetch_curl_used = false;
452
453                         if ($login && $pass){
454                                 $url_parts = array();
455
456                                 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
457
458                                 $pass = urlencode($pass);
459
460                                 if ($url_parts[1] && $url_parts[2]) {
461                                         $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
462                                 }
463                         }
464
465                         // TODO: should this support POST requests or not? idk
466
467                         if (!$post_query && $timestamp) {
468                                  $context = stream_context_create(array(
469                                           'http' => array(
470                                                         'method' => 'GET',
471                                                     'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
472                                                         'protocol_version'=> 1.1,
473                                                         'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
474                                           )));
475                         } else {
476                                  $context = stream_context_create(array(
477                                           'http' => array(
478                                                         'method' => 'GET',
479                                                     'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
480                                                         'protocol_version'=> 1.1
481                                           )));
482                         }
483
484                         $old_error = error_get_last();
485
486                         $data = @file_get_contents($url, false, $context);
487
488                         $fetch_last_content_type = false;  // reset if no type was sent from server
489                         if (isset($http_response_header) && is_array($http_response_header)) {
490                                 foreach ($http_response_header as $h) {
491                                         if (substr(strtolower($h), 0, 13) == 'content-type:') {
492                                                 $fetch_last_content_type = substr($h, 14);
493                                                 // don't abort here b/c there might be more than one
494                                                 // e.g. if we were being redirected -- last one is the right one
495                                         }
496
497                                         if (substr(strtolower($h), 0, 7) == 'http/1.') {
498                                                 $fetch_last_error_code = (int) substr($h, 9, 3);
499                                         }
500                                 }
501                         }
502
503                         if (!$data) {
504                                 $error = error_get_last();
505
506                                 if ($error['message'] != $old_error['message']) {
507                                         $fetch_last_error = $error["message"];
508                                 } else {
509                                         $fetch_last_error = "HTTP Code: $fetch_last_error_code";
510                                 }
511                         }
512                         return $data;
513                 }
514
515         }
516
517         /**
518          * Try to determine the favicon URL for a feed.
519          * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
520          * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
521          *
522          * @param string $url A feed or page URL
523          * @access public
524          * @return mixed The favicon URL, or false if none was found.
525          */
526         function get_favicon_url($url) {
527
528                 $favicon_url = false;
529
530                 if ($html = @fetch_file_contents($url)) {
531
532                         libxml_use_internal_errors(true);
533
534                         $doc = new DOMDocument();
535                         $doc->loadHTML($html);
536                         $xpath = new DOMXPath($doc);
537
538                         $base = $xpath->query('/html/head/base');
539                         foreach ($base as $b) {
540                                 $url = $b->getAttribute("href");
541                                 break;
542                         }
543
544                         $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
545                         if (count($entries) > 0) {
546                                 foreach ($entries as $entry) {
547                                         $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
548                                         break;
549                                 }
550                         }
551                 }
552
553                 if (!$favicon_url)
554                         $favicon_url = rewrite_relative_url($url, "/favicon.ico");
555
556                 return $favicon_url;
557         } // function get_favicon_url
558
559         function check_feed_favicon($site_url, $feed) {
560 #               print "FAVICON [$site_url]: $favicon_url\n";
561
562                 $icon_file = ICONS_DIR . "/$feed.ico";
563
564                 if (!file_exists($icon_file)) {
565                         $favicon_url = get_favicon_url($site_url);
566
567                         if ($favicon_url) {
568                                 // Limiting to "image" type misses those served with text/plain
569                                 $contents = fetch_file_contents($favicon_url); // , "image");
570
571                                 if ($contents) {
572                                         // Crude image type matching.
573                                         // Patterns gleaned from the file(1) source code.
574                                         if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
575                                                 // 0       string  \000\000\001\000        MS Windows icon resource
576                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
577                                         }
578                                         elseif (preg_match('/^GIF8/', $contents)) {
579                                                 // 0       string          GIF8            GIF image data
580                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
581                                         }
582                                         elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
583                                                 // 0       string          \x89PNG\x0d\x0a\x1a\x0a         PNG image data
584                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
585                                         }
586                                         elseif (preg_match('/^\xff\xd8/', $contents)) {
587                                                 // 0       beshort         0xffd8          JPEG image data
588                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
589                                         }
590                                         else {
591                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
592                                                 $contents = "";
593                                         }
594                                 }
595
596                                 if ($contents) {
597                                         $fp = @fopen($icon_file, "w");
598
599                                         if ($fp) {
600                                                 fwrite($fp, $contents);
601                                                 fclose($fp);
602                                                 chmod($icon_file, 0644);
603                                         }
604                                 }
605                         }
606             return $icon_file;
607                 }
608         }
609
610         function print_select($id, $default, $values, $attributes = "", $name = "") {
611                 if (!$name) $name = $id;
612
613                 print "<select name=\"$name\" id=\"$id\" $attributes>";
614                 foreach ($values as $v) {
615                         if ($v == $default)
616                                 $sel = "selected=\"1\"";
617                          else
618                                 $sel = "";
619
620                         $v = trim($v);
621
622                         print "<option value=\"$v\" $sel>$v</option>";
623                 }
624                 print "</select>";
625         }
626
627         function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
628                 if (!$name) $name = $id;
629
630                 print "<select name=\"$name\" id='$id' $attributes>";
631                 foreach (array_keys($values) as $v) {
632                         if ($v == $default)
633                                 $sel = 'selected="selected"';
634                          else
635                                 $sel = "";
636
637                         $v = trim($v);
638
639                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
640                 }
641
642                 print "</select>";
643         }
644
645         function print_radio($id, $default, $true_is, $values, $attributes = "") {
646                 foreach ($values as $v) {
647
648                         if ($v == $default)
649                                 $sel = "checked";
650                          else
651                                 $sel = "";
652
653                         if ($v == $true_is) {
654                                 $sel .= " value=\"1\"";
655                         } else {
656                                 $sel .= " value=\"0\"";
657                         }
658
659                         print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
660                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
661
662                 }
663         }
664
665         function initialize_user_prefs($uid, $profile = false) {
666
667                 $uid = db_escape_string($uid);
668
669                 if (!$profile) {
670                         $profile = "NULL";
671                         $profile_qpart = "AND profile IS NULL";
672                 } else {
673                         $profile_qpart = "AND profile = '$profile'";
674                 }
675
676                 if (get_schema_version() < 63) $profile_qpart = "";
677
678                 db_query("BEGIN");
679
680                 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
681
682                 $u_result = db_query("SELECT pref_name
683                         FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
684
685                 $active_prefs = array();
686
687                 while ($line = db_fetch_assoc($u_result)) {
688                         array_push($active_prefs, $line["pref_name"]);
689                 }
690
691                 while ($line = db_fetch_assoc($result)) {
692                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
693 //                              print "adding " . $line["pref_name"] . "<br>";
694
695                                 $line["def_value"] = db_escape_string($line["def_value"]);
696                                 $line["pref_name"] = db_escape_string($line["pref_name"]);
697
698                                 if (get_schema_version() < 63) {
699                                         db_query("INSERT INTO ttrss_user_prefs
700                                                 (owner_uid,pref_name,value) VALUES
701                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
702
703                                 } else {
704                                         db_query("INSERT INTO ttrss_user_prefs
705                                                 (owner_uid,pref_name,value, profile) VALUES
706                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
707                                 }
708
709                         }
710                 }
711
712                 db_query("COMMIT");
713
714         }
715
716         function get_ssl_certificate_id() {
717                 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
718                         return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
719                                 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
720                                 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
721                                 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
722                 }
723                 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
724                         return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
725                                 $_SERVER["SSL_CLIENT_V_START"] .
726                                 $_SERVER["SSL_CLIENT_V_END"] .
727                                 $_SERVER["SSL_CLIENT_S_DN"]);
728                 }
729                 return "";
730         }
731
732         function authenticate_user($login, $password, $check_only = false) {
733
734                 if (!SINGLE_USER_MODE) {
735                         $user_id = false;
736
737                         foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
738
739                                 $user_id = (int) $plugin->authenticate($login, $password);
740
741                                 if ($user_id) {
742                                         $_SESSION["auth_module"] = strtolower(get_class($plugin));
743                                         break;
744                                 }
745                         }
746
747                         if ($user_id && !$check_only) {
748                                 @session_start();
749
750                                 $_SESSION["uid"] = $user_id;
751                                 $_SESSION["version"] = VERSION_STATIC;
752
753                                 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
754                                         WHERE id = '$user_id'");
755
756                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
757                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
758                                 $_SESSION["csrf_token"] = uniqid_short();
759
760                                 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
761                                         $_SESSION["uid"]);
762
763                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
764                                 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
765                                 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
766
767                                 $_SESSION["last_version_check"] = time();
768
769                                 initialize_user_prefs($_SESSION["uid"]);
770
771                                 return true;
772                         }
773
774                         return false;
775
776                 } else {
777
778                         $_SESSION["uid"] = 1;
779                         $_SESSION["name"] = "admin";
780                         $_SESSION["access_level"] = 10;
781
782                         $_SESSION["hide_hello"] = true;
783                         $_SESSION["hide_logout"] = true;
784
785                         $_SESSION["auth_module"] = false;
786
787                         if (!$_SESSION["csrf_token"]) {
788                                 $_SESSION["csrf_token"] = uniqid_short();
789                         }
790
791                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
792
793                         initialize_user_prefs($_SESSION["uid"]);
794
795                         return true;
796                 }
797         }
798
799         function make_password($length = 8) {
800
801                 $password = "";
802                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
803
804         $i = 0;
805
806                 while ($i < $length) {
807                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
808
809                         if (!strstr($password, $char)) {
810                                 $password .= $char;
811                                 $i++;
812                         }
813                 }
814                 return $password;
815         }
816
817         // this is called after user is created to initialize default feeds, labels
818         // or whatever else
819
820         // user preferences are checked on every login, not here
821
822         function initialize_user($uid) {
823
824                 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
825                         values ('$uid', 'Tiny Tiny RSS: Forum',
826                                 'http://tt-rss.org/forum/rss.php')");
827         }
828
829         function logout_user() {
830                 session_destroy();
831                 if (isset($_COOKIE[session_name()])) {
832                    setcookie(session_name(), '', time()-42000, '/');
833                 }
834         }
835
836         function validate_csrf($csrf_token) {
837                 return $csrf_token == $_SESSION['csrf_token'];
838         }
839
840         function load_user_plugins($owner_uid, $pluginhost = false) {
841
842                 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
843
844                 if ($owner_uid && SCHEMA_VERSION >= 100) {
845                         $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
846
847                         $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
848
849                         if (get_schema_version() > 100) {
850                                 $pluginhost->load_data();
851                         }
852                 }
853         }
854
855         function login_sequence() {
856                 if (SINGLE_USER_MODE) {
857                         @session_start();
858                         authenticate_user("admin", null);
859                         startup_gettext();
860                         load_user_plugins($_SESSION["uid"]);
861                 } else {
862                         if (!validate_session()) $_SESSION["uid"] = false;
863
864                         if (!$_SESSION["uid"]) {
865
866                                 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
867                                     $_SESSION["ref_schema_version"] = get_schema_version(true);
868                                 } else {
869                                          authenticate_user(null, null, true);
870                                 }
871
872                                 if (!$_SESSION["uid"]) {
873                                         @session_destroy();
874                                         setcookie(session_name(), '', time()-42000, '/');
875
876                                         render_login_form();
877                                         exit;
878                                 }
879
880                         } else {
881                                 /* bump login timestamp */
882                                 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
883                                         $_SESSION["uid"]);
884                                 $_SESSION["last_login_update"] = time();
885                         }
886
887                         if ($_SESSION["uid"]) {
888                                 startup_gettext();
889                                 load_user_plugins($_SESSION["uid"]);
890
891                                 /* cleanup ccache */
892
893                                 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
894                                         $_SESSION["uid"] . " AND
895                                                 (SELECT COUNT(id) FROM ttrss_feeds WHERE
896                                                         ttrss_feeds.id = feed_id) = 0");
897
898                                 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
899                                         $_SESSION["uid"] . " AND
900                                                 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
901                                                         ttrss_feed_categories.id = feed_id) = 0");
902
903                         }
904
905                 }
906         }
907
908         function truncate_string($str, $max_len, $suffix = '&hellip;') {
909                 if (mb_strlen($str, "utf-8") > $max_len) {
910                         return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
911                 } else {
912                         return $str;
913                 }
914         }
915
916         // is not utf8 clean
917         function truncate_middle($str, $max_len, $suffix = '&hellip;') {
918                 if (strlen($str) > $max_len) {
919                         return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
920                 } else {
921                         return $str;
922                 }
923         }
924
925         function convert_timestamp($timestamp, $source_tz, $dest_tz) {
926
927                 try {
928                         $source_tz = new DateTimeZone($source_tz);
929                 } catch (Exception $e) {
930                         $source_tz = new DateTimeZone('UTC');
931                 }
932
933                 try {
934                         $dest_tz = new DateTimeZone($dest_tz);
935                 } catch (Exception $e) {
936                         $dest_tz = new DateTimeZone('UTC');
937                 }
938
939                 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
940                 return $dt->format('U') + $dest_tz->getOffset($dt);
941         }
942
943         function make_local_datetime($timestamp, $long, $owner_uid = false,
944                                         $no_smart_dt = false, $eta_min = false) {
945
946                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
947                 if (!$timestamp) $timestamp = '1970-01-01 0:00';
948
949                 global $utc_tz;
950                 global $user_tz;
951
952                 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
953
954                 $timestamp = substr($timestamp, 0, 19);
955
956                 # We store date in UTC internally
957                 $dt = new DateTime($timestamp, $utc_tz);
958
959                 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
960
961                 if ($user_tz_string != 'Automatic') {
962
963                         try {
964                                 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
965                         } catch (Exception $e) {
966                                 $user_tz = $utc_tz;
967                         }
968
969                         $tz_offset = $user_tz->getOffset($dt);
970                 } else {
971                         $tz_offset = (int) -$_SESSION["clientTzOffset"];
972                 }
973
974                 $user_timestamp = $dt->format('U') + $tz_offset;
975
976                 if (!$no_smart_dt) {
977                         return smart_date_time($user_timestamp,
978                                 $tz_offset, $owner_uid, $eta_min);
979                 } else {
980                         if ($long)
981                                 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
982                         else
983                                 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
984
985                         return date($format, $user_timestamp);
986                 }
987         }
988
989         function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
990                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
991
992                 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
993                         return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
994                 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
995                         return date("G:i", $timestamp);
996                 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
997                         $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
998                         return date($format, $timestamp);
999                 } else {
1000                         $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1001                         return date($format, $timestamp);
1002                 }
1003         }
1004
1005         function sql_bool_to_bool($s) {
1006                 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
1007                         return true;
1008                 } else {
1009                         return false;
1010                 }
1011         }
1012
1013         function bool_to_sql_bool($s) {
1014                 if ($s) {
1015                         return "true";
1016                 } else {
1017                         return "false";
1018                 }
1019         }
1020
1021         // Session caching removed due to causing wrong redirects to upgrade
1022         // script when get_schema_version() is called on an obsolete session
1023         // created on a previous schema version.
1024         function get_schema_version($nocache = false) {
1025                 global $schema_version;
1026
1027                 if (!$schema_version && !$nocache) {
1028                         $result = db_query("SELECT schema_version FROM ttrss_version");
1029                         $version = db_fetch_result($result, 0, "schema_version");
1030                         $schema_version = $version;
1031                         return $version;
1032                 } else {
1033                         return $schema_version;
1034                 }
1035         }
1036
1037         function sanity_check() {
1038                 require_once 'errors.php';
1039                 global $ERRORS;
1040
1041                 $error_code = 0;
1042                 $schema_version = get_schema_version(true);
1043
1044                 if ($schema_version != SCHEMA_VERSION) {
1045                         $error_code = 5;
1046                 }
1047
1048                 if (DB_TYPE == "mysql") {
1049                         $result = db_query("SELECT true", false);
1050                         if (db_num_rows($result) != 1) {
1051                                 $error_code = 10;
1052                         }
1053                 }
1054
1055                 if (db_escape_string("testTEST") != "testTEST") {
1056                         $error_code = 12;
1057                 }
1058
1059                 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1060         }
1061
1062         function file_is_locked($filename) {
1063                 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1064                         if (function_exists('flock')) {
1065                                 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1066                                 if ($fp) {
1067                                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1068                                                 flock($fp, LOCK_UN);
1069                                                 fclose($fp);
1070                                                 return false;
1071                                         }
1072                                         fclose($fp);
1073                                         return true;
1074                                 } else {
1075                                         return false;
1076                                 }
1077                         }
1078                         return true; // consider the file always locked and skip the test
1079                 } else {
1080                         return false;
1081                 }
1082         }
1083
1084
1085         function make_lockfile($filename) {
1086                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1087
1088                 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1089                         $stat_h = fstat($fp);
1090                         $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1091
1092                         if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1093                                 if ($stat_h["ino"] != $stat_f["ino"] ||
1094                                                 $stat_h["dev"] != $stat_f["dev"]) {
1095
1096                                         return false;
1097                                 }
1098                         }
1099
1100                         if (function_exists('posix_getpid')) {
1101                                 fwrite($fp, posix_getpid() . "\n");
1102                         }
1103                         return $fp;
1104                 } else {
1105                         return false;
1106                 }
1107         }
1108
1109         function make_stampfile($filename) {
1110                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1111
1112                 if (flock($fp, LOCK_EX | LOCK_NB)) {
1113                         fwrite($fp, time() . "\n");
1114                         flock($fp, LOCK_UN);
1115                         fclose($fp);
1116                         return true;
1117                 } else {
1118                         return false;
1119                 }
1120         }
1121
1122         function sql_random_function() {
1123                 if (DB_TYPE == "mysql") {
1124                         return "RAND()";
1125                 } else {
1126                         return "RANDOM()";
1127                 }
1128         }
1129
1130         function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1131
1132                         if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1133
1134                         //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1135
1136                         // Todo: all this interval stuff needs some generic generator function
1137
1138                         $date_qpart = "false";
1139
1140                         switch ($mode) {
1141                         case "1day":
1142                                 if (DB_TYPE == "pgsql") {
1143                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1144                                 } else {
1145                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1146                                 }
1147                                 break;
1148                         case "1week":
1149                                 if (DB_TYPE == "pgsql") {
1150                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1151                                 } else {
1152                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1153                                 }
1154                                 break;
1155                         case "2week":
1156                                 if (DB_TYPE == "pgsql") {
1157                                         $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1158                                 } else {
1159                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1160                                 }
1161                                 break;
1162                         default:
1163                                 $date_qpart = "true";
1164                         }
1165
1166                         if (is_numeric($feed)) {
1167                                 if ($cat_view) {
1168
1169                                         if ($feed >= 0) {
1170
1171                                                 if ($feed > 0) {
1172                                                         $children = getChildCategories($feed, $owner_uid);
1173                                                         array_push($children, $feed);
1174
1175                                                         $children = join(",", $children);
1176
1177                                                         $cat_qpart = "cat_id IN ($children)";
1178                                                 } else {
1179                                                         $cat_qpart = "cat_id IS NULL";
1180                                                 }
1181
1182                                                 db_query("UPDATE ttrss_user_entries
1183                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1184                                                                 (SELECT id FROM
1185                                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1186                                                                                 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1187                                                                                         (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1188
1189                                         } else if ($feed == -2) {
1190
1191                                                 db_query("UPDATE ttrss_user_entries
1192                                                         SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1193                                                                 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1194                                                                 AND unread = true AND owner_uid = $owner_uid");
1195                                         }
1196
1197                                 } else if ($feed > 0) {
1198
1199                                         db_query("UPDATE ttrss_user_entries
1200                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1201                                                         (SELECT id FROM
1202                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1203                                                                         AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1204
1205                                 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1206
1207                                         if ($feed == -1) {
1208                                                 db_query("UPDATE ttrss_user_entries
1209                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1210                                                                 (SELECT id FROM
1211                                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1212                                                                                 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1213                                         }
1214
1215                                         if ($feed == -2) {
1216                                                 db_query("UPDATE ttrss_user_entries
1217                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1218                                                                 (SELECT id FROM
1219                                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1220                                                                                 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1221                                         }
1222
1223                                         if ($feed == -3) {
1224
1225                                                 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1226
1227                                                 if (DB_TYPE == "pgsql") {
1228                                                         $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1229                                                 } else {
1230                                                         $match_part = "date_entered > DATE_SUB(NOW(),
1231                                                                 INTERVAL $intl HOUR) ";
1232                                                 }
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 score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1239                                         }
1240
1241                                         if ($feed == -4) {
1242                                                 db_query("UPDATE ttrss_user_entries
1243                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1244                                                                 (SELECT id FROM
1245                                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1246                                                                                 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1247                                         }
1248
1249                                 } else if ($feed < LABEL_BASE_INDEX) { // label
1250
1251                                         $label_id = feed_to_label_id($feed);
1252
1253                                         db_query("UPDATE ttrss_user_entries
1254                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1255                                                         (SELECT id FROM
1256                                                                 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1257                                                                         AND label_id = '$label_id' AND ref_id = article_id
1258                                                                         AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1259
1260                                 }
1261
1262                                 ccache_update($feed, $owner_uid, $cat_view);
1263
1264                         } else { // tag
1265                                 db_query("UPDATE ttrss_user_entries
1266                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1267                                                 (SELECT id FROM
1268                                                         (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1269                                                                 AND post_int_id = int_id AND tag_name = '$feed'
1270                                                                 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1271
1272                         }
1273         }
1274
1275         function getAllCounters() {
1276                 $data = getGlobalCounters();
1277
1278                 $data = array_merge($data, getVirtCounters());
1279                 $data = array_merge($data, getLabelCounters());
1280                 $data = array_merge($data, getFeedCounters());
1281                 $data = array_merge($data, getCategoryCounters());
1282
1283                 return $data;
1284         }
1285
1286         function getCategoryTitle($cat_id) {
1287
1288                 if ($cat_id == -1) {
1289                         return __("Special");
1290                 } else if ($cat_id == -2) {
1291                         return __("Labels");
1292                 } else {
1293
1294                         $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1295                                 id = '$cat_id'");
1296
1297                         if (db_num_rows($result) == 1) {
1298                                 return db_fetch_result($result, 0, "title");
1299                         } else {
1300                                 return __("Uncategorized");
1301                         }
1302                 }
1303         }
1304
1305
1306         function getCategoryCounters() {
1307                 $ret_arr = array();
1308
1309                 /* Labels category */
1310
1311                 $cv = array("id" => -2, "kind" => "cat",
1312                         "counter" => getCategoryUnread(-2));
1313
1314                 array_push($ret_arr, $cv);
1315
1316                 $result = db_query("SELECT id AS cat_id, value AS unread,
1317                         (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1318                                 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1319                         FROM ttrss_feed_categories, ttrss_cat_counters_cache
1320                         WHERE ttrss_cat_counters_cache.feed_id = id AND
1321                         ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1322                         ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1323
1324                 while ($line = db_fetch_assoc($result)) {
1325                         $line["cat_id"] = (int) $line["cat_id"];
1326
1327                         if ($line["num_children"] > 0) {
1328                                 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1329                         } else {
1330                                 $child_counter = 0;
1331                         }
1332
1333                         $cv = array("id" => $line["cat_id"], "kind" => "cat",
1334                                 "counter" => $line["unread"] + $child_counter);
1335
1336                         array_push($ret_arr, $cv);
1337                 }
1338
1339                 /* Special case: NULL category doesn't actually exist in the DB */
1340
1341                 $cv = array("id" => 0, "kind" => "cat",
1342                         "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1343
1344                 array_push($ret_arr, $cv);
1345
1346                 return $ret_arr;
1347         }
1348
1349         // only accepts real cats (>= 0)
1350         function getCategoryChildrenUnread($cat, $owner_uid = false) {
1351                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1352
1353                 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1354                                 AND owner_uid = $owner_uid");
1355
1356                 $unread = 0;
1357
1358                 while ($line = db_fetch_assoc($result)) {
1359                         $unread += getCategoryUnread($line["id"], $owner_uid);
1360                         $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1361                 }
1362
1363                 return $unread;
1364         }
1365
1366         function getCategoryUnread($cat, $owner_uid = false) {
1367
1368                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1369
1370                 if ($cat >= 0) {
1371
1372                         if ($cat != 0) {
1373                                 $cat_query = "cat_id = '$cat'";
1374                         } else {
1375                                 $cat_query = "cat_id IS NULL";
1376                         }
1377
1378                         $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1379                                         AND owner_uid = " . $owner_uid);
1380
1381                         $cat_feeds = array();
1382                         while ($line = db_fetch_assoc($result)) {
1383                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
1384                         }
1385
1386                         if (count($cat_feeds) == 0) return 0;
1387
1388                         $match_part = implode(" OR ", $cat_feeds);
1389
1390                         $result = db_query("SELECT COUNT(int_id) AS unread
1391                                 FROM ttrss_user_entries
1392                                 WHERE   unread = true AND ($match_part)
1393                                 AND owner_uid = " . $owner_uid);
1394
1395                         $unread = 0;
1396
1397                         # this needs to be rewritten
1398                         while ($line = db_fetch_assoc($result)) {
1399                                 $unread += $line["unread"];
1400                         }
1401
1402                         return $unread;
1403                 } else if ($cat == -1) {
1404                         return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1405                 } else if ($cat == -2) {
1406
1407                         $result = db_query("
1408                                 SELECT COUNT(unread) AS unread FROM
1409                                         ttrss_user_entries, ttrss_user_labels2
1410                                 WHERE article_id = ref_id AND unread = true
1411                                         AND ttrss_user_entries.owner_uid = '$owner_uid'");
1412
1413                         $unread = db_fetch_result($result, 0, "unread");
1414
1415                         return $unread;
1416
1417                 }
1418         }
1419
1420         function getFeedUnread($feed, $is_cat = false) {
1421                 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1422         }
1423
1424         function getLabelUnread($label_id, $owner_uid = false) {
1425                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1426
1427                 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1428                         WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1429
1430                 if (db_num_rows($result) != 0) {
1431                         return db_fetch_result($result, 0, "unread");
1432                 } else {
1433                         return 0;
1434                 }
1435         }
1436
1437         function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1438                 $owner_uid = false) {
1439
1440                 $n_feed = (int) $feed;
1441                 $need_entries = false;
1442
1443                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1444
1445                 if ($unread_only) {
1446                         $unread_qpart = "unread = true";
1447                 } else {
1448                         $unread_qpart = "true";
1449                 }
1450
1451                 if ($is_cat) {
1452                         return getCategoryUnread($n_feed, $owner_uid);
1453                 } else if ($n_feed == -6) {
1454                         return 0;
1455                 } else if ($feed != "0" && $n_feed == 0) {
1456
1457                         $feed = db_escape_string($feed);
1458
1459                         $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1460                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1461                                         AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1462                                 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1463                         return db_fetch_result($result, 0, "count");
1464
1465                 } else if ($n_feed == -1) {
1466                         $match_part = "marked = true";
1467                 } else if ($n_feed == -2) {
1468                         $match_part = "published = true";
1469                 } else if ($n_feed == -3) {
1470                         $match_part = "unread = true AND score >= 0";
1471
1472                         $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1473
1474                         if (DB_TYPE == "pgsql") {
1475                                 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1476                         } else {
1477                                 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1478                         }
1479
1480                         $need_entries = true;
1481
1482                 } else if ($n_feed == -4) {
1483                         $match_part = "true";
1484                 } else if ($n_feed >= 0) {
1485
1486                         if ($n_feed != 0) {
1487                                 $match_part = "feed_id = '$n_feed'";
1488                         } else {
1489                                 $match_part = "feed_id IS NULL";
1490                         }
1491
1492                 } else if ($feed < LABEL_BASE_INDEX) {
1493
1494                         $label_id = feed_to_label_id($feed);
1495
1496                         return getLabelUnread($label_id, $owner_uid);
1497
1498                 }
1499
1500                 if ($match_part) {
1501
1502                         if ($need_entries) {
1503                                 $from_qpart = "ttrss_user_entries,ttrss_entries";
1504                                 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1505                         } else {
1506                                 $from_qpart = "ttrss_user_entries";
1507                                 $from_where = "";
1508                         }
1509
1510                         $query = "SELECT count(int_id) AS unread
1511                                 FROM $from_qpart WHERE
1512                                 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1513
1514                         //echo "[$feed/$query]\n";
1515
1516                         $result = db_query($query);
1517
1518                 } else {
1519
1520                         $result = db_query("SELECT COUNT(post_int_id) AS unread
1521                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1522                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1523                                 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1524                 }
1525
1526                 $unread = db_fetch_result($result, 0, "unread");
1527
1528                 return $unread;
1529         }
1530
1531         function getGlobalUnread($user_id = false) {
1532
1533                 if (!$user_id) {
1534                         $user_id = $_SESSION["uid"];
1535                 }
1536
1537                 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1538                         WHERE owner_uid = '$user_id' AND feed_id > 0");
1539
1540                 $c_id = db_fetch_result($result, 0, "c_id");
1541
1542                 return $c_id;
1543         }
1544
1545         function getGlobalCounters($global_unread = -1) {
1546                 $ret_arr = array();
1547
1548                 if ($global_unread == -1) {
1549                         $global_unread = getGlobalUnread();
1550                 }
1551
1552                 $cv = array("id" => "global-unread",
1553                         "counter" => (int) $global_unread);
1554
1555                 array_push($ret_arr, $cv);
1556
1557                 $result = db_query("SELECT COUNT(id) AS fn FROM
1558                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1559
1560                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1561
1562                 $cv = array("id" => "subscribed-feeds",
1563                         "counter" => (int) $subscribed_feeds);
1564
1565                 array_push($ret_arr, $cv);
1566
1567                 return $ret_arr;
1568         }
1569
1570         function getVirtCounters() {
1571
1572                 $ret_arr = array();
1573
1574                 for ($i = 0; $i >= -4; $i--) {
1575
1576                         $count = getFeedUnread($i);
1577
1578                         if ($i == 0 || $i == -1 || $i == -2)
1579                                 $auxctr = getFeedArticles($i, false);
1580                         else
1581                                 $auxctr = 0;
1582
1583                         $cv = array("id" => $i,
1584                                 "counter" => (int) $count,
1585                                 "auxcounter" => $auxctr);
1586
1587 //                      if (get_pref('EXTENDED_FEEDLIST'))
1588 //                              $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1589
1590                         array_push($ret_arr, $cv);
1591                 }
1592
1593                 $feeds = PluginHost::getInstance()->get_feeds(-1);
1594
1595                 if (is_array($feeds)) {
1596                         foreach ($feeds as $feed) {
1597                                 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1598                                         "counter" => $feed['sender']->get_unread($feed['id']));
1599
1600                                 if (method_exists($feed['sender'], 'get_total'))
1601                                         $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1602
1603                                 array_push($ret_arr, $cv);
1604                         }
1605                 }
1606
1607                 return $ret_arr;
1608         }
1609
1610         function getLabelCounters($descriptions = false) {
1611
1612                 $ret_arr = array();
1613
1614                 $owner_uid = $_SESSION["uid"];
1615
1616                 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1617                         FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1618                                 (ttrss_labels2.id = label_id)
1619                                 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1620                                 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1621                                 GROUP BY ttrss_labels2.id,
1622                                         ttrss_labels2.caption");
1623
1624                 while ($line = db_fetch_assoc($result)) {
1625
1626                         $id = label_to_feed_id($line["id"]);
1627
1628                         $cv = array("id" => $id,
1629                                 "counter" => (int) $line["unread"],
1630                                 "auxcounter" => (int) $line["total"]);
1631
1632                         if ($descriptions)
1633                                 $cv["description"] = $line["caption"];
1634
1635                         array_push($ret_arr, $cv);
1636                 }
1637
1638                 return $ret_arr;
1639         }
1640
1641         function getFeedCounters($active_feed = false) {
1642
1643                 $ret_arr = array();
1644
1645                 $query = "SELECT ttrss_feeds.id,
1646                                 ttrss_feeds.title,
1647                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1648                                 last_error, value AS count
1649                         FROM ttrss_feeds, ttrss_counters_cache
1650                         WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1651                                 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1652                                 AND ttrss_counters_cache.feed_id = id";
1653
1654                 $result = db_query($query);
1655
1656                 while ($line = db_fetch_assoc($result)) {
1657
1658                         $id = $line["id"];
1659                         $count = $line["count"];
1660                         $last_error = htmlspecialchars($line["last_error"]);
1661
1662                         $last_updated = make_local_datetime($line['last_updated'], false);
1663
1664                         $has_img = feed_has_icon($id);
1665
1666                         if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1667                                 $last_updated = '';
1668
1669                         $cv = array("id" => $id,
1670                                 "updated" => $last_updated,
1671                                 "counter" => (int) $count,
1672                                 "has_img" => (int) $has_img);
1673
1674                         if ($last_error)
1675                                 $cv["error"] = $last_error;
1676
1677 //                      if (get_pref('EXTENDED_FEEDLIST'))
1678 //                              $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1679
1680                         if ($active_feed && $id == $active_feed)
1681                                 $cv["title"] = truncate_string($line["title"], 30);
1682
1683                         array_push($ret_arr, $cv);
1684
1685                 }
1686
1687                 return $ret_arr;
1688         }
1689
1690         function get_pgsql_version() {
1691                 $result = db_query("SELECT version() AS version");
1692                 $version = explode(" ", db_fetch_result($result, 0, "version"));
1693                 return $version[1];
1694         }
1695
1696         /**
1697          * @return array (code => Status code, message => error message if available)
1698          *
1699          *                 0 - OK, Feed already exists
1700          *                 1 - OK, Feed added
1701          *                 2 - Invalid URL
1702          *                 3 - URL content is HTML, no feeds available
1703          *                 4 - URL content is HTML which contains multiple feeds.
1704          *                     Here you should call extractfeedurls in rpc-backend
1705          *                     to get all possible feeds.
1706          *                 5 - Couldn't download the URL content.
1707          *                 6 - Content is an invalid XML.
1708          */
1709         function subscribe_to_feed($url, $cat_id = 0,
1710                         $auth_login = '', $auth_pass = '') {
1711
1712                 global $fetch_last_error;
1713
1714                 require_once "include/rssfuncs.php";
1715
1716                 $url = fix_url($url);
1717
1718                 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1719
1720                 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1721
1722                 if (!$contents) {
1723                         return array("code" => 5, "message" => $fetch_last_error);
1724                 }
1725
1726                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1727                         $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1728                 }
1729
1730                 if (is_html($contents)) {
1731                         $feedUrls = get_feeds_from_html($url, $contents);
1732
1733                         if (count($feedUrls) == 0) {
1734                                 return array("code" => 3);
1735                         } else if (count($feedUrls) > 1) {
1736                                 return array("code" => 4, "feeds" => $feedUrls);
1737                         }
1738                         //use feed url as new URL
1739                         $url = key($feedUrls);
1740                 }
1741
1742                 if ($cat_id == "0" || !$cat_id) {
1743                         $cat_qpart = "NULL";
1744                 } else {
1745                         $cat_qpart = "'$cat_id'";
1746                 }
1747
1748                 $result = db_query(
1749                         "SELECT id FROM ttrss_feeds
1750                         WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1751
1752                 if (strlen(FEED_CRYPT_KEY) > 0) {
1753                         require_once "crypt.php";
1754                         $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1755                         $auth_pass_encrypted = 'true';
1756                 } else {
1757                         $auth_pass_encrypted = 'false';
1758                 }
1759
1760                 $auth_pass = db_escape_string($auth_pass);
1761
1762                 if (db_num_rows($result) == 0) {
1763                         $result = db_query(
1764                                 "INSERT INTO ttrss_feeds
1765                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1766                                 VALUES ('".$_SESSION["uid"]."', '$url',
1767                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1768
1769                         $result = db_query(
1770                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1771                                         AND owner_uid = " . $_SESSION["uid"]);
1772
1773                         $feed_id = db_fetch_result($result, 0, "id");
1774
1775                         if ($feed_id) {
1776                                 set_basic_feed_info($feed_id);
1777                         }
1778
1779                         return array("code" => 1, "feed_id" => (int) $feed_id);
1780                 } else {
1781                         return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
1782                 }
1783         }
1784
1785         function print_feed_select($id, $default_id = "",
1786                 $attributes = "", $include_all_feeds = true,
1787                 $root_id = false, $nest_level = 0) {
1788
1789                 if (!$root_id) {
1790                         print "<select id=\"$id\" name=\"$id\" $attributes>";
1791                         if ($include_all_feeds) {
1792                                 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1793                                 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1794                         }
1795                 }
1796
1797                 if (get_pref('ENABLE_FEED_CATS')) {
1798
1799                         if ($root_id)
1800                                 $parent_qpart = "parent_cat = '$root_id'";
1801                         else
1802                                 $parent_qpart = "parent_cat IS NULL";
1803
1804                         $result = db_query("SELECT id,title,
1805                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1806                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1807                                 FROM ttrss_feed_categories
1808                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1809
1810                         while ($line = db_fetch_assoc($result)) {
1811
1812                                 for ($i = 0; $i < $nest_level; $i++)
1813                                         $line["title"] = " - " . $line["title"];
1814
1815                                 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1816
1817                                 printf("<option $is_selected value='CAT:%d'>%s</option>",
1818                                         $line["id"], htmlspecialchars($line["title"]));
1819
1820                                 if ($line["num_children"] > 0)
1821                                         print_feed_select($id, $default_id, $attributes,
1822                                                 $include_all_feeds, $line["id"], $nest_level+1);
1823
1824                                 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1825                                         WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1826
1827                                 while ($fline = db_fetch_assoc($feed_result)) {
1828                                         $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1829
1830                                         $fline["title"] = " + " . $fline["title"];
1831
1832                                         for ($i = 0; $i < $nest_level; $i++)
1833                                                 $fline["title"] = " - " . $fline["title"];
1834
1835                                         printf("<option $is_selected value='%d'>%s</option>",
1836                                                 $fline["id"], htmlspecialchars($fline["title"]));
1837                                 }
1838                         }
1839
1840                         if (!$root_id) {
1841                                 $default_is_cat = ($default_id == "CAT:0");
1842                                 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1843
1844                                 printf("<option $is_selected value='CAT:0'>%s</option>",
1845                                         __("Uncategorized"));
1846
1847                                 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1848                                         WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1849
1850                                 while ($fline = db_fetch_assoc($feed_result)) {
1851                                         $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1852
1853                                         $fline["title"] = " + " . $fline["title"];
1854
1855                                         for ($i = 0; $i < $nest_level; $i++)
1856                                                 $fline["title"] = " - " . $fline["title"];
1857
1858                                         printf("<option $is_selected value='%d'>%s</option>",
1859                                                 $fline["id"], htmlspecialchars($fline["title"]));
1860                                 }
1861                         }
1862
1863                 } else {
1864                         $result = db_query("SELECT id,title FROM ttrss_feeds
1865                                 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1866
1867                         while ($line = db_fetch_assoc($result)) {
1868
1869                                 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1870
1871                                 printf("<option $is_selected value='%d'>%s</option>",
1872                                         $line["id"], htmlspecialchars($line["title"]));
1873                         }
1874                 }
1875
1876                 if (!$root_id) {
1877                         print "</select>";
1878                 }
1879         }
1880
1881         function print_feed_cat_select($id, $default_id,
1882                 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1883
1884                         if (!$root_id) {
1885                                         print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1886                         }
1887
1888                         if ($root_id)
1889                                 $parent_qpart = "parent_cat = '$root_id'";
1890                         else
1891                                 $parent_qpart = "parent_cat IS NULL";
1892
1893                         $result = db_query("SELECT id,title,
1894                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1895                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1896                                 FROM ttrss_feed_categories
1897                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1898
1899                         while ($line = db_fetch_assoc($result)) {
1900                                 if ($line["id"] == $default_id) {
1901                                         $is_selected = "selected=\"1\"";
1902                                 } else {
1903                                         $is_selected = "";
1904                                 }
1905
1906                                 for ($i = 0; $i < $nest_level; $i++)
1907                                         $line["title"] = " - " . $line["title"];
1908
1909                                 if ($line["title"])
1910                                         printf("<option $is_selected value='%d'>%s</option>",
1911                                                 $line["id"], htmlspecialchars($line["title"]));
1912
1913                                 if ($line["num_children"] > 0)
1914                                         print_feed_cat_select($id, $default_id, $attributes,
1915                                                 $include_all_cats, $line["id"], $nest_level+1);
1916                         }
1917
1918                         if (!$root_id) {
1919                                 if ($include_all_cats) {
1920                                         if (db_num_rows($result) > 0) {
1921                                                 print "<option disabled=\"1\">--------</option>";
1922                                         }
1923
1924                                         if ($default_id == 0) {
1925                                                 $is_selected = "selected=\"1\"";
1926                                         } else {
1927                                                 $is_selected = "";
1928                                         }
1929
1930                                         print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1931                                 }
1932                                 print "</select>";
1933                         }
1934                 }
1935
1936         function checkbox_to_sql_bool($val) {
1937                 return ($val == "on") ? "true" : "false";
1938         }
1939
1940         function getFeedCatTitle($id) {
1941                 if ($id == -1) {
1942                         return __("Special");
1943                 } else if ($id < LABEL_BASE_INDEX) {
1944                         return __("Labels");
1945                 } else if ($id > 0) {
1946                         $result = db_query("SELECT ttrss_feed_categories.title
1947                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1948                                         cat_id = ttrss_feed_categories.id");
1949                         if (db_num_rows($result) == 1) {
1950                                 return db_fetch_result($result, 0, "title");
1951                         } else {
1952                                 return __("Uncategorized");
1953                         }
1954                 } else {
1955                         return "getFeedCatTitle($id) failed";
1956                 }
1957
1958         }
1959
1960         function getFeedIcon($id) {
1961                 switch ($id) {
1962                 case 0:
1963                         return "images/archive.png";
1964                         break;
1965                 case -1:
1966                         return "images/star.png";
1967                         break;
1968                 case -2:
1969                         return "images/feed.png";
1970                         break;
1971                 case -3:
1972                         return "images/fresh.png";
1973                         break;
1974                 case -4:
1975                         return "images/folder.png";
1976                         break;
1977                 case -6:
1978                         return "images/time.png";
1979                         break;
1980                 default:
1981                         if ($id < LABEL_BASE_INDEX) {
1982                                 return "images/label.png";
1983                         } else {
1984                                 if (file_exists(ICONS_DIR . "/$id.ico"))
1985                                         return ICONS_URL . "/$id.ico";
1986                         }
1987                         break;
1988                 }
1989
1990                 return false;
1991         }
1992
1993         function getFeedTitle($id, $cat = false) {
1994                 if ($cat) {
1995                         return getCategoryTitle($id);
1996                 } else if ($id == -1) {
1997                         return __("Starred articles");
1998                 } else if ($id == -2) {
1999                         return __("Published articles");
2000                 } else if ($id == -3) {
2001                         return __("Fresh articles");
2002                 } else if ($id == -4) {
2003                         return __("All articles");
2004                 } else if ($id === 0 || $id === "0") {
2005                         return __("Archived articles");
2006                 } else if ($id == -6) {
2007                         return __("Recently read");
2008                 } else if ($id < LABEL_BASE_INDEX) {
2009                         $label_id = feed_to_label_id($id);
2010                         $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2011                         if (db_num_rows($result) == 1) {
2012                                 return db_fetch_result($result, 0, "caption");
2013                         } else {
2014                                 return "Unknown label ($label_id)";
2015                         }
2016
2017                 } else if (is_numeric($id) && $id > 0) {
2018                         $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
2019                         if (db_num_rows($result) == 1) {
2020                                 return db_fetch_result($result, 0, "title");
2021                         } else {
2022                                 return "Unknown feed ($id)";
2023                         }
2024                 } else {
2025                         return $id;
2026                 }
2027         }
2028
2029         function uniqid_short() {
2030                 return uniqid(base_convert(rand(), 10, 36));
2031         }
2032
2033         // TODO: less dumb splitting
2034         require_once "functions2.php";
2035
2036 ?>