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