]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
update readme (c)
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
6e658547 2 define('EXPECTED_CONFIG_VERSION', 26);
a6b45187 3 define('SCHEMA_VERSION', 102);
545ca067 4
23d2471c 5 $fetch_last_error = false;
19b3992b 6 $pluginhost = false;
23d2471c 7
0d421af8 8 function __autoload($class) {
369dbc19
AD
9 $class_file = str_replace("_", "/", strtolower(basename($class)));
10
11 $file = dirname(__FILE__)."/../classes/$class_file.php";
12
0d421af8
AD
13 if (file_exists($file)) {
14 require $file;
15 }
cc85704f 16
0d421af8
AD
17 }
18
d68629dc 19 mb_internal_encoding("UTF-8");
324944f3 20 date_default_timezone_set('UTC');
8a7f5767
CW
21 if (defined('E_DEPRECATED')) {
22 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
23 } else {
24 error_reporting(E_ALL & ~E_NOTICE);
25 }
cce28758 26
40d13c28 27 require_once 'config.php';
cc17c205 28
fc2b26a6
AD
29 if (DB_TYPE == "pgsql") {
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
31 } else {
32 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
33 }
34
0c425dc7
AD
35 define('THEME_VERSION_REQUIRED', 1.1);
36
9632f884
AD
37 /**
38 * Return available translations names.
8d505d78 39 *
9632f884
AD
40 * @access public
41 * @return array A array of available translations.
42 */
f8c612d4 43 function get_translations() {
6a214f92 44 $tr = array(
8d505d78 45 "auto" => "Detect automatically",
a3162add 46 "ca_CA" => "Català",
6a214f92 47 "en_US" => "English",
36d0510c 48 "es_ES" => "Español",
a927fe7b 49 "de_DE" => "Deutsch",
6a214f92 50 "fr_FR" => "Français",
e78fd196 51 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 52 "it_IT" => "Italiano",
1d004f12 53 "ja_JP" => "日本語 (Japanese)",
592535d7 54 "nb_NO" => "Norwegian bokmål",
ea45791a 55 "pl_PL" => "Polski",
6a214f92 56 "ru_RU" => "Русский",
9a063469 57 "pt_BR" => "Portuguese/Brazil",
6a214f92 58 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
59
60 return $tr;
61 }
62
7b26a148
AD
63 require_once "lib/accept-to-gettext.php";
64 require_once "lib/gettext/gettext.inc";
aba609e0 65
87d7e850 66
7b26a148 67 function startup_gettext() {
8d505d78 68
7b26a148
AD
69 # Get locale from Accept-Language header
70 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 71
7b26a148
AD
72 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
73 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
74 }
89cb787e 75
7b26a148
AD
76 /* In login action of mobile version */
77 if ($_POST["language"] && defined('MOBILE_VERSION')) {
78 $lang = $_POST["language"];
afc3cf55
AD
79 } else {
80 $lang = $_SESSION["language"];
7b26a148 81 }
7c33dbd4 82
7b26a148
AD
83 if ($lang) {
84 if (defined('LC_MESSAGES')) {
85 _setlocale(LC_MESSAGES, $lang);
86 } else if (defined('LC_ALL')) {
87 _setlocale(LC_ALL, $lang);
8d039718 88 }
aba609e0 89
7b26a148
AD
90 if (defined('MOBILE_VERSION')) {
91 _bindtextdomain("messages", "../locale");
92 } else {
93 _bindtextdomain("messages", "locale");
94 }
865220a4 95
7b26a148
AD
96 _textdomain("messages");
97 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 98 }
7b26a148
AD
99 }
100
101 startup_gettext();
cc17c205 102
b619ff15 103 require_once 'db-prefs.php';
8911ac8b 104 require_once 'version.php';
87d7e850
AD
105 require_once 'ccache.php';
106 require_once 'labels.php';
40d13c28 107
500943a4
AD
108 ini_set('user_agent', SELF_USER_AGENT);
109
b0f379df 110 require_once 'lib/pubsubhubbub/publisher.php';
acccafe3 111 require_once 'lib/htmLawed.php';
010efc9b 112
7d96bfcd
AD
113 $tz_offset = -1;
114 $utc_tz = new DateTimeZone('UTC');
115 $schema_version = false;
116
45004d43
AD
117 /**
118 * Print a timestamped debug message.
8d505d78 119 *
45004d43
AD
120 * @param string $msg The debug message.
121 * @return void
122 */
6f9e33e4 123 function _debug($msg) {
5439d333
RW
124 if (defined('QUIET') && QUIET) {
125 return;
126 }
6f9e33e4 127 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
128 if (function_exists('posix_getpid')) {
129 $ts = "$ts/" . posix_getpid();
130 }
6f9e33e4 131 print "[$ts] $msg\n";
45004d43 132 } // function _debug
6f9e33e4 133
9632f884
AD
134 /**
135 * Purge a feed old posts.
8d505d78 136 *
9632f884
AD
137 * @param mixed $link A database connection.
138 * @param mixed $feed_id The id of the purged feed.
139 * @param mixed $purge_interval Olderness of purged posts.
140 * @param boolean $debug Set to True to enable the debug. False by default.
141 * @access public
142 * @return void
143 */
ad507f85
AD
144 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
145
07d0efe9 146 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
8d505d78 147
ad507f85 148 $rows = -1;
4c193675 149
8d505d78 150 $result = db_query($link,
07d0efe9
AD
151 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
152
153 $owner_uid = false;
154
155 if (db_num_rows($result) == 1) {
156 $owner_uid = db_fetch_result($result, 0, "owner_uid");
157 }
158
ab954dff
AD
159 if ($purge_interval == -1 || !$purge_interval) {
160 if ($owner_uid) {
161 ccache_update($link, $feed_id, $owner_uid);
162 }
163 return;
164 }
165
07d0efe9
AD
166 if (!$owner_uid) return;
167
3907ef71
AD
168 if (FORCE_ARTICLE_PURGE == 0) {
169 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
170 $owner_uid, false);
171 } else {
172 $purge_unread = true;
173 $purge_interval = FORCE_ARTICLE_PURGE;
174 }
07d0efe9
AD
175
176 if (!$purge_unread) $query_limit = " unread = false AND ";
177
fefa6ca3 178 if (DB_TYPE == "pgsql") {
6e7f8d26
AD
179 $pg_version = get_pgsql_version($link);
180
181 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 182
8d505d78
AD
183 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
184 ttrss_entries.id = ref_id AND
185 marked = false AND
186 feed_id = '$feed_id' AND
07d0efe9 187 $query_limit
25ea2805 188 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
189
190 } else {
191
8d505d78
AD
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
195 marked = false AND
196 feed_id = '$feed_id' AND
07d0efe9 197 $query_limit
25ea2805 198 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 199 }
ad507f85
AD
200
201 $rows = pg_affected_rows($result);
8d505d78 202
fefa6ca3 203 } else {
8d505d78 204
30f1746f 205/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 206 marked = false AND feed_id = '$feed_id' AND
8d505d78 207 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
208 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
209
8d505d78
AD
210 $result = db_query($link, "DELETE FROM ttrss_user_entries
211 USING ttrss_user_entries, ttrss_entries
212 WHERE ttrss_entries.id = ref_id AND
213 marked = false AND
214 feed_id = '$feed_id' AND
07d0efe9 215 $query_limit
25ea2805 216 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
8d505d78 217
ad507f85
AD
218 $rows = mysql_affected_rows($link);
219
220 }
221
ced46404
AD
222 ccache_update($link, $feed_id, $owner_uid);
223
ad507f85 224 if ($debug) {
6f9e33e4 225 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 226 }
9632f884 227 } // function purge_feed
fefa6ca3 228
07d0efe9
AD
229 function feed_purge_interval($link, $feed_id) {
230
8d505d78 231 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
232 WHERE id = '$feed_id'");
233
234 if (db_num_rows($result) == 1) {
235 $purge_interval = db_fetch_result($result, 0, "purge_interval");
236 $owner_uid = db_fetch_result($result, 0, "owner_uid");
237
8d505d78 238 if ($purge_interval == 0) $purge_interval = get_pref($link,
863be6ca 239 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
240
241 return $purge_interval;
242
243 } else {
244 return -1;
245 }
246 }
247
a2d79981
AD
248 function purge_orphans($link, $do_output = false) {
249
71604ca4 250 // purge orphaned posts in main content table
8d505d78 251 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4 252 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
253
254 if ($do_output) {
255 $rows = db_affected_rows($link, $result);
256 _debug("Purged $rows orphaned posts.");
257 }
c3a8d71a
AD
258 }
259
c7d57b66
AD
260 function get_feed_update_interval($link, $feed_id) {
261 $result = db_query($link, "SELECT owner_uid, update_interval FROM
262 ttrss_feeds WHERE id = '$feed_id'");
263
264 if (db_num_rows($result) == 1) {
265 $update_interval = db_fetch_result($result, 0, "update_interval");
266 $owner_uid = db_fetch_result($result, 0, "owner_uid");
267
268 if ($update_interval != 0) {
269 return $update_interval;
270 } else {
271 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
272 }
273
274 } else {
275 return -1;
276 }
277 }
278
ae5f7bb1 279 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
8d505d78
AD
280 $login = urlencode($login);
281 $pass = urlencode($pass);
282
23d2471c
AD
283 global $fetch_last_error;
284
3610b48b 285 if (function_exists('curl_init') && !ini_get("open_basedir")) {
4065b60b 286 $ch = curl_init($url);
a1af1574
AD
287
288 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
289 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
290 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
291 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
292 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
293 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
8d505d78 294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
5f6804bc 295 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
19929bbe 296 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
268a06dc 297 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
8d505d78 298
ae5f7bb1
AD
299 if ($post_query) {
300 curl_setopt($ch, CURLOPT_POST, true);
301 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
302 }
303
8d505d78
AD
304 if ($login && $pass)
305 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 306
fb074239 307 $contents = @curl_exec($ch);
268a06dc 308
a1af1574 309 if ($contents === false) {
23d2471c 310 $fetch_last_error = curl_error($ch);
a1af1574
AD
311 curl_close($ch);
312 return false;
4065b60b
AD
313 }
314
8d505d78 315 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
a1af1574
AD
316 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
317 curl_close($ch);
4065b60b 318
8d505d78 319 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
a1af1574
AD
320 return false;
321 }
4065b60b 322
a1af1574 323 return $contents;
4065b60b 324 } else {
9949bd15 325 if ($login && $pass ){
8d505d78
AD
326 $url_parts = array();
327
328 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
329
330 if ($url_parts[1] && $url_parts[2]) {
331 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
332 }
333 }
334
23d2471c
AD
335 $data = @file_get_contents($url);
336
337 if (!$data && function_exists('error_get_last')) {
338 $error = error_get_last();
339 $fetch_last_error = $error["message"];
340 }
341 return $data;
4065b60b
AD
342 }
343
344 }
78800912 345
9632f884
AD
346 /**
347 * Try to determine the favicon URL for a feed.
348 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
349 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
8d505d78 350 *
9632f884
AD
351 * @param string $url A feed or page URL
352 * @access public
353 * @return mixed The favicon URL, or false if none was found.
354 */
1bd11fdf 355 function get_favicon_url($url) {
99331724 356
1bd11fdf 357 $favicon_url = false;
ed214298 358
4065b60b 359 if ($html = @fetch_file_contents($url)) {
78800912 360
ed214298 361 libxml_use_internal_errors(true);
c798704b 362
ed214298
AD
363 $doc = new DOMDocument();
364 $doc->loadHTML($html);
365 $xpath = new DOMXPath($doc);
717f5e64 366
a712429e
AD
367 $base = $xpath->query('/html/head/base');
368 foreach ($base as $b) {
369 $url = $b->getAttribute("href");
370 break;
371 }
372
1bd11fdf 373 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
374 if (count($entries) > 0) {
375 foreach ($entries as $entry) {
1bd11fdf
AD
376 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
377 break;
ed214298 378 }
8d505d78 379 }
4065b60b 380 }
c798704b 381
1bd11fdf
AD
382 if (!$favicon_url)
383 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
384
385 return $favicon_url;
386 } // function get_favicon_url
387
388 function check_feed_favicon($site_url, $feed, $link) {
882311d9 389# print "FAVICON [$site_url]: $favicon_url\n";
4065b60b 390
1bd11fdf
AD
391 $icon_file = ICONS_DIR . "/$feed.ico";
392
393 if (!file_exists($icon_file)) {
394 $favicon_url = get_favicon_url($site_url);
395
396 if ($favicon_url) {
397 // Limiting to "image" type misses those served with text/plain
398 $contents = fetch_file_contents($favicon_url); // , "image");
399
400 if ($contents) {
401 // Crude image type matching.
402 // Patterns gleaned from the file(1) source code.
403 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
404 // 0 string \000\000\001\000 MS Windows icon resource
405 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
406 }
407 elseif (preg_match('/^GIF8/', $contents)) {
408 // 0 string GIF8 GIF image data
409 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
410 }
411 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
412 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
413 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
414 }
415 elseif (preg_match('/^\xff\xd8/', $contents)) {
416 // 0 beshort 0xffd8 JPEG image data
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
418 }
419 else {
420 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
421 $contents = "";
422 }
423 }
424
425 if ($contents) {
426 $fp = @fopen($icon_file, "w");
427
428 if ($fp) {
429 fwrite($fp, $contents);
430 fclose($fp);
431 chmod($icon_file, 0644);
432 }
433 }
434 }
78800912
AD
435 }
436 }
437
f175937c 438 function print_select($id, $default, $values, $attributes = "") {
79f3553b 439 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
440 foreach ($values as $v) {
441 if ($v == $default)
60807300 442 $sel = "selected=\"1\"";
a0d53889
AD
443 else
444 $sel = "";
8d505d78 445
60807300 446 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
447 }
448 print "</select>";
449 }
40d13c28 450
79f3553b
AD
451 function print_select_hash($id, $default, $values, $attributes = "") {
452 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
453 foreach (array_keys($values) as $v) {
454 if ($v == $default)
74d5c8fa 455 $sel = 'selected="selected"';
673d54ca
AD
456 else
457 $sel = "";
8d505d78 458
673d54ca
AD
459 print "<option $sel value=\"$v\">".$values[$v]."</option>";
460 }
461
462 print "</select>";
463 }
464
406d9489
AD
465 function getmicrotime() {
466 list($usec, $sec) = explode(" ",microtime());
467 return ((float)$usec + (float)$sec);
468 }
469
f541eb78 470 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 471 foreach ($values as $v) {
8d505d78 472
77e96719 473 if ($v == $default)
5da169d9 474 $sel = "checked";
77e96719 475 else
5da169d9
AD
476 $sel = "";
477
f541eb78 478 if ($v == $true_is) {
5da169d9
AD
479 $sel .= " value=\"1\"";
480 } else {
481 $sel .= " value=\"0\"";
482 }
8d505d78
AD
483
484 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 485 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
486
487 }
488 }
489
d9084cf2 490 function initialize_user_prefs($link, $uid, $profile = false) {
ff485f1d
AD
491
492 $uid = db_escape_string($uid);
493
d9084cf2
AD
494 if (!$profile) {
495 $profile = "NULL";
f9aa6a89 496 $profile_qpart = "AND profile IS NULL";
d9084cf2 497 } else {
f9aa6a89 498 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
499 }
500
f9aa6a89
AD
501 if (get_schema_version($link) < 63) $profile_qpart = "";
502
ff485f1d
AD
503 db_query($link, "BEGIN");
504
505 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78
AD
506
507 $u_result = db_query($link, "SELECT pref_name
f9aa6a89 508 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
509
510 $active_prefs = array();
511
512 while ($line = db_fetch_assoc($u_result)) {
8d505d78 513 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
514 }
515
516 while ($line = db_fetch_assoc($result)) {
517 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
518// print "adding " . $line["pref_name"] . "<br>";
519
f9aa6a89
AD
520 if (get_schema_version($link) < 63) {
521 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 522 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
523 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
524
525 } else {
526 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 527 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
528 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
529 }
ff485f1d
AD
530
531 }
532 }
533
534 db_query($link, "COMMIT");
535
536 }
956c7629 537
8de8bfb8
AD
538 function get_ssl_certificate_id() {
539 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
540 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
541 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
542 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
543 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
544 }
545 return "";
546 }
547
0d421af8 548 function authenticate_user($link, $login, $password, $check_only = false) {
c8437f35 549
131b01b3 550 if (!SINGLE_USER_MODE) {
c8437f35 551
0d421af8 552 $user_id = false;
0f28f81f
AD
553
554 global $pluginhost;
555 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
556
557 $user_id = (int) $plugin->authenticate($login, $password);
558
559 if ($user_id) {
560 $_SESSION["auth_module"] = strtolower(get_class($plugin));
561 break;
562 }
461766f3
AD
563 }
564
0d421af8
AD
565 if ($user_id && !$check_only) {
566 $_SESSION["uid"] = $user_id;
567
568 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
569 WHERE id = '$user_id'");
8d505d78 570
131b01b3
AD
571 $_SESSION["name"] = db_fetch_result($result, 0, "login");
572 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
8484ce22 573 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
8d505d78
AD
574
575 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 576 $_SESSION["uid"]);
8d505d78 577
131b01b3 578 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 579 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
580
581 $_SESSION["last_version_check"] = time();
8d505d78 582
131b01b3 583 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 584
131b01b3
AD
585 return true;
586 }
8d505d78 587
131b01b3 588 return false;
503eb349 589
131b01b3 590 } else {
503eb349 591
131b01b3
AD
592 $_SESSION["uid"] = 1;
593 $_SESSION["name"] = "admin";
787e5ebc 594 $_SESSION["access_level"] = 10;
21e42e5f 595
0d421af8
AD
596 $_SESSION["hide_hello"] = true;
597 $_SESSION["hide_logout"] = true;
598
d5fd183d
AD
599 $_SESSION["auth_module"] = false;
600
21e42e5f
AD
601 if (!$_SESSION["csrf_token"]) {
602 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
603 }
f557cd78 604
0bbba72d 605 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 606
0bbba72d 607 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 608
c8437f35
AD
609 return true;
610 }
c8437f35
AD
611 }
612
e6cb77a0
AD
613 function make_password($length = 8) {
614
85db6213
AD
615 $password = "";
616 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
617
618 $i = 0;
619
620 while ($i < $length) {
621 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
622
623 if (!strstr($password, $char)) {
624 $password .= $char;
625 $i++;
626 }
627 }
628 return $password;
e6cb77a0
AD
629 }
630
631 // this is called after user is created to initialize default feeds, labels
632 // or whatever else
8d505d78 633
e6cb77a0
AD
634 // user preferences are checked on every login, not here
635
636 function initialize_user($link, $uid) {
637
e6cb77a0 638 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 639 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 640 'http://tt-rss.org/releases.rss')");
3b0feb9b 641
cd2cd415
AD
642 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
643 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 644 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 645 }
e6cb77a0 646
b8aa49bc 647 function logout_user() {
5ccc1cf5
AD
648 session_destroy();
649 if (isset($_COOKIE[session_name()])) {
650 setcookie(session_name(), '', time()-42000, '/');
651 }
b8aa49bc
AD
652 }
653
8484ce22
AD
654 function validate_csrf($csrf_token) {
655 return $csrf_token == $_SESSION['csrf_token'];
656 }
657
916f788a 658 function validate_session($link) {
0f41fce8
AD
659 if (SINGLE_USER_MODE) return true;
660
661 $check_ip = $_SESSION['ip_address'];
662
663 switch (SESSION_CHECK_ADDRESS) {
664 case 0:
665 $check_ip = '';
666 break;
667 case 1:
668 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
669 break;
670 case 2:
671 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
672 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
673 break;
674 };
675
d769a0f7 676 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
8d505d78 677 $_SESSION["login_error_msg"] =
d769a0f7
AD
678 __("Session failed to validate (incorrect IP)");
679 return false;
680 }
0f41fce8
AD
681
682 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
05044a59 683 return false;
05044a59 684
e6684130
AD
685 if ($_SESSION["uid"]) {
686
8d505d78 687 $result = db_query($link,
e6684130
AD
688 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
689
690 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
691
692 if ($pwd_hash != $_SESSION["pwd_hash"]) {
693 return false;
694 }
695 }
696
a885f0ec 697/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 698
8e849206 699 //print_r($_SESSION);
d620cfe7
AD
700
701 if (time() > $_SESSION["cookie_lifetime"]) {
702 return false;
703 }
a885f0ec
AD
704 } */
705
916f788a
AD
706 return true;
707 }
708
de612e7a
AD
709 function load_user_plugins($link, $owner_uid) {
710 if ($owner_uid) {
711 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
712
713 global $pluginhost;
d8a1d2a2 714 $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
e9c04fd4
AD
715
716 if (get_schema_version($link) > 100) {
717 $pluginhost->load_data();
718 }
de612e7a
AD
719 }
720 }
721
97acbaf1 722 function login_sequence($link, $login_form = 0) {
75a316ab
AD
723 $_SESSION["prefs_cache"] = false;
724
97acbaf1 725 if (SINGLE_USER_MODE) {
de612e7a
AD
726 authenticate_user($link, "admin", null);
727 load_user_plugins($link, $_SESSION["uid"]);
97acbaf1
AD
728 } else {
729 if (!$_SESSION["uid"] || !validate_session($link)) {
730
731 if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
732 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
733 } else {
734 authenticate_user($link, null, null, true);
735 }
736
737 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
738
739 } else {
740 /* bump login timestamp */
741 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
742 $_SESSION["uid"]);
01a87dff
AD
743 }
744
afc3cf55
AD
745 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
746 setcookie("ttrss_lang", $_SESSION["language"],
747 time() + SESSION_COOKIE_LIFETIME);
b8aa49bc 748 }
de612e7a
AD
749
750 if ($_SESSION["uid"]) {
751 load_user_plugins($link, $_SESSION["uid"]);
752 }
b8aa49bc 753 }
afc3cf55 754 }
3547842a 755
411fe209 756 function truncate_string($str, $max_len, $suffix = '&hellip;') {
12db369c 757 if (mb_strlen($str, "utf-8") > $max_len - 3) {
411fe209 758 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
759 } else {
760 return $str;
761 }
762 }
54a60e1a 763
96f0a3e7 764 // Deprecated, TODO: remove
e9823609 765 function theme_image($link, $filename) {
96f0a3e7 766 return $filename;
54a60e1a 767 }
be773442 768
ab4b768f
AD
769 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
770
771 try {
772 $source_tz = new DateTimeZone($source_tz);
773 } catch (Exception $e) {
774 $source_tz = new DateTimeZone('UTC');
775 }
776
777 try {
778 $dest_tz = new DateTimeZone($dest_tz);
779 } catch (Exception $e) {
780 $dest_tz = new DateTimeZone('UTC');
781 }
782
783 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
784 return $dt->format('U') + $dest_tz->getOffset($dt);
785 }
786
324944f3
AD
787 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
788 $no_smart_dt = false) {
789
790 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
791 if (!$timestamp) $timestamp = '1970-01-01 0:00';
792
7d96bfcd
AD
793 global $utc_tz;
794 global $tz_offset;
324944f3 795
7d96bfcd
AD
796 # We store date in UTC internally
797 $dt = new DateTime($timestamp, $utc_tz);
798
799 if ($tz_offset == -1) {
800
801 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
802
803 try {
804 $user_tz = new DateTimeZone($user_tz_string);
805 } catch (Exception $e) {
806 $user_tz = $utc_tz;
807 }
808
809 $tz_offset = $user_tz->getOffset($dt);
324944f3
AD
810 }
811
7d96bfcd 812 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 813
1dc52ae7 814 if (!$no_smart_dt) {
8d505d78 815 return smart_date_time($link, $user_timestamp,
7d96bfcd 816 $tz_offset, $owner_uid);
324944f3
AD
817 } else {
818 if ($long)
819 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
820 else
821 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
822
823 return date($format, $user_timestamp);
824 }
825 }
826
2a5c136e
AD
827 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
828 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
829
830 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 831 return date("G:i", $timestamp);
2a5c136e
AD
832 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
833 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
834 return date($format, $timestamp);
be773442 835 } else {
2a5c136e
AD
836 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
837 return date($format, $timestamp);
be773442
AD
838 }
839 }
840
e3c99f3b 841 function sql_bool_to_bool($s) {
36184020 842 if ($s == "t" || $s == "1" || $s == "true") {
e3c99f3b
AD
843 return true;
844 } else {
845 return false;
846 }
847 }
8d505d78 848
badac687
AD
849 function bool_to_sql_bool($s) {
850 if ($s) {
851 return "true";
852 } else {
853 return "false";
854 }
855 }
e3c99f3b 856
fcfa9ef1
AD
857 // Session caching removed due to causing wrong redirects to upgrade
858 // script when get_schema_version() is called on an obsolete session
859 // created on a previous schema version.
199db684 860 function get_schema_version($link, $nocache = false) {
7d96bfcd
AD
861 global $schema_version;
862
863 if (!$schema_version) {
199db684
AD
864 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
865 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 866 $schema_version = $version;
199db684 867 return $version;
7d96bfcd
AD
868 } else {
869 return $schema_version;
870 }
e4c51a6c
AD
871 }
872
6043fb7e 873 function sanity_check($link) {
31303c6b 874 require_once 'errors.php';
ebb948c2 875
6043fb7e 876 $error_code = 0;
7d96bfcd 877 $schema_version = get_schema_version($link, true);
6043fb7e
AD
878
879 if ($schema_version != SCHEMA_VERSION) {
880 $error_code = 5;
881 }
882
aec3ce39
AD
883 if (DB_TYPE == "mysql") {
884 $result = db_query($link, "SELECT true", false);
885 if (db_num_rows($result) != 1) {
886 $error_code = 10;
887 }
888 }
889
f29ba148
AD
890 if (db_escape_string("testTEST") != "testTEST") {
891 $error_code = 12;
892 }
893
ebb948c2 894 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
895 }
896
27981ca3 897 function file_is_locked($filename) {
31a6d42d 898 if (function_exists('flock')) {
fb074239 899 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
900 if ($fp) {
901 if (flock($fp, LOCK_EX | LOCK_NB)) {
902 flock($fp, LOCK_UN);
903 fclose($fp);
904 return false;
905 }
27981ca3 906 fclose($fp);
31a6d42d 907 return true;
e89aed7b
AD
908 } else {
909 return false;
27981ca3 910 }
27981ca3 911 }
c1fb4a5e 912 return true; // consider the file always locked and skip the test
27981ca3
AD
913 }
914
fcb4c0c9 915 function make_lockfile($filename) {
cfa43e02 916 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 917
82acc36d 918 if (flock($fp, LOCK_EX | LOCK_NB)) {
4c59adb1
AD
919 if (function_exists('posix_getpid')) {
920 fwrite($fp, posix_getpid() . "\n");
921 }
fcb4c0c9
AD
922 return $fp;
923 } else {
924 return false;
925 }
926 }
927
bf7fcde8 928 function make_stampfile($filename) {
cfa43e02 929 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 930
8e00ae9b 931 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 932 fwrite($fp, time() . "\n");
8e00ae9b 933 flock($fp, LOCK_UN);
bf7fcde8
AD
934 fclose($fp);
935 return true;
936 } else {
937 return false;
938 }
939 }
940
894ebcf5
AD
941 function sql_random_function() {
942 if (DB_TYPE == "mysql") {
943 return "RAND()";
944 } else {
945 return "RANDOM()";
946 }
947 }
948
184f5195 949 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
c7e51de1
AD
950
951 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 952
37c03d3a 953 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 954
705b97b7
AD
955 $ref_check_qpart = ($max_id &&
956 !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
184f5195 957
37c03d3a 958 if (is_numeric($feed)) {
23aa0d16
AD
959 if ($cat_view) {
960
72a2f4f5 961 if ($feed >= 0) {
f9fca8cb
AD
962
963 if ($feed > 0) {
bda6afa2
AD
964 $children = getChildCategories($link, $feed, $owner_uid);
965 array_push($children, $feed);
966
967 $children = join(",", $children);
968
969 $cat_qpart = "cat_id IN ($children)";
f9fca8cb
AD
970 } else {
971 $cat_qpart = "cat_id IS NULL";
972 }
8d505d78 973
bda6afa2
AD
974 db_query($link, "UPDATE ttrss_user_entries
975 SET unread = false,last_read = NOW()
976 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
977 AND $ref_check_qpart
978 AND owner_uid = $owner_uid");
23aa0d16 979
f9fca8cb 980 } else if ($feed == -2) {
23aa0d16 981
8d505d78
AD
982 db_query($link, "UPDATE ttrss_user_entries
983 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
984 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
184f5195
AD
985 AND $ref_check_qpart
986 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
987 }
988
989 } else if ($feed > 0) {
990
8d505d78
AD
991 db_query($link, "UPDATE ttrss_user_entries
992 SET unread = false,last_read = NOW()
184f5195
AD
993 WHERE feed_id = '$feed'
994 AND $ref_check_qpart
995 AND owner_uid = $owner_uid");
8d505d78 996
23aa0d16
AD
997 } else if ($feed < 0 && $feed > -10) { // special, like starred
998
999 if ($feed == -1) {
8d505d78 1000 db_query($link, "UPDATE ttrss_user_entries
23aa0d16 1001 SET unread = false,last_read = NOW()
184f5195
AD
1002 WHERE marked = true
1003 AND $ref_check_qpart
1004 AND owner_uid = $owner_uid");
23aa0d16 1005 }
e4f4b46f
AD
1006
1007 if ($feed == -2) {
8d505d78 1008 db_query($link, "UPDATE ttrss_user_entries
e4f4b46f 1009 SET unread = false,last_read = NOW()
184f5195
AD
1010 WHERE published = true
1011 AND $ref_check_qpart
1012 AND owner_uid = $owner_uid");
e4f4b46f
AD
1013 }
1014
2d24f032
AD
1015 if ($feed == -3) {
1016
c1d7e6c3
AD
1017 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1018
2d24f032 1019 if (DB_TYPE == "pgsql") {
8d505d78 1020 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1021 } else {
8d505d78 1022 $match_part = "updated > DATE_SUB(NOW(),
c1d7e6c3 1023 INTERVAL $intl HOUR) ";
2d24f032
AD
1024 }
1025
8d505d78 1026 $result = db_query($link, "SELECT id FROM ttrss_entries,
1f3335dc
AD
1027 ttrss_user_entries WHERE $match_part AND
1028 unread = true AND
8d505d78 1029 ttrss_user_entries.ref_id = ttrss_entries.id AND
c7e51de1 1030 owner_uid = $owner_uid");
1f3335dc
AD
1031
1032 $affected_ids = array();
1033
1034 while ($line = db_fetch_assoc($result)) {
1035 array_push($affected_ids, $line["id"]);
1036 }
1037
1038 catchupArticlesById($link, $affected_ids, 0);
2d24f032
AD
1039 }
1040
3584cb11 1041 if ($feed == -4) {
8d505d78 1042 db_query($link, "UPDATE ttrss_user_entries
3584cb11 1043 SET unread = false,last_read = NOW()
184f5195 1044 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
3584cb11
AD
1045 }
1046
23aa0d16
AD
1047 } else if ($feed < -10) { // label
1048
23aa0d16
AD
1049 $label_id = -$feed - 11;
1050
8d505d78
AD
1051 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1052 SET unread = false, last_read = NOW()
338c238d 1053 WHERE label_id = '$label_id' AND unread = true
184f5195 1054 AND $ref_check_qpart
c7e51de1 1055 AND owner_uid = '$owner_uid' AND ref_id = article_id");
23aa0d16 1056
23aa0d16 1057 }
ad0056a8 1058
c7e51de1 1059 ccache_update($link, $feed, $owner_uid, $cat_view);
ad0056a8 1060
23aa0d16
AD
1061 } else { // tag
1062 db_query($link, "BEGIN");
1063
1064 $tag_name = db_escape_string($feed);
1065
1066 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
c7e51de1 1067 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
23aa0d16
AD
1068
1069 while ($line = db_fetch_assoc($result)) {
1070 db_query($link, "UPDATE ttrss_user_entries SET
8d505d78 1071 unread = false, last_read = NOW()
184f5195 1072 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
23aa0d16
AD
1073 }
1074 db_query($link, "COMMIT");
1075 }
1076 }
1077
5b55e9e2 1078 function getAllCounters($link) {
6a7817c1 1079 $data = getGlobalCounters($link);
8d505d78 1080
6a7817c1 1081 $data = array_merge($data, getVirtCounters($link));
5b55e9e2
AD
1082 $data = array_merge($data, getLabelCounters($link));
1083 $data = array_merge($data, getFeedCounters($link, $active_feed));
1084 $data = array_merge($data, getCategoryCounters($link));
6a7817c1
AD
1085
1086 return $data;
8d505d78 1087 }
a9cb1f83 1088
79178062
AD
1089 function getCategoryTitle($link, $cat_id) {
1090
1091 if ($cat_id == -1) {
1092 return __("Special");
1093 } else if ($cat_id == -2) {
1094 return __("Labels");
1095 } else {
1096
1097 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1098 id = '$cat_id'");
1099
1100 if (db_num_rows($result) == 1) {
1101 return db_fetch_result($result, 0, "title");
1102 } else {
f99759da 1103 return __("Uncategorized");
79178062
AD
1104 }
1105 }
1106 }
1107
1108
a9cb1f83 1109 function getCategoryCounters($link) {
6a7817c1 1110 $ret_arr = array();
bba7c4bf 1111
6a7817c1 1112 /* Labels category */
bba7c4bf 1113
8acc449c 1114 $cv = array("id" => -2, "kind" => "cat",
6a7817c1 1115 "counter" => getCategoryUnread($link, -2));
bba7c4bf 1116
6a7817c1 1117 array_push($ret_arr, $cv);
bba7c4bf 1118
2c5f231e
AD
1119 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1120 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1121 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
8d505d78
AD
1122 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1123 WHERE ttrss_cat_counters_cache.feed_id = id AND
fc9de939 1124 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
31375163 1125 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
1126
1127 while ($line = db_fetch_assoc($result)) {
22fdebff 1128 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 1129
2c5f231e 1130 if ($line["num_children"] > 0) {
99c9e91a 1131 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
2c5f231e
AD
1132 } else {
1133 $child_counter = 0;
1134 }
1135
8acc449c 1136 $cv = array("id" => $line["cat_id"], "kind" => "cat",
0ef32f48 1137 "counter" => $line["unread"] + $child_counter);
6a7817c1
AD
1138
1139 array_push($ret_arr, $cv);
a9cb1f83 1140 }
d232a40f
AD
1141
1142 /* Special case: NULL category doesn't actually exist in the DB */
1143
9798b2b4 1144 $cv = array("id" => 0, "kind" => "cat",
12e6de72 1145 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
d232a40f 1146
6a7817c1
AD
1147 array_push($ret_arr, $cv);
1148
1149 return $ret_arr;
a9cb1f83
AD
1150 }
1151
2c5f231e 1152 // only accepts real cats (>= 0)
99c9e91a 1153 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
2c5f231e
AD
1154 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1155
1156 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1157 AND owner_uid = $owner_uid");
1158
1159 $unread = 0;
1160
1161 while ($line = db_fetch_assoc($result)) {
1162 $unread += getCategoryUnread($link, $line["id"], $owner_uid);
99c9e91a 1163 $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
2c5f231e
AD
1164 }
1165
1166 return $unread;
1167 }
1168
b6d486a3
AD
1169 function getCategoryUnread($link, $cat, $owner_uid = false) {
1170
1171 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 1172
bba7c4bf 1173 if ($cat >= 0) {
18664970 1174
bba7c4bf
AD
1175 if ($cat != 0) {
1176 $cat_query = "cat_id = '$cat'";
1177 } else {
1178 $cat_query = "cat_id IS NULL";
1179 }
14073c0a 1180
8d505d78 1181 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 1182 AND owner_uid = " . $owner_uid);
8d505d78 1183
bba7c4bf
AD
1184 $cat_feeds = array();
1185 while ($line = db_fetch_assoc($result)) {
1186 array_push($cat_feeds, "feed_id = " . $line["id"]);
1187 }
8d505d78 1188
bba7c4bf 1189 if (count($cat_feeds) == 0) return 0;
8d505d78 1190
bba7c4bf 1191 $match_part = implode(" OR ", $cat_feeds);
8d505d78
AD
1192
1193 $result = db_query($link, "SELECT COUNT(int_id) AS unread
687bb90d
AD
1194 FROM ttrss_user_entries
1195 WHERE unread = true AND ($match_part)
1196 AND owner_uid = " . $owner_uid);
8d505d78 1197
bba7c4bf 1198 $unread = 0;
8d505d78 1199
bba7c4bf
AD
1200 # this needs to be rewritten
1201 while ($line = db_fetch_assoc($result)) {
1202 $unread += $line["unread"];
1203 }
8d505d78 1204
bba7c4bf
AD
1205 return $unread;
1206 } else if ($cat == -1) {
59e15af4 1207 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
bba7c4bf 1208 } else if ($cat == -2) {
f295c368 1209
b2531a28 1210 $result = db_query($link, "
8d505d78 1211 SELECT COUNT(unread) AS unread FROM
687bb90d
AD
1212 ttrss_user_entries, ttrss_user_labels2
1213 WHERE article_id = ref_id AND unread = true
b2531a28 1214 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 1215
b2531a28 1216 $unread = db_fetch_result($result, 0, "unread");
f295c368 1217
b2531a28 1218 return $unread;
f295c368 1219
8d505d78 1220 }
f295c368
AD
1221 }
1222
1223 function getFeedUnread($link, $feed, $is_cat = false) {
2627f2d0 1224 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
1225 }
1226
ceb30ba4
AD
1227 function getLabelUnread($link, $label_id, $owner_uid = false) {
1228 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1229
f360b028
AD
1230 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1231 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
ceb30ba4
AD
1232
1233 if (db_num_rows($result) != 0) {
1234 return db_fetch_result($result, 0, "unread");
1235 } else {
1236 return 0;
1237 }
1238 }
1239
2627f2d0
AD
1240 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1241 $owner_uid = false) {
1242
22fdebff 1243 $n_feed = (int) $feed;
687bb90d 1244 $need_entries = false;
f295c368 1245
2627f2d0
AD
1246 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1247
bdb7369b
AD
1248 if ($unread_only) {
1249 $unread_qpart = "unread = true";
1250 } else {
1251 $unread_qpart = "true";
1252 }
1253
f295c368 1254 if ($is_cat) {
8d505d78 1255 return getCategoryUnread($link, $n_feed, $owner_uid);
5417fbd7
AD
1256 } else if ($n_feed == -6) {
1257 return 0;
1258 } else if ($feed != "0" && $n_feed == 0) {
326469fc 1259
c5701e70
AD
1260 $feed = db_escape_string($feed);
1261
326469fc 1262 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
8d505d78 1263 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
687bb90d 1264 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
1265 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1266 return db_fetch_result($result, 0, "count");
1267
f295c368 1268 } else if ($n_feed == -1) {
a9cb1f83 1269 $match_part = "marked = true";
e4f4b46f
AD
1270 } else if ($n_feed == -2) {
1271 $match_part = "published = true";
2d24f032 1272 } else if ($n_feed == -3) {
cd2cc43d 1273 $match_part = "unread = true AND score >= 0";
2d24f032 1274
b71e188e 1275 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 1276
2d24f032 1277 if (DB_TYPE == "pgsql") {
8d505d78 1278 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 1279 } else {
7608b38a 1280 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 1281 }
687bb90d
AD
1282
1283 $need_entries = true;
1284
b2531a28
AD
1285 } else if ($n_feed == -4) {
1286 $match_part = "true";
e04c18a2 1287 } else if ($n_feed >= 0) {
831ff047 1288
6e63a7c3
AD
1289 if ($n_feed != 0) {
1290 $match_part = "feed_id = '$n_feed'";
831ff047 1291 } else {
6e63a7c3 1292 $match_part = "feed_id IS NULL";
831ff047 1293 }
6e63a7c3 1294
a9cb1f83 1295 } else if ($feed < -10) {
318260cc 1296
a9cb1f83
AD
1297 $label_id = -$feed - 11;
1298
ceb30ba4 1299 return getLabelUnread($link, $label_id, $owner_uid);
a9cb1f83 1300
a9cb1f83
AD
1301 }
1302
1303 if ($match_part) {
e04c18a2 1304
687bb90d 1305 if ($need_entries) {
e04c18a2 1306 $from_qpart = "ttrss_user_entries,ttrss_entries";
687bb90d
AD
1307 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1308 } else {
1309 $from_qpart = "ttrss_user_entries";
e04c18a2
AD
1310 }
1311
8d505d78 1312 $query = "SELECT count(int_id) AS unread
e04c18a2 1313 FROM $from_qpart WHERE
687bb90d
AD
1314 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1315
1316 //echo "[$feed/$query]\n";
dbfc4365
AD
1317
1318 $result = db_query($link, $query);
8d505d78 1319
a9cb1f83 1320 } else {
8d505d78 1321
a9cb1f83 1322 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
8d505d78
AD
1323 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1324 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
687bb90d 1325 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 1326 }
8d505d78 1327
a9cb1f83 1328 $unread = db_fetch_result($result, 0, "unread");
cfb02131 1329
a9cb1f83
AD
1330 return $unread;
1331 }
1332
f3acc32e
AD
1333 function getGlobalUnread($link, $user_id = false) {
1334
1335 if (!$user_id) {
1336 $user_id = $_SESSION["uid"];
1337 }
1338
8a4c759e
AD
1339 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1340 WHERE owner_uid = '$user_id' AND feed_id > 0");
1341
8d505d78 1342 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 1343
a9cb1f83
AD
1344 return $c_id;
1345 }
1346
1347 function getGlobalCounters($link, $global_unread = -1) {
6a7817c1
AD
1348 $ret_arr = array();
1349
8d505d78 1350 if ($global_unread == -1) {
a9cb1f83
AD
1351 $global_unread = getGlobalUnread($link);
1352 }
6a7817c1 1353
8d505d78 1354 $cv = array("id" => "global-unread",
12e6de72 1355 "counter" => (int) $global_unread);
6a7817c1
AD
1356
1357 array_push($ret_arr, $cv);
7bf7e4d3 1358
8d505d78 1359 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
1360 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1361
1362 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1363
8d505d78 1364 $cv = array("id" => "subscribed-feeds",
12e6de72 1365 "counter" => (int) $subscribed_feeds);
7bf7e4d3 1366
6a7817c1
AD
1367 array_push($ret_arr, $cv);
1368
1369 return $ret_arr;
a9cb1f83
AD
1370 }
1371
6a7817c1 1372 function getVirtCounters($link) {
a9cb1f83 1373
ef393de7 1374 $ret_arr = array();
bdb7369b 1375
e04c18a2 1376 for ($i = 0; $i >= -4; $i--) {
bdb7369b 1377
ceb30ba4 1378 $count = getFeedUnread($link, $i);
6a7817c1
AD
1379
1380 $cv = array("id" => $i,
12e6de72 1381 "counter" => (int) $count);
8d505d78 1382
296c8134
AD
1383// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1384// $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
bdb7369b 1385
6a7817c1 1386 array_push($ret_arr, $cv);
8d505d78 1387 }
0a6e5382
AD
1388
1389 return $ret_arr;
1390 }
1391
11232703 1392 function getLabelCounters($link, $descriptions = false) {
6a7817c1
AD
1393
1394 $ret_arr = array();
0a6e5382 1395
3809b278 1396 $owner_uid = $_SESSION["uid"];
bdb7369b 1397
3809b278
AD
1398 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1399 WHERE owner_uid = '$owner_uid'");
8d505d78 1400
3809b278 1401 while ($line = db_fetch_assoc($result)) {
2d24f032 1402
3809b278 1403 $id = -$line["id"] - 11;
e4f4b46f 1404
3809b278
AD
1405 $label_name = $line["caption"];
1406 $count = getFeedUnread($link, $id);
3809b278 1407
6a7817c1 1408 $cv = array("id" => $id,
12e6de72 1409 "counter" => (int) $count);
11232703
AD
1410
1411 if ($descriptions)
1412 $cv["description"] = $label_name;
a9cb1f83 1413
296c8134
AD
1414// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1415// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
ef393de7 1416
6a7817c1 1417 array_push($ret_arr, $cv);
3809b278 1418 }
8d505d78 1419
ef393de7 1420 return $ret_arr;
a9cb1f83
AD
1421 }
1422
3809b278 1423 function getFeedCounters($link, $active_feed = false) {
a9cb1f83 1424
6a7817c1
AD
1425 $ret_arr = array();
1426
8a4c759e
AD
1427 $query = "SELECT ttrss_feeds.id,
1428 ttrss_feeds.title,
8d505d78 1429 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
1430 last_error, value AS count
1431 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 1432 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
fc9de939 1433 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
55e01d7e 1434 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 1435
14073c0a 1436 $result = db_query($link, $query);
a9cb1f83
AD
1437 $fctrs_modified = false;
1438
1439 while ($line = db_fetch_assoc($result)) {
8d505d78 1440
a9cb1f83 1441 $id = $line["id"];
de0a2122 1442 $count = $line["count"];
a9cb1f83 1443 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 1444
324944f3 1445 $last_updated = make_local_datetime($link, $line['last_updated'], false);
fb1fb4ab 1446
7defa089 1447 $has_img = feed_has_icon($id);
a9cb1f83 1448
428b704d
AD
1449 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1450 $last_updated = '';
1451
6a7817c1 1452 $cv = array("id" => $id,
21884958 1453 "updated" => $last_updated,
12e6de72 1454 "counter" => (int) $count,
6a7817c1 1455 "has_img" => (int) $has_img);
a9cb1f83 1456
6a7817c1
AD
1457 if ($last_error)
1458 $cv["error"] = $last_error;
4ffa126e 1459
296c8134
AD
1460// if (get_pref($link, 'EXTENDED_FEEDLIST'))
1461// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
bdb7369b 1462
6a7817c1 1463 if ($active_feed && $id == $active_feed)
fbc95c5b 1464 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
1465
1466 array_push($ret_arr, $cv);
a9cb1f83 1467
a9cb1f83 1468 }
6a7817c1
AD
1469
1470 return $ret_arr;
a9cb1f83
AD
1471 }
1472
6e7f8d26
AD
1473 function get_pgsql_version($link) {
1474 $result = db_query($link, "SELECT version() AS version");
9949bd15 1475 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
1476 return $version[1];
1477 }
1478
2b8290cd 1479 /**
23d2471c
AD
1480 * @return array (code => Status code, message => error message if available)
1481 *
2b8290cd
CW
1482 * 0 - OK, Feed already exists
1483 * 1 - OK, Feed added
1484 * 2 - Invalid URL
9a8ce956
CW
1485 * 3 - URL content is HTML, no feeds available
1486 * 4 - URL content is HTML which contains multiple feeds.
1487 * Here you should call extractfeedurls in rpc-backend
1488 * to get all possible feeds.
5414ad4c 1489 * 5 - Couldn't download the URL content.
2b8290cd 1490 */
8d505d78 1491 function subscribe_to_feed($link, $url, $cat_id = 0,
aa60999b 1492 $auth_login = '', $auth_pass = '', $need_auth = false) {
bb0f29a4 1493
23d2471c
AD
1494 global $fetch_last_error;
1495
2c08214a
AD
1496 require_once "include/rssfuncs.php";
1497
f0266f51 1498 $url = fix_url($url);
ec39a02c 1499
23d2471c 1500 if (!$url || !validate_feed_url($url)) return array("code" => 2);
a5819bb3 1501
759e5132
AD
1502 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1503
1504 if (!$contents) {
304aadb9 1505 return array("code" => 5, "message" => $fetch_last_error);
759e5132
AD
1506 }
1507
1508 if (is_html($contents)) {
1509 $feedUrls = get_feeds_from_html($url, $contents);
304aadb9 1510
304aadb9
AD
1511 if (count($feedUrls) == 0) {
1512 return array("code" => 3);
1513 } else if (count($feedUrls) > 1) {
759e5132 1514 return array("code" => 4, "feeds" => $feedUrls);
f6d8345b 1515 }
304aadb9
AD
1516 //use feed url as new URL
1517 $url = key($feedUrls);
1518 }
f6d8345b 1519
956c7629
AD
1520 if ($cat_id == "0" || !$cat_id) {
1521 $cat_qpart = "NULL";
1522 } else {
1523 $cat_qpart = "'$cat_id'";
1524 }
8d505d78 1525
956c7629 1526 $result = db_query($link,
8d505d78 1527 "SELECT id FROM ttrss_feeds
a5819bb3 1528 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 1529
956c7629 1530 if (db_num_rows($result) == 0) {
956c7629 1531 $result = db_query($link,
8d505d78
AD
1532 "INSERT INTO ttrss_feeds
1533 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1534 VALUES ('".$_SESSION["uid"]."', '$url',
19b3992b 1535 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
8d505d78 1536
956c7629 1537 $result = db_query($link,
8d505d78 1538 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 1539 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 1540
956c7629 1541 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 1542
956c7629 1543 if ($feed_id) {
c633e370 1544 update_rss_feed($link, $feed_id, true);
956c7629
AD
1545 }
1546
23d2471c 1547 return array("code" => 1);
956c7629 1548 } else {
23d2471c 1549 return array("code" => 0);
956c7629
AD
1550 }
1551 }
1552
8d505d78 1553 function print_feed_select($link, $id, $default_id = "",
4c9d0490
AD
1554 $attributes = "", $include_all_feeds = true,
1555 $root_id = false, $nest_level = 0) {
1556
1557 if (!$root_id) {
1558 print "<select id=\"$id\" name=\"$id\" $attributes>";
1559 if ($include_all_feeds) {
1560 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1561 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1562 }
673d54ca 1563 }
8d505d78 1564
4c9d0490 1565 if (get_pref($link, 'ENABLE_FEED_CATS')) {
673d54ca 1566
4c9d0490
AD
1567 if ($root_id)
1568 $parent_qpart = "parent_cat = '$root_id'";
1569 else
1570 $parent_qpart = "parent_cat IS NULL";
673d54ca 1571
4c9d0490
AD
1572 $result = db_query($link, "SELECT id,title,
1573 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1574 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1575 FROM ttrss_feed_categories
1576 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1577
1578 while ($line = db_fetch_assoc($result)) {
1579
1580 for ($i = 0; $i < $nest_level; $i++)
1581 $line["title"] = " - " . $line["title"];
1582
1583 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1584
1585 printf("<option $is_selected value='CAT:%d'>%s</option>",
1586 $line["id"], htmlspecialchars($line["title"]));
1587
1588 if ($line["num_children"] > 0)
1589 print_feed_select($link, $id, $default_id, $attributes,
1590 $include_all_feeds, $line["id"], $nest_level+1);
1591
1592 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1593 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1594
1595 while ($fline = db_fetch_assoc($feed_result)) {
1596 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1597
1598 $fline["title"] = " + " . $fline["title"];
1599
1600 for ($i = 0; $i < $nest_level; $i++)
1601 $fline["title"] = " - " . $fline["title"];
1602
1603 printf("<option $is_selected value='%d'>%s</option>",
1604 $fline["id"], htmlspecialchars($fline["title"]));
1605 }
673d54ca 1606 }
b1710666 1607
4c9d0490
AD
1608 if (!$root_id) {
1609 $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
1610
1611 printf("<option $is_selected value='CAT:0'>%s</option>",
1612 __("Uncategorized"));
1613
1614 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1615 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1616
1617 while ($fline = db_fetch_assoc($feed_result)) {
1618 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1619
1620 $fline["title"] = " + " . $fline["title"];
1621
1622 for ($i = 0; $i < $nest_level; $i++)
1623 $fline["title"] = " - " . $fline["title"];
1624
1625 printf("<option $is_selected value='%d'>%s</option>",
1626 $fline["id"], htmlspecialchars($fline["title"]));
1627 }
1628 }
b1710666 1629
4c9d0490
AD
1630 } else {
1631 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1632 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1633
1634 while ($line = db_fetch_assoc($result)) {
1635
1636 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1637
1638 printf("<option $is_selected value='%d'>%s</option>",
1639 $line["id"], htmlspecialchars($line["title"]));
1640 }
673d54ca 1641 }
8d505d78 1642
4c9d0490
AD
1643 if (!$root_id) {
1644 print "</select>";
1645 }
673d54ca
AD
1646 }
1647
fbf85cf6
AD
1648 function print_feed_cat_select($link, $id, $default_id,
1649 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
8d505d78 1650
fbf85cf6
AD
1651 if (!$root_id) {
1652 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1653 }
673d54ca 1654
fbf85cf6
AD
1655 if ($root_id)
1656 $parent_qpart = "parent_cat = '$root_id'";
1657 else
1658 $parent_qpart = "parent_cat IS NULL";
673d54ca 1659
fbf85cf6
AD
1660 $result = db_query($link, "SELECT id,title,
1661 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1662 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1663 FROM ttrss_feed_categories
1664 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
673d54ca 1665
fbf85cf6
AD
1666 while ($line = db_fetch_assoc($result)) {
1667 if ($line["id"] == $default_id) {
1668 $is_selected = "selected=\"1\"";
1669 } else {
1670 $is_selected = "";
1671 }
673d54ca 1672
fbf85cf6
AD
1673 for ($i = 0; $i < $nest_level; $i++)
1674 $line["title"] = " - " . $line["title"];
c00907f2 1675
fbf85cf6
AD
1676 if ($line["title"])
1677 printf("<option $is_selected value='%d'>%s</option>",
1678 $line["id"], htmlspecialchars($line["title"]));
673d54ca 1679
fbf85cf6
AD
1680 if ($line["num_children"] > 0)
1681 print_feed_cat_select($link, $id, $default_id, $attributes,
1682 $include_all_cats, $line["id"], $nest_level+1);
1683 }
5c7c7da9 1684
fbf85cf6
AD
1685 if (!$root_id) {
1686 if ($include_all_cats) {
1687 if (db_num_rows($result) > 0) {
1688 print "<option disabled=\"1\">--------</option>";
1689 }
7e18f8e7
AD
1690
1691 if ($default_id == 0) {
1692 $is_selected = "selected=\"1\"";
1693 } else {
1694 $is_selected = "";
1695 }
1696
1697 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
fbf85cf6
AD
1698 }
1699 print "</select>";
1700 }
1701 }
8d505d78 1702
14f69488
AD
1703 function checkbox_to_sql_bool($val) {
1704 return ($val == "on") ? "true" : "false";
1705 }
86b682ce
AD
1706
1707 function getFeedCatTitle($link, $id) {
1708 if ($id == -1) {
d1db26aa 1709 return __("Special");
86b682ce 1710 } else if ($id < -10) {
d1db26aa 1711 return __("Labels");
86b682ce 1712 } else if ($id > 0) {
8d505d78 1713 $result = db_query($link, "SELECT ttrss_feed_categories.title
86b682ce
AD
1714 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1715 cat_id = ttrss_feed_categories.id");
1716 if (db_num_rows($result) == 1) {
1717 return db_fetch_result($result, 0, "title");
1718 } else {
d1db26aa 1719 return __("Uncategorized");
86b682ce
AD
1720 }
1721 } else {
1722 return "getFeedCatTitle($id) failed";
1723 }
1724
1725 }
1726
9299102f 1727 function getFeedIcon($id) {
af88c48a 1728 switch ($id) {
4bee8b5f
AD
1729 case 0:
1730 return "images/archive.png";
1731 break;
af88c48a 1732 case -1:
c2167866 1733 return "images/mark_set.svg";
af88c48a
AD
1734 break;
1735 case -2:
c2167866 1736 return "images/pub_set.svg";
af88c48a
AD
1737 break;
1738 case -3:
1739 return "images/fresh.png";
1740 break;
1741 case -4:
1742 return "images/tag.png";
1743 break;
5417fbd7
AD
1744 case -6:
1745 return "images/recently_read.png";
1746 break;
af88c48a 1747 default:
4bee8b5f
AD
1748 if ($id < -10) {
1749 return "images/label.png";
1750 } else {
8d505d78 1751 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 1752 return ICONS_URL . "/$id.ico";
4bee8b5f 1753 }
af88c48a
AD
1754 break;
1755 }
1756 }
1757
fd994f1a
AD
1758 function getFeedTitle($link, $id, $cat = false) {
1759 if ($cat) {
8add44ec 1760 return getCategoryTitle($link, $id);
fd994f1a 1761 } else if ($id == -1) {
d1db26aa 1762 return __("Starred articles");
945c243e
AD
1763 } else if ($id == -2) {
1764 return __("Published articles");
2d24f032
AD
1765 } else if ($id == -3) {
1766 return __("Fresh articles");
b2531a28
AD
1767 } else if ($id == -4) {
1768 return __("All articles");
80db1113 1769 } else if ($id === 0 || $id === "0") {
e04c18a2 1770 return __("Archived articles");
5417fbd7
AD
1771 } else if ($id == -6) {
1772 return __("Recently read");
86b682ce 1773 } else if ($id < -10) {
76626c72 1774 $label_id = -$id - 11;
ceb30ba4 1775 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 1776 if (db_num_rows($result) == 1) {
ceb30ba4 1777 return db_fetch_result($result, 0, "caption");
86b682ce
AD
1778 } else {
1779 return "Unknown label ($label_id)";
1780 }
1781
147f5632 1782 } else if (is_numeric($id) && $id > 0) {
86b682ce
AD
1783 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1784 if (db_num_rows($result) == 1) {
1785 return db_fetch_result($result, 0, "title");
1786 } else {
1787 return "Unknown feed ($id)";
1788 }
1789 } else {
22fdebff 1790 return $id;
86b682ce 1791 }
86b682ce 1792 }
3dd46f19 1793
d8221301 1794 function make_init_params($link) {
f1f3a642 1795 $params = array();
c9268ed5 1796
c4f7ba80
AD
1797 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1798 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
c2167866
AD
1799 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1800 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
be0801a1 1801
f1f3a642
AD
1802 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1803 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
7d12b6c8 1804 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
30b6ee8c 1805 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 1806
c4f7ba80 1807 $params[strtolower($param)] = (int) get_pref($link, $param);
f1f3a642 1808 }
40496720 1809
c4f7ba80
AD
1810 $params["icons_url"] = ICONS_URL;
1811 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
1812 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1813 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1814 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
c4f7ba80 1815 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
59b223d7 1816
8cd576a1 1817 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
1818 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1819
8cd576a1
AD
1820 $max_feed_id = db_fetch_result($result, 0, "mid");
1821 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 1822
8cd576a1 1823 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 1824 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 1825
c4f7ba80 1826 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
b8cb4d08 1827 $params["hotkeys"] = get_hotkeys_map($link);
9b7ecc0a 1828
8484ce22 1829 $params["csrf_token"] = $_SESSION["csrf_token"];
7d8f5657 1830 $params["widescreen"] = (int) $_SESSION["widescreen"];
8484ce22 1831
6b1a4ecd 1832 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
8b83bf5f 1833
d8221301 1834 return $params;
3ac2b520 1835 }
f54f515f 1836
b8cb4d08
AD
1837 function get_hotkeys_info($link) {
1838 $hotkeys = array(
1839 __("Navigation") => array(
1840 "next_feed" => __("Open next feed"),
1841 "prev_feed" => __("Open previous feed"),
1842 "next_article" => __("Open next article"),
1843 "prev_article" => __("Open previous article"),
1844 "search_dialog" => __("Show search dialog")),
1845 __("Article") => array(
1846 "toggle_mark" => __("Toggle starred"),
1847 "toggle_publ" => __("Toggle published"),
1848 "toggle_unread" => __("Toggle unread"),
1849 "edit_tags" => __("Edit tags"),
1850 "dismiss_selected" => __("Dismiss selected"),
1851 "dismiss_read" => __("Dismiss read"),
1852 "open_in_new_window" => __("Open in new window"),
1853 "catchup_below" => __("Mark below as read"),
1854 "catchup_above" => __("Mark above as read"),
1855 "article_scroll_down" => __("Scroll down"),
1856 "article_scroll_up" => __("Scroll up"),
1857 "select_article_cursor" => __("Select article under cursor"),
1bcf8f45 1858 "email_article" => __("Email article"),
2cda4314 1859 "close_article" => __("Close article"),
1bcf8f45 1860 "toggle_widescreen" => __("Toggle widescreen mode")),
b8cb4d08
AD
1861 __("Article selection") => array(
1862 "select_all" => __("Select all articles"),
1863 "select_unread" => __("Select unread"),
1864 "select_marked" => __("Select starred"),
1865 "select_published" => __("Select published"),
1866 "select_invert" => __("Invert selection"),
1867 "select_none" => __("Deselect everything")),
1868 __("Feed") => array(
1869 "feed_refresh" => __("Refresh current feed"),
1870 "feed_unhide_read" => __("Un/hide read feeds"),
1871 "feed_subscribe" => __("Subscribe to feed"),
1872 "feed_edit" => __("Edit feed"),
1873 "feed_catchup" => __("Mark as read"),
1874 "feed_reverse" => __("Reverse headlines"),
43f775de 1875 "feed_debug_update" => __("Debug feed update"),
b8cb4d08
AD
1876 "catchup_all" => __("Mark all feeds as read"),
1877 "cat_toggle_collapse" => __("Un/collapse current category")),
1878 __("Go to") => array(
1879 "goto_all" => __("All articles"),
1880 "goto_fresh" => __("Fresh"),
1881 "goto_marked" => __("Starred"),
1882 "goto_published" => __("Published"),
1883 "goto_tagcloud" => __("Tag cloud"),
1884 "goto_prefs" => __("Preferences")),
1885 __("Other") => array(
1886 "create_label" => __("Create label"),
1887 "create_filter" => __("Create filter"),
1888 "collapse_sidebar" => __("Un/collapse sidebar"),
1889 "help_dialog" => __("Show help dialog"))
1890 );
1891
1892 return $hotkeys;
1893 }
1894
1895 function get_hotkeys_map($link) {
a83b58f1 1896 $hotkeys = array(
e218c5f5
AD
1897// "navigation" => array(
1898 "k" => "next_feed",
1899 "j" => "prev_feed",
1900 "n" => "next_article",
1901 "p" => "prev_article",
e5e2cf3b
AD
1902 "(38)|up" => "prev_article",
1903 "(40)|down" => "next_article",
1904 "(191)|/" => "search_dialog",
e218c5f5
AD
1905// "article" => array(
1906 "s" => "toggle_mark",
1907 "S" => "toggle_publ",
1908 "u" => "toggle_unread",
1909 "T" => "edit_tags",
1910 "D" => "dismiss_selected",
1911 "X" => "dismiss_read",
1912 "o" => "open_in_new_window",
1913 "c p" => "catchup_below",
1914 "c n" => "catchup_above",
1915 "N" => "article_scroll_down",
1916 "P" => "article_scroll_up",
1bcf8f45 1917 "a W" => "toggle_widescreen",
e218c5f5 1918 "e" => "email_article",
2cda4314 1919 "a q" => "close_article",
e218c5f5
AD
1920// "article_selection" => array(
1921 "a a" => "select_all",
1922 "a u" => "select_unread",
1923 "a U" => "select_marked",
1924 "a p" => "select_published",
1925 "a i" => "select_invert",
1926 "a n" => "select_none",
1927// "feed" => array(
1928 "f r" => "feed_refresh",
1929 "f a" => "feed_unhide_read",
1930 "f s" => "feed_subscribe",
1931 "f e" => "feed_edit",
1932 "f q" => "feed_catchup",
1933 "f x" => "feed_reverse",
1934 "f D" => "feed_debug_update",
1935 "Q" => "catchup_all",
1936 "x" => "cat_toggle_collapse",
1937// "goto" => array(
1938 "g a" => "goto_all",
1939 "g f" => "goto_fresh",
1940 "g s" => "goto_marked",
1941 "g p" => "goto_published",
1942 "g t" => "goto_tagcloud",
1943 "g P" => "goto_prefs",
1944// "other" => array(
3fb40112 1945 "(9)|Tab" => "select_article_cursor", // tab
e218c5f5
AD
1946 "c l" => "create_label",
1947 "c f" => "create_filter",
1948 "c s" => "collapse_sidebar",
3fb40112 1949 "^(191)|Ctrl+/" => "help_dialog",
a83b58f1
AD
1950 );
1951
e218c5f5
AD
1952 global $pluginhost;
1953 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
1954 $hotkeys = $plugin->hook_hotkey_map($hotkeys);
1955 }
1956
1957 $prefixes = array();
1958
1959 foreach (array_keys($hotkeys) as $hotkey) {
1960 $pair = explode(" ", $hotkey, 2);
1961
1962 if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
1963 array_push($prefixes, $pair[0]);
1964 }
1965 }
1966
1967 return array($prefixes, $hotkeys);
a83b58f1
AD
1968 }
1969
c4f7ba80 1970 function make_runtime_info($link) {
8cd576a1
AD
1971 $data = array();
1972
1973 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
1974 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1975
8cd576a1
AD
1976 $max_feed_id = db_fetch_result($result, 0, "mid");
1977 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 1978
8cd576a1
AD
1979 $data["max_feed_id"] = (int) $max_feed_id;
1980 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 1981
f8fb4498 1982 $data['last_article_id'] = getLastArticleId($link);
5ae8f858 1983 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
f8fb4498 1984
dbaa4e4a 1985 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
1986
1987 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 1988
9041f58b 1989 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 1990
fb074239 1991 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 1992
8e00ae9b 1993 if ($stamp) {
9041f58b
AD
1994 $stamp_delta = time() - $stamp;
1995
1996 if ($stamp_delta > 1800) {
f6854e44 1997 $stamp_check = 0;
8e00ae9b 1998 } else {
f6854e44
AD
1999 $stamp_check = 1;
2000 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
2001 }
2002
c4f7ba80 2003 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 2004
8e00ae9b
AD
2005 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2006
c4f7ba80 2007 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 2008 }
8e00ae9b 2009 }
71ad883b 2010 }
8e00ae9b 2011
63855db1 2012 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
fb074239 2013 $new_version_details = @check_for_update($link);
d9fa39f1 2014
63855db1 2015 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
2016
2017 $_SESSION["last_version_check"] = time();
27211afe 2018 $_SESSION["version_data"] = $new_version_details;
d9fa39f1
AD
2019 }
2020
c4f7ba80 2021 return $data;
f54f515f 2022 }
ef393de7 2023
b7d1a163 2024 function search_to_sql($link, $search, $match_on) {
ef393de7 2025
88040f57 2026 $search_query_part = "";
e20c9d88 2027
9949bd15 2028 $keywords = explode(" ", $search);
88040f57 2029 $query_keywords = array();
e20c9d88 2030
ab4b768f
AD
2031 foreach ($keywords as $k) {
2032 if (strpos($k, "-") === 0) {
2033 $k = substr($k, 1);
2034 $not = "NOT";
2035 } else {
2036 $not = "";
88040f57 2037 }
e20c9d88 2038
9949bd15 2039 $commandpair = explode(":", mb_strtolower($k), 2);
53003548
AD
2040
2041 if ($commandpair[0] == "note" && $commandpair[1]) {
2042
2043 if ($commandpair[1] == "true")
2044 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2045 else
2046 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2047
2048 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2049
2050 if ($commandpair[1] == "true")
2051 array_push($query_keywords, "($not (marked = true))");
2052 else
2053 array_push($query_keywords, "($not (marked = false))");
2054
2055 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2056
2057 if ($commandpair[1] == "true")
2058 array_push($query_keywords, "($not (published = true))");
2059 else
2060 array_push($query_keywords, "($not (published = false))");
2061
2062 } else if (strpos($k, "@") === 0) {
e20c9d88 2063
ab4b768f
AD
2064 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2065 $orig_ts = strtotime(substr($k, 1));
ab4b768f 2066 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 2067
53003548
AD
2068 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2069
ab4b768f
AD
2070 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2071 } else if ($match_on == "both") {
2072 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2073 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2074 } else if ($match_on == "title") {
eb6c7f42 2075 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
ab4b768f 2076 } else if ($match_on == "content") {
eb6c7f42 2077 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
88040f57
AD
2078 }
2079 }
2080
2081 $search_query_part = implode("AND", $query_keywords);
2082
2083 return $search_query_part;
2084 }
2085
67bd0b1f
AD
2086 function getParentCategories($link, $cat, $owner_uid) {
2087 $rv = array();
2088
2089 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2090 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2091
2092 while ($line = db_fetch_assoc($result)) {
2093 array_push($rv, $line["parent_cat"]);
2094 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2095 }
2096
2097 return $rv;
2098 }
2099
6d8d00e8
AD
2100 function getChildCategories($link, $cat, $owner_uid) {
2101 $rv = array();
2102
2103 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2104 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2105
2106 while ($line = db_fetch_assoc($result)) {
2107 array_push($rv, $line["id"]);
2108 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2109 }
2110
2111 return $rv;
2112 }
147f5632 2113
09101297 2114 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false) {
c36bf4d5
AD
2115
2116 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 2117
c3fddd05
AD
2118 $ext_tables_part = "";
2119
88040f57 2120 if ($search) {
e4f7f8df
AD
2121
2122 if (SPHINX_ENABLED) {
2123 $ids = join(",", @sphinx_search($search, 0, 500));
2124
8d505d78 2125 if ($ids)
e4f7f8df
AD
2126 $search_query_part = "ref_id IN ($ids) AND ";
2127 else
2128 $search_query_part = "ref_id = -1 AND ";
2129
2130 } else {
b7d1a163 2131 $search_query_part = search_to_sql($link, $search, $match_on);
e4f7f8df 2132 $search_query_part .= " AND ";
8d505d78 2133 }
e20c9d88 2134
ef393de7
AD
2135 } else {
2136 $search_query_part = "";
2137 }
2138
36184020 2139 if ($filter) {
4e02f582
AD
2140
2141 if (DB_TYPE == "pgsql") {
2142 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2143 } else {
2144 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2145 }
2146
2147 $override_order = "updated DESC";
2148
2680295b 2149 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
dd8c36af
AD
2150
2151 // Try to check if SQL regexp implementation chokes on a valid regexp
809c8e62 2152 $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
2680295b 2153 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
dd8c36af
AD
2154 WHERE $filter_query_part LIMIT 1", false);
2155
809c8e62 2156 $test = db_fetch_result($result, 0, "true_val");
dd8c36af
AD
2157
2158 if (!$test) {
2159 $filter_query_part = "false AND";
2160 } else {
2161 $filter_query_part .= " AND";
2162 }
2163
36184020
AD
2164 } else {
2165 $filter_query_part = "";
2166 }
2167
97e5dbb2
AD
2168 if ($since_id) {
2169 $since_id_part = "ttrss_entries.id > $since_id AND ";
2170 } else {
2171 $since_id_part = "";
2172 }
2173
ef393de7 2174 $view_query_part = "";
8d505d78 2175
7b4d02a8 2176 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
ef393de7
AD
2177 if ($search) {
2178 $view_query_part = " ";
2179 } else if ($feed != -1) {
f295c368 2180 $unread = getFeedUnread($link, $feed, $cat_view);
6d8d00e8 2181
09101297 2182 if ($cat_view && $feed > 0 && $include_children)
99c9e91a 2183 $unread += getCategoryChildrenUnread($link, $feed);
6d8d00e8 2184
ef393de7 2185 if ($unread > 0) {
ff863e00 2186 $view_query_part = " unread = true AND ";
ef393de7
AD
2187 }
2188 }
2189 }
8d505d78 2190
ef393de7
AD
2191 if ($view_mode == "marked") {
2192 $view_query_part = " marked = true AND ";
2193 }
23d72f39
AD
2194
2195 if ($view_mode == "published") {
2196 $view_query_part = " published = true AND ";
2197 }
2198
ef393de7
AD
2199 if ($view_mode == "unread") {
2200 $view_query_part = " unread = true AND ";
2201 }
8b09eac8
AD
2202
2203 if ($view_mode == "updated") {
2204 $view_query_part = " (last_read is null and unread = false) AND ";
2205 }
2206
ef393de7
AD
2207 if ($limit > 0) {
2208 $limit_query_part = "LIMIT " . $limit;
8d505d78 2209 }
ef393de7 2210
8361e724
AD
2211 $allow_archived = false;
2212
ef393de7 2213 $vfeed_query_part = "";
8d505d78 2214
ef393de7
AD
2215 // override query strategy and enable feed display when searching globally
2216 if ($search && $search_mode == "all_feeds") {
7032f2a5 2217 $query_strategy_part = "true";
8d505d78 2218 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 2219 /* tags */
75c648cf 2220 } else if (!is_numeric($feed)) {
7032f2a5 2221 $query_strategy_part = "true";
ef393de7
AD
2222 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2223 id = feed_id) as feed_title,";
7032f2a5 2224 } else if ($search && $search_mode == "this_cat") {
8d505d78 2225 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846 2226
7032f2a5
AD
2227 if ($feed > 0) {
2228 if ($include_children) {
2229 $subcats = getChildCategories($link, $feed, $owner_uid);
2230 array_push($subcats, $feed);
2231 $cats_qpart = join(",", $subcats);
2232 } else {
2233 $cats_qpart = $feed;
ef393de7 2234 }
8d505d78 2235
7032f2a5 2236 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
8d505d78 2237
ef393de7 2238 } else {
7032f2a5 2239 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
ef393de7 2240 }
8d505d78 2241
e04c18a2 2242 } else if ($feed > 0) {
8d505d78 2243
ef393de7 2244 if ($cat_view) {
5c365f60 2245
ef393de7 2246 if ($feed > 0) {
09101297
AD
2247 if ($include_children) {
2248 # sub-cats
2249 $subcats = getChildCategories($link, $feed, $owner_uid);
2250
7032f2a5
AD
2251 array_push($subcats, $feed);
2252 $query_strategy_part = "cat_id IN (".
09101297 2253 implode(",", $subcats).")";
7032f2a5 2254
6d8d00e8 2255 } else {
09101297 2256 $query_strategy_part = "cat_id = '$feed'";
6d8d00e8
AD
2257 }
2258
ef393de7
AD
2259 } else {
2260 $query_strategy_part = "cat_id IS NULL";
2261 }
8d505d78 2262
ef393de7 2263 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 2264
8d505d78 2265 } else {
6e63a7c3 2266 $query_strategy_part = "feed_id = '$feed'";
ef393de7 2267 }
bfe5ddfc 2268 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 2269 $query_strategy_part = "feed_id IS NULL";
8361e724 2270 $allow_archived = true;
bfe5ddfc 2271 } else if ($feed == 0 && $cat_view) { // uncategorized
65dd90f2 2272 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
bfe5ddfc 2273 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2274 } else if ($feed == -1) { // starred virtual feed
2275 $query_strategy_part = "marked = true";
2276 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294
AD
2277 $allow_archived = true;
2278
e6a38cde
AD
2279 } else if ($feed == -2) { // published virtual feed OR labels category
2280
2281 if (!$cat_view) {
2282 $query_strategy_part = "published = true";
2283 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
8361e724 2284 $allow_archived = true;
46b78149
AD
2285
2286 if (!$override_order) $override_order = "last_read DESC, updated DESC";
e6a38cde
AD
2287 } else {
2288 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2289
2290 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 2291
e6a38cde
AD
2292 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2293 ttrss_user_labels2.article_id = ref_id";
2294
2295 }
5417fbd7 2296 } else if ($feed == -6) { // recently read
5089b30b 2297 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
5417fbd7 2298 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294 2299 $allow_archived = true;
46b78149
AD
2300
2301 if (!$override_order) $override_order = "last_read DESC";
2d24f032 2302 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 2303 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 2304
7a22dc2a 2305 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2306
2d24f032 2307 if (DB_TYPE == "pgsql") {
8d505d78 2308 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2309 } else {
7608b38a 2310 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
2311 }
2312
b2531a28
AD
2313 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2314 } else if ($feed == -4) { // all articles virtual feed
2315 $query_strategy_part = "true";
e4f4b46f 2316 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2317 } else if ($feed <= -10) { // labels
2318 $label_id = -$feed - 11;
3de0261a 2319
ceb30ba4
AD
2320 $query_strategy_part = "label_id = '$label_id' AND
2321 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2322 ttrss_user_labels2.article_id = ref_id";
3de0261a 2323
ef393de7 2324 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 2325 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
835fb294 2326 $allow_archived = true;
8d505d78 2327
ef393de7 2328 } else {
835fb294 2329 $query_strategy_part = "true";
ef393de7 2330 }
d6e5706d 2331
b3990c92
AD
2332 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2333 $date_sort_field = "updated";
2334 } else {
2335 $date_sort_field = "date_entered";
2336 }
2337
7a22dc2a 2338 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
b3990c92 2339 $order_by = "$date_sort_field";
8d505d78 2340 } else {
b3990c92 2341 $order_by = "$date_sort_field DESC";
d6e5706d 2342 }
e939722a 2343
7b4d02a8
AD
2344 if ($view_mode != "noscores") {
2345 $order_by = "score DESC, $order_by";
2346 }
48b0c4ec 2347
e939722a
AD
2348 if ($override_order) {
2349 $order_by = $override_order;
2350 }
8d505d78 2351
ef393de7
AD
2352 $feed_title = "";
2353
22fdebff 2354 if ($search) {
7032f2a5 2355 $feed_title = T_sprintf("Search results: %s", $search);
22fdebff 2356 } else {
ef393de7 2357 if ($cat_view) {
22fdebff 2358 $feed_title = getCategoryTitle($link, $feed);
ef393de7 2359 } else {
147f5632 2360 if (is_numeric($feed) && $feed > 0) {
8d505d78 2361 $result = db_query($link, "SELECT title,site_url,last_error
22fdebff 2362 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2363
22fdebff
AD
2364 $feed_title = db_fetch_result($result, 0, "title");
2365 $feed_site_url = db_fetch_result($result, 0, "site_url");
2366 $last_error = db_fetch_result($result, 0, "last_error");
2367 } else {
2368 $feed_title = getFeedTitle($link, $feed);
8d505d78 2369 }
88040f57 2370 }
ef393de7
AD
2371 }
2372
87764a50 2373 $content_query_part = "content as content_preview, cached_content, ";
62129e67 2374
75c648cf 2375 if (is_numeric($feed)) {
8d505d78 2376
ef393de7
AD
2377 if ($feed >= 0) {
2378 $feed_kind = "Feeds";
2379 } else {
2380 $feed_kind = "Labels";
2381 }
8d505d78 2382
95a82c08
AD
2383 if ($limit_query_part) {
2384 $offset_query_part = "OFFSET $offset";
2385 }
2386
7fdf8eca 2387 // proper override_order applied above
d00f22ac 2388 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 2389 if (!$override_order) {
8d505d78 2390 $order_by = "ttrss_feeds.title, $order_by";
7fdf8eca
AD
2391 } else {
2392 $order_by = "ttrss_feeds.title, $override_order";
43fc671f 2393 }
6cfea5c7
AD
2394 }
2395
8361e724 2396 if (!$allow_archived) {
e04c18a2 2397 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 2398 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2399
2400 } else {
835fb294 2401 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
e04c18a2
AD
2402 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2403 }
2404
8d505d78 2405 $query = "SELECT DISTINCT
f9b2d27c 2406 date_entered,
1f64b1be 2407 guid,
ef393de7 2408 ttrss_entries.id,ttrss_entries.title,
46921916 2409 updated,
9c506873
AD
2410 label_cache,
2411 tag_cache,
c0644ee4 2412 always_display_enclosures,
d1fc2f92 2413 site_url,
c7e51de1 2414 note,
13992673
AD
2415 num_comments,
2416 comments,
db16ae50 2417 int_id,
494a64ea 2418 unread,feed_id,marked,published,link,last_read,orig_feed_id,
fc2b26a6 2419 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
ef393de7
AD
2420 $vfeed_query_part
2421 $content_query_part
fc2b26a6 2422 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
ff6e357a 2423 author,score
ef393de7 2424 FROM
e04c18a2 2425 $from_qpart
ef393de7 2426 WHERE
e04c18a2 2427 $feed_check_qpart
ef393de7 2428 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 2429 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 2430 $search_query_part
36184020 2431 $filter_query_part
ef393de7 2432 $view_query_part
97e5dbb2 2433 $since_id_part
ef393de7 2434 $query_strategy_part ORDER BY $order_by
95a82c08 2435 $limit_query_part $offset_query_part";
4bc311fc 2436
b4e75b2a 2437 if ($_REQUEST["debug"]) print $query;
4bc311fc
AD
2438
2439 $result = db_query($link, $query);
8d505d78 2440
ef393de7
AD
2441 } else {
2442 // browsing by tag
8d505d78 2443
147f5632
CM
2444 $select_qpart = "SELECT DISTINCT " .
2445 "date_entered," .
2446 "guid," .
2447 "note," .
2448 "ttrss_entries.id as id," .
2449 "title," .
2450 "updated," .
2451 "unread," .
2452 "feed_id," .
2453 "orig_feed_id," .
2454 "marked," .
d1fc2f92
AD
2455 "num_comments, " .
2456 "comments, " .
c0644ee4
AD
2457 "tag_cache," .
2458 "label_cache," .
147f5632
CM
2459 "link," .
2460 "last_read," .
2461 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
97e5dbb2 2462 $since_id_part .
147f5632
CM
2463 $vfeed_query_part .
2464 $content_query_part .
2465 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
2466 "score ";
2467
ef393de7 2468 $feed_kind = "Tags";
147f5632
CM
2469 $all_tags = explode(",", $feed);
2470 if ($search_mode == 'any') {
2471 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2472 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2473 $where_qpart = " WHERE " .
2474 "ref_id = ttrss_entries.id AND " .
2475 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2476 "post_int_id = int_id AND $tag_sql AND " .
2477 $view_query_part .
2478 $search_query_part .
2479 $query_strategy_part . " ORDER BY $order_by " .
2480 $limit_query_part;
8d505d78 2481
147f5632
CM
2482 } else {
2483 $i = 1;
2484 $sub_selects = array();
2485 $sub_ands = array();
2486 foreach ($all_tags as $term) {
2487 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");
2488 $i++;
2489 }
2490 if ($i > 2) {
2491 $x = 1;
2492 $y = 2;
2493 do {
2494 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2495 $x++;
2496 $y++;
2497 } while ($y < $i);
2498 }
2499 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2500 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2501 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2502 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2503 }
2504 // error_log("TAG SQL: " . $tag_sql);
2505 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2506
2507 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2508 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
ef393de7
AD
2509 }
2510
c7188969 2511 return array($result, $feed_title, $feed_site_url, $last_error);
8d505d78 2512
ef393de7
AD
2513 }
2514
b3682750 2515 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
ceb0cab5
AD
2516 if (!$owner) $owner = $_SESSION["uid"];
2517
96811a55
AD
2518 $res = trim($str); if (!$res) return '';
2519
d8858f27 2520 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
acccafe3 2521 $res = htmLawed($res, $config);
f826eee1 2522
ceb0cab5 2523 if (get_pref($link, "STRIP_IMAGES", $owner)) {
8dccabed 2524 $res = preg_replace('/<img[^>]+>/is', '', $res);
7514749d 2525 }
8dccabed 2526
46137483
AD
2527 if (strpos($res, "href=") === false)
2528 $res = rewrite_urls($res);
533c0ea6 2529
8cc3c778
AD
2530 $charset_hack = '<head>
2531 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2532 </head>';
2533
96811a55
AD
2534 $res = trim($res); if (!$res) return '';
2535
8cc3c778
AD
2536 libxml_use_internal_errors(true);
2537
2538 $doc = new DOMDocument();
2539 $doc->loadHTML($charset_hack . $res);
2540 $xpath = new DOMXPath($doc);
8d505d78 2541
8cc3c778 2542 $entries = $xpath->query('(//a[@href]|//img[@src])');
3f770c87 2543 $br_inserted = 0;
8cc3c778
AD
2544
2545 foreach ($entries as $entry) {
2546
2547 if ($site_url) {
2548
2549 if ($entry->hasAttribute('href'))
2550 $entry->setAttribute('href',
2551 rewrite_relative_url($site_url, $entry->getAttribute('href')));
8d505d78 2552
8cc3c778 2553 if ($entry->hasAttribute('src'))
8d505d78 2554 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
b8998470
AD
2555 $entry->setAttribute('src',
2556 rewrite_relative_url($site_url, $entry->getAttribute('src')));
8cc3c778
AD
2557 }
2558
fa403733 2559 if (strtolower($entry->nodeName) == "a") {
c401d5c9 2560 $entry->setAttribute("target", "_blank");
fa403733
AD
2561 }
2562
3f770c87 2563 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
fa403733
AD
2564 $br = $doc->createElement("br");
2565
3f770c87 2566 if ($entry->parentNode->nextSibling) {
fa403733 2567 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3f770c87
AD
2568 $br_inserted = 1;
2569 }
fa403733 2570
8cc3c778 2571 }
8dccabed 2572 }
8d505d78 2573
1f6131f5 2574 $node = $doc->getElementsByTagName('body')->item(0);
8dccabed 2575
c5bb0440 2576 // http://tt-rss.org/redmine/issues/357
ec6732f4 2577 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
183ad07b 2578 }
b72c3ef8 2579
73495fd1 2580 function check_for_update($link) {
63855db1
AD
2581 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2582 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
b72c3ef8 2583
63855db1 2584 $version_data = @fetch_file_contents($version_url);
b72c3ef8 2585
63855db1
AD
2586 if ($version_data) {
2587 $version_data = json_decode($version_data, true);
8d505d78 2588 if ($version_data && $version_data['version']) {
f67d9754 2589
63855db1 2590 if (version_compare(VERSION, $version_data['version']) == -1) {
e91ad1e9 2591 return $version_data;
63855db1
AD
2592 }
2593 }
f67d9754 2594 }
b72c3ef8 2595 }
63855db1 2596 return false;
b72c3ef8 2597 }
472782e8 2598
9968d46f
AD
2599 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2600
2601 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 2602 if (count($ids) == 0) return;
472782e8
AD
2603
2604 $tmp_ids = array();
2605
2606 foreach ($ids as $id) {
2607 array_push($tmp_ids, "ref_id = '$id'");
2608 }
2609
2610 $ids_qpart = join(" OR ", $tmp_ids);
2611
2612 if ($cmode == 0) {
8d505d78 2613 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2614 unread = false,last_read = NOW()
9968d46f 2615 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2616 } else if ($cmode == 1) {
8d505d78 2617 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2618 unread = true
9968d46f 2619 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2620 } else {
8d505d78 2621 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 2622 unread = NOT unread,last_read = NOW()
9968d46f 2623 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 2624 }
0737b95a
AD
2625
2626 /* update ccache */
2627
2628 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2629 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2630
2631 while ($line = db_fetch_assoc($result)) {
2632 ccache_update($link, $line["feed_id"], $owner_uid);
2633 }
472782e8
AD
2634 }
2635
ca5133cb 2636 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
0b126ac2
AD
2637
2638 $a_id = db_escape_string($id);
2639
bc976a8c
AD
2640 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2641
8d505d78 2642 $query = "SELECT DISTINCT tag_name,
0c3d1c68 2643 owner_uid as owner FROM
0b126ac2 2644 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 2645 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 2646
bd3f2ade 2647 $obj_id = md5("TAGS:$owner_uid:$id");
8d505d78 2648 $tags = array();
bd3f2ade 2649
0e4a7d7a 2650 /* check cache first */
490c366d 2651
0e4a7d7a
AD
2652 if ($tag_cache === false) {
2653 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2654 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
490c366d 2655
0e4a7d7a
AD
2656 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2657 }
bd3f2ade 2658
0e4a7d7a
AD
2659 if ($tag_cache) {
2660 $tags = explode(",", $tag_cache);
2661 } else {
490c366d 2662
0e4a7d7a 2663 /* do it the hard way */
490c366d 2664
0e4a7d7a 2665 $tmp_result = db_query($link, $query);
490c366d 2666
0e4a7d7a
AD
2667 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2668 array_push($tags, $tmp_line["tag_name"]);
2669 }
490c366d 2670
0e4a7d7a 2671 /* update the cache */
490c366d 2672
0e4a7d7a 2673 $tags_str = db_escape_string(join(",", $tags));
bd3f2ade 2674
0e4a7d7a
AD
2675 db_query($link, "UPDATE ttrss_user_entries
2676 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2677 AND owner_uid = $owner_uid");
0b126ac2
AD
2678 }
2679
2680 return $tags;
2681 }
2682
d62a3b63
AD
2683 function trim_array($array) {
2684 $tmp = $array;
3415b075 2685 array_walk($tmp, 'trim');
d62a3b63
AD
2686 return $tmp;
2687 }
2688
be832a1a 2689 function tag_is_valid($tag) {
ef063748
AD
2690 if ($tag == '') return false;
2691 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 2692 if (mb_strlen($tag) > 250) return false;
ef063748 2693
31365729
AD
2694 if (function_exists('iconv')) {
2695 $tag = iconv("utf-8", "utf-8", $tag);
2696 }
2697
ef063748
AD
2698 if (!$tag) return false;
2699
2700 return true;
be832a1a
AD
2701 }
2702
97acbaf1
AD
2703 function render_login_form($link, $form_id = 0) {
2704 switch ($form_id) {
afb12ed0 2705 case 0:
793185a9 2706 require_once "login_form.php";
afb12ed0
AD
2707 break;
2708 case 1:
793185a9 2709 require_once "mobile/login_form.php";
afb12ed0 2710 break;
793185a9 2711 }
97acbaf1 2712 exit;
01a87dff
AD
2713 }
2714
dc56b3b7
AD
2715 // from http://developer.apple.com/internet/safari/faq.html
2716 function no_cache_incantation() {
2717 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2718 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2719 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2720 header("Cache-Control: post-check=0, pre-check=0", false);
2721 header("Pragma: no-cache"); // HTTP/1.0
2722 }
2723
42395d28 2724 function format_warning($msg, $id = "") {
883fee8d 2725 global $link;
8d505d78 2726 return "<div class=\"warning\" id=\"$id\">
c2167866 2727 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
0d32b41e
AD
2728 }
2729
08ac193a 2730 function format_notice($msg, $id = "") {
883fee8d 2731 global $link;
8d505d78 2732 return "<div class=\"notice\" id=\"$id\">
c2167866 2733 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
0d32b41e
AD
2734 }
2735
08ac193a 2736 function format_error($msg, $id = "") {
883fee8d 2737 global $link;
8d505d78 2738 return "<div class=\"error\" id=\"$id\">
c2167866 2739 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
68d2f95e
AD
2740 }
2741
4dccf1ed
AD
2742 function print_notice($msg) {
2743 return print format_notice($msg);
2744 }
2745
2746 function print_warning($msg) {
2747 return print format_warning($msg);
2748 }
2749
68d2f95e
AD
2750 function print_error($msg) {
2751 return print format_error($msg);
2752 }
2753
2754
4dccf1ed
AD
2755 function T_sprintf() {
2756 $args = func_get_args();
2757 return vsprintf(__(array_shift($args)), $args);
2758 }
2759
51682b23
AD
2760 function format_inline_player($link, $url, $ctype) {
2761
2762 $entry = "";
2763
8d505d78 2764 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
2765
2766 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
8d505d78 2767 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
c3edc667
AD
2768 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2769
2770 $id = 'AUDIO-' . uniqid();
2771
ca3bca99
AD
2772 $entry .= "<audio id=\"$id\"\" controls>
2773 <source type=\"$ctype\" src=\"$url\"></source>
8d505d78 2774 </audio>";
c3edc667 2775
8d505d78 2776 $entry .= "<span onclick=\"player(this)\"
c3edc667
AD
2777 title=\"".__("Click to play")."\" status=\"0\"
2778 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2779
2780 } else {
8d505d78
AD
2781
2782 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 2783 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
2784 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2785 <param name=\"movie\"
ad95edc2 2786 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 2787 </object>";
c3edc667 2788 }
ca3bca99
AD
2789
2790 if ($entry) $entry .= "&nbsp;" . basename($url);
2791
2792 return $entry;
2793
51682b23
AD
2794 }
2795
ca3bca99
AD
2796 return "";
2797
2798/* $filename = substr($url, strrpos($url, "/")+1);
c3edc667
AD
2799
2800 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
ca3bca99 2801 $filename . " (" . $ctype . ")" . "</a>"; */
c3edc667 2802
51682b23
AD
2803 }
2804
64436e10 2805 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
64436e10 2806 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3de0261a 2807
009646d2
AD
2808 $rv = array();
2809
2810 $rv['id'] = $id;
2811
10eb9da8 2812 /* we can figure out feed_id from article id anyway, why do we
e04c18a2 2813 * pass feed_id here? let's ignore the argument :( */
10eb9da8
AD
2814
2815 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2816 WHERE ref_id = '$id'");
2817
e04c18a2 2818 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 2819
009646d2
AD
2820 $rv['feed_id'] = $feed_id;
2821
2822 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 2823
87764a50 2824 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
64436e10 2825 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3de0261a
AD
2826
2827 if (db_num_rows($result) == 1) {
2828 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
54e61a68 2829 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
87764a50 2830 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
3de0261a
AD
2831 } else {
2832 $rtl_content = false;
54e61a68 2833 $always_display_enclosures = false;
87764a50 2834 $cache_content = false;
3de0261a
AD
2835 }
2836
2837 if ($rtl_content) {
2838 $rtl_tag = "dir=\"RTL\"";
2839 $rtl_class = "RTL";
2840 } else {
2841 $rtl_tag = "";
2842 $rtl_class = "";
2843 }
2844
2845 if ($mark_as_read) {
8d505d78
AD
2846 $result = db_query($link, "UPDATE ttrss_user_entries
2847 SET unread = false,last_read = NOW()
64436e10 2848 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
8a4c759e 2849
64436e10 2850 ccache_update($link, $feed_id, $owner_uid);
3de0261a
AD
2851 }
2852
7252abe3 2853 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
fc2b26a6 2854 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
8cc3c778 2855 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3de0261a 2856 num_comments,
9c506873 2857 tag_cache,
c7e51de1 2858 author,
ef83538d 2859 orig_feed_id,
87764a50
AD
2860 note,
2861 cached_content
3de0261a 2862 FROM ttrss_entries,ttrss_user_entries
64436e10 2863 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3de0261a
AD
2864
2865 if ($result) {
2866
3de0261a
AD
2867 $line = db_fetch_assoc($result);
2868
8cc3c778
AD
2869 $feed_site_url = $line['site_url'];
2870
3de0261a
AD
2871 $num_comments = $line["num_comments"];
2872 $entry_comments = "";
2873
2874 if ($num_comments > 0) {
2875 if ($line["comments"]) {
6e577ba1 2876 $comments_url = htmlspecialchars($line["comments"]);
3de0261a 2877 } else {
6e577ba1 2878 $comments_url = htmlspecialchars($line["link"]);
3de0261a 2879 }
7514749d 2880 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3de0261a
AD
2881 } else {
2882 if ($line["comments"] && $line["link"] != $line["comments"]) {
6e577ba1 2883 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
8d505d78 2884 }
3de0261a
AD
2885 }
2886
eedfb635
AD
2887 if ($zoom_mode) {
2888 header("Content-Type: text/html");
009646d2 2889 $rv['content'] .= "<html><head>
5bb0cc8e 2890 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
eedfb635
AD
2891 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2892 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2893 </head><body>";
2894 }
2895
5c568973 2896 $title_escaped = htmlspecialchars($line['title']);
2ea9bbfd 2897
e54dbacb
AD
2898 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2899 strip_tags($line['title']) . "</div>";
2900
009646d2 2901 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 2902
126e639a 2903 $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
2904
2905 $entry_author = $line["author"];
2906
2907 if ($entry_author) {
60164936 2908 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
2909 }
2910
8d505d78 2911 $parsed_updated = make_local_datetime($link, $line["updated"], true,
64436e10 2912 $owner_uid, true);
324944f3 2913
009646d2 2914 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3de0261a
AD
2915
2916 if ($line["link"]) {
c6c010d9 2917 $rv['content'] .= "<div class='postTitle'><a target='_blank'
a64029e5 2918 title=\"".htmlspecialchars($line['title'])."\"
8d505d78 2919 href=\"" .
5c568973 2920 htmlspecialchars($line["link"]) . "\">" .
c6c010d9 2921 $line["title"] .
a64029e5 2922 "<span class='author'>$entry_author</span></a></div>";
3de0261a 2923 } else {
c6c010d9 2924 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
2925 }
2926
9c506873
AD
2927 $tag_cache = $line["tag_cache"];
2928
2929 if (!$tag_cache)
64436e10 2930 $tags = get_article_tags($link, $id, $owner_uid);
9c506873
AD
2931 else
2932 $tags = explode(",", $tag_cache);
2933
0780f4f4
AD
2934 $tags_str = format_tags_string($tags, $id);
2935 $tags_str_full = join(", ", $tags);
2936
2937 if (!$tags_str_full) $tags_str_full = __("no tags");
e7544143 2938
3de0261a
AD
2939 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
2940
f0755b7c 2941 $rv['content'] .= "<div class='postTags' style='float : right'>
8d505d78 2942 <img src='".theme_image($link, 'images/tag.png')."'
e9823609 2943 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
2944
2945 if (!$zoom_mode) {
009646d2 2946 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 2947 <a title=\"".__('Edit tags for this article')."\"
31a53903 2948 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 2949
0780f4f4
AD
2950 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
2951 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
2952 position=\"below\">$tags_str_full</div>";
2953
009646d2 2954 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
9ed0b90f 2955 class='tagsPic' style=\"cursor : pointer\"
ca07f49e 2956 onclick=\"postOpenInNewTab(event, $id)\"
6f3976c9 2957 alt='Zoom' title='".__('Open article in new tab')."'>";
c7e51de1 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?>