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