]> git.wh0rd.org Git - tt-rss.git/blob - include/functions.php
No more "tunables.php" defaults dumped into "functions.php"
[tt-rss.git] / include / functions.php
1 <?php
2         define('EXPECTED_CONFIG_VERSION', 26);
3         define('SCHEMA_VERSION', 115);
4
5         define('LABEL_BASE_INDEX', -1024);
6         define('PLUGIN_FEED_BASE_INDEX', -128);
7
8         $fetch_last_error = false;
9         $fetch_last_error_code = false;
10         $pluginhost = false;
11
12         function __autoload($class) {
13                 $class_file = str_replace("_", "/", strtolower(basename($class)));
14
15                 $file = dirname(__FILE__)."/../classes/$class_file.php";
16
17                 if (file_exists($file)) {
18                         require $file;
19                 }
20
21         }
22
23         mb_internal_encoding("UTF-8");
24         date_default_timezone_set('UTC');
25         if (defined('E_DEPRECATED')) {
26                 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
27         } else {
28                 error_reporting(E_ALL & ~E_NOTICE);
29         }
30
31         require_once 'config.php';
32
33         /**
34          * Define a constant if not already defined
35          *
36          * @param string $name The constant name.
37          * @param mixed $value The constant value.
38          * @access public
39          * @return boolean True if defined successfully or not.
40          */
41         function define_default($name, $value) {
42                 // Note: performence freaks should define everything in 
43                 // config.php becasue if will make defined() run much faster, 
44                 // see comment by 'tris+php at tfconsulting dot com dot au' 
45                 // here: 
46                 // http://www.php.net/manual/en/function.defined.php#89886
47                 defined($name) or define($name, $value);
48         }
49
50         ///// Some defaults that you can override in config.php //////
51
52         define_default('FEED_FETCH_TIMEOUT', 45);
53         // How may seconds to wait for response when requesting feed from a site
54         define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
55         // How may seconds to wait for response when requesting feed from a
56         // site when that feed wasn't cached before
57         define_default('FILE_FETCH_TIMEOUT', 45);
58         // Default timeout when fetching files from remote sites
59         define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
60         // How many seconds to wait for initial response from website when
61         // fetching files from remote sites
62
63         if (DB_TYPE == "pgsql") {
64                 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
65         } else {
66                 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
67         }
68
69         define('THEME_VERSION_REQUIRED', 1.1);
70
71         /**
72          * Return available translations names.
73          *
74          * @access public
75          * @return array A array of available translations.
76          */
77         function get_translations() {
78                 $tr = array(
79                                         "auto"  => "Detect automatically",
80                                         "ca_CA" => "Català",
81                                         "cs_CZ" => "Česky",
82                                         "en_US" => "English",
83                                         "es_ES" => "Español",
84                                         "de_DE" => "Deutsch",
85                                         "fr_FR" => "Français",
86                                         "hu_HU" => "Magyar (Hungarian)",
87                                         "it_IT" => "Italiano",
88                                         "ja_JP" => "日本語 (Japanese)",
89                                         "lv_LV" => "Latviešu",
90                                         "nb_NO" => "Norwegian bokmål",
91                                         "nl_NL" => "Dutch",
92                                         "pl_PL" => "Polski",
93                                         "ru_RU" => "Русский",
94                                         "pt_BR" => "Portuguese/Brazil",
95                                         "zh_CN" => "Simplified Chinese",
96                                         "sv_SE" => "Svenska",
97                                         "fi_FI" => "Suomi");
98
99                 return $tr;
100         }
101
102         require_once "lib/accept-to-gettext.php";
103         require_once "lib/gettext/gettext.inc";
104
105
106         function startup_gettext() {
107
108                 # Get locale from Accept-Language header
109                 $lang = al2gt(array_keys(get_translations()), "text/html");
110
111                 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
112                         $lang = _TRANSLATION_OVERRIDE_DEFAULT;
113                 }
114
115                 if ($_SESSION["language"] && $_SESSION["language"] != "auto") {
116                         $lang = $_SESSION["language"];
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         startup_gettext();
134
135         require_once 'db-prefs.php';
136         require_once 'version.php';
137         require_once 'ccache.php';
138         require_once 'labels.php';
139
140         define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
141         ini_set('user_agent', SELF_USER_AGENT);
142
143         require_once 'lib/pubsubhubbub/publisher.php';
144
145         $tz_offset = -1;
146         $utc_tz = new DateTimeZone('UTC');
147         $schema_version = false;
148
149         /**
150          * Print a timestamped debug message.
151          *
152          * @param string $msg The debug message.
153          * @return void
154          */
155         function _debug($msg) {
156                 $ts = strftime("%H:%M:%S", time());
157                 if (function_exists('posix_getpid')) {
158                         $ts = "$ts/" . posix_getpid();
159                 }
160
161                 if (!(defined('QUIET') && QUIET)) {
162                         print "[$ts] $msg\n";
163                 }
164
165                 if (defined('LOGFILE'))  {
166                         $fp = fopen(LOGFILE, 'a+');
167
168                         if ($fp) {
169                                 fputs($fp, "[$ts] $msg\n");
170                                 fclose($fp);
171                         }
172                 }
173
174         } // function _debug
175
176         /**
177          * Purge a feed old posts.
178          *
179          * @param mixed $link A database connection.
180          * @param mixed $feed_id The id of the purged feed.
181          * @param mixed $purge_interval Olderness of purged posts.
182          * @param boolean $debug Set to True to enable the debug. False by default.
183          * @access public
184          * @return void
185          */
186         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
187
188                 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
189
190                 $rows = -1;
191
192                 $result = db_query($link,
193                         "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
194
195                 $owner_uid = false;
196
197                 if (db_num_rows($result) == 1) {
198                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
199                 }
200
201                 if ($purge_interval == -1 || !$purge_interval) {
202                         if ($owner_uid) {
203                                 ccache_update($link, $feed_id, $owner_uid);
204                         }
205                         return;
206                 }
207
208                 if (!$owner_uid) return;
209
210                 if (FORCE_ARTICLE_PURGE == 0) {
211                         $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
212                                 $owner_uid, false);
213                 } else {
214                         $purge_unread = true;
215                         $purge_interval = FORCE_ARTICLE_PURGE;
216                 }
217
218                 if (!$purge_unread) $query_limit = " unread = false AND ";
219
220                 if (DB_TYPE == "pgsql") {
221                         $pg_version = get_pgsql_version($link);
222
223                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
224
225                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
226                                         ttrss_entries.id = ref_id AND
227                                         marked = false AND
228                                         feed_id = '$feed_id' AND
229                                         $query_limit
230                                         ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
231
232                         } else {
233
234                                 $result = db_query($link, "DELETE FROM ttrss_user_entries
235                                         USING ttrss_entries
236                                         WHERE ttrss_entries.id = ref_id AND
237                                         marked = false AND
238                                         feed_id = '$feed_id' AND
239                                         $query_limit
240                                         ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
241                         }
242
243                         $rows = pg_affected_rows($result);
244
245                 } else {
246
247 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
248                                 marked = false AND feed_id = '$feed_id' AND
249                                 (SELECT date_updated FROM ttrss_entries WHERE
250                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
251
252                         $result = db_query($link, "DELETE FROM ttrss_user_entries
253                                 USING ttrss_user_entries, ttrss_entries
254                                 WHERE ttrss_entries.id = ref_id AND
255                                 marked = false AND
256                                 feed_id = '$feed_id' AND
257                                 $query_limit
258                                 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
259
260                         $rows = mysql_affected_rows($link);
261
262                 }
263
264                 ccache_update($link, $feed_id, $owner_uid);
265
266                 if ($debug) {
267                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
268                 }
269
270                 return $rows;
271         } // function purge_feed
272
273         function feed_purge_interval($link, $feed_id) {
274
275                 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
276                         WHERE id = '$feed_id'");
277
278                 if (db_num_rows($result) == 1) {
279                         $purge_interval = db_fetch_result($result, 0, "purge_interval");
280                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
281
282                         if ($purge_interval == 0) $purge_interval = get_pref($link,
283                                 'PURGE_OLD_DAYS', $owner_uid);
284
285                         return $purge_interval;
286
287                 } else {
288                         return -1;
289                 }
290         }
291
292         function purge_orphans($link, $do_output = false) {
293
294                 // purge orphaned posts in main content table
295                 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
296                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
297
298                 if ($do_output) {
299                         $rows = db_affected_rows($link, $result);
300                         _debug("Purged $rows orphaned posts.");
301                 }
302         }
303
304         function get_feed_update_interval($link, $feed_id) {
305                 $result = db_query($link, "SELECT owner_uid, update_interval FROM
306                         ttrss_feeds WHERE id = '$feed_id'");
307
308                 if (db_num_rows($result) == 1) {
309                         $update_interval = db_fetch_result($result, 0, "update_interval");
310                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
311
312                         if ($update_interval != 0) {
313                                 return $update_interval;
314                         } else {
315                                 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
316                         }
317
318                 } else {
319                         return -1;
320                 }
321         }
322
323         function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0) {
324
325                 global $fetch_last_error;
326                 global $fetch_last_error_code;
327
328                 if (function_exists('curl_init') && !ini_get("open_basedir")) {
329
330                         if (ini_get("safe_mode")) {
331                                 $ch = curl_init(geturl($url));
332                         } else {
333                                 $ch = curl_init($url);
334                         }
335
336                         if ($timestamp) {
337                                 curl_setopt($ch, CURLOPT_HTTPHEADER,
338                                         array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
339                         }
340
341                         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
342                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
343                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode"));
344                         curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
345                         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
346                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
347                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
348                         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
349                         curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
350                         curl_setopt($ch, CURLOPT_ENCODING , "gzip");
351                         curl_setopt($ch, CURLOPT_REFERER, $url);
352
353                         if ($post_query) {
354                                 curl_setopt($ch, CURLOPT_POST, true);
355                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
356                         }
357
358                         if ($login && $pass)
359                                 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
360
361                         $contents = @curl_exec($ch);
362
363                         if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
364                                 curl_setopt($ch, CURLOPT_ENCODING, 'none');
365                                 $contents = @curl_exec($ch);
366                         }
367
368                         if ($contents === false) {
369                                 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
370                                 curl_close($ch);
371                                 return false;
372                         }
373
374                         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
375                         $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
376
377                         $fetch_last_error_code = $http_code;
378
379                         if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
380                                 if (curl_errno($ch) != 0) {
381                                         $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
382                                 } else {
383                                         $fetch_last_error = "HTTP Code: $http_code";
384                                 }
385                                 curl_close($ch);
386                                 return false;
387                         }
388
389                         curl_close($ch);
390
391                         return $contents;
392                 } else {
393                         if ($login && $pass){
394                                 $url_parts = array();
395
396                                 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
397
398                                 $pass = urlencode($pass);
399
400                                 if ($url_parts[1] && $url_parts[2]) {
401                                         $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
402                                 }
403                         }
404
405                         $data = @file_get_contents($url);
406
407                         @$gzdecoded = gzdecode($data);
408                         if ($gzdecoded) $data = $gzdecoded;
409
410                         if (!$data && function_exists('error_get_last')) {
411                                 $error = error_get_last();
412                                 $fetch_last_error = $error["message"];
413                         }
414                         return $data;
415                 }
416
417         }
418
419         /**
420          * Try to determine the favicon URL for a feed.
421          * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
422          * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
423          *
424          * @param string $url A feed or page URL
425          * @access public
426          * @return mixed The favicon URL, or false if none was found.
427          */
428         function get_favicon_url($url) {
429
430                 $favicon_url = false;
431
432                 if ($html = @fetch_file_contents($url)) {
433
434                         libxml_use_internal_errors(true);
435
436                         $doc = new DOMDocument();
437                         $doc->loadHTML($html);
438                         $xpath = new DOMXPath($doc);
439
440                         $base = $xpath->query('/html/head/base');
441                         foreach ($base as $b) {
442                                 $url = $b->getAttribute("href");
443                                 break;
444                         }
445
446                         $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
447                         if (count($entries) > 0) {
448                                 foreach ($entries as $entry) {
449                                         $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
450                                         break;
451                                 }
452                         }
453                 }
454
455                 if (!$favicon_url)
456                         $favicon_url = rewrite_relative_url($url, "/favicon.ico");
457
458                 return $favicon_url;
459         } // function get_favicon_url
460
461         function check_feed_favicon($site_url, $feed, $link) {
462 #               print "FAVICON [$site_url]: $favicon_url\n";
463
464                 $icon_file = ICONS_DIR . "/$feed.ico";
465
466                 if (!file_exists($icon_file)) {
467                         $favicon_url = get_favicon_url($site_url);
468
469                         if ($favicon_url) {
470                                 // Limiting to "image" type misses those served with text/plain
471                                 $contents = fetch_file_contents($favicon_url); // , "image");
472
473                                 if ($contents) {
474                                         // Crude image type matching.
475                                         // Patterns gleaned from the file(1) source code.
476                                         if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
477                                                 // 0       string  \000\000\001\000        MS Windows icon resource
478                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
479                                         }
480                                         elseif (preg_match('/^GIF8/', $contents)) {
481                                                 // 0       string          GIF8            GIF image data
482                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
483                                         }
484                                         elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
485                                                 // 0       string          \x89PNG\x0d\x0a\x1a\x0a         PNG image data
486                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
487                                         }
488                                         elseif (preg_match('/^\xff\xd8/', $contents)) {
489                                                 // 0       beshort         0xffd8          JPEG image data
490                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
491                                         }
492                                         else {
493                                                 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
494                                                 $contents = "";
495                                         }
496                                 }
497
498                                 if ($contents) {
499                                         $fp = @fopen($icon_file, "w");
500
501                                         if ($fp) {
502                                                 fwrite($fp, $contents);
503                                                 fclose($fp);
504                                                 chmod($icon_file, 0644);
505                                         }
506                                 }
507                         }
508                 }
509         }
510
511         function print_select($id, $default, $values, $attributes = "") {
512                 print "<select name=\"$id\" id=\"$id\" $attributes>";
513                 foreach ($values as $v) {
514                         if ($v == $default)
515                                 $sel = "selected=\"1\"";
516                          else
517                                 $sel = "";
518
519                         $v = trim($v);
520
521                         print "<option value=\"$v\" $sel>$v</option>";
522                 }
523                 print "</select>";
524         }
525
526         function print_select_hash($id, $default, $values, $attributes = "") {
527                 print "<select name=\"$id\" id='$id' $attributes>";
528                 foreach (array_keys($values) as $v) {
529                         if ($v == $default)
530                                 $sel = 'selected="selected"';
531                          else
532                                 $sel = "";
533
534                         $v = trim($v);
535
536                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
537                 }
538
539                 print "</select>";
540         }
541
542         function print_radio($id, $default, $true_is, $values, $attributes = "") {
543                 foreach ($values as $v) {
544
545                         if ($v == $default)
546                                 $sel = "checked";
547                          else
548                                 $sel = "";
549
550                         if ($v == $true_is) {
551                                 $sel .= " value=\"1\"";
552                         } else {
553                                 $sel .= " value=\"0\"";
554                         }
555
556                         print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
557                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
558
559                 }
560         }
561
562         function initialize_user_prefs($link, $uid, $profile = false) {
563
564                 $uid = db_escape_string($link, $uid);
565
566                 if (!$profile) {
567                         $profile = "NULL";
568                         $profile_qpart = "AND profile IS NULL";
569                 } else {
570                         $profile_qpart = "AND profile = '$profile'";
571                 }
572
573                 if (get_schema_version($link) < 63) $profile_qpart = "";
574
575                 db_query($link, "BEGIN");
576
577                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
578
579                 $u_result = db_query($link, "SELECT pref_name
580                         FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
581
582                 $active_prefs = array();
583
584                 while ($line = db_fetch_assoc($u_result)) {
585                         array_push($active_prefs, $line["pref_name"]);
586                 }
587
588                 while ($line = db_fetch_assoc($result)) {
589                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
590 //                              print "adding " . $line["pref_name"] . "<br>";
591
592                                 $line["def_value"] = db_escape_string($link, $line["def_value"]);
593                                 $line["pref_name"] = db_escape_string($link, $line["pref_name"]);
594
595                                 if (get_schema_version($link) < 63) {
596                                         db_query($link, "INSERT INTO ttrss_user_prefs
597                                                 (owner_uid,pref_name,value) VALUES
598                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
599
600                                 } else {
601                                         db_query($link, "INSERT INTO ttrss_user_prefs
602                                                 (owner_uid,pref_name,value, profile) VALUES
603                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
604                                 }
605
606                         }
607                 }
608
609                 db_query($link, "COMMIT");
610
611         }
612
613         function get_ssl_certificate_id() {
614                 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
615                         return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
616                                 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
617                                 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
618                                 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
619                 }
620                 return "";
621         }
622
623         function authenticate_user($link, $login, $password, $check_only = false) {
624
625                 if (!SINGLE_USER_MODE) {
626                         $user_id = false;
627
628                         global $pluginhost;
629                         foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
630
631                                 $user_id = (int) $plugin->authenticate($login, $password);
632
633                                 if ($user_id) {
634                                         $_SESSION["auth_module"] = strtolower(get_class($plugin));
635                                         break;
636                                 }
637                         }
638
639                         if ($user_id && !$check_only) {
640                                 @session_start();
641
642                                 $_SESSION["uid"] = $user_id;
643
644                                 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
645                                         WHERE id = '$user_id'");
646
647                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
648                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
649                                 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
650
651                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
652                                         $_SESSION["uid"]);
653
654                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
655                                 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
656                                 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
657
658                                 $_SESSION["last_version_check"] = time();
659
660                                 initialize_user_prefs($link, $_SESSION["uid"]);
661
662                                 return true;
663                         }
664
665                         return false;
666
667                 } else {
668
669                         $_SESSION["uid"] = 1;
670                         $_SESSION["name"] = "admin";
671                         $_SESSION["access_level"] = 10;
672
673                         $_SESSION["hide_hello"] = true;
674                         $_SESSION["hide_logout"] = true;
675
676                         $_SESSION["auth_module"] = false;
677
678                         if (!$_SESSION["csrf_token"]) {
679                                 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
680                         }
681
682                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
683
684                         initialize_user_prefs($link, $_SESSION["uid"]);
685
686                         return true;
687                 }
688         }
689
690         function make_password($length = 8) {
691
692                 $password = "";
693                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
694
695         $i = 0;
696
697                 while ($i < $length) {
698                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
699
700                         if (!strstr($password, $char)) {
701                                 $password .= $char;
702                                 $i++;
703                         }
704                 }
705                 return $password;
706         }
707
708         // this is called after user is created to initialize default feeds, labels
709         // or whatever else
710
711         // user preferences are checked on every login, not here
712
713         function initialize_user($link, $uid) {
714
715                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
716                         values ('$uid', 'Tiny Tiny RSS: New Releases',
717                         'http://tt-rss.org/releases.rss')");
718
719                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
720                         values ('$uid', 'Tiny Tiny RSS: Forum',
721                                 'http://tt-rss.org/forum/rss.php')");
722         }
723
724         function logout_user() {
725                 session_destroy();
726                 if (isset($_COOKIE[session_name()])) {
727                    setcookie(session_name(), '', time()-42000, '/');
728                 }
729         }
730
731         function validate_csrf($csrf_token) {
732                 return $csrf_token == $_SESSION['csrf_token'];
733         }
734
735         function load_user_plugins($link, $owner_uid) {
736                 if ($owner_uid) {
737                         $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
738
739                         global $pluginhost;
740                         $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
741
742                         if (get_schema_version($link) > 100) {
743                                 $pluginhost->load_data();
744                         }
745                 }
746         }
747
748         function login_sequence($link) {
749                 $_SESSION["prefs_cache"] = false;
750
751                 if (SINGLE_USER_MODE) {
752                         @session_start();
753                         authenticate_user($link, "admin", null);
754                         cache_prefs($link);
755                         load_user_plugins($link, $_SESSION["uid"]);
756                 } else {
757                         if (!$_SESSION["uid"] || !validate_session($link)) {
758
759                                 if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
760                                     $_SESSION["ref_schema_version"] = get_schema_version($link, true);
761                                 } else {
762                                          authenticate_user($link, null, null, true);
763                                 }
764
765                                 if (!$_SESSION["uid"]) render_login_form($link);
766
767                         } else {
768                                 /* bump login timestamp */
769                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
770                                         $_SESSION["uid"]);
771                                 $_SESSION["last_login_update"] = time();
772                         }
773
774                         if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
775                                 setcookie("ttrss_lang", $_SESSION["language"],
776                                         time() + SESSION_COOKIE_LIFETIME);
777                         }
778
779                         if ($_SESSION["uid"]) {
780                                 cache_prefs($link);
781                                 load_user_plugins($link, $_SESSION["uid"]);
782
783                                 /* cleanup ccache */
784
785                                 db_query($link, "DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
786                                         $_SESSION["uid"] . " AND
787                                                 (SELECT COUNT(id) FROM ttrss_feeds WHERE
788                                                         ttrss_feeds.id = feed_id) = 0");
789
790                                 db_query($link, "DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
791                                         $_SESSION["uid"] . " AND
792                                                 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
793                                                         ttrss_feed_categories.id = feed_id) = 0");
794
795                         }
796
797                 }
798         }
799
800         function truncate_string($str, $max_len, $suffix = '&hellip;') {
801                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
802                         return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
803                 } else {
804                         return $str;
805                 }
806         }
807
808         function convert_timestamp($timestamp, $source_tz, $dest_tz) {
809
810                 try {
811                         $source_tz = new DateTimeZone($source_tz);
812                 } catch (Exception $e) {
813                         $source_tz = new DateTimeZone('UTC');
814                 }
815
816                 try {
817                         $dest_tz = new DateTimeZone($dest_tz);
818                 } catch (Exception $e) {
819                         $dest_tz = new DateTimeZone('UTC');
820                 }
821
822                 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
823                 return $dt->format('U') + $dest_tz->getOffset($dt);
824         }
825
826         function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
827                                         $no_smart_dt = false) {
828
829                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
830                 if (!$timestamp) $timestamp = '1970-01-01 0:00';
831
832                 global $utc_tz;
833                 global $tz_offset;
834
835                 # We store date in UTC internally
836                 $dt = new DateTime($timestamp, $utc_tz);
837
838                 if ($tz_offset == -1) {
839
840                         $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
841
842                         try {
843                                 $user_tz = new DateTimeZone($user_tz_string);
844                         } catch (Exception $e) {
845                                 $user_tz = $utc_tz;
846                         }
847
848                         $tz_offset = $user_tz->getOffset($dt);
849                 }
850
851                 $user_timestamp = $dt->format('U') + $tz_offset;
852
853                 if (!$no_smart_dt) {
854                         return smart_date_time($link, $user_timestamp,
855                                 $tz_offset, $owner_uid);
856                 } else {
857                         if ($long)
858                                 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
859                         else
860                                 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
861
862                         return date($format, $user_timestamp);
863                 }
864         }
865
866         function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
867                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
868
869                 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
870                         return date("G:i", $timestamp);
871                 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
872                         $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
873                         return date($format, $timestamp);
874                 } else {
875                         $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
876                         return date($format, $timestamp);
877                 }
878         }
879
880         function sql_bool_to_bool($s) {
881                 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
882                         return true;
883                 } else {
884                         return false;
885                 }
886         }
887
888         function bool_to_sql_bool($s) {
889                 if ($s) {
890                         return "true";
891                 } else {
892                         return "false";
893                 }
894         }
895
896         // Session caching removed due to causing wrong redirects to upgrade
897         // script when get_schema_version() is called on an obsolete session
898         // created on a previous schema version.
899         function get_schema_version($link, $nocache = false) {
900                 global $schema_version;
901
902                 if (!$schema_version) {
903                         $result = db_query($link, "SELECT schema_version FROM ttrss_version");
904                         $version = db_fetch_result($result, 0, "schema_version");
905                         $schema_version = $version;
906                         return $version;
907                 } else {
908                         return $schema_version;
909                 }
910         }
911
912         function sanity_check($link) {
913                 require_once 'errors.php';
914
915                 $error_code = 0;
916                 $schema_version = get_schema_version($link, true);
917
918                 if ($schema_version != SCHEMA_VERSION) {
919                         $error_code = 5;
920                 }
921
922                 if (DB_TYPE == "mysql") {
923                         $result = db_query($link, "SELECT true", false);
924                         if (db_num_rows($result) != 1) {
925                                 $error_code = 10;
926                         }
927                 }
928
929                 if (db_escape_string($link, "testTEST") != "testTEST") {
930                         $error_code = 12;
931                 }
932
933                 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
934         }
935
936         function file_is_locked($filename) {
937                 if (function_exists('flock')) {
938                         $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
939                         if ($fp) {
940                                 if (flock($fp, LOCK_EX | LOCK_NB)) {
941                                         flock($fp, LOCK_UN);
942                                         fclose($fp);
943                                         return false;
944                                 }
945                                 fclose($fp);
946                                 return true;
947                         } else {
948                                 return false;
949                         }
950                 }
951                 return true; // consider the file always locked and skip the test
952         }
953
954         function make_lockfile($filename) {
955                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
956
957                 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
958                         if (function_exists('posix_getpid')) {
959                                 fwrite($fp, posix_getpid() . "\n");
960                         }
961                         return $fp;
962                 } else {
963                         return false;
964                 }
965         }
966
967         function make_stampfile($filename) {
968                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
969
970                 if (flock($fp, LOCK_EX | LOCK_NB)) {
971                         fwrite($fp, time() . "\n");
972                         flock($fp, LOCK_UN);
973                         fclose($fp);
974                         return true;
975                 } else {
976                         return false;
977                 }
978         }
979
980         function sql_random_function() {
981                 if (DB_TYPE == "mysql") {
982                         return "RAND()";
983                 } else {
984                         return "RANDOM()";
985                 }
986         }
987
988         function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
989
990                         if (!$owner_uid) $owner_uid = $_SESSION['uid'];
991
992                         //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
993
994                         // Todo: all this interval stuff needs some generic generator function
995
996                         $date_qpart = "false";
997
998                         switch ($mode) {
999                         case "1day":
1000                                 if (DB_TYPE == "pgsql") {
1001                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1002                                 } else {
1003                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1004                                 }
1005                                 break;
1006                         case "1week":
1007                                 if (DB_TYPE == "pgsql") {
1008                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1009                                 } else {
1010                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1011                                 }
1012                                 break;
1013                         case "2weeks":
1014                                 if (DB_TYPE == "pgsql") {
1015                                         $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1016                                 } else {
1017                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1018                                 }
1019                                 break;
1020                         default:
1021                                 $date_qpart = "true";
1022                         }
1023
1024                         if (is_numeric($feed)) {
1025                                 if ($cat_view) {
1026
1027                                         if ($feed >= 0) {
1028
1029                                                 if ($feed > 0) {
1030                                                         $children = getChildCategories($link, $feed, $owner_uid);
1031                                                         array_push($children, $feed);
1032
1033                                                         $children = join(",", $children);
1034
1035                                                         $cat_qpart = "cat_id IN ($children)";
1036                                                 } else {
1037                                                         $cat_qpart = "cat_id IS NULL";
1038                                                 }
1039
1040                                                 db_query($link, "UPDATE ttrss_user_entries
1041                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1042                                                                 (SELECT id FROM
1043                                                                         (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1044                                                                                 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1045                                                                                         (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1046
1047                                         } else if ($feed == -2) {
1048
1049                                                 db_query($link, "UPDATE ttrss_user_entries
1050                                                         SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1051                                                                 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1052                                                                 AND unread = true AND $date_qpart AND owner_uid = $owner_uid");
1053                                         }
1054
1055                                 } else if ($feed > 0) {
1056
1057                                         db_query($link, "UPDATE ttrss_user_entries
1058                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1059                                                         (SELECT id FROM
1060                                                                 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1061                                                                         AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1062
1063                                 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1064
1065                                         if ($feed == -1) {
1066                                                 db_query($link, "UPDATE ttrss_user_entries
1067                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1068                                                                 (SELECT id FROM
1069                                                                         (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1070                                                                                 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1071                                         }
1072
1073                                         if ($feed == -2) {
1074                                                 db_query($link, "UPDATE ttrss_user_entries
1075                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1076                                                                 (SELECT id FROM
1077                                                                         (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1078                                                                                 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1079                                         }
1080
1081                                         if ($feed == -3) {
1082
1083                                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1084
1085                                                 if (DB_TYPE == "pgsql") {
1086                                                         $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1087                                                 } else {
1088                                                         $match_part = "updated > DATE_SUB(NOW(),
1089                                                                 INTERVAL $intl HOUR) ";
1090                                                 }
1091
1092                                                 db_query($link, "UPDATE ttrss_user_entries
1093                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1094                                                                 (SELECT id FROM
1095                                                                         (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1096                                                                                 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart AND $match_part) as tmp)");
1097                                         }
1098
1099                                         if ($feed == -4) {
1100                                                 db_query($link, "UPDATE ttrss_user_entries
1101                                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1102                                                                 (SELECT id FROM
1103                                                                         (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1104                                                                                 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1105                                         }
1106
1107                                 } else if ($feed < LABEL_BASE_INDEX) { // label
1108
1109                                         $label_id = feed_to_label_id($feed);
1110
1111                                         db_query($link, "UPDATE ttrss_user_entries
1112                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1113                                                         (SELECT id FROM
1114                                                                 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1115                                                                         AND label_id = '$label_id' AND ref_id = article_id
1116                                                                         AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1117
1118                                 }
1119
1120                                 ccache_update($link, $feed, $owner_uid, $cat_view);
1121
1122                         } else { // tag
1123                                 db_query($link, "UPDATE ttrss_user_entries
1124                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1125                                                 (SELECT id FROM
1126                                                         (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1127                                                                 AND post_int_id = int_id AND tag_name = '$feed'
1128                                                                 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1129
1130                         }
1131         }
1132
1133         function getAllCounters($link) {
1134                 $data = getGlobalCounters($link);
1135
1136                 $data = array_merge($data, getVirtCounters($link));
1137                 $data = array_merge($data, getLabelCounters($link));
1138                 $data = array_merge($data, getFeedCounters($link, $active_feed));
1139                 $data = array_merge($data, getCategoryCounters($link));
1140
1141                 return $data;
1142         }
1143
1144         function getCategoryTitle($link, $cat_id) {
1145
1146                 if ($cat_id == -1) {
1147                         return __("Special");
1148                 } else if ($cat_id == -2) {
1149                         return __("Labels");
1150                 } else {
1151
1152                         $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1153                                 id = '$cat_id'");
1154
1155                         if (db_num_rows($result) == 1) {
1156                                 return db_fetch_result($result, 0, "title");
1157                         } else {
1158                                 return __("Uncategorized");
1159                         }
1160                 }
1161         }
1162
1163
1164         function getCategoryCounters($link) {
1165                 $ret_arr = array();
1166
1167                 /* Labels category */
1168
1169                 $cv = array("id" => -2, "kind" => "cat",
1170                         "counter" => getCategoryUnread($link, -2));
1171
1172                 array_push($ret_arr, $cv);
1173
1174                 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1175                         (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1176                                 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1177                         FROM ttrss_feed_categories, ttrss_cat_counters_cache
1178                         WHERE ttrss_cat_counters_cache.feed_id = id AND
1179                         ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1180                         ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1181
1182                 while ($line = db_fetch_assoc($result)) {
1183                         $line["cat_id"] = (int) $line["cat_id"];
1184
1185                         if ($line["num_children"] > 0) {
1186                                 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1187                         } else {
1188                                 $child_counter = 0;
1189                         }
1190
1191                         $cv = array("id" => $line["cat_id"], "kind" => "cat",
1192                                 "counter" => $line["unread"] + $child_counter);
1193
1194                         array_push($ret_arr, $cv);
1195                 }
1196
1197                 /* Special case: NULL category doesn't actually exist in the DB */
1198
1199                 $cv = array("id" => 0, "kind" => "cat",
1200                         "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1201
1202                 array_push($ret_arr, $cv);
1203
1204                 return $ret_arr;
1205         }
1206
1207         // only accepts real cats (>= 0)
1208         function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1209                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1210
1211                 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1212                                 AND owner_uid = $owner_uid");
1213
1214                 $unread = 0;
1215
1216                 while ($line = db_fetch_assoc($result)) {
1217                         $unread += getCategoryUnread($link, $line["id"], $owner_uid);
1218                         $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1219                 }
1220
1221                 return $unread;
1222         }
1223
1224         function getCategoryUnread($link, $cat, $owner_uid = false) {
1225
1226                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1227
1228                 if ($cat >= 0) {
1229
1230                         if ($cat != 0) {
1231                                 $cat_query = "cat_id = '$cat'";
1232                         } else {
1233                                 $cat_query = "cat_id IS NULL";
1234                         }
1235
1236                         $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1237                                         AND owner_uid = " . $owner_uid);
1238
1239                         $cat_feeds = array();
1240                         while ($line = db_fetch_assoc($result)) {
1241                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
1242                         }
1243
1244                         if (count($cat_feeds) == 0) return 0;
1245
1246                         $match_part = implode(" OR ", $cat_feeds);
1247
1248                         $result = db_query($link, "SELECT COUNT(int_id) AS unread
1249                                 FROM ttrss_user_entries
1250                                 WHERE   unread = true AND ($match_part)
1251                                 AND owner_uid = " . $owner_uid);
1252
1253                         $unread = 0;
1254
1255                         # this needs to be rewritten
1256                         while ($line = db_fetch_assoc($result)) {
1257                                 $unread += $line["unread"];
1258                         }
1259
1260                         return $unread;
1261                 } else if ($cat == -1) {
1262                         return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
1263                 } else if ($cat == -2) {
1264
1265                         $result = db_query($link, "
1266                                 SELECT COUNT(unread) AS unread FROM
1267                                         ttrss_user_entries, ttrss_user_labels2
1268                                 WHERE article_id = ref_id AND unread = true
1269                                         AND ttrss_user_entries.owner_uid = '$owner_uid'");
1270
1271                         $unread = db_fetch_result($result, 0, "unread");
1272
1273                         return $unread;
1274
1275                 }
1276         }
1277
1278         function getFeedUnread($link, $feed, $is_cat = false) {
1279                 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1280         }
1281
1282         function getLabelUnread($link, $label_id, $owner_uid = false) {
1283                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1284
1285                 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1286                         WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1287
1288                 if (db_num_rows($result) != 0) {
1289                         return db_fetch_result($result, 0, "unread");
1290                 } else {
1291                         return 0;
1292                 }
1293         }
1294
1295         function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1296                 $owner_uid = false) {
1297
1298                 $n_feed = (int) $feed;
1299                 $need_entries = false;
1300
1301                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1302
1303                 if ($unread_only) {
1304                         $unread_qpart = "unread = true";
1305                 } else {
1306                         $unread_qpart = "true";
1307                 }
1308
1309                 if ($is_cat) {
1310                         return getCategoryUnread($link, $n_feed, $owner_uid);
1311                 } else if ($n_feed == -6) {
1312                         return 0;
1313                 } else if ($feed != "0" && $n_feed == 0) {
1314
1315                         $feed = db_escape_string($link, $feed);
1316
1317                         $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1318                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1319                                         AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1320                                 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1321                         return db_fetch_result($result, 0, "count");
1322
1323                 } else if ($n_feed == -1) {
1324                         $match_part = "marked = true";
1325                 } else if ($n_feed == -2) {
1326                         $match_part = "published = true";
1327                 } else if ($n_feed == -3) {
1328                         $match_part = "unread = true AND score >= 0";
1329
1330                         $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1331
1332                         if (DB_TYPE == "pgsql") {
1333                                 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1334                         } else {
1335                                 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1336                         }
1337
1338                         $need_entries = true;
1339
1340                 } else if ($n_feed == -4) {
1341                         $match_part = "true";
1342                 } else if ($n_feed >= 0) {
1343
1344                         if ($n_feed != 0) {
1345                                 $match_part = "feed_id = '$n_feed'";
1346                         } else {
1347                                 $match_part = "feed_id IS NULL";
1348                         }
1349
1350                 } else if ($feed < LABEL_BASE_INDEX) {
1351
1352                         $label_id = feed_to_label_id($feed);
1353
1354                         return getLabelUnread($link, $label_id, $owner_uid);
1355
1356                 }
1357
1358                 if ($match_part) {
1359
1360                         if ($need_entries) {
1361                                 $from_qpart = "ttrss_user_entries,ttrss_entries";
1362                                 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1363                         } else {
1364                                 $from_qpart = "ttrss_user_entries";
1365                         }
1366
1367                         $query = "SELECT count(int_id) AS unread
1368                                 FROM $from_qpart WHERE
1369                                 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1370
1371                         //echo "[$feed/$query]\n";
1372
1373                         $result = db_query($link, $query);
1374
1375                 } else {
1376
1377                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1378                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1379                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1380                                 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1381                 }
1382
1383                 $unread = db_fetch_result($result, 0, "unread");
1384
1385                 return $unread;
1386         }
1387
1388         function getGlobalUnread($link, $user_id = false) {
1389
1390                 if (!$user_id) {
1391                         $user_id = $_SESSION["uid"];
1392                 }
1393
1394                 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1395                         WHERE owner_uid = '$user_id' AND feed_id > 0");
1396
1397                 $c_id = db_fetch_result($result, 0, "c_id");
1398
1399                 return $c_id;
1400         }
1401
1402         function getGlobalCounters($link, $global_unread = -1) {
1403                 $ret_arr = array();
1404
1405                 if ($global_unread == -1) {
1406                         $global_unread = getGlobalUnread($link);
1407                 }
1408
1409                 $cv = array("id" => "global-unread",
1410                         "counter" => (int) $global_unread);
1411
1412                 array_push($ret_arr, $cv);
1413
1414                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1415                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1416
1417                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1418
1419                 $cv = array("id" => "subscribed-feeds",
1420                         "counter" => (int) $subscribed_feeds);
1421
1422                 array_push($ret_arr, $cv);
1423
1424                 return $ret_arr;
1425         }
1426
1427         function getVirtCounters($link) {
1428
1429                 $ret_arr = array();
1430
1431                 for ($i = 0; $i >= -4; $i--) {
1432
1433                         $count = getFeedUnread($link, $i);
1434
1435                         $cv = array("id" => $i,
1436                                 "counter" => (int) $count);
1437
1438 //                      if (get_pref($link, 'EXTENDED_FEEDLIST'))
1439 //                              $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1440
1441                         array_push($ret_arr, $cv);
1442                 }
1443
1444                 global $pluginhost;
1445
1446                 if ($pluginhost) {
1447                         $feeds = $pluginhost->get_feeds(-1);
1448
1449                         if (is_array($feeds)) {
1450                                 foreach ($feeds as $feed) {
1451                                         $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1452                                                 "counter" => $feed['sender']->get_unread($feed['id']));
1453
1454                                         array_push($ret_arr, $cv);
1455                                 }
1456                         }
1457                 }
1458
1459                 return $ret_arr;
1460         }
1461
1462         function getLabelCounters($link, $descriptions = false) {
1463
1464                 $ret_arr = array();
1465
1466                 $owner_uid = $_SESSION["uid"];
1467
1468                 $result = db_query($link, "SELECT id,caption,COUNT(unread) AS unread
1469                         FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1470                                 (ttrss_labels2.id = label_id)
1471                                         LEFT JOIN ttrss_user_entries ON (ref_id = article_id AND unread = true)
1472                                 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1473                                         ttrss_labels2.caption");
1474
1475                 while ($line = db_fetch_assoc($result)) {
1476
1477                         $id = label_to_feed_id($line["id"]);
1478
1479                         $label_name = $line["caption"];
1480                         $count = $line["unread"];
1481
1482                         $cv = array("id" => $id,
1483                                 "counter" => (int) $count);
1484
1485                         if ($descriptions)
1486                                 $cv["description"] = $label_name;
1487
1488 //                      if (get_pref($link, 'EXTENDED_FEEDLIST'))
1489 //                              $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1490
1491                         array_push($ret_arr, $cv);
1492                 }
1493
1494                 return $ret_arr;
1495         }
1496
1497         function getFeedCounters($link, $active_feed = false) {
1498
1499                 $ret_arr = array();
1500
1501                 $query = "SELECT ttrss_feeds.id,
1502                                 ttrss_feeds.title,
1503                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1504                                 last_error, value AS count
1505                         FROM ttrss_feeds, ttrss_counters_cache
1506                         WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1507                                 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1508                                 AND ttrss_counters_cache.feed_id = id";
1509
1510                 $result = db_query($link, $query);
1511                 $fctrs_modified = false;
1512
1513                 while ($line = db_fetch_assoc($result)) {
1514
1515                         $id = $line["id"];
1516                         $count = $line["count"];
1517                         $last_error = htmlspecialchars($line["last_error"]);
1518
1519                         $last_updated = make_local_datetime($link, $line['last_updated'], false);
1520
1521                         $has_img = feed_has_icon($id);
1522
1523                         if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1524                                 $last_updated = '';
1525
1526                         $cv = array("id" => $id,
1527                                 "updated" => $last_updated,
1528                                 "counter" => (int) $count,
1529                                 "has_img" => (int) $has_img);
1530
1531                         if ($last_error)
1532                                 $cv["error"] = $last_error;
1533
1534 //                      if (get_pref($link, 'EXTENDED_FEEDLIST'))
1535 //                              $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1536
1537                         if ($active_feed && $id == $active_feed)
1538                                 $cv["title"] = truncate_string($line["title"], 30);
1539
1540                         array_push($ret_arr, $cv);
1541
1542                 }
1543
1544                 return $ret_arr;
1545         }
1546
1547         function get_pgsql_version($link) {
1548                 $result = db_query($link, "SELECT version() AS version");
1549                 $version = explode(" ", db_fetch_result($result, 0, "version"));
1550                 return $version[1];
1551         }
1552
1553         /**
1554          * @return array (code => Status code, message => error message if available)
1555          *
1556          *                 0 - OK, Feed already exists
1557          *                 1 - OK, Feed added
1558          *                 2 - Invalid URL
1559          *                 3 - URL content is HTML, no feeds available
1560          *                 4 - URL content is HTML which contains multiple feeds.
1561          *                     Here you should call extractfeedurls in rpc-backend
1562          *                     to get all possible feeds.
1563          *                 5 - Couldn't download the URL content.
1564          */
1565         function subscribe_to_feed($link, $url, $cat_id = 0,
1566                         $auth_login = '', $auth_pass = '') {
1567
1568                 global $fetch_last_error;
1569
1570                 require_once "include/rssfuncs.php";
1571
1572                 $url = fix_url($url);
1573
1574                 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1575
1576                 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1577
1578                 if (!$contents) {
1579                         return array("code" => 5, "message" => $fetch_last_error);
1580                 }
1581
1582                 if (is_html($contents)) {
1583                         $feedUrls = get_feeds_from_html($url, $contents);
1584
1585                         if (count($feedUrls) == 0) {
1586                                 return array("code" => 3);
1587                         } else if (count($feedUrls) > 1) {
1588                                 return array("code" => 4, "feeds" => $feedUrls);
1589                         }
1590                         //use feed url as new URL
1591                         $url = key($feedUrls);
1592                 }
1593
1594                 if ($cat_id == "0" || !$cat_id) {
1595                         $cat_qpart = "NULL";
1596                 } else {
1597                         $cat_qpart = "'$cat_id'";
1598                 }
1599
1600                 $result = db_query($link,
1601                         "SELECT id FROM ttrss_feeds
1602                         WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1603
1604                 if (db_num_rows($result) == 0) {
1605                         $result = db_query($link,
1606                                 "INSERT INTO ttrss_feeds
1607                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1608                                 VALUES ('".$_SESSION["uid"]."', '$url',
1609                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1610
1611                         $result = db_query($link,
1612                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1613                                         AND owner_uid = " . $_SESSION["uid"]);
1614
1615                         $feed_id = db_fetch_result($result, 0, "id");
1616
1617                         if ($feed_id) {
1618                                 update_rss_feed($link, $feed_id, true);
1619                         }
1620
1621                         return array("code" => 1);
1622                 } else {
1623                         return array("code" => 0);
1624                 }
1625         }
1626
1627         function print_feed_select($link, $id, $default_id = "",
1628                 $attributes = "", $include_all_feeds = true,
1629                 $root_id = false, $nest_level = 0) {
1630
1631                 if (!$root_id) {
1632                         print "<select id=\"$id\" name=\"$id\" $attributes>";
1633                         if ($include_all_feeds) {
1634                                 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1635                                 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1636                         }
1637                 }
1638
1639                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1640
1641                         if ($root_id)
1642                                 $parent_qpart = "parent_cat = '$root_id'";
1643                         else
1644                                 $parent_qpart = "parent_cat IS NULL";
1645
1646                         $result = db_query($link, "SELECT id,title,
1647                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1648                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1649                                 FROM ttrss_feed_categories
1650                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1651
1652                         while ($line = db_fetch_assoc($result)) {
1653
1654                                 for ($i = 0; $i < $nest_level; $i++)
1655                                         $line["title"] = " - " . $line["title"];
1656
1657                                 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1658
1659                                 printf("<option $is_selected value='CAT:%d'>%s</option>",
1660                                         $line["id"], htmlspecialchars($line["title"]));
1661
1662                                 if ($line["num_children"] > 0)
1663                                         print_feed_select($link, $id, $default_id, $attributes,
1664                                                 $include_all_feeds, $line["id"], $nest_level+1);
1665
1666                                 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1667                                         WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1668
1669                                 while ($fline = db_fetch_assoc($feed_result)) {
1670                                         $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1671
1672                                         $fline["title"] = " + " . $fline["title"];
1673
1674                                         for ($i = 0; $i < $nest_level; $i++)
1675                                                 $fline["title"] = " - " . $fline["title"];
1676
1677                                         printf("<option $is_selected value='%d'>%s</option>",
1678                                                 $fline["id"], htmlspecialchars($fline["title"]));
1679                                 }
1680                         }
1681
1682                         if (!$root_id) {
1683                                 $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
1684
1685                                 printf("<option $is_selected value='CAT:0'>%s</option>",
1686                                         __("Uncategorized"));
1687
1688                                 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1689                                         WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1690
1691                                 while ($fline = db_fetch_assoc($feed_result)) {
1692                                         $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1693
1694                                         $fline["title"] = " + " . $fline["title"];
1695
1696                                         for ($i = 0; $i < $nest_level; $i++)
1697                                                 $fline["title"] = " - " . $fline["title"];
1698
1699                                         printf("<option $is_selected value='%d'>%s</option>",
1700                                                 $fline["id"], htmlspecialchars($fline["title"]));
1701                                 }
1702                         }
1703
1704                 } else {
1705                         $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1706                                 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1707
1708                         while ($line = db_fetch_assoc($result)) {
1709
1710                                 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1711
1712                                 printf("<option $is_selected value='%d'>%s</option>",
1713                                         $line["id"], htmlspecialchars($line["title"]));
1714                         }
1715                 }
1716
1717                 if (!$root_id) {
1718                         print "</select>";
1719                 }
1720         }
1721
1722         function print_feed_cat_select($link, $id, $default_id,
1723                 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1724
1725                         if (!$root_id) {
1726                                         print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1727                         }
1728
1729                         if ($root_id)
1730                                 $parent_qpart = "parent_cat = '$root_id'";
1731                         else
1732                                 $parent_qpart = "parent_cat IS NULL";
1733
1734                         $result = db_query($link, "SELECT id,title,
1735                                 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1736                                         c2.parent_cat = ttrss_feed_categories.id) AS num_children
1737                                 FROM ttrss_feed_categories
1738                                 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1739
1740                         while ($line = db_fetch_assoc($result)) {
1741                                 if ($line["id"] == $default_id) {
1742                                         $is_selected = "selected=\"1\"";
1743                                 } else {
1744                                         $is_selected = "";
1745                                 }
1746
1747                                 for ($i = 0; $i < $nest_level; $i++)
1748                                         $line["title"] = " - " . $line["title"];
1749
1750                                 if ($line["title"])
1751                                         printf("<option $is_selected value='%d'>%s</option>",
1752                                                 $line["id"], htmlspecialchars($line["title"]));
1753
1754                                 if ($line["num_children"] > 0)
1755                                         print_feed_cat_select($link, $id, $default_id, $attributes,
1756                                                 $include_all_cats, $line["id"], $nest_level+1);
1757                         }
1758
1759                         if (!$root_id) {
1760                                 if ($include_all_cats) {
1761                                         if (db_num_rows($result) > 0) {
1762                                                 print "<option disabled=\"1\">--------</option>";
1763                                         }
1764
1765                                         if ($default_id == 0) {
1766                                                 $is_selected = "selected=\"1\"";
1767                                         } else {
1768                                                 $is_selected = "";
1769                                         }
1770
1771                                         print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1772                                 }
1773                                 print "</select>";
1774                         }
1775                 }
1776
1777         function checkbox_to_sql_bool($val) {
1778                 return ($val == "on") ? "true" : "false";
1779         }
1780
1781         function getFeedCatTitle($link, $id) {
1782                 if ($id == -1) {
1783                         return __("Special");
1784                 } else if ($id < LABEL_BASE_INDEX) {
1785                         return __("Labels");
1786                 } else if ($id > 0) {
1787                         $result = db_query($link, "SELECT ttrss_feed_categories.title
1788                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1789                                         cat_id = ttrss_feed_categories.id");
1790                         if (db_num_rows($result) == 1) {
1791                                 return db_fetch_result($result, 0, "title");
1792                         } else {
1793                                 return __("Uncategorized");
1794                         }
1795                 } else {
1796                         return "getFeedCatTitle($id) failed";
1797                 }
1798
1799         }
1800
1801         function getFeedIcon($id) {
1802                 switch ($id) {
1803                 case 0:
1804                         return "images/archive.png";
1805                         break;
1806                 case -1:
1807                         return "images/mark_set.svg";
1808                         break;
1809                 case -2:
1810                         return "images/pub_set.svg";
1811                         break;
1812                 case -3:
1813                         return "images/fresh.png";
1814                         break;
1815                 case -4:
1816                         return "images/tag.png";
1817                         break;
1818                 case -6:
1819                         return "images/recently_read.png";
1820                         break;
1821                 default:
1822                         if ($id < LABEL_BASE_INDEX) {
1823                                 return "images/label.png";
1824                         } else {
1825                                 if (file_exists(ICONS_DIR . "/$id.ico"))
1826                                         return ICONS_URL . "/$id.ico";
1827                         }
1828                         break;
1829                 }
1830         }
1831
1832         function getFeedTitle($link, $id, $cat = false) {
1833                 if ($cat) {
1834                         return getCategoryTitle($link, $id);
1835                 } else if ($id == -1) {
1836                         return __("Starred articles");
1837                 } else if ($id == -2) {
1838                         return __("Published articles");
1839                 } else if ($id == -3) {
1840                         return __("Fresh articles");
1841                 } else if ($id == -4) {
1842                         return __("All articles");
1843                 } else if ($id === 0 || $id === "0") {
1844                         return __("Archived articles");
1845                 } else if ($id == -6) {
1846                         return __("Recently read");
1847                 } else if ($id < LABEL_BASE_INDEX) {
1848                         $label_id = feed_to_label_id($id);
1849                         $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1850                         if (db_num_rows($result) == 1) {
1851                                 return db_fetch_result($result, 0, "caption");
1852                         } else {
1853                                 return "Unknown label ($label_id)";
1854                         }
1855
1856                 } else if (is_numeric($id) && $id > 0) {
1857                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1858                         if (db_num_rows($result) == 1) {
1859                                 return db_fetch_result($result, 0, "title");
1860                         } else {
1861                                 return "Unknown feed ($id)";
1862                         }
1863                 } else {
1864                         return $id;
1865                 }
1866         }
1867
1868         function make_init_params($link) {
1869                 $params = array();
1870
1871                 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1872                         "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1873                         "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
1874                         "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1875
1876                                  $params[strtolower($param)] = (int) get_pref($link, $param);
1877                  }
1878
1879                 $params["icons_url"] = ICONS_URL;
1880                 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
1881                 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1882                 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1883                 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1884                 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1885                 $params["label_base_index"] = (int) LABEL_BASE_INDEX;
1886
1887                 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1888                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1889
1890                 $max_feed_id = db_fetch_result($result, 0, "mid");
1891                 $num_feeds = db_fetch_result($result, 0, "nf");
1892
1893                 $params["max_feed_id"] = (int) $max_feed_id;
1894                 $params["num_feeds"] = (int) $num_feeds;
1895
1896                 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1897                 $params["hotkeys"] = get_hotkeys_map($link);
1898
1899                 $params["csrf_token"] = $_SESSION["csrf_token"];
1900                 $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
1901
1902                 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
1903
1904                 return $params;
1905         }
1906
1907         function get_hotkeys_info($link) {
1908                 $hotkeys = array(
1909                         __("Navigation") => array(
1910                                 "next_feed" => __("Open next feed"),
1911                                 "prev_feed" => __("Open previous feed"),
1912                                 "next_article" => __("Open next article"),
1913                                 "prev_article" => __("Open previous article"),
1914                                 "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
1915                                 "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
1916                                 "search_dialog" => __("Show search dialog")),
1917                         __("Article") => array(
1918                                 "toggle_mark" => __("Toggle starred"),
1919                                 "toggle_publ" => __("Toggle published"),
1920                                 "toggle_unread" => __("Toggle unread"),
1921                                 "edit_tags" => __("Edit tags"),
1922                                 "dismiss_selected" => __("Dismiss selected"),
1923                                 "dismiss_read" => __("Dismiss read"),
1924                                 "open_in_new_window" => __("Open in new window"),
1925                                 "catchup_below" => __("Mark below as read"),
1926                                 "catchup_above" => __("Mark above as read"),
1927                                 "article_scroll_down" => __("Scroll down"),
1928                                 "article_scroll_up" => __("Scroll up"),
1929                                 "select_article_cursor" => __("Select article under cursor"),
1930                                 "email_article" => __("Email article"),
1931                                 "close_article" => __("Close/collapse article"),
1932                                 "toggle_widescreen" => __("Toggle widescreen mode"),
1933                                 "toggle_embed_original" => __("Toggle embed original")),
1934                         __("Article selection") => array(
1935                                 "select_all" => __("Select all articles"),
1936                                 "select_unread" => __("Select unread"),
1937                                 "select_marked" => __("Select starred"),
1938                                 "select_published" => __("Select published"),
1939                                 "select_invert" => __("Invert selection"),
1940                                 "select_none" => __("Deselect everything")),
1941                         __("Feed") => array(
1942                                 "feed_refresh" => __("Refresh current feed"),
1943                                 "feed_unhide_read" => __("Un/hide read feeds"),
1944                                 "feed_subscribe" => __("Subscribe to feed"),
1945                                 "feed_edit" => __("Edit feed"),
1946                                 "feed_catchup" => __("Mark as read"),
1947                                 "feed_reverse" => __("Reverse headlines"),
1948                                 "feed_debug_update" => __("Debug feed update"),
1949                                 "catchup_all" => __("Mark all feeds as read"),
1950                                 "cat_toggle_collapse" => __("Un/collapse current category"),
1951                                 "toggle_combined_mode" => __("Toggle combined mode"),
1952                                 "toggle_cdm_expanded" => __("Toggle auto expand in combined mode")),
1953                         __("Go to") => array(
1954                                 "goto_all" => __("All articles"),
1955                                 "goto_fresh" => __("Fresh"),
1956                                 "goto_marked" => __("Starred"),
1957                                 "goto_published" => __("Published"),
1958                                 "goto_tagcloud" => __("Tag cloud"),
1959                                 "goto_prefs" => __("Preferences")),
1960                         __("Other") => array(
1961                                 "create_label" => __("Create label"),
1962                                 "create_filter" => __("Create filter"),
1963                                 "collapse_sidebar" => __("Un/collapse sidebar"),
1964                                 "help_dialog" => __("Show help dialog"))
1965                         );
1966
1967                 global $pluginhost;
1968                 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_INFO) as $plugin) {
1969                         $hotkeys = $plugin->hook_hotkey_info($hotkeys);
1970                 }
1971
1972                 return $hotkeys;
1973         }
1974
1975         function get_hotkeys_map($link) {
1976                 $hotkeys = array(
1977 //                      "navigation" => array(
1978                                 "k" => "next_feed",
1979                                 "j" => "prev_feed",
1980                                 "n" => "next_article",
1981                                 "p" => "prev_article",
1982                                 "(38)|up" => "prev_article",
1983                                 "(40)|down" => "next_article",
1984 //                              "^(38)|Ctrl-up" => "prev_article_noscroll",
1985 //                              "^(40)|Ctrl-down" => "next_article_noscroll",
1986                                 "(191)|/" => "search_dialog",
1987 //                      "article" => array(
1988                                 "s" => "toggle_mark",
1989                                 "*s" => "toggle_publ",
1990                                 "u" => "toggle_unread",
1991                                 "*t" => "edit_tags",
1992                                 "*d" => "dismiss_selected",
1993                                 "*x" => "dismiss_read",
1994                                 "o" => "open_in_new_window",
1995                                 "c p" => "catchup_below",
1996                                 "c n" => "catchup_above",
1997                                 "*n" => "article_scroll_down",
1998                                 "*p" => "article_scroll_up",
1999                                 "*(38)|Shift+up" => "article_scroll_up",
2000                                 "*(40)|Shift+down" => "article_scroll_down",
2001                                 "a *w" => "toggle_widescreen",
2002                                 "a e" => "toggle_embed_original",
2003                                 "e" => "email_article",
2004                                 "a q" => "close_article",
2005 //                      "article_selection" => array(
2006                                 "a a" => "select_all",
2007                                 "a u" => "select_unread",
2008                                 "a *u" => "select_marked",
2009                                 "a p" => "select_published",
2010                                 "a i" => "select_invert",
2011                                 "a n" => "select_none",
2012 //                      "feed" => array(
2013                                 "f r" => "feed_refresh",
2014                                 "f a" => "feed_unhide_read",
2015                                 "f s" => "feed_subscribe",
2016                                 "f e" => "feed_edit",
2017                                 "f q" => "feed_catchup",
2018                                 "f x" => "feed_reverse",
2019                                 "f *d" => "feed_debug_update",
2020                                 "f *c" => "toggle_combined_mode",
2021                                 "f c" => "toggle_cdm_expanded",
2022                                 "*q" => "catchup_all",
2023                                 "x" => "cat_toggle_collapse",
2024 //                      "goto" => array(
2025                                 "g a" => "goto_all",
2026                                 "g f" => "goto_fresh",
2027                                 "g s" => "goto_marked",
2028                                 "g p" => "goto_published",
2029                                 "g t" => "goto_tagcloud",
2030                                 "g *p" => "goto_prefs",
2031 //                      "other" => array(
2032                                 "(9)|Tab" => "select_article_cursor", // tab
2033                                 "c l" => "create_label",
2034                                 "c f" => "create_filter",
2035                                 "c s" => "collapse_sidebar",
2036                                 "^(191)|Ctrl+/" => "help_dialog",
2037                         );
2038
2039                 if (get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2040                         $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
2041                         $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
2042                 }
2043
2044                 global $pluginhost;
2045                 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
2046                         $hotkeys = $plugin->hook_hotkey_map($hotkeys);
2047                 }
2048
2049                 $prefixes = array();
2050
2051                 foreach (array_keys($hotkeys) as $hotkey) {
2052                         $pair = explode(" ", $hotkey, 2);
2053
2054                         if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
2055                                 array_push($prefixes, $pair[0]);
2056                         }
2057                 }
2058
2059                 return array($prefixes, $hotkeys);
2060         }
2061
2062         function make_runtime_info($link) {
2063                 $data = array();
2064
2065                 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2066                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2067
2068                 $max_feed_id = db_fetch_result($result, 0, "mid");
2069                 $num_feeds = db_fetch_result($result, 0, "nf");
2070
2071                 $data["max_feed_id"] = (int) $max_feed_id;
2072                 $data["num_feeds"] = (int) $num_feeds;
2073
2074                 $data['last_article_id'] = getLastArticleId($link);
2075                 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2076
2077                 $data['dep_ts'] = calculate_dep_timestamp();
2078                 $data['reload_on_ts_change'] = !defined('_NO_RELOAD_ON_TS_CHANGE');
2079
2080                 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
2081
2082                         $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2083
2084                         if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2085
2086                                 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
2087
2088                                 if ($stamp) {
2089                                         $stamp_delta = time() - $stamp;
2090
2091                                         if ($stamp_delta > 1800) {
2092                                                 $stamp_check = 0;
2093                                         } else {
2094                                                 $stamp_check = 1;
2095                                                 $_SESSION["daemon_stamp_check"] = time();
2096                                         }
2097
2098                                         $data['daemon_stamp_ok'] = $stamp_check;
2099
2100                                         $stamp_fmt = date("Y.m.d, G:i", $stamp);
2101
2102                                         $data['daemon_stamp'] = $stamp_fmt;
2103                                 }
2104                         }
2105                 }
2106
2107                 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
2108                                 $new_version_details = @check_for_update($link);
2109
2110                                 $data['new_version_available'] = (int) ($new_version_details != false);
2111
2112                                 $_SESSION["last_version_check"] = time();
2113                                 $_SESSION["version_data"] = $new_version_details;
2114                 }
2115
2116                 return $data;
2117         }
2118
2119         function search_to_sql($link, $search) {
2120
2121                 $search_query_part = "";
2122
2123                 $keywords = explode(" ", $search);
2124                 $query_keywords = array();
2125
2126                 foreach ($keywords as $k) {
2127                         if (strpos($k, "-") === 0) {
2128                                 $k = substr($k, 1);
2129                                 $not = "NOT";
2130                         } else {
2131                                 $not = "";
2132                         }
2133
2134                         $commandpair = explode(":", mb_strtolower($k), 2);
2135
2136                         if ($commandpair[0] == "note" && $commandpair[1]) {
2137
2138                                 if ($commandpair[1] == "true")
2139                                         array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2140                                 else
2141                                         array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2142
2143                         } else if ($commandpair[0] == "star" && $commandpair[1]) {
2144
2145                                 if ($commandpair[1] == "true")
2146                                         array_push($query_keywords, "($not (marked = true))");
2147                                 else
2148                                         array_push($query_keywords, "($not (marked = false))");
2149
2150                         } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2151
2152                                 if ($commandpair[1] == "true")
2153                                         array_push($query_keywords, "($not (published = true))");
2154                                 else
2155                                         array_push($query_keywords, "($not (published = false))");
2156
2157                         } else if (strpos($k, "@") === 0) {
2158
2159                                 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2160                                 $orig_ts = strtotime(substr($k, 1));
2161                                 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2162
2163                                 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2164
2165                                 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2166                         } else {
2167                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2168                                                 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2169                         }
2170                 }
2171
2172                 $search_query_part = implode("AND", $query_keywords);
2173
2174                 return $search_query_part;
2175         }
2176
2177         function getParentCategories($link, $cat, $owner_uid) {
2178                 $rv = array();
2179
2180                 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2181                         WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2182
2183                 while ($line = db_fetch_assoc($result)) {
2184                         array_push($rv, $line["parent_cat"]);
2185                         $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2186                 }
2187
2188                 return $rv;
2189         }
2190
2191         function getChildCategories($link, $cat, $owner_uid) {
2192                 $rv = array();
2193
2194                 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2195                         WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2196
2197                 while ($line = db_fetch_assoc($result)) {
2198                         array_push($rv, $line["id"]);
2199                         $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2200                 }
2201
2202                 return $rv;
2203         }
2204
2205         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false, $ignore_vfeed_group = false) {
2206
2207                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2208
2209                 $ext_tables_part = "";
2210
2211                         if ($search) {
2212
2213                                 if (SPHINX_ENABLED) {
2214                                         $ids = join(",", @sphinx_search($search, 0, 500));
2215
2216                                         if ($ids)
2217                                                 $search_query_part = "ref_id IN ($ids) AND ";
2218                                         else
2219                                                 $search_query_part = "ref_id = -1 AND ";
2220
2221                                 } else {
2222                                         $search_query_part = search_to_sql($link, $search);
2223                                         $search_query_part .= " AND ";
2224                                 }
2225
2226                         } else {
2227                                 $search_query_part = "";
2228                         }
2229
2230                         if ($filter) {
2231
2232                                 if (DB_TYPE == "pgsql") {
2233                                         $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2234                                 } else {
2235                                         $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2236                                 }
2237
2238                                 $override_order = "updated DESC";
2239
2240                                 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2241
2242                                 // Try to check if SQL regexp implementation chokes on a valid regexp
2243                                 $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
2244                                         ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2245                                         WHERE $filter_query_part LIMIT 1", false);
2246
2247                                 if ($result) {
2248                                         $test = db_fetch_result($result, 0, "true_val");
2249
2250                                         if (!$test) {
2251                                                 $filter_query_part = "false AND";
2252                                         } else {
2253                                                 $filter_query_part .= " AND";
2254                                         }
2255                                 } else {
2256                                         $filter_query_part = "false AND";
2257                                 }
2258
2259                         } else {
2260                                 $filter_query_part = "";
2261                         }
2262
2263                         if ($since_id) {
2264                                 $since_id_part = "ttrss_entries.id > $since_id AND ";
2265                         } else {
2266                                 $since_id_part = "";
2267                         }
2268
2269                         $view_query_part = "";
2270
2271                         if ($view_mode == "adaptive") {
2272                                 if ($search) {
2273                                         $view_query_part = " ";
2274                                 } else if ($feed != -1) {
2275
2276                                         $unread = getFeedUnread($link, $feed, $cat_view);
2277
2278                                         if ($cat_view && $feed > 0 && $include_children)
2279                                                 $unread += getCategoryChildrenUnread($link, $feed);
2280
2281                                         if ($unread > 0)
2282                                 $view_query_part = " unread = true AND ";
2283
2284                                 }
2285                         }
2286
2287                         if ($view_mode == "marked") {
2288                                 $view_query_part = " marked = true AND ";
2289                         }
2290
2291                         if ($view_mode == "has_note") {
2292                                 $view_query_part = " (note IS NOT NULL AND note != '') AND ";
2293                         }
2294
2295                         if ($view_mode == "published") {
2296                                 $view_query_part = " published = true AND ";
2297                         }
2298
2299                         if ($view_mode == "unread" && $feed != -6) {
2300                                 $view_query_part = " unread = true AND ";
2301                         }
2302
2303                         if ($limit > 0) {
2304                                 $limit_query_part = "LIMIT " . $limit;
2305                         }
2306
2307                         $allow_archived = false;
2308
2309                         $vfeed_query_part = "";
2310
2311                         // override query strategy and enable feed display when searching globally
2312                         if ($search && $search_mode == "all_feeds") {
2313                                 $query_strategy_part = "true";
2314                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2315                         /* tags */
2316                         } else if (!is_numeric($feed)) {
2317                                 $query_strategy_part = "true";
2318                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2319                                         id = feed_id) as feed_title,";
2320                         } else if ($search && $search_mode == "this_cat") {
2321                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2322
2323                                 if ($feed > 0) {
2324                                         if ($include_children) {
2325                                                 $subcats = getChildCategories($link, $feed, $owner_uid);
2326                                                 array_push($subcats, $feed);
2327                                                 $cats_qpart = join(",", $subcats);
2328                                         } else {
2329                                                 $cats_qpart = $feed;
2330                                         }
2331
2332                                         $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2333
2334                                 } else {
2335                                         $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2336                                 }
2337
2338                         } else if ($feed > 0) {
2339
2340                                 if ($cat_view) {
2341
2342                                         if ($feed > 0) {
2343                                                 if ($include_children) {
2344                                                         # sub-cats
2345                                                         $subcats = getChildCategories($link, $feed, $owner_uid);
2346
2347                                                         array_push($subcats, $feed);
2348                                                         $query_strategy_part = "cat_id IN (".
2349                                                                         implode(",", $subcats).")";
2350
2351                                                 } else {
2352                                                         $query_strategy_part = "cat_id = '$feed'";
2353                                                 }
2354
2355                                         } else {
2356                                                 $query_strategy_part = "cat_id IS NULL";
2357                                         }
2358
2359                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2360
2361                                 } else {
2362                                         $query_strategy_part = "feed_id = '$feed'";
2363                                 }
2364                         } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2365                                 $query_strategy_part = "feed_id IS NULL";
2366                                 $allow_archived = true;
2367                         } else if ($feed == 0 && $cat_view) { // uncategorized
2368                                 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2369                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2370                         } else if ($feed == -1) { // starred virtual feed
2371                                 $query_strategy_part = "marked = true";
2372                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2373                                 $allow_archived = true;
2374
2375                                 if (!$override_order) {
2376                                         $override_order = "last_marked DESC, date_entered DESC, updated DESC";
2377                                 }
2378
2379                         } else if ($feed == -2) { // published virtual feed OR labels category
2380
2381                                 if (!$cat_view) {
2382                                         $query_strategy_part = "published = true";
2383                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2384                                         $allow_archived = true;
2385
2386                                         if (!$override_order) {
2387                                                 $override_order = "last_published DESC, date_entered DESC, updated DESC";
2388                                         }
2389
2390                                 } else {
2391                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2392
2393                                         $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2394
2395                                         $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2396                                                 ttrss_user_labels2.article_id = ref_id";
2397
2398                                 }
2399                         } else if ($feed == -6) { // recently read
2400                                 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2401                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2402                                 $allow_archived = true;
2403
2404                                 if (!$override_order) $override_order = "last_read DESC";
2405                         } else if ($feed == -3) { // fresh virtual feed
2406                                 $query_strategy_part = "unread = true AND score >= 0";
2407
2408                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2409
2410                                 if (DB_TYPE == "pgsql") {
2411                                         $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2412                                 } else {
2413                                         $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2414                                 }
2415
2416                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2417                         } else if ($feed == -4) { // all articles virtual feed
2418                                 $query_strategy_part = "true";
2419                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2420                         } else if ($feed <= LABEL_BASE_INDEX) { // labels
2421                                 $label_id = feed_to_label_id($feed);
2422
2423                                 $query_strategy_part = "label_id = '$label_id' AND
2424                                         ttrss_labels2.id = ttrss_user_labels2.label_id AND
2425                                         ttrss_user_labels2.article_id = ref_id";
2426
2427                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2428                                 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2429                                 $allow_archived = true;
2430
2431                         } else {
2432                                 $query_strategy_part = "true";
2433                         }
2434
2435                         if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2436                                 $date_sort_field = "updated";
2437                         } else {
2438                                 $date_sort_field = "date_entered";
2439                         }
2440
2441                         $order_by = "$date_sort_field DESC, updated DESC";
2442
2443                         if ($view_mode == "unread_first") {
2444                                 $order_by = "unread DESC, $order_by";
2445                         }
2446
2447                         if ($override_order) {
2448                                 $order_by = $override_order;
2449                         }
2450
2451                         $feed_title = "";
2452
2453                         if ($search) {
2454                                 $feed_title = T_sprintf("Search results: %s", $search);
2455                         } else {
2456                                 if ($cat_view) {
2457                                         $feed_title = getCategoryTitle($link, $feed);
2458                                 } else {
2459                                         if (is_numeric($feed) && $feed > 0) {
2460                                                 $result = db_query($link, "SELECT title,site_url,last_error
2461                                                         FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2462
2463                                                 $feed_title = db_fetch_result($result, 0, "title");
2464                                                 $feed_site_url = db_fetch_result($result, 0, "site_url");
2465                                                 $last_error = db_fetch_result($result, 0, "last_error");
2466                                         } else {
2467                                                 $feed_title = getFeedTitle($link, $feed);
2468                                         }
2469                                 }
2470                         }
2471
2472                         $content_query_part = "content as content_preview, cached_content, ";
2473
2474                         if (is_numeric($feed)) {
2475
2476                                 if ($feed >= 0) {
2477                                         $feed_kind = "Feeds";
2478                                 } else {
2479                                         $feed_kind = "Labels";
2480                                 }
2481
2482                                 if ($limit_query_part) {
2483                                         $offset_query_part = "OFFSET $offset";
2484                                 }
2485
2486                                 // proper override_order applied above
2487                                 if ($vfeed_query_part && !$ignore_vfeed_group && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2488                                         if (!$override_order) {
2489                                                 $order_by = "ttrss_feeds.title, $order_by";
2490                                         } else {
2491                                                 $order_by = "ttrss_feeds.title, $override_order";
2492                                         }
2493                                 }
2494
2495                                 if (!$allow_archived) {
2496                                         $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2497                                         $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2498
2499                                 } else {
2500                                         $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2501                                                 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2502                                 }
2503
2504                                 $query = "SELECT DISTINCT
2505                                                 date_entered,
2506                                                 guid,
2507                                                 ttrss_entries.id,ttrss_entries.title,
2508                                                 updated,
2509                                                 label_cache,
2510                                                 tag_cache,
2511                                                 always_display_enclosures,
2512                                                 site_url,
2513                                                 note,
2514                                                 num_comments,
2515                                                 comments,
2516                                                 int_id,
2517                                                 hide_images,
2518                                                 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2519                                                 last_marked, last_published,
2520                                                 $vfeed_query_part
2521                                                 $content_query_part
2522                                                 author,score
2523                                         FROM
2524                                                 $from_qpart
2525                                         WHERE
2526                                         $feed_check_qpart
2527                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2528                                         ttrss_user_entries.owner_uid = '$owner_uid' AND
2529                                         $search_query_part
2530                                         $filter_query_part
2531                                         $view_query_part
2532                                         $since_id_part
2533                                         $query_strategy_part ORDER BY $order_by
2534                                         $limit_query_part $offset_query_part";
2535
2536                                 if ($_REQUEST["debug"]) print $query;
2537
2538                                 $result = db_query($link, $query);
2539
2540                         } else {
2541                                 // browsing by tag
2542
2543                                 $select_qpart = "SELECT DISTINCT " .
2544                                                                 "date_entered," .
2545                                                                 "guid," .
2546                                                                 "note," .
2547                                                                 "ttrss_entries.id as id," .
2548                                                                 "title," .
2549                                                                 "updated," .
2550                                                                 "unread," .
2551                                                                 "feed_id," .
2552                                                                 "orig_feed_id," .
2553                                                                 "marked," .
2554                                                                 "num_comments, " .
2555                                                                 "comments, " .
2556                                                                 "tag_cache," .
2557                                                                 "label_cache," .
2558                                                                 "link," .
2559                                                                 "last_read," .
2560                                                                 "(SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images," .
2561                                                                 "last_marked, last_published, " .
2562                                                                 $since_id_part .
2563                                                                 $vfeed_query_part .
2564                                                                 $content_query_part .
2565                                                                 "score ";
2566
2567                                 $feed_kind = "Tags";
2568                                 $all_tags = explode(",", $feed);
2569                                 if ($search_mode == 'any') {
2570                                         $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2571                                         $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2572                                         $where_qpart = " WHERE " .
2573                                                                    "ref_id = ttrss_entries.id AND " .
2574                                                                    "ttrss_user_entries.owner_uid = $owner_uid AND " .
2575                                                                    "post_int_id = int_id AND $tag_sql AND " .
2576                                                                    $view_query_part .
2577                                                                    $search_query_part .
2578                                                                    $query_strategy_part . " ORDER BY $order_by " .
2579                                                                    $limit_query_part;
2580
2581                                 } else {
2582                                         $i = 1;
2583                                         $sub_selects = array();
2584                                         $sub_ands = array();
2585                                         foreach ($all_tags as $term) {
2586                                                 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2587                                                 $i++;
2588                                         }
2589                                         if ($i > 2) {
2590                                                 $x = 1;
2591                                                 $y = 2;
2592                                                 do {
2593                                                         array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2594                                                         $x++;
2595                                                         $y++;
2596                                                 } while ($y < $i);
2597                                         }
2598                                         array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2599                                         array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2600                                         $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2601                                         $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2602                                 }
2603                                 //                              error_log("TAG SQL: " . $tag_sql);
2604                                 // $tag_sql = "tag_name = '$feed'";   DEFAULT way
2605
2606                                 //                              error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2607                                 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2608                         }
2609
2610                         return array($result, $feed_title, $feed_site_url, $last_error);
2611
2612         }
2613
2614         function sanitize($link, $str, $force_remove_images = false, $owner = false, $site_url = false) {
2615                 if (!$owner) $owner = $_SESSION["uid"];
2616
2617                 $res = trim($str); if (!$res) return '';
2618
2619                 if (strpos($res, "href=") === false)
2620                         $res = rewrite_urls($res);
2621
2622                 $charset_hack = '<head>
2623                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2624                 </head>';
2625
2626                 $res = trim($res); if (!$res) return '';
2627
2628                 libxml_use_internal_errors(true);
2629
2630                 $doc = new DOMDocument();
2631                 $doc->loadHTML($charset_hack . $res);
2632                 $xpath = new DOMXPath($doc);
2633
2634                 $entries = $xpath->query('(//a[@href]|//img[@src])');
2635
2636                 foreach ($entries as $entry) {
2637
2638                         if ($site_url) {
2639
2640                                 if ($entry->hasAttribute('href'))
2641                                         $entry->setAttribute('href',
2642                                                 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2643
2644                                 if ($entry->hasAttribute('src')) {
2645                                         $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
2646
2647                                         $cached_filename = CACHE_DIR . '/images/' . sha1($src) . '.png';
2648
2649                                         if (file_exists($cached_filename)) {
2650                                                 $src = SELF_URL_PATH . '/image.php?hash=' . sha1($src);
2651                                         }
2652
2653                                         $entry->setAttribute('src', $src);
2654                                 }
2655
2656                                 if ($entry->nodeName == 'img') {
2657                                         if (($owner && get_pref($link, "STRIP_IMAGES", $owner)) ||
2658                                                         $force_remove_images || $_SESSION["bw_limit"]) {
2659
2660                                                 $p = $doc->createElement('p');
2661
2662                                                 $a = $doc->createElement('a');
2663                                                 $a->setAttribute('href', $entry->getAttribute('src'));
2664
2665                                                 $a->appendChild(new DOMText($entry->getAttribute('src')));
2666                                                 $a->setAttribute('target', '_blank');
2667
2668                                                 $p->appendChild($a);
2669
2670                                                 $entry->parentNode->replaceChild($p, $entry);
2671                                         }
2672                                 }
2673                         }
2674
2675                         if (strtolower($entry->nodeName) == "a") {
2676                                 $entry->setAttribute("target", "_blank");
2677                         }
2678                 }
2679
2680                 $entries = $xpath->query('//iframe');
2681                 foreach ($entries as $entry) {
2682                         $entry->setAttribute('sandbox', 'allow-scripts');
2683
2684                 }
2685
2686                 $allowed_elements = array('a', 'address', 'audio', 'article',
2687                         'b', 'big', 'blockquote', 'body', 'br', 'cite', 'center',
2688                         'code', 'dd', 'del', 'details', 'div', 'dl', 'font',
2689                         'dt', 'em', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
2690                         'header', 'html', 'i', 'img', 'ins', 'kbd',
2691                         'li', 'nav', 'noscript', 'ol', 'p', 'pre', 'q', 's','small',
2692                         'source', 'span', 'strike', 'strong', 'sub', 'summary',
2693                         'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
2694                         'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video' );
2695
2696                 if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
2697
2698                 $disallowed_attributes = array('id', 'style', 'class');
2699
2700                 global $pluginhost;
2701
2702                 if (isset($pluginhost)) {
2703                         foreach ($pluginhost->get_hooks($pluginhost::HOOK_SANITIZE) as $plugin) {
2704                                 $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes);
2705                                 if (is_array($retval)) {
2706                                         $doc = $retval[0];
2707                                         $allowed_elements = $retval[1];
2708                                         $disallowed_attributes = $retval[2];
2709                                 } else {
2710                                         $doc = $retval;
2711                                 }
2712                         }
2713                 }
2714
2715                 $doc->removeChild($doc->firstChild); //remove doctype
2716                 $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
2717                 $res = $doc->saveHTML();
2718                 return $res;
2719         }
2720
2721         function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
2722                 $entries = $doc->getElementsByTagName("*");
2723
2724                 foreach ($entries as $entry) {
2725                         if (!in_array($entry->nodeName, $allowed_elements)) {
2726                                 $entry->parentNode->removeChild($entry);
2727                         }
2728
2729                         if ($entry->hasAttributes()) {
2730                                 $attrs_to_remove = array();
2731
2732                                 foreach ($entry->attributes as $attr) {
2733
2734                                         if (strpos($attr->nodeName, 'on') === 0) {
2735                                                 array_push($attrs_to_remove, $attr);
2736                                         }
2737
2738                                         if (in_array($attr->nodeName, $disallowed_attributes)) {
2739                                                 array_push($attrs_to_remove, $attr);
2740                                         }
2741                                 }
2742
2743                                 foreach ($attrs_to_remove as $attr) {
2744                                         $entry->removeAttributeNode($attr);
2745                                 }
2746                         }
2747                 }
2748
2749                 return $doc;
2750         }
2751
2752         function check_for_update($link) {
2753                 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2754                         $version_url = "http://tt-rss.org/version.php?ver=" . VERSION .
2755                                 "&iid=" . sha1(SELF_URL_PATH);
2756
2757                         $version_data = @fetch_file_contents($version_url);
2758
2759                         if ($version_data) {
2760                                 $version_data = json_decode($version_data, true);
2761                                 if ($version_data && $version_data['version']) {
2762
2763                                         if (version_compare(VERSION, $version_data['version']) == -1) {
2764                                                 return $version_data;
2765                                         }
2766                                 }
2767                         }
2768                 }
2769                 return false;
2770         }
2771
2772         function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2773
2774                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2775                 if (count($ids) == 0) return;
2776
2777                 $tmp_ids = array();
2778
2779                 foreach ($ids as $id) {
2780                         array_push($tmp_ids, "ref_id = '$id'");
2781                 }
2782
2783                 $ids_qpart = join(" OR ", $tmp_ids);
2784
2785                 if ($cmode == 0) {
2786                         db_query($link, "UPDATE ttrss_user_entries SET
2787                         unread = false,last_read = NOW()
2788                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2789                 } else if ($cmode == 1) {
2790                         db_query($link, "UPDATE ttrss_user_entries SET
2791                         unread = true
2792                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2793                 } else {
2794                         db_query($link, "UPDATE ttrss_user_entries SET
2795                         unread = NOT unread,last_read = NOW()
2796                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2797                 }
2798
2799                 /* update ccache */
2800
2801                 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2802                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2803
2804                 while ($line = db_fetch_assoc($result)) {
2805                         ccache_update($link, $line["feed_id"], $owner_uid);
2806                 }
2807         }
2808
2809         function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2810
2811                 $a_id = db_escape_string($link, $id);
2812
2813                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2814
2815                 $query = "SELECT DISTINCT tag_name,
2816                         owner_uid as owner FROM
2817                         ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2818                         ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2819
2820                 $obj_id = md5("TAGS:$owner_uid:$id");
2821                 $tags = array();
2822
2823                 /* check cache first */
2824
2825                 if ($tag_cache === false) {
2826                         $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2827                                 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2828
2829                         $tag_cache = db_fetch_result($result, 0, "tag_cache");
2830                 }
2831
2832                 if ($tag_cache) {
2833                         $tags = explode(",", $tag_cache);
2834                 } else {
2835
2836                         /* do it the hard way */
2837
2838                         $tmp_result = db_query($link, $query);
2839
2840                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
2841                                 array_push($tags, $tmp_line["tag_name"]);
2842                         }
2843
2844                         /* update the cache */
2845
2846                         $tags_str = db_escape_string($link, join(",", $tags));
2847
2848                         db_query($link, "UPDATE ttrss_user_entries
2849                                 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2850                                 AND owner_uid = $owner_uid");
2851                 }
2852
2853                 return $tags;
2854         }
2855
2856         function trim_array($array) {
2857                 $tmp = $array;
2858                 array_walk($tmp, 'trim');
2859                 return $tmp;
2860         }
2861
2862         function tag_is_valid($tag) {
2863                 if ($tag == '') return false;
2864                 if (preg_match("/^[0-9]*$/", $tag)) return false;
2865                 if (mb_strlen($tag) > 250) return false;
2866
2867                 if (function_exists('iconv')) {
2868                         $tag = iconv("utf-8", "utf-8", $tag);
2869                 }
2870
2871                 if (!$tag) return false;
2872
2873                 return true;
2874         }
2875
2876         function render_login_form($link) {
2877                 require_once "login_form.php";
2878                 exit;
2879         }
2880
2881         // from http://developer.apple.com/internet/safari/faq.html
2882         function no_cache_incantation() {
2883                 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2884                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2885                 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2886                 header("Cache-Control: post-check=0, pre-check=0", false);
2887                 header("Pragma: no-cache"); // HTTP/1.0
2888         }
2889
2890         function format_warning($msg, $id = "") {
2891                 global $link;
2892                 return "<div class=\"warning\" id=\"$id\">
2893                         <img src=\"images/sign_excl.svg\"><div class='inner'>$msg</div></div>";
2894         }
2895
2896         function format_notice($msg, $id = "") {
2897                 global $link;
2898                 return "<div class=\"notice\" id=\"$id\">
2899                         <img src=\"images/sign_info.svg\"><div class='inner'>$msg</div></div>";
2900         }
2901
2902         function format_error($msg, $id = "") {
2903                 global $link;
2904                 return "<div class=\"error\" id=\"$id\">
2905                         <img src=\"images/sign_excl.svg\"><div class='inner'>$msg</div></div>";
2906         }
2907
2908         function print_notice($msg) {
2909                 return print format_notice($msg);
2910         }
2911
2912         function print_warning($msg) {
2913                 return print format_warning($msg);
2914         }
2915
2916         function print_error($msg) {
2917                 return print format_error($msg);
2918         }
2919
2920
2921         function T_sprintf() {
2922                 $args = func_get_args();
2923                 return vsprintf(__(array_shift($args)), $args);
2924         }
2925
2926         function format_inline_player($link, $url, $ctype) {
2927
2928                 $entry = "";
2929
2930                 $url = htmlspecialchars($url);
2931
2932                 if (strpos($ctype, "audio/") === 0) {
2933
2934                         if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2935                                 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2936                                 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2937
2938                                 $id = 'AUDIO-' . uniqid();
2939
2940                                 $entry .= "<audio id=\"$id\"\" controls style='display : none'>
2941                                         <source type=\"$ctype\" src=\"$url\"></source>
2942                                         </audio>";
2943
2944                                 $entry .= "<span onclick=\"player(this)\"
2945                                         title=\"".__("Click to play")."\" status=\"0\"
2946                                         class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2947
2948                         } else {
2949
2950                                 $entry .= "<object type=\"application/x-shockwave-flash\"
2951                                         data=\"lib/button/musicplayer.swf?song_url=$url\"
2952                                         width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2953                                         <param name=\"movie\"
2954                                                 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2955                                         </object>";
2956                         }
2957
2958                         if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
2959                                 href=\"$url\">" . basename($url) . "</a>";
2960
2961                         return $entry;
2962
2963                 }
2964
2965                 return "";
2966
2967 /*              $filename = substr($url, strrpos($url, "/")+1);
2968
2969                 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2970                         $filename . " (" . $ctype . ")" . "</a>"; */
2971
2972         }
2973
2974         function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2975                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2976
2977                 $rv = array();
2978
2979                 $rv['id'] = $id;
2980
2981                 /* we can figure out feed_id from article id anyway, why do we
2982                  * pass feed_id here? let's ignore the argument :( */
2983
2984                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2985                         WHERE ref_id = '$id'");
2986
2987                 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2988
2989                 $rv['feed_id'] = $feed_id;
2990
2991                 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2992
2993                 if ($mark_as_read) {
2994                         $result = db_query($link, "UPDATE ttrss_user_entries
2995                                 SET unread = false,last_read = NOW()
2996                                 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2997
2998                         ccache_update($link, $feed_id, $owner_uid);
2999                 }
3000
3001                 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
3002                         ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3003                         (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3004                         (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) as hide_images,
3005                         num_comments,
3006                         tag_cache,
3007                         author,
3008                         orig_feed_id,
3009                         note,
3010                         cached_content
3011                         FROM ttrss_entries,ttrss_user_entries
3012                         WHERE   id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3013
3014                 if ($result) {
3015
3016                         $line = db_fetch_assoc($result);
3017
3018                         $tag_cache = $line["tag_cache"];
3019
3020                         $line["tags"] = get_article_tags($link, $id, $owner_uid, $line["tag_cache"]);
3021                         unset($line["tag_cache"]);
3022
3023                         $line["content"] = sanitize($link, $line["content"], false, $owner_uid, $line["site_url"]);
3024
3025                         global $pluginhost;
3026
3027                         foreach ($pluginhost->get_hooks($pluginhost::HOOK_RENDER_ARTICLE) as $p) {
3028                                 $line = $p->hook_render_article($line);
3029                         }
3030
3031                         $num_comments = $line["num_comments"];
3032                         $entry_comments = "";
3033
3034                         if ($num_comments > 0) {
3035                                 if ($line["comments"]) {
3036                                         $comments_url = htmlspecialchars($line["comments"]);
3037                                 } else {
3038                                         $comments_url = htmlspecialchars($line["link"]);
3039                                 }
3040                                 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3041                         } else {
3042                                 if ($line["comments"] && $line["link"] != $line["comments"]) {
3043                                         $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
3044                                 }
3045                         }
3046
3047                         if ($zoom_mode) {
3048                                 header("Content-Type: text/html");
3049                                 $rv['content'] .= "<html><head>
3050                                                 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3051                                                 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3052                                                 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3053                                         </head><body id=\"ttrssZoom\">";
3054                         }
3055
3056                         $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3057
3058                         $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
3059
3060                         $entry_author = $line["author"];
3061
3062                         if ($entry_author) {
3063                                 $entry_author = __(" - ") . $entry_author;
3064                         }
3065
3066                         $parsed_updated = make_local_datetime($link, $line["updated"], true,
3067                                 $owner_uid, true);
3068
3069                         $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
3070
3071                         if ($line["link"]) {
3072                                 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3073                                         title=\"".htmlspecialchars($line['title'])."\"
3074                                         href=\"" .
3075                                         htmlspecialchars($line["link"]) . "\">" .
3076                                         $line["title"] . "</a>" .
3077                                         "<span class='author'>$entry_author</span></div>";
3078                         } else {
3079                                 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3080                         }
3081
3082                         $tags_str = format_tags_string($line["tags"], $id);
3083                         $tags_str_full = join(", ", $line["tags"]);
3084
3085                         if (!$tags_str_full) $tags_str_full = __("no tags");
3086
3087                         if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3088
3089                         $rv['content'] .= "<div class='postTags' style='float : right'>
3090                                 <img src='images/tag.png'
3091                                 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
3092
3093                         if (!$zoom_mode) {
3094                                 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3095                                         <a title=\"".__('Edit tags for this article')."\"
3096                                         href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3097
3098                                 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3099                                         id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3100                                         position=\"below\">$tags_str_full</div>";
3101
3102                                 global $pluginhost;
3103
3104                                 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
3105                                         $rv['content'] .= $p->hook_article_button($line);
3106                                 }
3107
3108
3109                         } else {
3110                                 $tags_str = strip_tags($tags_str);
3111                                 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3112                         }
3113                         $rv['content'] .= "</div>";
3114                         $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3115
3116                         if ($line["orig_feed_id"]) {
3117
3118                                 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3119                                         WHERE id = ".$line["orig_feed_id"]);
3120
3121                                 if (db_num_rows($tmp_result) != 0) {
3122
3123                                         $rv['content'] .= "<div clear='both'>";
3124                                         $rv['content'] .= __("Originally from:");
3125
3126                                         $rv['content'] .= "&nbsp;";
3127
3128                                         $tmp_line = db_fetch_assoc($tmp_result);
3129
3130                                         $rv['content'] .= "<a target='_blank'
3131                                                 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3132                                                 $tmp_line['title'] . "</a>";
3133
3134                                         $rv['content'] .= "&nbsp;";
3135
3136                                         $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3137                                         $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
3138
3139                                         $rv['content'] .= "</div>";
3140                                 }
3141                         }
3142
3143                         $rv['content'] .= "</div>";
3144
3145                         $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3146                                 if ($line['note']) {
3147                                         $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
3148                                 }
3149                         $rv['content'] .= "</div>";
3150
3151                         $rv['content'] .= "<div class=\"postContent\">";
3152
3153                         $rv['content'] .= $line["content"];
3154
3155                         $rv['content'] .= format_article_enclosures($link, $id,
3156                                 $always_display_enclosures, $line["content"], $line["hide_images"]);
3157
3158                         $rv['content'] .= "</div>";
3159
3160                         $rv['content'] .= "</div>";
3161
3162                 }
3163
3164                 if ($zoom_mode) {
3165                         $rv['content'] .= "
3166                                 <div class='footer'>
3167                                 <button onclick=\"return window.close()\">".
3168                                         __("Close this window")."</button></div>";
3169                         $rv['content'] .= "</body></html>";
3170                 }
3171
3172                 return $rv;
3173
3174         }
3175
3176         function print_checkpoint($n, $s) {
3177                 $ts = microtime(true);
3178                 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3179                 return $ts;
3180         }
3181
3182         function sanitize_tag($tag) {
3183                 $tag = trim($tag);
3184
3185                 $tag = mb_strtolower($tag, 'utf-8');
3186
3187                 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3188
3189 //              $tag = str_replace('"', "", $tag);
3190 //              $tag = str_replace("+", " ", $tag);
3191                 $tag = str_replace("technorati tag: ", "", $tag);
3192
3193                 return $tag;
3194         }
3195
3196         function get_self_url_prefix() {
3197                 if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
3198                         return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
3199                 } else {
3200                         return SELF_URL_PATH;
3201                 }
3202         }
3203
3204         /**
3205          * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3206          *
3207          * @return string The Mozilla Firefox feed adding URL.
3208          */
3209         function add_feed_url() {
3210                 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' :  'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3211
3212                 $url_path = get_self_url_prefix() .
3213                         "/public.php?op=subscribe&feed_url=%s";
3214                 return $url_path;
3215         } // function add_feed_url
3216
3217         function encrypt_password($pass, $salt = '', $mode2 = false) {
3218                 if ($salt && $mode2) {
3219                         return "MODE2:" . hash('sha256', $salt . $pass);
3220                 } else if ($salt) {
3221                         return "SHA1X:" . sha1("$salt:$pass");
3222                 } else {
3223                         return "SHA1:" . sha1($pass);
3224                 }
3225         } // function encrypt_password
3226
3227         function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3228                 $filters = array();
3229
3230                 $cat_id = (int)getFeedCategory($link, $feed_id);
3231
3232                 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3233                         owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
3234
3235                 $check_cats = join(",", array_merge(
3236                         getParentCategories($link, $cat_id, $owner_uid),
3237                         array($cat_id)));
3238
3239                 while ($line = db_fetch_assoc($result)) {
3240                         $filter_id = $line["id"];
3241
3242                         $result2 = db_query($link, "SELECT
3243                                 r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3244                                 FROM ttrss_filters2_rules AS r,
3245                                 ttrss_filter_types AS t
3246                                 WHERE
3247                                         (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3248                                         (feed_id IS NULL OR feed_id = '$feed_id') AND
3249                                         filter_type = t.id AND filter_id = '$filter_id'");
3250
3251                         $rules = array();
3252                         $actions = array();
3253
3254                         while ($rule_line = db_fetch_assoc($result2)) {
3255 #                               print_r($rule_line);
3256
3257                                 $rule = array();
3258                                 $rule["reg_exp"] = $rule_line["reg_exp"];
3259                                 $rule["type"] = $rule_line["type_name"];
3260                                 $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
3261
3262                                 array_push($rules, $rule);
3263                         }
3264
3265                         $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3266                                 FROM ttrss_filters2_actions AS a,
3267                                 ttrss_filter_actions AS t
3268                                 WHERE
3269                                         action_id = t.id AND filter_id = '$filter_id'");
3270
3271                         while ($action_line = db_fetch_assoc($result2)) {
3272 #                               print_r($action_line);
3273
3274                                 $action = array();
3275                                 $action["type"] = $action_line["type_name"];
3276                                 $action["param"] = $action_line["action_param"];
3277
3278                                 array_push($actions, $action);
3279                         }
3280
3281
3282                         $filter = array();
3283                         $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3284                         $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3285                         $filter["rules"] = $rules;
3286                         $filter["actions"] = $actions;
3287
3288                         if (count($rules) > 0 && count($actions) > 0) {
3289                                 array_push($filters, $filter);
3290                         }
3291                 }
3292
3293                 return $filters;
3294         }
3295
3296         function get_score_pic($score) {
3297                 if ($score > 100) {
3298                         return "score_high.png";
3299                 } else if ($score > 0) {
3300                         return "score_half_high.png";
3301                 } else if ($score < -100) {
3302                         return "score_low.png";
3303                 } else if ($score < 0) {
3304                         return "score_half_low.png";
3305                 } else {
3306                         return "score_neutral.png";
3307                 }
3308         }
3309
3310         function feed_has_icon($id) {
3311                 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3312         }
3313
3314         function init_connection($link) {
3315                 if ($link) {
3316
3317                         if (DB_TYPE == "pgsql") {
3318                                 pg_query($link, "set client_encoding = 'UTF-8'");
3319                                 pg_set_client_encoding("UNICODE");
3320                                 pg_query($link, "set datestyle = 'ISO, european'");
3321                                 pg_query($link, "set TIME ZONE 0");
3322                         } else {
3323                                 db_query($link, "SET time_zone = '+0:0'");
3324
3325                                 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
3326                                         db_query($link, "SET NAMES " . MYSQL_CHARSET);
3327                                 }
3328                         }
3329
3330                         global $pluginhost;
3331
3332                         $pluginhost = new PluginHost($link);
3333                         $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
3334
3335                         return true;
3336                 } else {
3337                         print "Unable to connect to database:" . db_last_error();
3338                         return false;
3339                 }
3340         }
3341
3342         function format_tags_string($tags, $id) {
3343
3344                 $tags_str = "";
3345                 $tags_nolinks_str = "";
3346
3347                 $num_tags = 0;
3348
3349                 $tag_limit = 6;
3350
3351                 $formatted_tags = array();
3352
3353                 foreach ($tags as $tag) {
3354                         $num_tags++;
3355                         $tag_escaped = str_replace("'", "\\'", $tag);
3356
3357                         if (mb_strlen($tag) > 30) {
3358                                 $tag = truncate_string($tag, 30);
3359                         }
3360
3361                         $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3362
3363                         array_push($formatted_tags, $tag_str);
3364
3365                         $tmp_tags_str = implode(", ", $formatted_tags);
3366
3367                         if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
3368                                 break;
3369                         }
3370                 }
3371
3372                 $tags_str = implode(", ", $formatted_tags);
3373
3374                 if ($num_tags < count($tags)) {
3375                         $tags_str .= ", &hellip;";
3376                 }
3377
3378                 if ($num_tags == 0) {
3379                         $tags_str = __("no tags");
3380                 }
3381
3382                 return $tags_str;
3383
3384         }
3385
3386         function format_article_labels($labels, $id) {
3387
3388                 $labels_str = "";
3389
3390                 foreach ($labels as $l) {
3391                         $labels_str .= sprintf("<span class='hlLabelRef'
3392                                 style='color : %s; background-color : %s'>%s</span>",
3393                                         $l[2], $l[3], $l[1]);
3394                         }
3395
3396                 return $labels_str;
3397
3398         }
3399
3400         function format_article_note($id, $note, $allow_edit = true) {
3401
3402                 $str = "<div class='articleNote'        onclick=\"editArticleNote($id)\">
3403                         <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3404                         ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
3405
3406                 return $str;
3407         }
3408
3409
3410         function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3411                 if ($parent_cat_id) {
3412                         $parent_qpart = "parent_cat = '$parent_cat_id'";
3413                         $parent_insert = "'$parent_cat_id'";
3414                 } else {
3415                         $parent_qpart = "parent_cat IS NULL";
3416                         $parent_insert = "NULL";
3417                 }
3418
3419                 $result = db_query($link,
3420                         "SELECT id FROM ttrss_feed_categories
3421                         WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3422
3423                 if (db_num_rows($result) == 0) {
3424                         return false;
3425                 } else {
3426                         return db_fetch_result($result, 0, "id");
3427                 }
3428         }
3429
3430         function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3431
3432                 if (!$feed_cat) return false;
3433
3434                 db_query($link, "BEGIN");
3435
3436                 if ($parent_cat_id) {
3437                         $parent_qpart = "parent_cat = '$parent_cat_id'";
3438                         $parent_insert = "'$parent_cat_id'";
3439                 } else {
3440                         $parent_qpart = "parent_cat IS NULL";
3441                         $parent_insert = "NULL";
3442                 }
3443
3444                 $feed_cat = mb_substr($feed_cat, 0, 250);
3445
3446                 $result = db_query($link,
3447                         "SELECT id FROM ttrss_feed_categories
3448                         WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3449
3450                 if (db_num_rows($result) == 0) {
3451
3452                         $result = db_query($link,
3453                                 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3454                                 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3455
3456                         db_query($link, "COMMIT");
3457
3458                         return true;
3459                 }
3460
3461                 return false;
3462         }
3463
3464         function getArticleFeed($link, $id) {
3465                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3466                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3467
3468                 if (db_num_rows($result) != 0) {
3469                         return db_fetch_result($result, 0, "feed_id");
3470                 } else {
3471                         return 0;
3472                 }
3473         }
3474
3475         /**
3476          * Fixes incomplete URLs by prepending "http://".
3477          * Also replaces feed:// with http://, and
3478          * prepends a trailing slash if the url is a domain name only.
3479          *
3480          * @param string $url Possibly incomplete URL
3481          *
3482          * @return string Fixed URL.
3483          */
3484         function fix_url($url) {
3485                 if (strpos($url, '://') === false) {
3486                         $url = 'http://' . $url;
3487                 } else if (substr($url, 0, 5) == 'feed:') {
3488                         $url = 'http:' . substr($url, 5);
3489                 }
3490
3491                 //prepend slash if the URL has no slash in it
3492                 // "http://www.example" -> "http://www.example/"
3493                 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
3494                         $url .= '/';
3495                 }
3496
3497                 if ($url != "http:///")
3498                         return $url;
3499                 else
3500                         return '';
3501         }
3502
3503         function validate_feed_url($url) {
3504                 $parts = parse_url($url);
3505
3506                 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
3507
3508         }
3509
3510         function get_article_enclosures($link, $id) {
3511
3512                 $query = "SELECT * FROM ttrss_enclosures
3513                         WHERE post_id = '$id' AND content_url != ''";
3514
3515                 $rv = array();
3516
3517                 $result = db_query($link, $query);
3518
3519                 if (db_num_rows($result) > 0) {
3520                         while ($line = db_fetch_assoc($result)) {
3521                                 array_push($rv, $line);
3522                         }
3523                 }
3524
3525                 return $rv;
3526         }
3527
3528         function save_email_address($link, $email) {
3529                 // FIXME: implement persistent storage of emails
3530
3531                 if (!$_SESSION['stored_emails'])
3532                         $_SESSION['stored_emails'] = array();
3533
3534                 if (!in_array($email, $_SESSION['stored_emails']))
3535                         array_push($_SESSION['stored_emails'], $email);
3536         }
3537
3538
3539         function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
3540
3541                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3542
3543                 $sql_is_cat = bool_to_sql_bool($is_cat);
3544
3545                 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
3546                         WHERE feed_id = '$feed_id'      AND is_cat = $sql_is_cat
3547                         AND owner_uid = " . $owner_uid);
3548
3549                 if (db_num_rows($result) == 1) {
3550                         return db_fetch_result($result, 0, "access_key");
3551                 } else {
3552                         $key = db_escape_string($link, sha1(uniqid(rand(), true)));
3553
3554                         $result = db_query($link, "INSERT INTO ttrss_access_keys
3555                                 (access_key, feed_id, is_cat, owner_uid)
3556                                 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
3557
3558                         return $key;
3559                 }
3560                 return false;
3561         }
3562
3563         function get_feeds_from_html($url, $content)
3564         {
3565                 $url     = fix_url($url);
3566                 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
3567
3568                 libxml_use_internal_errors(true);
3569
3570                 $doc = new DOMDocument();
3571                 $doc->loadHTML($content);
3572                 $xpath = new DOMXPath($doc);
3573                 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
3574                 $feedUrls = array();
3575                 foreach ($entries as $entry) {
3576                         if ($entry->hasAttribute('href')) {
3577                                 $title = $entry->getAttribute('title');
3578                                 if ($title == '') {
3579                                         $title = $entry->getAttribute('type');
3580                                 }
3581                                 $feedUrl = rewrite_relative_url(
3582                                         $baseUrl, $entry->getAttribute('href')
3583                                 );
3584                                 $feedUrls[$feedUrl] = $title;
3585                         }
3586                 }
3587                 return $feedUrls;
3588         }
3589
3590         function is_html($content) {
3591                 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
3592         }
3593
3594         function url_is_html($url, $login = false, $pass = false) {
3595                 return is_html(fetch_file_contents($url, false, $login, $pass));
3596         }
3597
3598         function print_label_select($link, $name, $value, $attributes = "") {
3599
3600                 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3601                         WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3602
3603                 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
3604                         "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
3605
3606                 while ($line = db_fetch_assoc($result)) {
3607
3608                         $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
3609
3610                         print "<option value=\"".htmlspecialchars($line["caption"])."\"
3611                                 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
3612
3613                 }
3614
3615 #               print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
3616
3617                 print "</select>";
3618
3619
3620         }
3621
3622         function format_article_enclosures($link, $id, $always_display_enclosures,
3623                                         $article_content, $hide_images = false) {
3624
3625                 $result = get_article_enclosures($link, $id);
3626                 $rv = '';
3627
3628                 if (count($result) > 0) {
3629
3630                         $entries_html = array();
3631                         $entries = array();
3632                         $entries_inline = array();
3633
3634                         foreach ($result as $line) {
3635
3636                                 $url = $line["content_url"];
3637                                 $ctype = $line["content_type"];
3638
3639                                 if (!$ctype) $ctype = __("unknown type");
3640
3641                                 $filename = substr($url, strrpos($url, "/")+1);
3642
3643                                 $player = format_inline_player($link, $url, $ctype);
3644
3645                                 if ($player) array_push($entries_inline, $player);
3646
3647 #                               $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3648 #                                       $filename . " (" . $ctype . ")" . "</a>";
3649
3650                                 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
3651                                         dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
3652
3653                                 array_push($entries_html, $entry);
3654
3655                                 $entry = array();
3656
3657                                 $entry["type"] = $ctype;
3658                                 $entry["filename"] = $filename;
3659                                 $entry["url"] = $url;
3660
3661                                 array_push($entries, $entry);
3662                         }
3663
3664                         if ($_SESSION['uid'] && !get_pref($link, "STRIP_IMAGES") && !$_SESSION["bw_limit"]) {
3665                                 if ($always_display_enclosures ||
3666                                                         !preg_match("/<img/i", $article_content)) {
3667
3668                                         foreach ($entries as $entry) {
3669
3670                                                 if (preg_match("/image/", $entry["type"]) ||
3671                                                                 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
3672
3673                                                                 if (!$hide_images) {
3674                                                                         $rv .= "<p><img
3675                                                                         alt=\"".htmlspecialchars($entry["filename"])."\"
3676                                                                         src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
3677                                                                 } else {
3678                                                                         $rv .= "<p><a target=\"_blank\"
3679                                                                         href=\"".htmlspecialchars($entry["url"])."\"
3680                                                                         >" .htmlspecialchars($entry["url"]) . "</a></p>";
3681
3682                                                                 }
3683                                                 }
3684                                         }
3685                                 }
3686                         }
3687
3688                         if (count($entries_inline) > 0) {
3689                                 $rv .= "<hr clear='both'/>";
3690                                 foreach ($entries_inline as $entry) { $rv .= $entry; };
3691                                 $rv .= "<hr clear='both'/>";
3692                         }
3693
3694                         $rv .= "<select class=\"attachments\" onchange=\"openSelectedAttachment(this)\">".
3695                                 "<option value=''>" . __('Attachments')."</option>";
3696
3697                         foreach ($entries as $entry) {
3698                                 $rv .= "<option value=\"".htmlspecialchars($entry["url"])."\">" . htmlspecialchars($entry["filename"]) . "</option>";
3699
3700                         };
3701
3702                         $rv .= "</select>";
3703                 }
3704
3705                 return $rv;
3706         }
3707
3708         function getLastArticleId($link) {
3709                 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
3710                         WHERE owner_uid = " . $_SESSION["uid"]);
3711
3712                 if (db_num_rows($result) == 1) {
3713                         return db_fetch_result($result, 0, "id");
3714                 } else {
3715                         return -1;
3716                 }
3717         }
3718
3719         function build_url($parts) {
3720                 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
3721         }
3722
3723         /**
3724          * Converts a (possibly) relative URL to a absolute one.
3725          *
3726          * @param string $url     Base URL (i.e. from where the document is)
3727          * @param string $rel_url Possibly relative URL in the document
3728          *
3729          * @return string Absolute URL
3730          */
3731         function rewrite_relative_url($url, $rel_url) {
3732                 if (strpos($rel_url, "magnet:") === 0) {
3733                         return $rel_url;
3734                 } else if (strpos($rel_url, "://") !== false) {
3735                         return $rel_url;
3736                 } else if (strpos($rel_url, "//") === 0) {
3737                         # protocol-relative URL (rare but they exist)
3738                         return $rel_url;
3739                 } else if (strpos($rel_url, "/") === 0)
3740                 {
3741                         $parts = parse_url($url);
3742                         $parts['path'] = $rel_url;
3743
3744                         return build_url($parts);
3745
3746                 } else {
3747                         $parts = parse_url($url);
3748                         if (!isset($parts['path'])) {
3749                                 $parts['path'] = '/';
3750                         }
3751                         $dir = $parts['path'];
3752                         if (substr($dir, -1) !== '/') {
3753                                 $dir = dirname($parts['path']);
3754                                 $dir !== '/' && $dir .= '/';
3755                         }
3756                         $parts['path'] = $dir . $rel_url;
3757
3758                         return build_url($parts);
3759                 }
3760         }
3761
3762         function sphinx_search($query, $offset = 0, $limit = 30) {
3763                 require_once 'lib/sphinxapi.php';
3764
3765                 $sphinxClient = new SphinxClient();
3766
3767                 $sphinxClient->SetServer('localhost', 9312);
3768                 $sphinxClient->SetConnectTimeout(1);
3769
3770                 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
3771                         'feed_title' => 20));
3772
3773                 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
3774                 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
3775                 $sphinxClient->SetLimits($offset, $limit, 1000);
3776                 $sphinxClient->SetArrayResult(false);
3777                 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
3778
3779                 $result = $sphinxClient->Query($query, SPHINX_INDEX);
3780
3781                 $ids = array();
3782
3783                 if (is_array($result['matches'])) {
3784                         foreach (array_keys($result['matches']) as $int_id) {
3785                                 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
3786                                 array_push($ids, $ref_id);
3787                         }
3788                 }
3789
3790                 return $ids;
3791         }
3792
3793         function cleanup_tags($link, $days = 14, $limit = 1000) {
3794
3795                 if (DB_TYPE == "pgsql") {
3796                         $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
3797                 } else if (DB_TYPE == "mysql") {
3798                         $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
3799                 }
3800
3801                 $tags_deleted = 0;
3802
3803                 while ($limit > 0) {
3804                         $limit_part = 500;
3805
3806                         $query = "SELECT ttrss_tags.id AS id
3807                                 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
3808                                 WHERE post_int_id = int_id AND $interval_query AND
3809                                 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
3810
3811                         $result = db_query($link, $query);
3812
3813                         $ids = array();
3814
3815                         while ($line = db_fetch_assoc($result)) {
3816                                 array_push($ids, $line['id']);
3817                         }
3818
3819                         if (count($ids) > 0) {
3820                                 $ids = join(",", $ids);
3821
3822                                 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
3823                                 $tags_deleted += db_affected_rows($link, $tmp_result);
3824                         } else {
3825                                 break;
3826                         }
3827
3828                         $limit -= $limit_part;
3829                 }
3830
3831                 return $tags_deleted;
3832         }
3833
3834         function print_user_stylesheet($link) {
3835                 $value = get_pref($link, 'USER_STYLESHEET');
3836
3837                 if ($value) {
3838                         print "<style type=\"text/css\">";
3839                         print str_replace("<br/>", "\n", $value);
3840                         print "</style>";
3841                 }
3842
3843         }
3844
3845         function rewrite_urls($html) {
3846                 libxml_use_internal_errors(true);
3847
3848                 $charset_hack = '<head>
3849                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3850                 </head>';
3851
3852                 $doc = new DOMDocument();
3853                 $doc->loadHTML($charset_hack . $html);
3854                 $xpath = new DOMXPath($doc);
3855
3856                 $entries = $xpath->query('//*/text()');
3857
3858                 foreach ($entries as $entry) {
3859                         if (strstr($entry->wholeText, "://") !== false) {
3860                                 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
3861                                         "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
3862
3863                                 if ($text != $entry->wholeText) {
3864                                         $cdoc = new DOMDocument();
3865                                         $cdoc->loadHTML($charset_hack . $text);
3866
3867
3868                                         foreach ($cdoc->childNodes as $cnode) {
3869                                                 $cnode = $doc->importNode($cnode, true);
3870
3871                                                 if ($cnode) {
3872                                                         $entry->parentNode->insertBefore($cnode);
3873                                                 }
3874                                         }
3875
3876                                         $entry->parentNode->removeChild($entry);
3877
3878                                 }
3879                         }
3880                 }
3881
3882                 $node = $doc->getElementsByTagName('body')->item(0);
3883
3884                 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
3885                 if ($node)
3886                         return $doc->saveXML($node);
3887                 else
3888                         return $html;
3889         }
3890
3891         function filter_to_sql($link, $filter, $owner_uid) {
3892                 $query = array();
3893
3894                 if (DB_TYPE == "pgsql")
3895                         $reg_qpart = "~";
3896                 else
3897                         $reg_qpart = "REGEXP";
3898
3899                 foreach ($filter["rules"] AS $rule) {
3900                         $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
3901                                 $rule['reg_exp']) !== FALSE;
3902
3903                         if ($regexp_valid) {
3904
3905                                 $rule['reg_exp'] = db_escape_string($link, $rule['reg_exp']);
3906
3907                                         switch ($rule["type"]) {
3908                                         case "title":
3909                                                 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3910                                                         $rule['reg_exp'] . "')";
3911                                                 break;
3912                                         case "content":
3913                                                 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
3914                                                         $rule['reg_exp'] . "')";
3915                                                 break;
3916                                         case "both":
3917                                                 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3918                                                         $rule['reg_exp'] . "') OR LOWER(" .
3919                                                         "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
3920                                                 break;
3921                                         case "tag":
3922                                                 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
3923                                                         $rule['reg_exp'] . "')";
3924                                                 break;
3925                                         case "link":
3926                                                 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
3927                                                         $rule['reg_exp'] . "')";
3928                                                 break;
3929                                         case "author":
3930                                                 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
3931                                                         $rule['reg_exp'] . "')";
3932                                                 break;
3933                                 }
3934
3935                                 if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
3936
3937                                 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
3938                                         $qpart .= " AND feed_id = " . db_escape_string($link, $rule["feed_id"]);
3939                                 }
3940
3941                                 if (isset($rule["cat_id"])) {
3942
3943                                         if ($rule["cat_id"] > 0) {
3944                                                 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
3945                                                 array_push($children, $rule["cat_id"]);
3946
3947                                                 $children = join(",", $children);
3948
3949                                                 $cat_qpart = "cat_id IN ($children)";
3950                                         } else {
3951                                                 $cat_qpart = "cat_id IS NULL";
3952                                         }
3953
3954                                         $qpart .= " AND $cat_qpart";
3955                                 }
3956
3957                                 array_push($query, "($qpart)");
3958
3959                         }
3960                 }
3961
3962                 if (count($query) > 0) {
3963                         $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
3964                 } else {
3965                         $fullquery = "(false)";
3966                 }
3967
3968                 if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
3969
3970                 return $fullquery;
3971         }
3972
3973         if (!function_exists('gzdecode')) {
3974                 function gzdecode($string) { // no support for 2nd argument
3975                         return file_get_contents('compress.zlib://data:who/cares;base64,'.
3976                                 base64_encode($string));
3977                 }
3978         }
3979
3980         function get_random_bytes($length) {
3981                 if (function_exists('openssl_random_pseudo_bytes')) {
3982                         return openssl_random_pseudo_bytes($length);
3983                 } else {
3984                         $output = "";
3985
3986                         for ($i = 0; $i < $length; $i++)
3987                                 $output .= chr(mt_rand(0, 255));
3988
3989                         return $output;
3990                 }
3991         }
3992
3993         function read_stdin() {
3994                 $fp = fopen("php://stdin", "r");
3995
3996                 if ($fp) {
3997                         $line = trim(fgets($fp));
3998                         fclose($fp);
3999                         return $line;
4000                 }
4001
4002                 return null;
4003         }
4004
4005         function tmpdirname($path, $prefix) {
4006                 // Use PHP's tmpfile function to create a temporary
4007                 // directory name. Delete the file and keep the name.
4008                 $tempname = tempnam($path,$prefix);
4009                 if (!$tempname)
4010                         return false;
4011
4012                 if (!unlink($tempname))
4013                         return false;
4014
4015        return $tempname;
4016         }
4017
4018         function getFeedCategory($link, $feed) {
4019                 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
4020                         WHERE id = '$feed'");
4021
4022                 if (db_num_rows($result) > 0) {
4023                         return db_fetch_result($result, 0, "cat_id");
4024                 } else {
4025                         return false;
4026                 }
4027
4028         }
4029
4030         function implements_interface($class, $interface) {
4031                 return in_array($interface, class_implements($class));
4032         }
4033
4034         function geturl($url){
4035
4036                 (function_exists('curl_init')) ? '' : die('cURL Must be installed for geturl function to work. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini');
4037
4038                 $curl = curl_init();
4039                 $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
4040                 $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
4041                 $header[] = "Cache-Control: max-age=0";
4042                 $header[] = "Connection: keep-alive";
4043                 $header[] = "Keep-Alive: 300";
4044                 $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
4045                 $header[] = "Accept-Language: en-us,en;q=0.5";
4046                 $header[] = "Pragma: ";
4047
4048                 curl_setopt($curl, CURLOPT_URL, $url);
4049                 curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0');
4050                 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
4051                 curl_setopt($curl, CURLOPT_HEADER, true);
4052                 curl_setopt($curl, CURLOPT_REFERER, $url);
4053                 curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
4054                 curl_setopt($curl, CURLOPT_AUTOREFERER, true);
4055                 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
4056                 //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //CURLOPT_FOLLOWLOCATION Disabled...
4057                 curl_setopt($curl, CURLOPT_TIMEOUT, 60);
4058
4059                 $html = curl_exec($curl);
4060
4061                 $status = curl_getinfo($curl);
4062                 curl_close($curl);
4063
4064                 if($status['http_code']!=200){
4065                         if($status['http_code'] == 301 || $status['http_code'] == 302) {
4066                                 list($header) = explode("\r\n\r\n", $html, 2);
4067                                 $matches = array();
4068                                 preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
4069                                 $url = trim(str_replace($matches[1],"",$matches[0]));
4070                                 $url_parsed = parse_url($url);
4071                                 return (isset($url_parsed))? geturl($url, $referer):'';
4072                         }
4073                         $oline='';
4074                         foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';}
4075                         $line =$oline." \r\n ".$url."\r\n-----------------\r\n";
4076 #                       $handle = @fopen('./curl.error.log', 'a');
4077 #                       fwrite($handle, $line);
4078                         return FALSE;
4079                 }
4080                 return $url;
4081         }
4082
4083         function get_minified_js($files) {
4084                 require_once 'lib/jshrink/Minifier.php';
4085
4086                 $rv = '';
4087
4088                 foreach ($files as $js) {
4089                         if (!isset($_GET['debug'])) {
4090                                 $cached_file = CACHE_DIR . "/js/$js.js";
4091
4092                                 if (file_exists($cached_file) &&
4093                                                 is_readable($cached_file) &&
4094                                                 filemtime($cached_file) >= filemtime("js/$js.js")) {
4095
4096                                         $rv .= file_get_contents($cached_file);
4097
4098                                 } else {
4099                                         $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
4100                                         file_put_contents($cached_file, $minified);
4101                                         $rv .= $minified;
4102                                 }
4103                         } else {
4104                                 $rv .= file_get_contents("js/$js.js");
4105                         }
4106                 }
4107
4108                 return $rv;
4109         }
4110
4111         function stylesheet_tag($filename) {
4112                 $timestamp = filemtime($filename);
4113
4114                 echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
4115         }
4116
4117         function javascript_tag($filename) {
4118                 $query = "";
4119
4120                 if (!(strpos($filename, "?") === FALSE)) {
4121                         $query = substr($filename, strpos($filename, "?")+1);
4122                         $filename = substr($filename, 0, strpos($filename, "?"));
4123                 }
4124
4125                 $timestamp = filemtime($filename);
4126
4127                 if ($query) $timestamp .= "&$query";
4128
4129                 echo "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
4130         }
4131
4132         function calculate_dep_timestamp() {
4133                 $files = array_merge(glob("js/*.js"), glob("*.css"));
4134
4135                 $max_ts = -1;
4136
4137                 foreach ($files as $file) {
4138                         if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
4139                 }
4140
4141                 return $max_ts;
4142         }
4143
4144         function T_js_decl($s1, $s2) {
4145                 if ($s1 && $s2) {
4146                         $s1 = preg_replace("/\n/", "", $s1);
4147                         $s2 = preg_replace("/\n/", "", $s2);
4148
4149                         $s1 = preg_replace("/\"/", "\\\"", $s1);
4150                         $s2 = preg_replace("/\"/", "\\\"", $s2);
4151
4152                         return "T_messages[\"$s1\"] = \"$s2\";\n";
4153                 }
4154         }
4155
4156         function init_js_translations() {
4157
4158         print 'var T_messages = new Object();
4159
4160                 function __(msg) {
4161                         if (T_messages[msg]) {
4162                                 return T_messages[msg];
4163                         } else {
4164                                 return msg;
4165                         }
4166                 }
4167
4168                 function ngettext(msg1, msg2, n) {
4169                         return (parseInt(n) > 1) ? msg2 : msg1;
4170                 }';
4171
4172                 $l10n = _get_reader();
4173
4174                 for ($i = 0; $i < $l10n->total; $i++) {
4175                         $orig = $l10n->get_original_string($i);
4176                         $translation = __($orig);
4177
4178                         print T_js_decl($orig, $translation);
4179                 }
4180         }
4181
4182         function label_to_feed_id($label) {
4183                 return LABEL_BASE_INDEX - 1 - abs($label);
4184         }
4185
4186         function feed_to_label_id($feed) {
4187                 return LABEL_BASE_INDEX - 1 + abs($feed);
4188         }
4189
4190 ?>