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