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