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