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