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