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