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