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