]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
subtoolbar: only show mail action if plugin is enabled
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
6e658547 2 define('EXPECTED_CONFIG_VERSION', 26);
a6b45187 3 define('SCHEMA_VERSION', 102);
545ca067 4
23d2471c 5 $fetch_last_error = false;
19b3992b 6 $pluginhost = false;
23d2471c 7
0d421af8 8 function __autoload($class) {
369dbc19
AD
9 $class_file = str_replace("_", "/", strtolower(basename($class)));
10
11 $file = dirname(__FILE__)."/../classes/$class_file.php";
12
0d421af8
AD
13 if (file_exists($file)) {
14 require $file;
15 }
cc85704f 16
0d421af8
AD
17 }
18
d68629dc 19 mb_internal_encoding("UTF-8");
324944f3 20 date_default_timezone_set('UTC');
8a7f5767
CW
21 if (defined('E_DEPRECATED')) {
22 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
23 } else {
24 error_reporting(E_ALL & ~E_NOTICE);
25 }
cce28758 26
40d13c28 27 require_once 'config.php';
cc17c205 28
fc2b26a6
AD
29 if (DB_TYPE == "pgsql") {
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
31 } else {
32 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
33 }
34
0c425dc7
AD
35 define('THEME_VERSION_REQUIRED', 1.1);
36
9632f884
AD
37 /**
38 * Return available translations names.
8d505d78 39 *
9632f884
AD
40 * @access public
41 * @return array A array of available translations.
42 */
f8c612d4 43 function get_translations() {
6a214f92 44 $tr = array(
8d505d78 45 "auto" => "Detect automatically",
a3162add 46 "ca_CA" => "Català",
6a214f92 47 "en_US" => "English",
36d0510c 48 "es_ES" => "Español",
a927fe7b 49 "de_DE" => "Deutsch",
6a214f92 50 "fr_FR" => "Français",
e78fd196 51 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 52 "it_IT" => "Italiano",
1d004f12 53 "ja_JP" => "日本語 (Japanese)",
592535d7 54 "nb_NO" => "Norwegian bokmål",
ea45791a 55 "pl_PL" => "Polski",
6a214f92 56 "ru_RU" => "Русский",
9a063469 57 "pt_BR" => "Portuguese/Brazil",
6a214f92 58 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
59
60 return $tr;
61 }
62
7b26a148
AD
63 require_once "lib/accept-to-gettext.php";
64 require_once "lib/gettext/gettext.inc";
aba609e0 65
87d7e850 66
7b26a148 67 function startup_gettext() {
8d505d78 68
7b26a148
AD
69 # Get locale from Accept-Language header
70 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 71
7b26a148
AD
72 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
73 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
74 }
89cb787e 75
7b26a148
AD
76 /* In login action of mobile version */
77 if ($_POST["language"] && defined('MOBILE_VERSION')) {
78 $lang = $_POST["language"];
afc3cf55
AD
79 } else {
80 $lang = $_SESSION["language"];
7b26a148 81 }
7c33dbd4 82
7b26a148
AD
83 if ($lang) {
84 if (defined('LC_MESSAGES')) {
85 _setlocale(LC_MESSAGES, $lang);
86 } else if (defined('LC_ALL')) {
87 _setlocale(LC_ALL, $lang);
8d039718 88 }
aba609e0 89
7b26a148
AD
90 if (defined('MOBILE_VERSION')) {
91 _bindtextdomain("messages", "../locale");
92 } else {
93 _bindtextdomain("messages", "locale");
94 }
865220a4 95
7b26a148
AD
96 _textdomain("messages");
97 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 98 }
7b26a148
AD
99 }
100
101 startup_gettext();
cc17c205 102
b619ff15 103 require_once 'db-prefs.php';
8911ac8b 104 require_once 'version.php';
87d7e850
AD
105 require_once 'ccache.php';
106 require_once 'labels.php';
40d13c28 107
500943a4
AD
108 ini_set('user_agent', SELF_USER_AGENT);
109
b0f379df 110 require_once 'lib/pubsubhubbub/publisher.php';
acccafe3 111 require_once 'lib/htmLawed.php';
010efc9b 112
7d96bfcd
AD
113 $tz_offset = -1;
114 $utc_tz = new DateTimeZone('UTC');
115 $schema_version = false;
116
45004d43
AD
117 /**
118 * Print a timestamped debug message.
8d505d78 119 *
45004d43
AD
120 * @param string $msg The debug message.
121 * @return void
122 */
6f9e33e4 123 function _debug($msg) {
5439d333
RW
124 if (defined('QUIET') && QUIET) {
125 return;
126 }
6f9e33e4 127 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
128 if (function_exists('posix_getpid')) {
129 $ts = "$ts/" . posix_getpid();
130 }
6f9e33e4 131 print "[$ts] $msg\n";
45004d43 132 } // function _debug
6f9e33e4 133
9632f884
AD
134 /**
135 * Purge a feed old posts.
8d505d78 136 *
9632f884
AD
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 */
ad507f85
AD
144 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
145
07d0efe9 146 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
8d505d78 147
ad507f85 148 $rows = -1;
4c193675 149
8d505d78 150 $result = db_query($link,
07d0efe9
AD
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
ab954dff
AD
159 if ($purge_interval == -1 || !$purge_interval) {
160 if ($owner_uid) {
161 ccache_update($link, $feed_id, $owner_uid);
162 }
163 return;
164 }
165
07d0efe9
AD
166 if (!$owner_uid) return;
167
3907ef71
AD
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 }
07d0efe9
AD
175
176 if (!$purge_unread) $query_limit = " unread = false AND ";
177
fefa6ca3 178 if (DB_TYPE == "pgsql") {
6e7f8d26
AD
179 $pg_version = get_pgsql_version($link);
180
181 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 182
8d505d78
AD
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
07d0efe9 187 $query_limit
25ea2805 188 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
189
190 } else {
191
8d505d78
AD
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
07d0efe9 197 $query_limit
25ea2805 198 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 199 }
ad507f85
AD
200
201 $rows = pg_affected_rows($result);
8d505d78 202
fefa6ca3 203 } else {
8d505d78 204
30f1746f 205/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 206 marked = false AND feed_id = '$feed_id' AND
8d505d78 207 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
208 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
209
8d505d78
AD
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
07d0efe9 215 $query_limit
25ea2805 216 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
8d505d78 217
ad507f85
AD
218 $rows = mysql_affected_rows($link);
219
220 }
221
ced46404
AD
222 ccache_update($link, $feed_id, $owner_uid);
223
ad507f85 224 if ($debug) {
6f9e33e4 225 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 226 }
9632f884 227 } // function purge_feed
fefa6ca3 228
07d0efe9
AD
229 function feed_purge_interval($link, $feed_id) {
230
8d505d78 231 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
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
8d505d78 238 if ($purge_interval == 0) $purge_interval = get_pref($link,
863be6ca 239 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
240
241 return $purge_interval;
242
243 } else {
244 return -1;
245 }
246 }
247
a2d79981
AD
248 function purge_orphans($link, $do_output = false) {
249
71604ca4 250 // purge orphaned posts in main content table
8d505d78 251 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4 252 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
253
254 if ($do_output) {
255 $rows = db_affected_rows($link, $result);
256 _debug("Purged $rows orphaned posts.");
257 }
c3a8d71a
AD
258 }
259
c7d57b66
AD
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
ae5f7bb1 279 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
8d505d78
AD
280 $login = urlencode($login);
281 $pass = urlencode($pass);
282
23d2471c
AD
283 global $fetch_last_error;
284
3610b48b 285 if (function_exists('curl_init') && !ini_get("open_basedir")) {
4065b60b 286 $ch = curl_init($url);
a1af1574
AD
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);
8d505d78 294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
5f6804bc 295 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
19929bbe 296 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
268a06dc 297 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
8d505d78 298
ae5f7bb1
AD
299 if ($post_query) {
300 curl_setopt($ch, CURLOPT_POST, true);
301 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
302 }
303
8d505d78
AD
304 if ($login && $pass)
305 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 306
fb074239 307 $contents = @curl_exec($ch);
268a06dc 308
a1af1574 309 if ($contents === false) {
23d2471c 310 $fetch_last_error = curl_error($ch);
a1af1574
AD
311 curl_close($ch);
312 return false;
4065b60b
AD
313 }
314
8d505d78 315 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
a1af1574
AD
316 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
317 curl_close($ch);
4065b60b 318
8d505d78 319 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
a1af1574
AD
320 return false;
321 }
4065b60b 322
a1af1574 323 return $contents;
4065b60b 324 } else {
9949bd15 325 if ($login && $pass ){
8d505d78
AD
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
23d2471c
AD
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;
4065b60b
AD
342 }
343
344 }
78800912 345
9632f884
AD
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
8d505d78 350 *
9632f884
AD
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 */
1bd11fdf 355 function get_favicon_url($url) {
99331724 356
1bd11fdf 357 $favicon_url = false;
ed214298 358
4065b60b 359 if ($html = @fetch_file_contents($url)) {
78800912 360
ed214298 361 libxml_use_internal_errors(true);
c798704b 362
ed214298
AD
363 $doc = new DOMDocument();
364 $doc->loadHTML($html);
365 $xpath = new DOMXPath($doc);
717f5e64 366
a712429e
AD
367 $base = $xpath->query('/html/head/base');
368 foreach ($base as $b) {
369 $url = $b->getAttribute("href");
370 break;
371 }
372
1bd11fdf 373 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
374 if (count($entries) > 0) {
375 foreach ($entries as $entry) {
1bd11fdf
AD
376 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
377 break;
ed214298 378 }
8d505d78 379 }
4065b60b 380 }
c798704b 381
1bd11fdf
AD
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) {
882311d9 389# print "FAVICON [$site_url]: $favicon_url\n";
4065b60b 390
1bd11fdf
AD
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 }
78800912
AD
435 }
436 }
437
f175937c 438 function print_select($id, $default, $values, $attributes = "") {
79f3553b 439 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
440 foreach ($values as $v) {
441 if ($v == $default)
60807300 442 $sel = "selected=\"1\"";
a0d53889
AD
443 else
444 $sel = "";
8d505d78 445
60807300 446 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
447 }
448 print "</select>";
449 }
40d13c28 450
79f3553b
AD
451 function print_select_hash($id, $default, $values, $attributes = "") {
452 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
453 foreach (array_keys($values) as $v) {
454 if ($v == $default)
74d5c8fa 455 $sel = 'selected="selected"';
673d54ca
AD
456 else
457 $sel = "";
8d505d78 458
673d54ca
AD
459 print "<option $sel value=\"$v\">".$values[$v]."</option>";
460 }
461
462 print "</select>";
463 }
464
406d9489
AD
465 function getmicrotime() {
466 list($usec, $sec) = explode(" ",microtime());
467 return ((float)$usec + (float)$sec);
468 }
469
f541eb78 470 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 471 foreach ($values as $v) {
8d505d78 472
77e96719 473 if ($v == $default)
5da169d9 474 $sel = "checked";
77e96719 475 else
5da169d9
AD
476 $sel = "";
477
f541eb78 478 if ($v == $true_is) {
5da169d9
AD
479 $sel .= " value=\"1\"";
480 } else {
481 $sel .= " value=\"0\"";
482 }
8d505d78
AD
483
484 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 485 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
486
487 }
488 }
489
d9084cf2 490 function initialize_user_prefs($link, $uid, $profile = false) {
ff485f1d
AD
491
492 $uid = db_escape_string($uid);
493
d9084cf2
AD
494 if (!$profile) {
495 $profile = "NULL";
f9aa6a89 496 $profile_qpart = "AND profile IS NULL";
d9084cf2 497 } else {
f9aa6a89 498 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
499 }
500
f9aa6a89
AD
501 if (get_schema_version($link) < 63) $profile_qpart = "";
502
ff485f1d
AD
503 db_query($link, "BEGIN");
504
505 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78
AD
506
507 $u_result = db_query($link, "SELECT pref_name
f9aa6a89 508 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
509
510 $active_prefs = array();
511
512 while ($line = db_fetch_assoc($u_result)) {
8d505d78 513 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
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
f9aa6a89
AD
520 if (get_schema_version($link) < 63) {
521 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 522 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
523 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
524
525 } else {
526 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 527 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
528 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
529 }
ff485f1d
AD
530
531 }
532 }
533
534 db_query($link, "COMMIT");
535
536 }
956c7629 537
8de8bfb8
AD
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
0d421af8 548 function authenticate_user($link, $login, $password, $check_only = false) {
c8437f35 549
131b01b3 550 if (!SINGLE_USER_MODE) {
c8437f35 551
0d421af8 552 $user_id = false;
0f28f81f
AD
553
554 global $pluginhost;
555 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
556
557 $user_id = (int) $plugin->authenticate($login, $password);
558
559 if ($user_id) {
560 $_SESSION["auth_module"] = strtolower(get_class($plugin));
561 break;
562 }
461766f3
AD
563 }
564
0d421af8
AD
565 if ($user_id && !$check_only) {
566 $_SESSION["uid"] = $user_id;
567
568 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
569 WHERE id = '$user_id'");
8d505d78 570
131b01b3
AD
571 $_SESSION["name"] = db_fetch_result($result, 0, "login");
572 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
8484ce22 573 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
8d505d78
AD
574
575 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 576 $_SESSION["uid"]);
8d505d78 577
131b01b3 578 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 579 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
580
581 $_SESSION["last_version_check"] = time();
8d505d78 582
131b01b3 583 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 584
131b01b3
AD
585 return true;
586 }
8d505d78 587
131b01b3 588 return false;
503eb349 589
131b01b3 590 } else {
503eb349 591
131b01b3
AD
592 $_SESSION["uid"] = 1;
593 $_SESSION["name"] = "admin";
787e5ebc 594 $_SESSION["access_level"] = 10;
21e42e5f 595
0d421af8
AD
596 $_SESSION["hide_hello"] = true;
597 $_SESSION["hide_logout"] = true;
598
d5fd183d
AD
599 $_SESSION["auth_module"] = false;
600
21e42e5f
AD
601 if (!$_SESSION["csrf_token"]) {
602 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
603 }
f557cd78 604
0bbba72d 605 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 606
0bbba72d 607 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 608
c8437f35
AD
609 return true;
610 }
c8437f35
AD
611 }
612
e6cb77a0
AD
613 function make_password($length = 8) {
614
85db6213
AD
615 $password = "";
616 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
617
618 $i = 0;
619
620 while ($i < $length) {
621 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
622
623 if (!strstr($password, $char)) {
624 $password .= $char;
625 $i++;
626 }
627 }
628 return $password;
e6cb77a0
AD
629 }
630
631 // this is called after user is created to initialize default feeds, labels
632 // or whatever else
8d505d78 633
e6cb77a0
AD
634 // user preferences are checked on every login, not here
635
636 function initialize_user($link, $uid) {
637
e6cb77a0 638 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 639 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 640 'http://tt-rss.org/releases.rss')");
3b0feb9b 641
cd2cd415
AD
642 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
643 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 644 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 645 }
e6cb77a0 646
b8aa49bc 647 function logout_user() {
5ccc1cf5
AD
648 session_destroy();
649 if (isset($_COOKIE[session_name()])) {
650 setcookie(session_name(), '', time()-42000, '/');
651 }
b8aa49bc
AD
652 }
653
8484ce22
AD
654 function validate_csrf($csrf_token) {
655 return $csrf_token == $_SESSION['csrf_token'];
656 }
657
916f788a 658 function validate_session($link) {
0f41fce8
AD
659 if (SINGLE_USER_MODE) return true;
660
661 $check_ip = $_SESSION['ip_address'];
662
663 switch (SESSION_CHECK_ADDRESS) {
664 case 0:
665 $check_ip = '';
666 break;
667 case 1:
668 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
669 break;
670 case 2:
671 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
672 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
673 break;
674 };
675
d769a0f7 676 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
8d505d78 677 $_SESSION["login_error_msg"] =
d769a0f7
AD
678 __("Session failed to validate (incorrect IP)");
679 return false;
680 }
0f41fce8
AD
681
682 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
05044a59 683 return false;
05044a59 684
e6684130
AD
685 if ($_SESSION["uid"]) {
686
8d505d78 687 $result = db_query($link,
e6684130
AD
688 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
689
690 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
691
692 if ($pwd_hash != $_SESSION["pwd_hash"]) {
693 return false;
694 }
695 }
696
a885f0ec 697/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 698
8e849206 699 //print_r($_SESSION);
d620cfe7
AD
700
701 if (time() > $_SESSION["cookie_lifetime"]) {
702 return false;
703 }
a885f0ec
AD
704 } */
705
916f788a
AD
706 return true;
707 }
708
de612e7a
AD
709 function load_user_plugins($link, $owner_uid) {
710 if ($owner_uid) {
711 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
712
713 global $pluginhost;
d8a1d2a2 714 $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
e9c04fd4
AD
715
716 if (get_schema_version($link) > 100) {
717 $pluginhost->load_data();
718 }
de612e7a
AD
719 }
720 }
721
97acbaf1
AD
722 function login_sequence($link, $login_form = 0) {
723 if (SINGLE_USER_MODE) {
de612e7a
AD
724 authenticate_user($link, "admin", null);
725 load_user_plugins($link, $_SESSION["uid"]);
97acbaf1
AD
726 } else {
727 if (!$_SESSION["uid"] || !validate_session($link)) {
728
729 if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
730 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
731 } else {
732 authenticate_user($link, null, null, true);
733 }
734
735 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
736
737 } else {
738 /* bump login timestamp */
739 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
740 $_SESSION["uid"]);
01a87dff
AD
741 }
742
afc3cf55
AD
743 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
744 setcookie("ttrss_lang", $_SESSION["language"],
745 time() + SESSION_COOKIE_LIFETIME);
b8aa49bc 746 }
de612e7a
AD
747
748 if ($_SESSION["uid"]) {
749 load_user_plugins($link, $_SESSION["uid"]);
750 }
b8aa49bc 751 }
afc3cf55 752 }
3547842a 753
411fe209 754 function truncate_string($str, $max_len, $suffix = '&hellip;') {
12db369c 755 if (mb_strlen($str, "utf-8") > $max_len - 3) {
411fe209 756 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
757 } else {
758 return $str;
759 }
760 }
54a60e1a 761
96f0a3e7 762 // Deprecated, TODO: remove
e9823609 763 function theme_image($link, $filename) {
96f0a3e7 764 return $filename;
54a60e1a 765 }
be773442 766
ab4b768f
AD
767 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
768
769 try {
770 $source_tz = new DateTimeZone($source_tz);
771 } catch (Exception $e) {
772 $source_tz = new DateTimeZone('UTC');
773 }
774
775 try {
776 $dest_tz = new DateTimeZone($dest_tz);
777 } catch (Exception $e) {
778 $dest_tz = new DateTimeZone('UTC');
779 }
780
781 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
782 return $dt->format('U') + $dest_tz->getOffset($dt);
783 }
784
324944f3
AD
785 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
786 $no_smart_dt = false) {
787
788 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
789 if (!$timestamp) $timestamp = '1970-01-01 0:00';
790
7d96bfcd
AD
791 global $utc_tz;
792 global $tz_offset;
324944f3 793
7d96bfcd
AD
794 # We store date in UTC internally
795 $dt = new DateTime($timestamp, $utc_tz);
796
797 if ($tz_offset == -1) {
798
799 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
800
801 try {
802 $user_tz = new DateTimeZone($user_tz_string);
803 } catch (Exception $e) {
804 $user_tz = $utc_tz;
805 }
806
807 $tz_offset = $user_tz->getOffset($dt);
324944f3
AD
808 }
809
7d96bfcd 810 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 811
1dc52ae7 812 if (!$no_smart_dt) {
8d505d78 813 return smart_date_time($link, $user_timestamp,
7d96bfcd 814 $tz_offset, $owner_uid);
324944f3
AD
815 } else {
816 if ($long)
817 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
818 else
819 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
820
821 return date($format, $user_timestamp);
822 }
823 }
824
2a5c136e
AD
825 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
826 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
827
828 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 829 return date("G:i", $timestamp);
2a5c136e
AD
830 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
831 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
832 return date($format, $timestamp);
be773442 833 } else {
2a5c136e
AD
834 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
835 return date($format, $timestamp);
be773442
AD
836 }
837 }
838
e3c99f3b 839 function sql_bool_to_bool($s) {
36184020 840 if ($s == "t" || $s == "1" || $s == "true") {
e3c99f3b
AD
841 return true;
842 } else {
843 return false;
844 }
845 }
8d505d78 846
badac687
AD
847 function bool_to_sql_bool($s) {
848 if ($s) {
849 return "true";
850 } else {
851 return "false";
852 }
853 }
e3c99f3b 854
fcfa9ef1
AD
855 // Session caching removed due to causing wrong redirects to upgrade
856 // script when get_schema_version() is called on an obsolete session
857 // created on a previous schema version.
199db684 858 function get_schema_version($link, $nocache = false) {
7d96bfcd
AD
859 global $schema_version;
860
861 if (!$schema_version) {
199db684
AD
862 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
863 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 864 $schema_version = $version;
199db684 865 return $version;
7d96bfcd
AD
866 } else {
867 return $schema_version;
868 }
e4c51a6c
AD
869 }
870
6043fb7e 871 function sanity_check($link) {
31303c6b 872 require_once 'errors.php';
ebb948c2 873
6043fb7e 874 $error_code = 0;
7d96bfcd 875 $schema_version = get_schema_version($link, true);
6043fb7e
AD
876
877 if ($schema_version != SCHEMA_VERSION) {
878 $error_code = 5;
879 }
880
aec3ce39
AD
881 if (DB_TYPE == "mysql") {
882 $result = db_query($link, "SELECT true", false);
883 if (db_num_rows($result) != 1) {
884 $error_code = 10;
885 }
886 }
887
f29ba148
AD
888 if (db_escape_string("testTEST") != "testTEST") {
889 $error_code = 12;
890 }
891
ebb948c2 892 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
893 }
894
27981ca3 895 function file_is_locked($filename) {
31a6d42d 896 if (function_exists('flock')) {
fb074239 897 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
898 if ($fp) {
899 if (flock($fp, LOCK_EX | LOCK_NB)) {
900 flock($fp, LOCK_UN);
901 fclose($fp);
902 return false;
903 }
27981ca3 904 fclose($fp);
31a6d42d 905 return true;
e89aed7b
AD
906 } else {
907 return false;
27981ca3 908 }
27981ca3 909 }
c1fb4a5e 910 return true; // consider the file always locked and skip the test
27981ca3
AD
911 }
912
fcb4c0c9 913 function make_lockfile($filename) {
cfa43e02 914 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 915
82acc36d 916 if (flock($fp, LOCK_EX | LOCK_NB)) {
4c59adb1
AD
917 if (function_exists('posix_getpid')) {
918 fwrite($fp, posix_getpid() . "\n");
919 }
fcb4c0c9
AD
920 return $fp;
921 } else {
922 return false;
923 }
924 }
925
bf7fcde8 926 function make_stampfile($filename) {
cfa43e02 927 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 928
8e00ae9b 929 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 930 fwrite($fp, time() . "\n");
8e00ae9b 931 flock($fp, LOCK_UN);
bf7fcde8
AD
932 fclose($fp);
933 return true;
934 } else {
935 return false;
936 }
937 }
938
894ebcf5
AD
939 function sql_random_function() {
940 if (DB_TYPE == "mysql") {
941 return "RAND()";
942 } else {
943 return "RANDOM()";
944 }
945 }
946
184f5195 947 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
c7e51de1
AD
948
949 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 950
37c03d3a 951 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 952
705b97b7
AD
953 $ref_check_qpart = ($max_id &&
954 !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
184f5195 955
37c03d3a 956 if (is_numeric($feed)) {
23aa0d16
AD
957 if ($cat_view) {
958
72a2f4f5 959 if ($feed >= 0) {
f9fca8cb
AD
960
961 if ($feed > 0) {
bda6afa2
AD
962 $children = getChildCategories($link, $feed, $owner_uid);
963 array_push($children, $feed);
964
965 $children = join(",", $children);
966
967 $cat_qpart = "cat_id IN ($children)";
f9fca8cb
AD
968 } else {
969 $cat_qpart = "cat_id IS NULL";
970 }
8d505d78 971
bda6afa2
AD
972 db_query($link, "UPDATE ttrss_user_entries
973 SET unread = false,last_read = NOW()
974 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
975 AND $ref_check_qpart
976 AND owner_uid = $owner_uid");
23aa0d16 977
f9fca8cb 978 } else if ($feed == -2) {
23aa0d16 979
8d505d78
AD
980 db_query($link, "UPDATE ttrss_user_entries
981 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
982 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
184f5195
AD
983 AND $ref_check_qpart
984 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
985 }
986
987 } else if ($feed > 0) {
988
8d505d78
AD
989 db_query($link, "UPDATE ttrss_user_entries
990 SET unread = false,last_read = NOW()
184f5195
AD
991 WHERE feed_id = '$feed'
992 AND $ref_check_qpart
993 AND owner_uid = $owner_uid");
8d505d78 994
23aa0d16
AD
995 } else if ($feed < 0 && $feed > -10) { // special, like starred
996
997 if ($feed == -1) {
8d505d78 998 db_query($link, "UPDATE ttrss_user_entries
23aa0d16 999 SET unread = false,last_read = NOW()
184f5195
AD
1000 WHERE marked = true
1001 AND $ref_check_qpart
1002 AND owner_uid = $owner_uid");
23aa0d16 1003 }
e4f4b46f
AD
1004
1005 if ($feed == -2) {
8d505d78 1006 db_query($link, "UPDATE ttrss_user_entries
e4f4b46f 1007 SET unread = false,last_read = NOW()
184f5195
AD
1008 WHERE published = true
1009 AND $ref_check_qpart
1010 AND owner_uid = $owner_uid");
e4f4b46f
AD
1011 }
1012
2d24f032
AD
1013 if ($feed == -3) {
1014
c1d7e6c3
AD
1015 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1016
2d24f032 1017 if (DB_TYPE == "pgsql") {
8d505d78 1018 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1019 } else {
8d505d78 1020 $match_part = "updated > DATE_SUB(NOW(),
c1d7e6c3 1021 INTERVAL $intl HOUR) ";
2d24f032
AD
1022 }
1023
8d505d78 1024 $result = db_query($link, "SELECT id FROM ttrss_entries,
1f3335dc
AD
1025 ttrss_user_entries WHERE $match_part AND
1026 unread = true AND
8d505d78 1027 ttrss_user_entries.ref_id = ttrss_entries.id AND
c7e51de1 1028 owner_uid = $owner_uid");
1f3335dc
AD
1029
1030 $affected_ids = array();
1031
1032 while ($line = db_fetch_assoc($result)) {
1033 array_push($affected_ids, $line["id"]);
1034 }
1035
1036 catchupArticlesById($link, $affected_ids, 0);
2d24f032
AD
1037 }
1038
3584cb11 1039 if ($feed == -4) {
8d505d78 1040 db_query($link, "UPDATE ttrss_user_entries
3584cb11 1041 SET unread = false,last_read = NOW()
184f5195 1042 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
3584cb11
AD
1043 }
1044
23aa0d16
AD
1045 } else if ($feed < -10) { // label
1046
23aa0d16
AD
1047 $label_id = -$feed - 11;
1048
8d505d78
AD
1049 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1050 SET unread = false, last_read = NOW()
338c238d 1051 WHERE label_id = '$label_id' AND unread = true
184f5195 1052 AND $ref_check_qpart
c7e51de1 1053 AND owner_uid = '$owner_uid' AND ref_id = article_id");
23aa0d16 1054
23aa0d16 1055 }
ad0056a8 1056
c7e51de1 1057 ccache_update($link, $feed, $owner_uid, $cat_view);
ad0056a8 1058
23aa0d16
AD
1059 } else { // tag
1060 db_query($link, "BEGIN");
1061
1062 $tag_name = db_escape_string($feed);
1063
1064 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
c7e51de1 1065 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
23aa0d16
AD
1066
1067 while ($line = db_fetch_assoc($result)) {
1068 db_query($link, "UPDATE ttrss_user_entries SET
8d505d78 1069 unread = false, last_read = NOW()
184f5195 1070 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
23aa0d16
AD
1071 }
1072 db_query($link, "COMMIT");
1073 }
1074 }
1075
4ffa126e 1076 function getAllCounters($link, $omode = "flc", $active_feed = false) {
cf4d339c 1077
e33fe293 1078 if (!$omode) $omode = "flc";
0a6e5382 1079
6a7817c1 1080 $data = getGlobalCounters($link);
8d505d78 1081
6a7817c1
AD
1082 $data = array_merge($data, getVirtCounters($link));
1083
1084 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1085 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1086 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
798f5a64 1087 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
6a7817c1
AD
1088
1089 return $data;
8d505d78 1090 }
a9cb1f83 1091
79178062
AD
1092 function getCategoryTitle($link, $cat_id) {
1093
1094 if ($cat_id == -1) {
1095 return __("Special");
1096 } else if ($cat_id == -2) {
1097 return __("Labels");
1098 } else {
1099
1100 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1101 id = '$cat_id'");
1102
1103 if (db_num_rows($result) == 1) {
1104 return db_fetch_result($result, 0, "title");
1105 } else {
f99759da 1106 return __("Uncategorized");
79178062
AD
1107 }
1108 }
1109 }
1110
1111
a9cb1f83 1112 function getCategoryCounters($link) {
6a7817c1 1113 $ret_arr = array();
bba7c4bf 1114
6a7817c1 1115 /* Labels category */
bba7c4bf 1116
8acc449c 1117 $cv = array("id" => -2, "kind" => "cat",
6a7817c1 1118 "counter" => getCategoryUnread($link, -2));
bba7c4bf 1119
6a7817c1 1120 array_push($ret_arr, $cv);
bba7c4bf 1121
2c5f231e
AD
1122 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1123 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1124 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
8d505d78
AD
1125 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1126 WHERE ttrss_cat_counters_cache.feed_id = id AND
fc9de939 1127 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
31375163 1128 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
1129
1130 while ($line = db_fetch_assoc($result)) {
22fdebff 1131 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 1132
2c5f231e 1133 if ($line["num_children"] > 0) {
99c9e91a 1134 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
2c5f231e
AD
1135 } else {
1136 $child_counter = 0;
1137 }
1138
8acc449c 1139 $cv = array("id" => $line["cat_id"], "kind" => "cat",
0ef32f48 1140 "counter" => $line["unread"] + $child_counter);
6a7817c1
AD
1141
1142 array_push($ret_arr, $cv);
a9cb1f83 1143 }
d232a40f
AD
1144
1145 /* Special case: NULL category doesn't actually exist in the DB */
1146
9798b2b4 1147 $cv = array("id" => 0, "kind" => "cat",
12e6de72 1148 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
d232a40f 1149
6a7817c1
AD
1150 array_push($ret_arr, $cv);
1151
1152 return $ret_arr;
a9cb1f83
AD
1153 }
1154
2c5f231e 1155 // only accepts real cats (>= 0)
99c9e91a 1156 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
2c5f231e
AD
1157 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1158
1159 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1160 AND owner_uid = $owner_uid");
1161
1162 $unread = 0;
1163
1164 while ($line = db_fetch_assoc($result)) {
1165 $unread += getCategoryUnread($link, $line["id"], $owner_uid);
99c9e91a 1166 $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
2c5f231e
AD
1167 }
1168
1169 return $unread;
1170 }
1171
b6d486a3
AD
1172 function getCategoryUnread($link, $cat, $owner_uid = false) {
1173
1174 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 1175
bba7c4bf 1176 if ($cat >= 0) {
18664970 1177
bba7c4bf
AD
1178 if ($cat != 0) {
1179 $cat_query = "cat_id = '$cat'";
1180 } else {
1181 $cat_query = "cat_id IS NULL";
1182 }
14073c0a 1183
8d505d78 1184 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 1185 AND owner_uid = " . $owner_uid);
8d505d78 1186
bba7c4bf
AD
1187 $cat_feeds = array();
1188 while ($line = db_fetch_assoc($result)) {
1189 array_push($cat_feeds, "feed_id = " . $line["id"]);
1190 }
8d505d78 1191
bba7c4bf 1192 if (count($cat_feeds) == 0) return 0;
8d505d78 1193
bba7c4bf 1194 $match_part = implode(" OR ", $cat_feeds);
8d505d78
AD
1195
1196 $result = db_query($link, "SELECT COUNT(int_id) AS unread
687bb90d
AD
1197 FROM ttrss_user_entries
1198 WHERE unread = true AND ($match_part)
1199 AND owner_uid = " . $owner_uid);
8d505d78 1200
bba7c4bf 1201 $unread = 0;
8d505d78 1202
bba7c4bf
AD
1203 # this needs to be rewritten
1204 while ($line = db_fetch_assoc($result)) {
1205 $unread += $line["unread"];
1206 }
8d505d78 1207
bba7c4bf
AD
1208 return $unread;
1209 } else if ($cat == -1) {
59e15af4 1210 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
bba7c4bf 1211 } else if ($cat == -2) {
f295c368 1212
b2531a28 1213 $result = db_query($link, "
8d505d78 1214 SELECT COUNT(unread) AS unread FROM
687bb90d
AD
1215 ttrss_user_entries, ttrss_user_labels2
1216 WHERE article_id = ref_id AND unread = true
b2531a28 1217 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 1218
b2531a28 1219 $unread = db_fetch_result($result, 0, "unread");
f295c368 1220
b2531a28 1221 return $unread;
f295c368 1222
8d505d78 1223 }
f295c368
AD
1224 }
1225
1226 function getFeedUnread($link, $feed, $is_cat = false) {
2627f2d0 1227 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
1228 }
1229
ceb30ba4
AD
1230 function getLabelUnread($link, $label_id, $owner_uid = false) {
1231 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1232
f360b028
AD
1233 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1234 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
ceb30ba4
AD
1235
1236 if (db_num_rows($result) != 0) {
1237 return db_fetch_result($result, 0, "unread");
1238 } else {
1239 return 0;
1240 }
1241 }
1242
2627f2d0
AD
1243 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1244 $owner_uid = false) {
1245
22fdebff 1246 $n_feed = (int) $feed;
687bb90d 1247 $need_entries = false;
f295c368 1248
2627f2d0
AD
1249 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1250
bdb7369b
AD
1251 if ($unread_only) {
1252 $unread_qpart = "unread = true";
1253 } else {
1254 $unread_qpart = "true";
1255 }
1256
f295c368 1257 if ($is_cat) {
8d505d78 1258 return getCategoryUnread($link, $n_feed, $owner_uid);
5417fbd7
AD
1259 } else if ($n_feed == -6) {
1260 return 0;
1261 } else if ($feed != "0" && $n_feed == 0) {
326469fc 1262
c5701e70
AD
1263 $feed = db_escape_string($feed);
1264
326469fc 1265 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
8d505d78 1266 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
687bb90d 1267 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
1268 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1269 return db_fetch_result($result, 0, "count");
1270
f295c368 1271 } else if ($n_feed == -1) {
a9cb1f83 1272 $match_part = "marked = true";
e4f4b46f
AD
1273 } else if ($n_feed == -2) {
1274 $match_part = "published = true";
2d24f032 1275 } else if ($n_feed == -3) {
cd2cc43d 1276 $match_part = "unread = true AND score >= 0";
2d24f032 1277
b71e188e 1278 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 1279
2d24f032 1280 if (DB_TYPE == "pgsql") {
8d505d78 1281 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1282 } else {
7608b38a 1283 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 1284 }
687bb90d
AD
1285
1286 $need_entries = true;
1287
b2531a28
AD
1288 } else if ($n_feed == -4) {
1289 $match_part = "true";
e04c18a2 1290 } else if ($n_feed >= 0) {
831ff047 1291
6e63a7c3
AD
1292 if ($n_feed != 0) {
1293 $match_part = "feed_id = '$n_feed'";
831ff047 1294 } else {
6e63a7c3 1295 $match_part = "feed_id IS NULL";
831ff047 1296 }
6e63a7c3 1297
a9cb1f83 1298 } else if ($feed < -10) {
318260cc 1299
a9cb1f83
AD
1300 $label_id = -$feed - 11;
1301
ceb30ba4 1302 return getLabelUnread($link, $label_id, $owner_uid);
a9cb1f83 1303
a9cb1f83
AD
1304 }
1305
1306 if ($match_part) {
e04c18a2 1307
687bb90d 1308 if ($need_entries) {
e04c18a2 1309 $from_qpart = "ttrss_user_entries,ttrss_entries";
687bb90d
AD
1310 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1311 } else {
1312 $from_qpart = "ttrss_user_entries";
e04c18a2
AD
1313 }
1314
8d505d78 1315 $query = "SELECT count(int_id) AS unread
e04c18a2 1316 FROM $from_qpart WHERE
687bb90d
AD
1317 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1318
1319 //echo "[$feed/$query]\n";
dbfc4365
AD
1320
1321 $result = db_query($link, $query);
8d505d78 1322
a9cb1f83 1323 } else {
8d505d78 1324
a9cb1f83 1325 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
8d505d78
AD
1326 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1327 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
687bb90d 1328 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 1329 }
8d505d78 1330
a9cb1f83 1331 $unread = db_fetch_result($result, 0, "unread");
cfb02131 1332
a9cb1f83
AD
1333 return $unread;
1334 }
1335
f3acc32e
AD
1336 function getGlobalUnread($link, $user_id = false) {
1337
1338 if (!$user_id) {
1339 $user_id = $_SESSION["uid"];
1340 }
1341
8a4c759e
AD
1342 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1343 WHERE owner_uid = '$user_id' AND feed_id > 0");
1344
8d505d78 1345 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 1346
a9cb1f83
AD
1347 return $c_id;
1348 }
1349
1350 function getGlobalCounters($link, $global_unread = -1) {
6a7817c1
AD
1351 $ret_arr = array();
1352
8d505d78 1353 if ($global_unread == -1) {
a9cb1f83
AD
1354 $global_unread = getGlobalUnread($link);
1355 }
6a7817c1 1356
8d505d78 1357 $cv = array("id" => "global-unread",
12e6de72 1358 "counter" => (int) $global_unread);
6a7817c1
AD
1359
1360 array_push($ret_arr, $cv);
7bf7e4d3 1361
8d505d78 1362 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
1363 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1364
1365 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1366
8d505d78 1367 $cv = array("id" => "subscribed-feeds",
12e6de72 1368 "counter" => (int) $subscribed_feeds);
7bf7e4d3 1369
6a7817c1
AD
1370 array_push($ret_arr, $cv);
1371
1372 return $ret_arr;
a9cb1f83
AD
1373 }
1374
3809b278 1375 function getTagCounters($link) {
8d505d78 1376
6a7817c1 1377 $ret_arr = array();
a9cb1f83 1378
8d505d78
AD
1379 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1380 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
687bb90d 1381 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
8d505d78 1382 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
ef1ac7c7 1383 ORDER BY count DESC LIMIT 55");
8d505d78 1384
a9cb1f83
AD
1385 $tags = array();
1386
1387 while ($line = db_fetch_assoc($result)) {
1388 $tags[$line["tag_name"]] += $line["count"];
1389 }
1390
1391 foreach (array_keys($tags) as $tag) {
8d505d78 1392 $unread = $tags[$tag];
a9cb1f83 1393 $tag = htmlspecialchars($tag);
6a7817c1
AD
1394
1395 $cv = array("id" => $tag,
8acc449c 1396 "kind" => "tag",
6a7817c1
AD
1397 "counter" => $unread);
1398
1399 array_push($ret_arr, $cv);
1400 }
1401
8d505d78 1402 return $ret_arr;
a9cb1f83
AD
1403 }
1404
6a7817c1 1405 function getVirtCounters($link) {
a9cb1f83 1406
ef393de7 1407 $ret_arr = array();
bdb7369b 1408
e04c18a2 1409 for ($i = 0; $i >= -4; $i--) {
bdb7369b 1410
ceb30ba4 1411 $count = getFeedUnread($link, $i);
6a7817c1
AD
1412
1413 $cv = array("id" => $i,
12e6de72 1414 "counter" => (int) $count);
8d505d78 1415
296c8134
AD
1416// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1417// $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
bdb7369b 1418
6a7817c1 1419 array_push($ret_arr, $cv);
8d505d78 1420 }
0a6e5382
AD
1421
1422 return $ret_arr;
1423 }
1424
11232703 1425 function getLabelCounters($link, $descriptions = false) {
6a7817c1
AD
1426
1427 $ret_arr = array();
0a6e5382 1428
3809b278 1429 $owner_uid = $_SESSION["uid"];
bdb7369b 1430
3809b278
AD
1431 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1432 WHERE owner_uid = '$owner_uid'");
8d505d78 1433
3809b278 1434 while ($line = db_fetch_assoc($result)) {
2d24f032 1435
3809b278 1436 $id = -$line["id"] - 11;
e4f4b46f 1437
3809b278
AD
1438 $label_name = $line["caption"];
1439 $count = getFeedUnread($link, $id);
3809b278 1440
6a7817c1 1441 $cv = array("id" => $id,
12e6de72 1442 "counter" => (int) $count);
11232703
AD
1443
1444 if ($descriptions)
1445 $cv["description"] = $label_name;
a9cb1f83 1446
296c8134
AD
1447// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1448// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
ef393de7 1449
6a7817c1 1450 array_push($ret_arr, $cv);
3809b278 1451 }
8d505d78 1452
ef393de7 1453 return $ret_arr;
a9cb1f83
AD
1454 }
1455
3809b278 1456 function getFeedCounters($link, $active_feed = false) {
a9cb1f83 1457
6a7817c1
AD
1458 $ret_arr = array();
1459
8a4c759e
AD
1460 $query = "SELECT ttrss_feeds.id,
1461 ttrss_feeds.title,
8d505d78 1462 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
1463 last_error, value AS count
1464 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 1465 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
fc9de939 1466 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
55e01d7e 1467 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 1468
14073c0a 1469 $result = db_query($link, $query);
a9cb1f83
AD
1470 $fctrs_modified = false;
1471
1472 while ($line = db_fetch_assoc($result)) {
8d505d78 1473
a9cb1f83 1474 $id = $line["id"];
de0a2122 1475 $count = $line["count"];
a9cb1f83 1476 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 1477
324944f3 1478 $last_updated = make_local_datetime($link, $line['last_updated'], false);
fb1fb4ab 1479
7defa089 1480 $has_img = feed_has_icon($id);
a9cb1f83 1481
428b704d
AD
1482 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1483 $last_updated = '';
1484
6a7817c1 1485 $cv = array("id" => $id,
21884958 1486 "updated" => $last_updated,
12e6de72 1487 "counter" => (int) $count,
6a7817c1 1488 "has_img" => (int) $has_img);
a9cb1f83 1489
6a7817c1
AD
1490 if ($last_error)
1491 $cv["error"] = $last_error;
4ffa126e 1492
296c8134
AD
1493// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1494// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
bdb7369b 1495
6a7817c1 1496 if ($active_feed && $id == $active_feed)
fbc95c5b 1497 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
1498
1499 array_push($ret_arr, $cv);
a9cb1f83 1500
a9cb1f83 1501 }
6a7817c1
AD
1502
1503 return $ret_arr;
a9cb1f83
AD
1504 }
1505
6e7f8d26
AD
1506 function get_pgsql_version($link) {
1507 $result = db_query($link, "SELECT version() AS version");
9949bd15 1508 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
1509 return $version[1];
1510 }
1511
2b8290cd 1512 /**
23d2471c
AD
1513 * @return array (code => Status code, message => error message if available)
1514 *
2b8290cd
CW
1515 * 0 - OK, Feed already exists
1516 * 1 - OK, Feed added
1517 * 2 - Invalid URL
9a8ce956
CW
1518 * 3 - URL content is HTML, no feeds available
1519 * 4 - URL content is HTML which contains multiple feeds.
1520 * Here you should call extractfeedurls in rpc-backend
1521 * to get all possible feeds.
5414ad4c 1522 * 5 - Couldn't download the URL content.
2b8290cd 1523 */
8d505d78 1524 function subscribe_to_feed($link, $url, $cat_id = 0,
aa60999b 1525 $auth_login = '', $auth_pass = '', $need_auth = false) {
bb0f29a4 1526
23d2471c
AD
1527 global $fetch_last_error;
1528
2c08214a
AD
1529 require_once "include/rssfuncs.php";
1530
f0266f51 1531 $url = fix_url($url);
ec39a02c 1532
23d2471c 1533 if (!$url || !validate_feed_url($url)) return array("code" => 2);
a5819bb3 1534
759e5132
AD
1535 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1536
1537 if (!$contents) {
304aadb9 1538 return array("code" => 5, "message" => $fetch_last_error);
759e5132
AD
1539 }
1540
1541 if (is_html($contents)) {
1542 $feedUrls = get_feeds_from_html($url, $contents);
304aadb9 1543
304aadb9
AD
1544 if (count($feedUrls) == 0) {
1545 return array("code" => 3);
1546 } else if (count($feedUrls) > 1) {
759e5132 1547 return array("code" => 4, "feeds" => $feedUrls);
f6d8345b 1548 }
304aadb9
AD
1549 //use feed url as new URL
1550 $url = key($feedUrls);
1551 }
f6d8345b 1552
956c7629
AD
1553 if ($cat_id == "0" || !$cat_id) {
1554 $cat_qpart = "NULL";
1555 } else {
1556 $cat_qpart = "'$cat_id'";
1557 }
8d505d78 1558
956c7629 1559 $result = db_query($link,
8d505d78 1560 "SELECT id FROM ttrss_feeds
a5819bb3 1561 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 1562
956c7629 1563 if (db_num_rows($result) == 0) {
956c7629 1564 $result = db_query($link,
8d505d78
AD
1565 "INSERT INTO ttrss_feeds
1566 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1567 VALUES ('".$_SESSION["uid"]."', '$url',
19b3992b 1568 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
8d505d78 1569
956c7629 1570 $result = db_query($link,
8d505d78 1571 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 1572 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 1573
956c7629 1574 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 1575
956c7629 1576 if ($feed_id) {
c633e370 1577 update_rss_feed($link, $feed_id, true);
956c7629
AD
1578 }
1579
23d2471c 1580 return array("code" => 1);
956c7629 1581 } else {
23d2471c 1582 return array("code" => 0);
956c7629
AD
1583 }
1584 }
1585
8d505d78 1586 function print_feed_select($link, $id, $default_id = "",
4c9d0490
AD
1587 $attributes = "", $include_all_feeds = true,
1588 $root_id = false, $nest_level = 0) {
1589
1590 if (!$root_id) {
1591 print "<select id=\"$id\" name=\"$id\" $attributes>";
1592 if ($include_all_feeds) {
1593 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1594 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1595 }
673d54ca 1596 }
8d505d78 1597
4c9d0490 1598 if (get_pref($link, 'ENABLE_FEED_CATS')) {
673d54ca 1599
4c9d0490
AD
1600 if ($root_id)
1601 $parent_qpart = "parent_cat = '$root_id'";
1602 else
1603 $parent_qpart = "parent_cat IS NULL";
673d54ca 1604
4c9d0490
AD
1605 $result = db_query($link, "SELECT id,title,
1606 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1607 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1608 FROM ttrss_feed_categories
1609 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1610
1611 while ($line = db_fetch_assoc($result)) {
1612
1613 for ($i = 0; $i < $nest_level; $i++)
1614 $line["title"] = " - " . $line["title"];
1615
1616 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1617
1618 printf("<option $is_selected value='CAT:%d'>%s</option>",
1619 $line["id"], htmlspecialchars($line["title"]));
1620
1621 if ($line["num_children"] > 0)
1622 print_feed_select($link, $id, $default_id, $attributes,
1623 $include_all_feeds, $line["id"], $nest_level+1);
1624
1625 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1626 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1627
1628 while ($fline = db_fetch_assoc($feed_result)) {
1629 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1630
1631 $fline["title"] = " + " . $fline["title"];
1632
1633 for ($i = 0; $i < $nest_level; $i++)
1634 $fline["title"] = " - " . $fline["title"];
1635
1636 printf("<option $is_selected value='%d'>%s</option>",
1637 $fline["id"], htmlspecialchars($fline["title"]));
1638 }
673d54ca 1639 }
b1710666 1640
4c9d0490
AD
1641 if (!$root_id) {
1642 $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
1643
1644 printf("<option $is_selected value='CAT:0'>%s</option>",
1645 __("Uncategorized"));
1646
1647 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1648 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1649
1650 while ($fline = db_fetch_assoc($feed_result)) {
1651 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1652
1653 $fline["title"] = " + " . $fline["title"];
1654
1655 for ($i = 0; $i < $nest_level; $i++)
1656 $fline["title"] = " - " . $fline["title"];
1657
1658 printf("<option $is_selected value='%d'>%s</option>",
1659 $fline["id"], htmlspecialchars($fline["title"]));
1660 }
1661 }
b1710666 1662
4c9d0490
AD
1663 } else {
1664 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1665 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1666
1667 while ($line = db_fetch_assoc($result)) {
1668
1669 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1670
1671 printf("<option $is_selected value='%d'>%s</option>",
1672 $line["id"], htmlspecialchars($line["title"]));
1673 }
673d54ca 1674 }
8d505d78 1675
4c9d0490
AD
1676 if (!$root_id) {
1677 print "</select>";
1678 }
673d54ca
AD
1679 }
1680
fbf85cf6
AD
1681 function print_feed_cat_select($link, $id, $default_id,
1682 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
8d505d78 1683
fbf85cf6
AD
1684 if (!$root_id) {
1685 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1686 }
673d54ca 1687
fbf85cf6
AD
1688 if ($root_id)
1689 $parent_qpart = "parent_cat = '$root_id'";
1690 else
1691 $parent_qpart = "parent_cat IS NULL";
673d54ca 1692
fbf85cf6
AD
1693 $result = db_query($link, "SELECT id,title,
1694 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1695 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1696 FROM ttrss_feed_categories
1697 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
673d54ca 1698
fbf85cf6
AD
1699 while ($line = db_fetch_assoc($result)) {
1700 if ($line["id"] == $default_id) {
1701 $is_selected = "selected=\"1\"";
1702 } else {
1703 $is_selected = "";
1704 }
673d54ca 1705
fbf85cf6
AD
1706 for ($i = 0; $i < $nest_level; $i++)
1707 $line["title"] = " - " . $line["title"];
c00907f2 1708
fbf85cf6
AD
1709 if ($line["title"])
1710 printf("<option $is_selected value='%d'>%s</option>",
1711 $line["id"], htmlspecialchars($line["title"]));
673d54ca 1712
fbf85cf6
AD
1713 if ($line["num_children"] > 0)
1714 print_feed_cat_select($link, $id, $default_id, $attributes,
1715 $include_all_cats, $line["id"], $nest_level+1);
1716 }
5c7c7da9 1717
fbf85cf6
AD
1718 if (!$root_id) {
1719 if ($include_all_cats) {
1720 if (db_num_rows($result) > 0) {
1721 print "<option disabled=\"1\">--------</option>";
1722 }
7e18f8e7
AD
1723
1724 if ($default_id == 0) {
1725 $is_selected = "selected=\"1\"";
1726 } else {
1727 $is_selected = "";
1728 }
1729
1730 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
fbf85cf6
AD
1731 }
1732 print "</select>";
1733 }
1734 }
8d505d78 1735
14f69488
AD
1736 function checkbox_to_sql_bool($val) {
1737 return ($val == "on") ? "true" : "false";
1738 }
86b682ce
AD
1739
1740 function getFeedCatTitle($link, $id) {
1741 if ($id == -1) {
d1db26aa 1742 return __("Special");
86b682ce 1743 } else if ($id < -10) {
d1db26aa 1744 return __("Labels");
86b682ce 1745 } else if ($id > 0) {
8d505d78 1746 $result = db_query($link, "SELECT ttrss_feed_categories.title
86b682ce
AD
1747 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1748 cat_id = ttrss_feed_categories.id");
1749 if (db_num_rows($result) == 1) {
1750 return db_fetch_result($result, 0, "title");
1751 } else {
d1db26aa 1752 return __("Uncategorized");
86b682ce
AD
1753 }
1754 } else {
1755 return "getFeedCatTitle($id) failed";
1756 }
1757
1758 }
1759
9299102f 1760 function getFeedIcon($id) {
af88c48a 1761 switch ($id) {
4bee8b5f
AD
1762 case 0:
1763 return "images/archive.png";
1764 break;
af88c48a 1765 case -1:
c2167866 1766 return "images/mark_set.svg";
af88c48a
AD
1767 break;
1768 case -2:
c2167866 1769 return "images/pub_set.svg";
af88c48a
AD
1770 break;
1771 case -3:
1772 return "images/fresh.png";
1773 break;
1774 case -4:
1775 return "images/tag.png";
1776 break;
5417fbd7
AD
1777 case -6:
1778 return "images/recently_read.png";
1779 break;
af88c48a 1780 default:
4bee8b5f
AD
1781 if ($id < -10) {
1782 return "images/label.png";
1783 } else {
8d505d78 1784 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 1785 return ICONS_URL . "/$id.ico";
4bee8b5f 1786 }
af88c48a
AD
1787 break;
1788 }
1789 }
1790
fd994f1a
AD
1791 function getFeedTitle($link, $id, $cat = false) {
1792 if ($cat) {
8add44ec 1793 return getCategoryTitle($link, $id);
fd994f1a 1794 } else if ($id == -1) {
d1db26aa 1795 return __("Starred articles");
945c243e
AD
1796 } else if ($id == -2) {
1797 return __("Published articles");
2d24f032
AD
1798 } else if ($id == -3) {
1799 return __("Fresh articles");
b2531a28
AD
1800 } else if ($id == -4) {
1801 return __("All articles");
80db1113 1802 } else if ($id === 0 || $id === "0") {
e04c18a2 1803 return __("Archived articles");
5417fbd7
AD
1804 } else if ($id == -6) {
1805 return __("Recently read");
86b682ce 1806 } else if ($id < -10) {
76626c72 1807 $label_id = -$id - 11;
ceb30ba4 1808 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 1809 if (db_num_rows($result) == 1) {
ceb30ba4 1810 return db_fetch_result($result, 0, "caption");
86b682ce
AD
1811 } else {
1812 return "Unknown label ($label_id)";
1813 }
1814
147f5632 1815 } else if (is_numeric($id) && $id > 0) {
86b682ce
AD
1816 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1817 if (db_num_rows($result) == 1) {
1818 return db_fetch_result($result, 0, "title");
1819 } else {
1820 return "Unknown feed ($id)";
1821 }
1822 } else {
22fdebff 1823 return $id;
86b682ce 1824 }
86b682ce 1825 }
3dd46f19 1826
d8221301 1827 function make_init_params($link) {
f1f3a642 1828 $params = array();
c9268ed5 1829
c4f7ba80
AD
1830 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1831 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
c2167866
AD
1832 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1833 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
be0801a1 1834
f1f3a642
AD
1835 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1836 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
7d12b6c8 1837 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
30b6ee8c 1838 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 1839
c4f7ba80 1840 $params[strtolower($param)] = (int) get_pref($link, $param);
f1f3a642 1841 }
40496720 1842
c4f7ba80
AD
1843 $params["icons_url"] = ICONS_URL;
1844 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
1845 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1846 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1847 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
c4f7ba80 1848 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
59b223d7 1849
8cd576a1 1850 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
1851 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1852
8cd576a1
AD
1853 $max_feed_id = db_fetch_result($result, 0, "mid");
1854 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 1855
8cd576a1 1856 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 1857 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 1858
c4f7ba80 1859 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
b8cb4d08 1860 $params["hotkeys"] = get_hotkeys_map($link);
9b7ecc0a 1861
8484ce22 1862 $params["csrf_token"] = $_SESSION["csrf_token"];
7d8f5657 1863 $params["widescreen"] = (int) $_SESSION["widescreen"];
8484ce22 1864
6b1a4ecd 1865 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
8b83bf5f 1866
d8221301 1867 return $params;
3ac2b520 1868 }
f54f515f 1869
b8cb4d08
AD
1870 function get_hotkeys_info($link) {
1871 $hotkeys = array(
1872 __("Navigation") => array(
1873 "next_feed" => __("Open next feed"),
1874 "prev_feed" => __("Open previous feed"),
1875 "next_article" => __("Open next article"),
1876 "prev_article" => __("Open previous article"),
1877 "search_dialog" => __("Show search dialog")),
1878 __("Article") => array(
1879 "toggle_mark" => __("Toggle starred"),
1880 "toggle_publ" => __("Toggle published"),
1881 "toggle_unread" => __("Toggle unread"),
1882 "edit_tags" => __("Edit tags"),
1883 "dismiss_selected" => __("Dismiss selected"),
1884 "dismiss_read" => __("Dismiss read"),
1885 "open_in_new_window" => __("Open in new window"),
1886 "catchup_below" => __("Mark below as read"),
1887 "catchup_above" => __("Mark above as read"),
1888 "article_scroll_down" => __("Scroll down"),
1889 "article_scroll_up" => __("Scroll up"),
1890 "select_article_cursor" => __("Select article under cursor"),
1bcf8f45 1891 "email_article" => __("Email article"),
2cda4314 1892 "close_article" => __("Close article"),
1bcf8f45 1893 "toggle_widescreen" => __("Toggle widescreen mode")),
b8cb4d08
AD
1894 __("Article selection") => array(
1895 "select_all" => __("Select all articles"),
1896 "select_unread" => __("Select unread"),
1897 "select_marked" => __("Select starred"),
1898 "select_published" => __("Select published"),
1899 "select_invert" => __("Invert selection"),
1900 "select_none" => __("Deselect everything")),
1901 __("Feed") => array(
1902 "feed_refresh" => __("Refresh current feed"),
1903 "feed_unhide_read" => __("Un/hide read feeds"),
1904 "feed_subscribe" => __("Subscribe to feed"),
1905 "feed_edit" => __("Edit feed"),
1906 "feed_catchup" => __("Mark as read"),
1907 "feed_reverse" => __("Reverse headlines"),
43f775de 1908 "feed_debug_update" => __("Debug feed update"),
b8cb4d08
AD
1909 "catchup_all" => __("Mark all feeds as read"),
1910 "cat_toggle_collapse" => __("Un/collapse current category")),
1911 __("Go to") => array(
1912 "goto_all" => __("All articles"),
1913 "goto_fresh" => __("Fresh"),
1914 "goto_marked" => __("Starred"),
1915 "goto_published" => __("Published"),
1916 "goto_tagcloud" => __("Tag cloud"),
1917 "goto_prefs" => __("Preferences")),
1918 __("Other") => array(
1919 "create_label" => __("Create label"),
1920 "create_filter" => __("Create filter"),
1921 "collapse_sidebar" => __("Un/collapse sidebar"),
1922 "help_dialog" => __("Show help dialog"))
1923 );
1924
1925 return $hotkeys;
1926 }
1927
1928 function get_hotkeys_map($link) {
a83b58f1 1929 $hotkeys = array(
e218c5f5
AD
1930// "navigation" => array(
1931 "k" => "next_feed",
1932 "j" => "prev_feed",
1933 "n" => "next_article",
1934 "p" => "prev_article",
e5e2cf3b
AD
1935 "(38)|up" => "prev_article",
1936 "(40)|down" => "next_article",
1937 "(191)|/" => "search_dialog",
e218c5f5
AD
1938// "article" => array(
1939 "s" => "toggle_mark",
1940 "S" => "toggle_publ",
1941 "u" => "toggle_unread",
1942 "T" => "edit_tags",
1943 "D" => "dismiss_selected",
1944 "X" => "dismiss_read",
1945 "o" => "open_in_new_window",
1946 "c p" => "catchup_below",
1947 "c n" => "catchup_above",
1948 "N" => "article_scroll_down",
1949 "P" => "article_scroll_up",
1bcf8f45 1950 "a W" => "toggle_widescreen",
e218c5f5 1951 "e" => "email_article",
2cda4314 1952 "a q" => "close_article",
e218c5f5
AD
1953// "article_selection" => array(
1954 "a a" => "select_all",
1955 "a u" => "select_unread",
1956 "a U" => "select_marked",
1957 "a p" => "select_published",
1958 "a i" => "select_invert",
1959 "a n" => "select_none",
1960// "feed" => array(
1961 "f r" => "feed_refresh",
1962 "f a" => "feed_unhide_read",
1963 "f s" => "feed_subscribe",
1964 "f e" => "feed_edit",
1965 "f q" => "feed_catchup",
1966 "f x" => "feed_reverse",
1967 "f D" => "feed_debug_update",
1968 "Q" => "catchup_all",
1969 "x" => "cat_toggle_collapse",
1970// "goto" => array(
1971 "g a" => "goto_all",
1972 "g f" => "goto_fresh",
1973 "g s" => "goto_marked",
1974 "g p" => "goto_published",
1975 "g t" => "goto_tagcloud",
1976 "g P" => "goto_prefs",
1977// "other" => array(
3fb40112 1978 "(9)|Tab" => "select_article_cursor", // tab
e218c5f5
AD
1979 "c l" => "create_label",
1980 "c f" => "create_filter",
1981 "c s" => "collapse_sidebar",
3fb40112 1982 "^(191)|Ctrl+/" => "help_dialog",
a83b58f1
AD
1983 );
1984
e218c5f5
AD
1985 global $pluginhost;
1986 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
1987 $hotkeys = $plugin->hook_hotkey_map($hotkeys);
1988 }
1989
1990 $prefixes = array();
1991
1992 foreach (array_keys($hotkeys) as $hotkey) {
1993 $pair = explode(" ", $hotkey, 2);
1994
1995 if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
1996 array_push($prefixes, $pair[0]);
1997 }
1998 }
1999
2000 return array($prefixes, $hotkeys);
a83b58f1
AD
2001 }
2002
c4f7ba80 2003 function make_runtime_info($link) {
8cd576a1
AD
2004 $data = array();
2005
2006 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
2007 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2008
8cd576a1
AD
2009 $max_feed_id = db_fetch_result($result, 0, "mid");
2010 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 2011
8cd576a1
AD
2012 $data["max_feed_id"] = (int) $max_feed_id;
2013 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 2014
f8fb4498 2015 $data['last_article_id'] = getLastArticleId($link);
5ae8f858 2016 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
f8fb4498 2017
dbaa4e4a 2018 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
2019
2020 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 2021
9041f58b 2022 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 2023
fb074239 2024 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 2025
8e00ae9b 2026 if ($stamp) {
9041f58b
AD
2027 $stamp_delta = time() - $stamp;
2028
2029 if ($stamp_delta > 1800) {
f6854e44 2030 $stamp_check = 0;
8e00ae9b 2031 } else {
f6854e44
AD
2032 $stamp_check = 1;
2033 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
2034 }
2035
c4f7ba80 2036 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 2037
8e00ae9b
AD
2038 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2039
c4f7ba80 2040 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 2041 }
8e00ae9b 2042 }
71ad883b 2043 }
8e00ae9b 2044
63855db1 2045 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
fb074239 2046 $new_version_details = @check_for_update($link);
d9fa39f1 2047
63855db1 2048 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
2049
2050 $_SESSION["last_version_check"] = time();
27211afe 2051 $_SESSION["version_data"] = $new_version_details;
d9fa39f1
AD
2052 }
2053
c4f7ba80 2054 return $data;
f54f515f 2055 }
ef393de7 2056
b7d1a163 2057 function search_to_sql($link, $search, $match_on) {
ef393de7 2058
88040f57 2059 $search_query_part = "";
e20c9d88 2060
9949bd15 2061 $keywords = explode(" ", $search);
88040f57 2062 $query_keywords = array();
e20c9d88 2063
ab4b768f
AD
2064 foreach ($keywords as $k) {
2065 if (strpos($k, "-") === 0) {
2066 $k = substr($k, 1);
2067 $not = "NOT";
2068 } else {
2069 $not = "";
88040f57 2070 }
e20c9d88 2071
9949bd15 2072 $commandpair = explode(":", mb_strtolower($k), 2);
53003548
AD
2073
2074 if ($commandpair[0] == "note" && $commandpair[1]) {
2075
2076 if ($commandpair[1] == "true")
2077 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2078 else
2079 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2080
2081 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2082
2083 if ($commandpair[1] == "true")
2084 array_push($query_keywords, "($not (marked = true))");
2085 else
2086 array_push($query_keywords, "($not (marked = false))");
2087
2088 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2089
2090 if ($commandpair[1] == "true")
2091 array_push($query_keywords, "($not (published = true))");
2092 else
2093 array_push($query_keywords, "($not (published = false))");
2094
2095 } else if (strpos($k, "@") === 0) {
e20c9d88 2096
ab4b768f
AD
2097 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2098 $orig_ts = strtotime(substr($k, 1));
ab4b768f 2099 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 2100
53003548
AD
2101 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2102
ab4b768f
AD
2103 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2104 } else if ($match_on == "both") {
2105 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2106 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2107 } else if ($match_on == "title") {
eb6c7f42 2108 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
ab4b768f 2109 } else if ($match_on == "content") {
eb6c7f42 2110 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
88040f57
AD
2111 }
2112 }
2113
2114 $search_query_part = implode("AND", $query_keywords);
2115
2116 return $search_query_part;
2117 }
2118
67bd0b1f
AD
2119 function getParentCategories($link, $cat, $owner_uid) {
2120 $rv = array();
2121
2122 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2123 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2124
2125 while ($line = db_fetch_assoc($result)) {
2126 array_push($rv, $line["parent_cat"]);
2127 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2128 }
2129
2130 return $rv;
2131 }
2132
6d8d00e8
AD
2133 function getChildCategories($link, $cat, $owner_uid) {
2134 $rv = array();
2135
2136 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2137 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2138
2139 while ($line = db_fetch_assoc($result)) {
2140 array_push($rv, $line["id"]);
2141 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2142 }
2143
2144 return $rv;
2145 }
147f5632 2146
09101297 2147 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) {
c36bf4d5
AD
2148
2149 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 2150
c3fddd05
AD
2151 $ext_tables_part = "";
2152
88040f57 2153 if ($search) {
e4f7f8df
AD
2154
2155 if (SPHINX_ENABLED) {
2156 $ids = join(",", @sphinx_search($search, 0, 500));
2157
8d505d78 2158 if ($ids)
e4f7f8df
AD
2159 $search_query_part = "ref_id IN ($ids) AND ";
2160 else
2161 $search_query_part = "ref_id = -1 AND ";
2162
2163 } else {
b7d1a163 2164 $search_query_part = search_to_sql($link, $search, $match_on);
e4f7f8df 2165 $search_query_part .= " AND ";
8d505d78 2166 }
e20c9d88 2167
ef393de7
AD
2168 } else {
2169 $search_query_part = "";
2170 }
2171
36184020 2172 if ($filter) {
4e02f582
AD
2173
2174 if (DB_TYPE == "pgsql") {
2175 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2176 } else {
2177 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2178 }
2179
2180 $override_order = "updated DESC";
2181
2680295b 2182 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
dd8c36af
AD
2183
2184 // Try to check if SQL regexp implementation chokes on a valid regexp
809c8e62 2185 $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
2680295b 2186 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
dd8c36af
AD
2187 WHERE $filter_query_part LIMIT 1", false);
2188
809c8e62 2189 $test = db_fetch_result($result, 0, "true_val");
dd8c36af
AD
2190
2191 if (!$test) {
2192 $filter_query_part = "false AND";
2193 } else {
2194 $filter_query_part .= " AND";
2195 }
2196
36184020
AD
2197 } else {
2198 $filter_query_part = "";
2199 }
2200
97e5dbb2
AD
2201 if ($since_id) {
2202 $since_id_part = "ttrss_entries.id > $since_id AND ";
2203 } else {
2204 $since_id_part = "";
2205 }
2206
ef393de7 2207 $view_query_part = "";
8d505d78 2208
7b4d02a8 2209 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
ef393de7
AD
2210 if ($search) {
2211 $view_query_part = " ";
2212 } else if ($feed != -1) {
f295c368 2213 $unread = getFeedUnread($link, $feed, $cat_view);
6d8d00e8 2214
09101297 2215 if ($cat_view && $feed > 0 && $include_children)
99c9e91a 2216 $unread += getCategoryChildrenUnread($link, $feed);
6d8d00e8 2217
ef393de7 2218 if ($unread > 0) {
ff863e00 2219 $view_query_part = " unread = true AND ";
ef393de7
AD
2220 }
2221 }
2222 }
8d505d78 2223
ef393de7
AD
2224 if ($view_mode == "marked") {
2225 $view_query_part = " marked = true AND ";
2226 }
23d72f39
AD
2227
2228 if ($view_mode == "published") {
2229 $view_query_part = " published = true AND ";
2230 }
2231
ef393de7
AD
2232 if ($view_mode == "unread") {
2233 $view_query_part = " unread = true AND ";
2234 }
8b09eac8
AD
2235
2236 if ($view_mode == "updated") {
2237 $view_query_part = " (last_read is null and unread = false) AND ";
2238 }
2239
ef393de7
AD
2240 if ($limit > 0) {
2241 $limit_query_part = "LIMIT " . $limit;
8d505d78 2242 }
ef393de7 2243
8361e724
AD
2244 $allow_archived = false;
2245
ef393de7 2246 $vfeed_query_part = "";
8d505d78 2247
ef393de7
AD
2248 // override query strategy and enable feed display when searching globally
2249 if ($search && $search_mode == "all_feeds") {
7032f2a5 2250 $query_strategy_part = "true";
8d505d78 2251 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 2252 /* tags */
75c648cf 2253 } else if (!is_numeric($feed)) {
7032f2a5 2254 $query_strategy_part = "true";
ef393de7
AD
2255 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2256 id = feed_id) as feed_title,";
7032f2a5 2257 } else if ($search && $search_mode == "this_cat") {
8d505d78 2258 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846 2259
7032f2a5
AD
2260 if ($feed > 0) {
2261 if ($include_children) {
2262 $subcats = getChildCategories($link, $feed, $owner_uid);
2263 array_push($subcats, $feed);
2264 $cats_qpart = join(",", $subcats);
2265 } else {
2266 $cats_qpart = $feed;
ef393de7 2267 }
8d505d78 2268
7032f2a5 2269 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
8d505d78 2270
ef393de7 2271 } else {
7032f2a5 2272 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
ef393de7 2273 }
8d505d78 2274
e04c18a2 2275 } else if ($feed > 0) {
8d505d78 2276
ef393de7 2277 if ($cat_view) {
5c365f60 2278
ef393de7 2279 if ($feed > 0) {
09101297
AD
2280 if ($include_children) {
2281 # sub-cats
2282 $subcats = getChildCategories($link, $feed, $owner_uid);
2283
7032f2a5
AD
2284 array_push($subcats, $feed);
2285 $query_strategy_part = "cat_id IN (".
09101297 2286 implode(",", $subcats).")";
7032f2a5 2287
6d8d00e8 2288 } else {
09101297 2289 $query_strategy_part = "cat_id = '$feed'";
6d8d00e8
AD
2290 }
2291
ef393de7
AD
2292 } else {
2293 $query_strategy_part = "cat_id IS NULL";
2294 }
8d505d78 2295
ef393de7 2296 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 2297
8d505d78 2298 } else {
6e63a7c3 2299 $query_strategy_part = "feed_id = '$feed'";
ef393de7 2300 }
bfe5ddfc 2301 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 2302 $query_strategy_part = "feed_id IS NULL";
8361e724 2303 $allow_archived = true;
bfe5ddfc 2304 } else if ($feed == 0 && $cat_view) { // uncategorized
65dd90f2 2305 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
bfe5ddfc 2306 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2307 } else if ($feed == -1) { // starred virtual feed
2308 $query_strategy_part = "marked = true";
2309 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294
AD
2310 $allow_archived = true;
2311
e6a38cde
AD
2312 } else if ($feed == -2) { // published virtual feed OR labels category
2313
2314 if (!$cat_view) {
2315 $query_strategy_part = "published = true";
2316 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
8361e724 2317 $allow_archived = true;
46b78149
AD
2318
2319 if (!$override_order) $override_order = "last_read DESC, updated DESC";
e6a38cde
AD
2320 } else {
2321 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2322
2323 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 2324
e6a38cde
AD
2325 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2326 ttrss_user_labels2.article_id = ref_id";
2327
2328 }
5417fbd7 2329 } else if ($feed == -6) { // recently read
5089b30b 2330 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
5417fbd7 2331 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294 2332 $allow_archived = true;
46b78149
AD
2333
2334 if (!$override_order) $override_order = "last_read DESC";
2d24f032 2335 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 2336 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 2337
7a22dc2a 2338 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2339
2d24f032 2340 if (DB_TYPE == "pgsql") {
8d505d78 2341 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2342 } else {
7608b38a 2343 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
2344 }
2345
b2531a28
AD
2346 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2347 } else if ($feed == -4) { // all articles virtual feed
2348 $query_strategy_part = "true";
e4f4b46f 2349 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2350 } else if ($feed <= -10) { // labels
2351 $label_id = -$feed - 11;
3de0261a 2352
ceb30ba4
AD
2353 $query_strategy_part = "label_id = '$label_id' AND
2354 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2355 ttrss_user_labels2.article_id = ref_id";
3de0261a 2356
ef393de7 2357 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 2358 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
835fb294 2359 $allow_archived = true;
8d505d78 2360
ef393de7 2361 } else {
835fb294 2362 $query_strategy_part = "true";
ef393de7 2363 }
d6e5706d 2364
b3990c92
AD
2365 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2366 $date_sort_field = "updated";
2367 } else {
2368 $date_sort_field = "date_entered";
2369 }
2370
7a22dc2a 2371 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
b3990c92 2372 $order_by = "$date_sort_field";
8d505d78 2373 } else {
b3990c92 2374 $order_by = "$date_sort_field DESC";
d6e5706d 2375 }
e939722a 2376
7b4d02a8
AD
2377 if ($view_mode != "noscores") {
2378 $order_by = "score DESC, $order_by";
2379 }
48b0c4ec 2380
e939722a
AD
2381 if ($override_order) {
2382 $order_by = $override_order;
2383 }
8d505d78 2384
ef393de7
AD
2385 $feed_title = "";
2386
22fdebff 2387 if ($search) {
7032f2a5 2388 $feed_title = T_sprintf("Search results: %s", $search);
22fdebff 2389 } else {
ef393de7 2390 if ($cat_view) {
22fdebff 2391 $feed_title = getCategoryTitle($link, $feed);
ef393de7 2392 } else {
147f5632 2393 if (is_numeric($feed) && $feed > 0) {
8d505d78 2394 $result = db_query($link, "SELECT title,site_url,last_error
22fdebff 2395 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2396
22fdebff
AD
2397 $feed_title = db_fetch_result($result, 0, "title");
2398 $feed_site_url = db_fetch_result($result, 0, "site_url");
2399 $last_error = db_fetch_result($result, 0, "last_error");
2400 } else {
2401 $feed_title = getFeedTitle($link, $feed);
8d505d78 2402 }
88040f57 2403 }
ef393de7
AD
2404 }
2405
87764a50 2406 $content_query_part = "content as content_preview, cached_content, ";
62129e67 2407
75c648cf 2408 if (is_numeric($feed)) {
8d505d78 2409
ef393de7
AD
2410 if ($feed >= 0) {
2411 $feed_kind = "Feeds";
2412 } else {
2413 $feed_kind = "Labels";
2414 }
8d505d78 2415
95a82c08
AD
2416 if ($limit_query_part) {
2417 $offset_query_part = "OFFSET $offset";
2418 }
2419
7fdf8eca 2420 // proper override_order applied above
d00f22ac 2421 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 2422 if (!$override_order) {
8d505d78 2423 $order_by = "ttrss_feeds.title, $order_by";
7fdf8eca
AD
2424 } else {
2425 $order_by = "ttrss_feeds.title, $override_order";
43fc671f 2426 }
6cfea5c7
AD
2427 }
2428
8361e724 2429 if (!$allow_archived) {
e04c18a2 2430 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 2431 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2432
2433 } else {
835fb294 2434 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
e04c18a2
AD
2435 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2436 }
2437
8d505d78 2438 $query = "SELECT DISTINCT
f9b2d27c 2439 date_entered,
1f64b1be 2440 guid,
ef393de7 2441 ttrss_entries.id,ttrss_entries.title,
46921916 2442 updated,
9c506873
AD
2443 label_cache,
2444 tag_cache,
c0644ee4 2445 always_display_enclosures,
d1fc2f92 2446 site_url,
c7e51de1 2447 note,
13992673
AD
2448 num_comments,
2449 comments,
db16ae50 2450 int_id,
494a64ea 2451 unread,feed_id,marked,published,link,last_read,orig_feed_id,
fc2b26a6 2452 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
ef393de7
AD
2453 $vfeed_query_part
2454 $content_query_part
fc2b26a6 2455 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
ff6e357a 2456 author,score
ef393de7 2457 FROM
e04c18a2 2458 $from_qpart
ef393de7 2459 WHERE
e04c18a2 2460 $feed_check_qpart
ef393de7 2461 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 2462 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 2463 $search_query_part
36184020 2464 $filter_query_part
ef393de7 2465 $view_query_part
97e5dbb2 2466 $since_id_part
ef393de7 2467 $query_strategy_part ORDER BY $order_by
95a82c08 2468 $limit_query_part $offset_query_part";
4bc311fc 2469
b4e75b2a 2470 if ($_REQUEST["debug"]) print $query;
4bc311fc
AD
2471
2472 $result = db_query($link, $query);
8d505d78 2473
ef393de7
AD
2474 } else {
2475 // browsing by tag
8d505d78 2476
147f5632
CM
2477 $select_qpart = "SELECT DISTINCT " .
2478 "date_entered," .
2479 "guid," .
2480 "note," .
2481 "ttrss_entries.id as id," .
2482 "title," .
2483 "updated," .
2484 "unread," .
2485 "feed_id," .
2486 "orig_feed_id," .
2487 "marked," .
d1fc2f92
AD
2488 "num_comments, " .
2489 "comments, " .
c0644ee4
AD
2490 "tag_cache," .
2491 "label_cache," .
147f5632
CM
2492 "link," .
2493 "last_read," .
2494 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
97e5dbb2 2495 $since_id_part .
147f5632
CM
2496 $vfeed_query_part .
2497 $content_query_part .
2498 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
2499 "score ";
2500
ef393de7 2501 $feed_kind = "Tags";
147f5632
CM
2502 $all_tags = explode(",", $feed);
2503 if ($search_mode == 'any') {
2504 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2505 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2506 $where_qpart = " WHERE " .
2507 "ref_id = ttrss_entries.id AND " .
2508 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2509 "post_int_id = int_id AND $tag_sql AND " .
2510 $view_query_part .
2511 $search_query_part .
2512 $query_strategy_part . " ORDER BY $order_by " .
2513 $limit_query_part;
8d505d78 2514
147f5632
CM
2515 } else {
2516 $i = 1;
2517 $sub_selects = array();
2518 $sub_ands = array();
2519 foreach ($all_tags as $term) {
2520 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");
2521 $i++;
2522 }
2523 if ($i > 2) {
2524 $x = 1;
2525 $y = 2;
2526 do {
2527 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2528 $x++;
2529 $y++;
2530 } while ($y < $i);
2531 }
2532 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2533 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2534 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2535 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2536 }
2537 // error_log("TAG SQL: " . $tag_sql);
2538 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2539
2540 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2541 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
ef393de7
AD
2542 }
2543
c7188969 2544 return array($result, $feed_title, $feed_site_url, $last_error);
8d505d78 2545
ef393de7
AD
2546 }
2547
b3682750 2548 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
ceb0cab5
AD
2549 if (!$owner) $owner = $_SESSION["uid"];
2550
96811a55
AD
2551 $res = trim($str); if (!$res) return '';
2552
d8858f27 2553 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
acccafe3 2554 $res = htmLawed($res, $config);
f826eee1 2555
ceb0cab5 2556 if (get_pref($link, "STRIP_IMAGES", $owner)) {
8dccabed 2557 $res = preg_replace('/<img[^>]+>/is', '', $res);
7514749d 2558 }
8dccabed 2559
46137483
AD
2560 if (strpos($res, "href=") === false)
2561 $res = rewrite_urls($res);
533c0ea6 2562
8cc3c778
AD
2563 $charset_hack = '<head>
2564 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2565 </head>';
2566
96811a55
AD
2567 $res = trim($res); if (!$res) return '';
2568
8cc3c778
AD
2569 libxml_use_internal_errors(true);
2570
2571 $doc = new DOMDocument();
2572 $doc->loadHTML($charset_hack . $res);
2573 $xpath = new DOMXPath($doc);
8d505d78 2574
8cc3c778 2575 $entries = $xpath->query('(//a[@href]|//img[@src])');
3f770c87 2576 $br_inserted = 0;
8cc3c778
AD
2577
2578 foreach ($entries as $entry) {
2579
2580 if ($site_url) {
2581
2582 if ($entry->hasAttribute('href'))
2583 $entry->setAttribute('href',
2584 rewrite_relative_url($site_url, $entry->getAttribute('href')));
8d505d78 2585
8cc3c778 2586 if ($entry->hasAttribute('src'))
8d505d78 2587 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
b8998470
AD
2588 $entry->setAttribute('src',
2589 rewrite_relative_url($site_url, $entry->getAttribute('src')));
8cc3c778
AD
2590 }
2591
fa403733 2592 if (strtolower($entry->nodeName) == "a") {
c401d5c9 2593 $entry->setAttribute("target", "_blank");
fa403733
AD
2594 }
2595
3f770c87 2596 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
fa403733
AD
2597 $br = $doc->createElement("br");
2598
3f770c87 2599 if ($entry->parentNode->nextSibling) {
fa403733 2600 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3f770c87
AD
2601 $br_inserted = 1;
2602 }
fa403733 2603
8cc3c778 2604 }
8dccabed 2605 }
8d505d78 2606
1f6131f5 2607 $node = $doc->getElementsByTagName('body')->item(0);
8dccabed 2608
c5bb0440 2609 // http://tt-rss.org/redmine/issues/357
ec6732f4 2610 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
183ad07b 2611 }
b72c3ef8 2612
73495fd1 2613 function check_for_update($link) {
63855db1
AD
2614 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2615 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
b72c3ef8 2616
63855db1 2617 $version_data = @fetch_file_contents($version_url);
b72c3ef8 2618
63855db1
AD
2619 if ($version_data) {
2620 $version_data = json_decode($version_data, true);
8d505d78 2621 if ($version_data && $version_data['version']) {
f67d9754 2622
63855db1 2623 if (version_compare(VERSION, $version_data['version']) == -1) {
e91ad1e9 2624 return $version_data;
63855db1
AD
2625 }
2626 }
f67d9754 2627 }
b72c3ef8 2628 }
63855db1 2629 return false;
b72c3ef8 2630 }
472782e8 2631
9968d46f
AD
2632 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2633
2634 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 2635 if (count($ids) == 0) return;
472782e8
AD
2636
2637 $tmp_ids = array();
2638
2639 foreach ($ids as $id) {
2640 array_push($tmp_ids, "ref_id = '$id'");
2641 }
2642
2643 $ids_qpart = join(" OR ", $tmp_ids);
2644
2645 if ($cmode == 0) {
8d505d78 2646 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2647 unread = false,last_read = NOW()
9968d46f 2648 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2649 } else if ($cmode == 1) {
8d505d78 2650 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2651 unread = true
9968d46f 2652 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2653 } else {
8d505d78 2654 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2655 unread = NOT unread,last_read = NOW()
9968d46f 2656 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2657 }
0737b95a
AD
2658
2659 /* update ccache */
2660
2661 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2662 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2663
2664 while ($line = db_fetch_assoc($result)) {
2665 ccache_update($link, $line["feed_id"], $owner_uid);
2666 }
472782e8
AD
2667 }
2668
ca5133cb 2669 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
0b126ac2
AD
2670
2671 $a_id = db_escape_string($id);
2672
bc976a8c
AD
2673 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2674
8d505d78 2675 $query = "SELECT DISTINCT tag_name,
0c3d1c68 2676 owner_uid as owner FROM
0b126ac2 2677 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 2678 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 2679
bd3f2ade 2680 $obj_id = md5("TAGS:$owner_uid:$id");
8d505d78 2681 $tags = array();
bd3f2ade 2682
0e4a7d7a 2683 /* check cache first */
490c366d 2684
0e4a7d7a
AD
2685 if ($tag_cache === false) {
2686 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2687 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
490c366d 2688
0e4a7d7a
AD
2689 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2690 }
bd3f2ade 2691
0e4a7d7a
AD
2692 if ($tag_cache) {
2693 $tags = explode(",", $tag_cache);
2694 } else {
490c366d 2695
0e4a7d7a 2696 /* do it the hard way */
490c366d 2697
0e4a7d7a 2698 $tmp_result = db_query($link, $query);
490c366d 2699
0e4a7d7a
AD
2700 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2701 array_push($tags, $tmp_line["tag_name"]);
2702 }
490c366d 2703
0e4a7d7a 2704 /* update the cache */
490c366d 2705
0e4a7d7a 2706 $tags_str = db_escape_string(join(",", $tags));
bd3f2ade 2707
0e4a7d7a
AD
2708 db_query($link, "UPDATE ttrss_user_entries
2709 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2710 AND owner_uid = $owner_uid");
0b126ac2
AD
2711 }
2712
2713 return $tags;
2714 }
2715
d62a3b63
AD
2716 function trim_array($array) {
2717 $tmp = $array;
3415b075 2718 array_walk($tmp, 'trim');
d62a3b63
AD
2719 return $tmp;
2720 }
2721
be832a1a 2722 function tag_is_valid($tag) {
ef063748
AD
2723 if ($tag == '') return false;
2724 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 2725 if (mb_strlen($tag) > 250) return false;
ef063748 2726
31365729
AD
2727 if (function_exists('iconv')) {
2728 $tag = iconv("utf-8", "utf-8", $tag);
2729 }
2730
ef063748
AD
2731 if (!$tag) return false;
2732
2733 return true;
be832a1a
AD
2734 }
2735
97acbaf1
AD
2736 function render_login_form($link, $form_id = 0) {
2737 switch ($form_id) {
afb12ed0 2738 case 0:
793185a9 2739 require_once "login_form.php";
afb12ed0
AD
2740 break;
2741 case 1:
793185a9 2742 require_once "mobile/login_form.php";
afb12ed0 2743 break;
793185a9 2744 }
97acbaf1 2745 exit;
01a87dff
AD
2746 }
2747
dc56b3b7
AD
2748 // from http://developer.apple.com/internet/safari/faq.html
2749 function no_cache_incantation() {
2750 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2751 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2752 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2753 header("Cache-Control: post-check=0, pre-check=0", false);
2754 header("Pragma: no-cache"); // HTTP/1.0
2755 }
2756
42395d28 2757 function format_warning($msg, $id = "") {
883fee8d 2758 global $link;
8d505d78 2759 return "<div class=\"warning\" id=\"$id\">
c2167866 2760 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
0d32b41e
AD
2761 }
2762
08ac193a 2763 function format_notice($msg, $id = "") {
883fee8d 2764 global $link;
8d505d78 2765 return "<div class=\"notice\" id=\"$id\">
c2167866 2766 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
0d32b41e
AD
2767 }
2768
08ac193a 2769 function format_error($msg, $id = "") {
883fee8d 2770 global $link;
8d505d78 2771 return "<div class=\"error\" id=\"$id\">
c2167866 2772 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
68d2f95e
AD
2773 }
2774
4dccf1ed
AD
2775 function print_notice($msg) {
2776 return print format_notice($msg);
2777 }
2778
2779 function print_warning($msg) {
2780 return print format_warning($msg);
2781 }
2782
68d2f95e
AD
2783 function print_error($msg) {
2784 return print format_error($msg);
2785 }
2786
2787
4dccf1ed
AD
2788 function T_sprintf() {
2789 $args = func_get_args();
2790 return vsprintf(__(array_shift($args)), $args);
2791 }
2792
51682b23
AD
2793 function format_inline_player($link, $url, $ctype) {
2794
2795 $entry = "";
2796
8d505d78 2797 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
2798
2799 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
8d505d78 2800 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
c3edc667
AD
2801 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2802
2803 $id = 'AUDIO-' . uniqid();
2804
ca3bca99
AD
2805 $entry .= "<audio id=\"$id\"\" controls>
2806 <source type=\"$ctype\" src=\"$url\"></source>
8d505d78 2807 </audio>";
c3edc667 2808
8d505d78 2809 $entry .= "<span onclick=\"player(this)\"
c3edc667
AD
2810 title=\"".__("Click to play")."\" status=\"0\"
2811 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2812
2813 } else {
8d505d78
AD
2814
2815 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 2816 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
2817 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2818 <param name=\"movie\"
ad95edc2 2819 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 2820 </object>";
c3edc667 2821 }
ca3bca99
AD
2822
2823 if ($entry) $entry .= "&nbsp;" . basename($url);
2824
2825 return $entry;
2826
51682b23
AD
2827 }
2828
ca3bca99
AD
2829 return "";
2830
2831/* $filename = substr($url, strrpos($url, "/")+1);
c3edc667
AD
2832
2833 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
ca3bca99 2834 $filename . " (" . $ctype . ")" . "</a>"; */
c3edc667 2835
51682b23
AD
2836 }
2837
64436e10 2838 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
64436e10 2839 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3de0261a 2840
009646d2
AD
2841 $rv = array();
2842
2843 $rv['id'] = $id;
2844
10eb9da8 2845 /* we can figure out feed_id from article id anyway, why do we
e04c18a2 2846 * pass feed_id here? let's ignore the argument :( */
10eb9da8
AD
2847
2848 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2849 WHERE ref_id = '$id'");
2850
e04c18a2 2851 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 2852
009646d2
AD
2853 $rv['feed_id'] = $feed_id;
2854
2855 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 2856
87764a50 2857 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
64436e10 2858 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3de0261a
AD
2859
2860 if (db_num_rows($result) == 1) {
2861 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
54e61a68 2862 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
87764a50 2863 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
3de0261a
AD
2864 } else {
2865 $rtl_content = false;
54e61a68 2866 $always_display_enclosures = false;
87764a50 2867 $cache_content = false;
3de0261a
AD
2868 }
2869
2870 if ($rtl_content) {
2871 $rtl_tag = "dir=\"RTL\"";
2872 $rtl_class = "RTL";
2873 } else {
2874 $rtl_tag = "";
2875 $rtl_class = "";
2876 }
2877
2878 if ($mark_as_read) {
8d505d78
AD
2879 $result = db_query($link, "UPDATE ttrss_user_entries
2880 SET unread = false,last_read = NOW()
64436e10 2881 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
8a4c759e 2882
64436e10 2883 ccache_update($link, $feed_id, $owner_uid);
3de0261a
AD
2884 }
2885
7252abe3 2886 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
fc2b26a6 2887 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3de0261a 2888 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
8cc3c778 2889 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3de0261a 2890 num_comments,
9c506873 2891 tag_cache,
c7e51de1 2892 author,
ef83538d 2893 orig_feed_id,
87764a50
AD
2894 note,
2895 cached_content
3de0261a 2896 FROM ttrss_entries,ttrss_user_entries
64436e10 2897 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3de0261a
AD
2898
2899 if ($result) {
2900
3de0261a
AD
2901 $line = db_fetch_assoc($result);
2902
2903 if ($line["icon_url"]) {
8e289ca1 2904 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3de0261a
AD
2905 } else {
2906 $feed_icon = "&nbsp;";
2907 }
2908
8cc3c778
AD
2909 $feed_site_url = $line['site_url'];
2910
3de0261a
AD
2911 $num_comments = $line["num_comments"];
2912 $entry_comments = "";
2913
2914 if ($num_comments > 0) {
2915 if ($line["comments"]) {
6e577ba1 2916 $comments_url = htmlspecialchars($line["comments"]);
3de0261a 2917 } else {
6e577ba1 2918 $comments_url = htmlspecialchars($line["link"]);
3de0261a 2919 }
7514749d 2920 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3de0261a
AD
2921 } else {
2922 if ($line["comments"] && $line["link"] != $line["comments"]) {
6e577ba1 2923 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
8d505d78 2924 }
3de0261a
AD
2925 }
2926
eedfb635
AD
2927 if ($zoom_mode) {
2928 header("Content-Type: text/html");
009646d2 2929 $rv['content'] .= "<html><head>
5bb0cc8e 2930 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
eedfb635
AD
2931 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2932 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2933 </head><body>";
2934 }
2935
5c568973 2936 $title_escaped = htmlspecialchars($line['title']);
2ea9bbfd 2937
009646d2 2938 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
6f3976c9 2939 truncate_string(strip_tags($line['title']), 15) . "</div>";
eedfb635 2940
e54dbacb
AD
2941 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2942 strip_tags($line['title']) . "</div>";
2943
009646d2 2944 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 2945
009646d2 2946 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
bc372fe3 2947 class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
2948
2949 $entry_author = $line["author"];
2950
2951 if ($entry_author) {
60164936 2952 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
2953 }
2954
8d505d78 2955 $parsed_updated = make_local_datetime($link, $line["updated"], true,
64436e10 2956 $owner_uid, true);
324944f3 2957
009646d2 2958 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3de0261a
AD
2959
2960 if ($line["link"]) {
c6c010d9 2961 $rv['content'] .= "<div class='postTitle'><a target='_blank'
a64029e5 2962 title=\"".htmlspecialchars($line['title'])."\"
8d505d78 2963 href=\"" .
5c568973 2964 htmlspecialchars($line["link"]) . "\">" .
c6c010d9 2965 $line["title"] .
a64029e5 2966 "<span class='author'>$entry_author</span></a></div>";
3de0261a 2967 } else {
c6c010d9 2968 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
2969 }
2970
9c506873
AD
2971 $tag_cache = $line["tag_cache"];
2972
2973 if (!$tag_cache)
64436e10 2974 $tags = get_article_tags($link, $id, $owner_uid);
9c506873
AD
2975 else
2976 $tags = explode(",", $tag_cache);
2977
0780f4f4
AD
2978 $tags_str = format_tags_string($tags, $id);
2979 $tags_str_full = join(", ", $tags);
2980
2981 if (!$tags_str_full) $tags_str_full = __("no tags");
e7544143 2982
3de0261a
AD
2983 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
2984
f0755b7c 2985 $rv['content'] .= "<div class='postTags' style='float : right'>
8d505d78 2986 <img src='".theme_image($link, 'images/tag.png')."'
e9823609 2987 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
2988
2989 if (!$zoom_mode) {
009646d2 2990 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 2991 <a title=\"".__('Edit tags for this article')."\"
31a53903 2992 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 2993
0780f4f4
AD
2994 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
2995 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
2996 position=\"below\">$tags_str_full</div>";
2997
009646d2 2998 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
9ed0b90f 2999 class='tagsPic' style=\"cursor : pointer\"
ca07f49e 3000 onclick=\"postOpenInNewTab(event, $id)\"
6f3976c9 3001 alt='Zoom' title='".__('Open article in new tab')."'>";
c7e51de1 3002
19c73507 3003 global $pluginhost;
f9ac31d6 3004
19c73507
AD
3005 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
3006 $rv['content'] .= $p->hook_article_button($line);
411fe209
AD
3007 }
3008
6f3976c9 3009
24ecbcae
AD
3010 } else {
3011 $tags_str = strip_tags($tags_str);
009646d2 3012 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
eedfb635 3013 }
009646d2
AD
3014 $rv['content'] .= "</div>";
3015 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3de0261a 3016
ef83538d
AD
3017 if ($line["orig_feed_id"]) {
3018
3019 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3020 WHERE id = ".$line["orig_feed_id"]);
3021
3022 if (db_num_rows($tmp_result) != 0) {
3023
009646d2
AD
3024 $rv['content'] .= "<div clear='both'>";
3025 $rv['content'] .= __("Originally from:");
ef83538d 3026
009646d2 3027 $rv['content'] .= "&nbsp;";
ef83538d
AD
3028
3029 $tmp_line = db_fetch_assoc($tmp_result);
3030
009646d2 3031 $rv['content'] .= "<a target='_blank'
ef83538d
AD
3032 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3033 $tmp_line['title'] . "</a>";
3034
009646d2 3035 $rv['content'] .= "&nbsp;";
ef83538d 3036
009646d2 3037 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
c2167866 3038 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
ef83538d 3039
009646d2 3040 $rv['content'] .= "</div>";
ef83538d
AD
3041 }
3042 }
3043
009646d2 3044 $rv['content'] .= "</div>";
3de0261a 3045
009646d2 3046 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 3047 if ($line['note']) {
16cbc19a 3048 $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
c7e51de1 3049 }
009646d2 3050 $rv['content'] .= "</div>";
c7e51de1 3051
fcfa9ef1
AD
3052 $rv['content'] .= "<div class=\"postIcon\">" .
3053 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3054 href=\"".htmlspecialchars($feed_site_url)."\">".
3055 $feed_icon . "</a></div>";
3056
009646d2 3057 $rv['content'] .= "<div class=\"postContent\">";
741b6090 3058
d3d69daa
AD
3059 // N-grams
3060
6f4bd262 3061 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
d3d69daa
AD
3062
3063 $ngram_result = db_query($link, "SELECT id,title FROM
3064 ttrss_entries,ttrss_user_entries
3065 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
6f4bd262 3066 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
d3d69daa
AD
3067 AND title != '$title_escaped'
3068 AND owner_uid = $owner_uid");
3069
3070 if (db_num_rows($ngram_result) > 0) {
3071 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3072 "<span>" . __('Related')."</span>";
3073 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3074
3075 while ($nline = db_fetch_assoc($ngram_result)) {
3076 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3077 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3078
3079 }
3080 $rv['content'] .= "</div></div><br/";
3081 }
3082 }
3083
87764a50
AD
3084 if ($cache_content && $line["cached_content"] != "") {
3085 $line["content"] =& $line["cached_content"];
3086 }
3087
64436e10 3088 $article_content = sanitize($link, $line["content"], false, $owner_uid,
741b6090
AD
3089 $feed_site_url);
3090
009646d2 3091 $rv['content'] .= $article_content;
db54143e 3092
009646d2
AD
3093 $rv['content'] .= format_article_enclosures($link, $id,
3094 $always_display_enclosures, $article_content);
ce53e200 3095
009646d2 3096 $rv['content'] .= "</div>";
dad14b51 3097
009646d2 3098 $rv['content'] .= "</div>";
3de0261a
AD
3099
3100 }
3101
009646d2
AD
3102 if ($zoom_mode) {
3103 $rv['content'] .= "
eedfb635 3104 <div style=\"text-align : center\">
2ae69126
AD
3105 <button onclick=\"return window.close()\">".
3106 __("Close this window")."</button></div>";
009646d2 3107 $rv['content'] .= "</body></html>";
eedfb635 3108 }
3de0261a 3109
009646d2
AD
3110 return $rv;
3111
3de0261a
AD
3112 }
3113
79178062
AD
3114 function print_checkpoint($n, $s) {
3115 $ts = getmicrotime();
3116 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3117 return $ts;
3118 }
3de0261a 3119
79178062
AD
3120 function sanitize_tag($tag) {
3121 $tag = trim($tag);
52d7e7da 3122
79178062 3123 $tag = mb_strtolower($tag, 'utf-8');
bd202c3f 3124
79178062 3125 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
46921916 3126
79178062
AD
3127// $tag = str_replace('"', "", $tag);
3128// $tag = str_replace("+", " ", $tag);
3129 $tag = str_replace("technorati tag: ", "", $tag);
961f4c73 3130
79178062
AD
3131 return $tag;
3132 }
3de0261a 3133
79178062 3134 function get_self_url_prefix() {
51cc3873
AD
3135 if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
3136 return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
3137 } else {
3138 return SELF_URL_PATH;
3139 }
79178062 3140 }
a9bcfb8f 3141
45004d43
AD
3142 /**
3143 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3144 *
3145 * @return string The Mozilla Firefox feed adding URL.
3146 */
3147 function add_feed_url() {
ed102aa0
AD
3148 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3149
3150 $url_path = get_self_url_prefix() .
97acbaf1 3151 "/public.php?op=subscribe&feed_url=%s";
755a43ee 3152 return $url_path;
45004d43
AD
3153 } // function add_feed_url
3154
e90053fe
AD
3155 function encrypt_password($pass, $salt = '', $mode2 = false) {
3156 if ($salt && $mode2) {
3157 return "MODE2:" . hash('sha256', $salt . $pass);
3158 } else if ($salt) {
3159 return "SHA1X:" . sha1("$salt:$pass");
1a9f4d3c
AD
3160 } else {
3161 return "SHA1:" . sha1($pass);
3162 }
45004d43
AD
3163 } // function encrypt_password
3164
6aff7845 3165 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
fee840fb
AD
3166 $filters = array();
3167
5574b09e 3168 $cat_id = (int)getFeedCategory($link, $feed_id);
fee840fb 3169
6aff7845
AD
3170 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3171 owner_uid = $owner_uid AND enabled = true");
8d505d78 3172
67bd0b1f
AD
3173 $check_cats = join(",", array_merge(
3174 getParentCategories($link, $cat_id, $owner_uid),
3175 array($cat_id)));
3176
0e4a7d7a 3177 while ($line = db_fetch_assoc($result)) {
6aff7845
AD
3178 $filter_id = $line["id"];
3179
3180 $result2 = db_query($link, "SELECT
3181 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3182 FROM ttrss_filters2_rules AS r,
3183 ttrss_filter_types AS t
3184 WHERE
67bd0b1f 3185 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
6aff7845
AD
3186 (feed_id IS NULL OR feed_id = '$feed_id') AND
3187 filter_type = t.id AND filter_id = '$filter_id'");
3188
3189 $rules = array();
3190 $actions = array();
ba975b2e 3191
6aff7845
AD
3192 while ($rule_line = db_fetch_assoc($result2)) {
3193# print_r($rule_line);
8d505d78 3194
6aff7845
AD
3195 $rule = array();
3196 $rule["reg_exp"] = $rule_line["reg_exp"];
3197 $rule["type"] = $rule_line["type_name"];
3198
3199 array_push($rules, $rule);
3200 }
3201
3202 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3203 FROM ttrss_filters2_actions AS a,
3204 ttrss_filter_actions AS t
3205 WHERE
3206 action_id = t.id AND filter_id = '$filter_id'");
3207
3208 while ($action_line = db_fetch_assoc($result2)) {
3209# print_r($action_line);
3210
3211 $action = array();
3212 $action["type"] = $action_line["type_name"];
3213 $action["param"] = $action_line["action_param"];
3214
3215 array_push($actions, $action);
0e4a7d7a 3216 }
b8ffa322 3217
b8ffa322 3218
6aff7845
AD
3219 $filter = array();
3220 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3221 $filter["rules"] = $rules;
3222 $filter["actions"] = $actions;
3223
3224 if (count($rules) > 0 && count($actions) > 0) {
3225 array_push($filters, $filter);
3226 }
3227 }
3228
0e4a7d7a 3229 return $filters;
fee840fb 3230 }
1e36af0c
AD
3231
3232 function get_score_pic($score) {
8d505d78
AD
3233 if ($score > 100) {
3234 return "score_high.png";
3235 } else if ($score > 0) {
883fee8d 3236 return "score_half_high.png";
1cce3aca 3237 } else if ($score < -100) {
883fee8d 3238 return "score_low.png";
1cce3aca 3239 } else if ($score < 0) {
883fee8d 3240 return "score_half_low.png";
8d505d78 3241 } else {
883fee8d 3242 return "score_neutral.png";
1e36af0c
AD
3243 }
3244 }
ec92c9d1 3245
7defa089
AD
3246 function feed_has_icon($id) {
3247 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3248 }
f29ba148
AD
3249
3250 function init_connection($link) {
5f0a3741 3251 if ($link) {
324944f3 3252
5f0a3741
AD
3253 if (DB_TYPE == "pgsql") {
3254 pg_query($link, "set client_encoding = 'UTF-8'");
3255 pg_set_client_encoding("UNICODE");
3256 pg_query($link, "set datestyle = 'ISO, european'");
3257 pg_query($link, "set TIME ZONE 0");
3258 } else {
3259 db_query($link, "SET time_zone = '+0:0'");
3260
3261 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
3262 db_query($link, "SET NAMES " . MYSQL_CHARSET);
3263 }
f29ba148 3264 }
19c73507
AD
3265
3266 global $pluginhost;
3267
3268 $pluginhost = new PluginHost($link);
d2a421e3 3269 $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
19c73507 3270
5f0a3741
AD
3271 return true;
3272 } else {
3273 print "Unable to connect to database:" . db_last_error();
3274 return false;
f29ba148
AD
3275 }
3276 }
5e96ca9d 3277
307d187c
AD
3278 function format_tags_string($tags, $id) {
3279
3280 $tags_str = "";
3281 $tags_nolinks_str = "";
3282
3283 $num_tags = 0;
3284
d9084cf2 3285 $tag_limit = 6;
307d187c
AD
3286
3287 $formatted_tags = array();
3288
3289 foreach ($tags as $tag) {
3290 $num_tags++;
3291 $tag_escaped = str_replace("'", "\\'", $tag);
3292
275a0af2
AD
3293 if (mb_strlen($tag) > 30) {
3294 $tag = truncate_string($tag, 30);
3295 }
3296
307d187c
AD
3297 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3298
3299 array_push($formatted_tags, $tag_str);
275a0af2
AD
3300
3301 $tmp_tags_str = implode(", ", $formatted_tags);
8d505d78 3302
275a0af2 3303 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
307d187c
AD
3304 break;
3305 }
3306 }
3307
3308 $tags_str = implode(", ", $formatted_tags);
3309
3310 if ($num_tags < count($tags)) {
3311 $tags_str .= ", &hellip;";
3312 }
3313
3314 if ($num_tags == 0) {
3315 $tags_str = __("no tags");
3316 }
3317
3318 return $tags_str;
3319
3320 }
2eb9c95c
AD
3321
3322 function format_article_labels($labels, $id) {
3323
3324 $labels_str = "";
3325
3326 foreach ($labels as $l) {
8d505d78 3327 $labels_str .= sprintf("<span class='hlLabelRef'
2eb9c95c
AD
3328 style='color : %s; background-color : %s'>%s</span>",
3329 $l[2], $l[3], $l[1]);
3330 }
3331
3332 return $labels_str;
3333
3334 }
c7e51de1 3335
16cbc19a 3336 function format_article_note($id, $note, $allow_edit = true) {
c7e51de1 3337
fcfa9ef1
AD
3338 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3339 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
16cbc19a 3340 ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
c7e51de1
AD
3341
3342 return $str;
3343 }
7f969260 3344
fcf70c51 3345 function toggle_collapse_cat($link, $cat_id, $mode) {
7f969260 3346 if ($cat_id > 0) {
fcf70c51
AD
3347 $mode = bool_to_sql_bool($mode);
3348
7f969260 3349 db_query($link, "UPDATE ttrss_feed_categories SET
8d505d78 3350 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
7f969260
AD
3351 $_SESSION["uid"]);
3352 } else {
3353 $pref_name = '';
3354
3355 switch ($cat_id) {
3356 case -1:
3357 $pref_name = '_COLLAPSED_SPECIAL';
3358 break;
3359 case -2:
3360 $pref_name = '_COLLAPSED_LABELS';
3361 break;
3362 case 0:
3363 $pref_name = '_COLLAPSED_UNCAT';
3364 break;
3365 }
3366
3367 if ($pref_name) {
fcf70c51 3368 if ($mode) {
7f969260 3369 set_pref($link, $pref_name, 'true');
fcf70c51
AD
3370 } else {
3371 set_pref($link, $pref_name, 'false');
7f969260
AD
3372 }
3373 }
3374 }
3375 }
7e329f13 3376
7e329f13 3377
d2a317e3
AD
3378 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3379 if ($parent_cat_id) {
3380 $parent_qpart = "parent_cat = '$parent_cat_id'";
3381 $parent_insert = "'$parent_cat_id'";
3382 } else {
3383 $parent_qpart = "parent_cat IS NULL";
3384 $parent_insert = "NULL";
3385 }
3386
3387 $result = db_query($link,
3388 "SELECT id FROM ttrss_feed_categories
3389 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3390
3391 if (db_num_rows($result) == 0) {
3392 return false;
3393 } else {
3394 return db_fetch_result($result, 0, "id");
3395 }
3396 }
3397
3398 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
c00907f2
AD
3399
3400 if (!$feed_cat) return false;
3401
5c7c7da9
AD
3402 db_query($link, "BEGIN");
3403
d2a317e3
AD
3404 if ($parent_cat_id) {
3405 $parent_qpart = "parent_cat = '$parent_cat_id'";
3406 $parent_insert = "'$parent_cat_id'";
3407 } else {
3408 $parent_qpart = "parent_cat IS NULL";
3409 $parent_insert = "NULL";
3410 }
3411
5c7c7da9
AD
3412 $result = db_query($link,
3413 "SELECT id FROM ttrss_feed_categories
d2a317e3 3414 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
5c7c7da9
AD
3415
3416 if (db_num_rows($result) == 0) {
8d505d78 3417
5c7c7da9 3418 $result = db_query($link,
d2a317e3
AD
3419 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3420 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
5c7c7da9
AD
3421
3422 db_query($link, "COMMIT");
3423
3424 return true;
3425 }
3426
3427 return false;
8d505d78 3428 }
5c7c7da9 3429
ab197ae1 3430 function getArticleFeed($link, $id) {
8d505d78 3431 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
a545dc31 3432 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
ab197ae1
AD
3433
3434 if (db_num_rows($result) != 0) {
3435 return db_fetch_result($result, 0, "feed_id");
3436 } else {
3437 return 0;
3438 }
3439 }
a5819bb3 3440
f2c6c008
CW
3441 /**
3442 * Fixes incomplete URLs by prepending "http://".
f0266f51
CW
3443 * Also replaces feed:// with http://, and
3444 * prepends a trailing slash if the url is a domain name only.
f2c6c008
CW
3445 *
3446 * @param string $url Possibly incomplete URL
3447 *
3448 * @return string Fixed URL.
3449 */
3450 function fix_url($url) {
3451 if (strpos($url, '://') === false) {
3452 $url = 'http://' . $url;
f0266f51
CW
3453 } else if (substr($url, 0, 5) == 'feed:') {
3454 $url = 'http:' . substr($url, 5);
3455 }
3456
3457 //prepend slash if the URL has no slash in it
3458 // "http://www.example" -> "http://www.example/"
44453773 3459 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
f0266f51 3460 $url .= '/';
f2c6c008 3461 }
ec39a02c
AD
3462
3463 if ($url != "http:///")
3464 return $url;
3465 else
3466 return '';
f2c6c008
CW
3467 }
3468
a5819bb3
AD
3469 function validate_feed_url($url) {
3470 $parts = parse_url($url);
3471
3472 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
3473
3474 }
d9084cf2 3475
be35798b
AD
3476 function get_article_enclosures($link, $id) {
3477
8d505d78 3478 $query = "SELECT * FROM ttrss_enclosures
be35798b
AD
3479 WHERE post_id = '$id' AND content_url != ''";
3480
be35798b
AD
3481 $rv = array();
3482
0e4a7d7a 3483 $result = db_query($link, $query);
be35798b 3484
0e4a7d7a
AD
3485 if (db_num_rows($result) > 0) {
3486 while ($line = db_fetch_assoc($result)) {
3487 array_push($rv, $line);
be35798b
AD
3488 }
3489 }
3490
3491 return $rv;
3492 }
3493
31a53903
AD
3494 function save_email_address($link, $email) {
3495 // FIXME: implement persistent storage of emails
3496
8d505d78 3497 if (!$_SESSION['stored_emails'])
31a53903
AD
3498 $_SESSION['stored_emails'] = array();
3499
3500 if (!in_array($email, $_SESSION['stored_emails']))
3501 array_push($_SESSION['stored_emails'], $email);
3502 }
8801fb01 3503
8801fb01
AD
3504
3505 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
3506
3507 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3508
3509 $sql_is_cat = bool_to_sql_bool($is_cat);
3510
8d505d78
AD
3511 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
3512 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
3513 AND owner_uid = " . $owner_uid);
3514
3515 if (db_num_rows($result) == 1) {
3516 return db_fetch_result($result, 0, "access_key");
3517 } else {
3518 $key = db_escape_string(sha1(uniqid(rand(), true)));
3519
8d505d78 3520 $result = db_query($link, "INSERT INTO ttrss_access_keys
8801fb01
AD
3521 (access_key, feed_id, is_cat, owner_uid)
3522 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
3523
3524 return $key;
3525 }
3526 return false;
3527 }
f0266f51 3528
759e5132 3529 function get_feeds_from_html($url, $content)
f0266f51
CW
3530 {
3531 $url = fix_url($url);
3532 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
3533
fb074239
AD
3534 libxml_use_internal_errors(true);
3535
f0266f51 3536 $doc = new DOMDocument();
8d505d78 3537 $doc->loadHTML($content);
f0266f51
CW
3538 $xpath = new DOMXPath($doc);
3539 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
3540 $feedUrls = array();
3541 foreach ($entries as $entry) {
3542 if ($entry->hasAttribute('href')) {
3543 $title = $entry->getAttribute('title');
3544 if ($title == '') {
3545 $title = $entry->getAttribute('type');
3546 }
923818fc
CW
3547 $feedUrl = rewrite_relative_url(
3548 $baseUrl, $entry->getAttribute('href')
3549 );
f0266f51
CW
3550 $feedUrls[$feedUrl] = $title;
3551 }
3552 }
3553 return $feedUrls;
3554 }
3555
759e5132 3556 function is_html($content) {
32b86711 3557 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
759e5132 3558 }
f33479da 3559
759e5132
AD
3560 function url_is_html($url, $login = false, $pass = false) {
3561 return is_html(fetch_file_contents($url, false, $login, $pass));
f33479da 3562 }
24e2bb3a 3563
d90868d7 3564 function print_label_select($link, $name, $value, $attributes = "") {
24e2bb3a
AD
3565
3566 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3567 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3568
8d505d78 3569 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
d90868d7 3570 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
24e2bb3a
AD
3571
3572 while ($line = db_fetch_assoc($result)) {
3573
3574 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
3575
d90868d7
AD
3576 print "<option value=\"".htmlspecialchars($line["caption"])."\"
3577 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
24e2bb3a
AD
3578
3579 }
3580
d90868d7 3581# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
24e2bb3a
AD
3582
3583 print "</select>";
3584
3585
3586 }
3587
009646d2 3588 function format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51
AD
3589 $article_content) {
3590
3591 $result = get_article_enclosures($link, $id);
009646d2 3592 $rv = '';
8d505d78 3593
dad14b51 3594 if (count($result) > 0) {
8d505d78 3595
dad14b51
AD
3596 $entries_html = array();
3597 $entries = array();
ca3bca99 3598 $entries_inline = array();
8d505d78 3599
dad14b51 3600 foreach ($result as $line) {
8d505d78 3601
dad14b51
AD
3602 $url = $line["content_url"];
3603 $ctype = $line["content_type"];
8d505d78 3604
dad14b51 3605 if (!$ctype) $ctype = __("unknown type");
8d505d78 3606
749b56bd 3607 $filename = substr($url, strrpos($url, "/")+1);
8d505d78 3608
ca3bca99
AD
3609 $player = format_inline_player($link, $url, $ctype);
3610
3611 if ($player) array_push($entries_inline, $player);
8d505d78 3612
c3edc667
AD
3613# $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3614# $filename . " (" . $ctype . ")" . "</a>";
8d505d78 3615
749b56bd
AD
3616 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
3617 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
3618
dad14b51 3619 array_push($entries_html, $entry);
8d505d78 3620
dad14b51 3621 $entry = array();
8d505d78 3622
dad14b51
AD
3623 $entry["type"] = $ctype;
3624 $entry["filename"] = $filename;
3625 $entry["url"] = $url;
8d505d78 3626
dad14b51
AD
3627 array_push($entries, $entry);
3628 }
8d505d78 3629
dad14b51
AD
3630 if (!get_pref($link, "STRIP_IMAGES")) {
3631 if ($always_display_enclosures ||
3632 !preg_match("/<img/i", $article_content)) {
8d505d78 3633
dad14b51 3634 foreach ($entries as $entry) {
8d505d78 3635
dad14b51
AD
3636 if (preg_match("/image/", $entry["type"]) ||
3637 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
8d505d78 3638
009646d2 3639 $rv .= "<p><img
dad14b51
AD
3640 alt=\"".htmlspecialchars($entry["filename"])."\"
3641 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
749b56bd 3642
dad14b51
AD
3643 }
3644 }
3645 }
3646 }
8d505d78 3647
ca3bca99
AD
3648 if (count($entries_inline) > 0) {
3649 $rv .= "<hr clear='both'/>";
3650 foreach ($entries_inline as $entry) { $rv .= $entry; };
3651 $rv .= "<hr clear='both'/>";
3652 }
3653
2a3d00bb 3654 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
749b56bd
AD
3655 "<span>" . __('Attachments')."</span>";
3656 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
8d505d78 3657
749b56bd 3658 foreach ($entries_html as $entry) { $rv .= $entry; };
8d505d78 3659
749b56bd 3660 $rv .= "</div></div>";
dad14b51 3661 }
009646d2
AD
3662
3663 return $rv;
dad14b51
AD
3664 }
3665
f8fb4498
AD
3666 function getLastArticleId($link) {
3667 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
3668 WHERE owner_uid = " . $_SESSION["uid"]);
3669
3670 if (db_num_rows($result) == 1) {
3671 return db_fetch_result($result, 0, "id");
3672 } else {
3673 return -1;
3674 }
3675 }
8cc3c778
AD
3676
3677 function build_url($parts) {
3678 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
3679 }
3680
f679105c
CW
3681 /**
3682 * Converts a (possibly) relative URL to a absolute one.
3683 *
3684 * @param string $url Base URL (i.e. from where the document is)
3685 * @param string $rel_url Possibly relative URL in the document
3686 *
3687 * @return string Absolute URL
3688 */
8cc3c778 3689 function rewrite_relative_url($url, $rel_url) {
b4520bb8
AD
3690 if (strpos($rel_url, "magnet:") === 0) {
3691 return $rel_url;
3692 } else if (strpos($rel_url, "://") !== false) {
8cc3c778 3693 return $rel_url;
f9052d35 3694 } else if (strpos($rel_url, "//") === 0) {
3695 # protocol-relative URL (rare but they exist)
3696 return $rel_url;
8d505d78 3697 } else if (strpos($rel_url, "/") === 0)
8cc3c778
AD
3698 {
3699 $parts = parse_url($url);
3700 $parts['path'] = $rel_url;
3701
3702 return build_url($parts);
3703
3704 } else {
3705 $parts = parse_url($url);
f679105c
CW
3706 if (!isset($parts['path'])) {
3707 $parts['path'] = '/';
3708 }
3709 $dir = $parts['path'];
3710 if (substr($dir, -1) !== '/') {
3711 $dir = dirname($parts['path']);
3712 $dir !== '/' && $dir .= '/';
3713 }
3714 $parts['path'] = $dir . $rel_url;
8cc3c778
AD
3715
3716 return build_url($parts);
3717 }
3718 }
3719
e4f7f8df 3720 function sphinx_search($query, $offset = 0, $limit = 30) {
31303c6b
AD
3721 require_once 'lib/sphinxapi.php';
3722
e4f7f8df
AD
3723 $sphinxClient = new SphinxClient();
3724
3725 $sphinxClient->SetServer('localhost', 9312);
3726 $sphinxClient->SetConnectTimeout(1);
3727
8d505d78 3728 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
e4f7f8df
AD
3729 'feed_title' => 20));
3730
3731 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
3732 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
3733 $sphinxClient->SetLimits($offset, $limit, 1000);
3734 $sphinxClient->SetArrayResult(false);
3735 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
8d505d78 3736
e4f7f8df
AD
3737 $result = $sphinxClient->Query($query, SPHINX_INDEX);
3738
3739 $ids = array();
3740
3741 if (is_array($result['matches'])) {
3742 foreach (array_keys($result['matches']) as $int_id) {
3743 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
3744 array_push($ids, $ref_id);
3745 }
3746 }
3747
3748 return $ids;
3749 }
3750
868650e4
AD
3751 function cleanup_tags($link, $days = 14, $limit = 1000) {
3752
3753 if (DB_TYPE == "pgsql") {
3754 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
3755 } else if (DB_TYPE == "mysql") {
3756 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
3757 }
3758
b5ec13fa 3759 $tags_deleted = 0;
868650e4 3760
b5ec13fa
AD
3761 while ($limit > 0) {
3762 $limit_part = 500;
3763
8d505d78
AD
3764 $query = "SELECT ttrss_tags.id AS id
3765 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
b5ec13fa
AD
3766 WHERE post_int_id = int_id AND $interval_query AND
3767 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
8d505d78 3768
b5ec13fa
AD
3769 $result = db_query($link, $query);
3770
3771 $ids = array();
3772
3773 while ($line = db_fetch_assoc($result)) {
3774 array_push($ids, $line['id']);
3775 }
3776
3777 if (count($ids) > 0) {
3778 $ids = join(",", $ids);
3779 print ".";
3780
3781 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
3782 $tags_deleted += db_affected_rows($link, $tmp_result);
3783 } else {
3784 break;
3785 }
3786
3787 $limit -= $limit_part;
3788 }
3789
3790 print "\n";
868650e4 3791
b5ec13fa 3792 return $tags_deleted;
868650e4
AD
3793 }
3794
88e4e597
AD
3795 function print_user_stylesheet($link) {
3796 $value = get_pref($link, 'USER_STYLESHEET');
3797
3798 if ($value) {
3799 print "<style type=\"text/css\">";
5823f9fb 3800 print str_replace("<br/>", "\n", $value);
88e4e597
AD
3801 print "</style>";
3802 }
3803
3804 }
3805
73c32678
AD
3806 function rewrite_urls($html) {
3807 libxml_use_internal_errors(true);
3808
3809 $charset_hack = '<head>
3810 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3811 </head>';
3812
3813 $doc = new DOMDocument();
3814 $doc->loadHTML($charset_hack . $html);
3815 $xpath = new DOMXPath($doc);
3816
3817 $entries = $xpath->query('//*/text()');
3818
3819 foreach ($entries as $entry) {
3820 if (strstr($entry->wholeText, "://") !== false) {
3821 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
3822 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
3823
3824 if ($text != $entry->wholeText) {
3825 $cdoc = new DOMDocument();
3826 $cdoc->loadHTML($charset_hack . $text);
3827
3828
3829 foreach ($cdoc->childNodes as $cnode) {
3830 $cnode = $doc->importNode($cnode, true);
3831
3832 if ($cnode) {
3833 $entry->parentNode->insertBefore($cnode);
3834 }
3835 }
3836
3837 $entry->parentNode->removeChild($entry);
3838
3839 }
3840 }
3841 }
3842
3843 $node = $doc->getElementsByTagName('body')->item(0);
3844
376897af
AD
3845 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
3846 if ($node)
7b8ff151 3847 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
376897af
AD
3848 else
3849 return $html;
533c0ea6
AD
3850 }
3851
2680295b 3852 function filter_to_sql($link, $filter, $owner_uid) {
4e02f582 3853 $query = array();
36184020 3854
4e02f582
AD
3855 if (DB_TYPE == "pgsql")
3856 $reg_qpart = "~";
3857 else
3858 $reg_qpart = "REGEXP";
36184020 3859
4e02f582
AD
3860 foreach ($filter["rules"] AS $rule) {
3861 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
3862 $rule['reg_exp']) !== FALSE;
36184020 3863
4e02f582 3864 if ($regexp_valid) {
36184020 3865
4e02f582 3866 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
36184020 3867
4e02f582
AD
3868 switch ($rule["type"]) {
3869 case "title":
3870 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3871 $rule['reg_exp'] . "')";
3872 break;
3873 case "content":
3874 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
3875 $rule['reg_exp'] . "')";
3876 break;
3877 case "both":
3878 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3879 $rule['reg_exp'] . "') OR LOWER(" .
3880 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
3881 break;
3882 case "tag":
3883 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
3884 $rule['reg_exp'] . "')";
3885 break;
3886 case "link":
3887 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
3888 $rule['reg_exp'] . "')";
3889 break;
3890 case "author":
3891 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
3892 $rule['reg_exp'] . "')";
3893 break;
3894 }
36184020 3895
6b218731
AD
3896 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
3897 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4e02f582 3898 }
6b8b3af8 3899
4e02f582 3900 if (isset($rule["cat_id"])) {
2680295b
AD
3901
3902 if ($rule["cat_id"] > 0) {
3903 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
3904 array_push($children, $rule["cat_id"]);
3905
3906 $children = join(",", $children);
3907
3908 $cat_qpart = "cat_id IN ($children)";
3909 } else {
3910 $cat_qpart = "cat_id IS NULL";
3911 }
3912
3913 $qpart .= " AND $cat_qpart";
56fbb82c 3914 }
4e02f582
AD
3915
3916 array_push($query, "($qpart)");
3917
56fbb82c 3918 }
4e02f582 3919 }
56fbb82c 3920
4e02f582
AD
3921 if (count($query) > 0) {
3922 return "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
56fbb82c 3923 } else {
4e02f582 3924 return "(false)";
56fbb82c 3925 }
36184020 3926 }
ae5f7bb1 3927
3382bce1
AD
3928 if (!function_exists('gzdecode')) {
3929 function gzdecode($string) { // no support for 2nd argument
3930 return file_get_contents('compress.zlib://data:who/cares;base64,'.
3931 base64_encode($string));
3932 }
3933 }
3934
8db5d8ea
AD
3935 function get_random_bytes($length) {
3936 if (function_exists('openssl_random_pseudo_bytes')) {
3937 return openssl_random_pseudo_bytes($length);
3938 } else {
3939 $output = "";
3940
3941 for ($i = 0; $i < $length; $i++)
3942 $output .= chr(mt_rand(0, 255));
3943
3944 return $output;
3945 }
3946 }
871f0a7a
AD
3947
3948 function read_stdin() {
3949 $fp = fopen("php://stdin", "r");
3950
3951 if ($fp) {
3952 $line = trim(fgets($fp));
3953 fclose($fp);
3954 return $line;
3955 }
3956
3957 return null;
3958 }
e3449aa1
AD
3959
3960 function tmpdirname($path, $prefix) {
3961 // Use PHP's tmpfile function to create a temporary
3962 // directory name. Delete the file and keep the name.
3963 $tempname = tempnam($path,$prefix);
3964 if (!$tempname)
3965 return false;
3966
3967 if (!unlink($tempname))
3968 return false;
3969
3970 return $tempname;
3971 }
3972
6aff7845
AD
3973 function getFeedCategory($link, $feed) {
3974 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3975 WHERE id = '$feed'");
3976
3977 if (db_num_rows($result) > 0) {
3978 return db_fetch_result($result, 0, "cat_id");
3979 } else {
3980 return false;
3981 }
3982
3983 }
3984
8dcb2b47
AD
3985 function implements_interface($class, $interface) {
3986 return in_array($interface, class_implements($class));
3987 }
3988
40d13c28 3989?>