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