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