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