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