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