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