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