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