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