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