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