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