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