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