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