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