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