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