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