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