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