2 date_default_timezone_set('UTC');
3 if (defined('E_DEPRECATED')) {
4 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
6 error_reporting(E_ALL
& ~E_NOTICE
);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
17 define('THEME_VERSION_REQUIRED', 1.1);
20 * Return available translations names.
23 * @return array A array of available translations.
25 function get_translations() {
27 "auto" => "Detect automatically",
32 "fr_FR" => "Français",
33 "hu_HU" => "Magyar (Hungarian)",
34 "it_IT" => "Italiano",
35 "ja_JP" => "日本語 (Japanese)",
36 "nb_NO" => "Norwegian bokmål",
38 "pt_BR" => "Portuguese/Brazil",
39 "zh_CN" => "Simplified Chinese");
44 require_once "lib/accept-to-gettext.php";
45 require_once "lib/gettext/gettext.inc";
47 function startup_gettext() {
49 # Get locale from Accept-Language header
50 $lang = al2gt(array_keys(get_translations()), "text/html");
52 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
53 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
56 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
57 $lang = $_COOKIE["ttrss_lang"];
60 /* In login action of mobile version */
61 if ($_POST["language"] && defined('MOBILE_VERSION')) {
62 $lang = $_POST["language"];
63 $_COOKIE["ttrss_lang"] = $lang;
67 if (defined('LC_MESSAGES')) {
68 _setlocale(LC_MESSAGES
, $lang);
69 } else if (defined('LC_ALL')) {
70 _setlocale(LC_ALL
, $lang);
73 if (defined('MOBILE_VERSION')) {
74 _bindtextdomain("messages", "../locale");
76 _bindtextdomain("messages", "locale");
79 _textdomain("messages");
80 _bind_textdomain_codeset("messages", "UTF-8");
86 require_once 'db-prefs.php';
87 require_once 'version.php';
89 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
91 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
92 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
94 ini_set('user_agent', SELF_USER_AGENT
);
96 require_once 'lib/pubsubhubbub/publisher.php';
101 $utc_tz = new DateTimeZone('UTC');
102 $schema_version = false;
105 * Print a timestamped debug message.
107 * @param string $msg The debug message.
110 function _debug($msg) {
111 $ts = strftime("%H:%M:%S", time());
112 if (function_exists('posix_getpid')) {
113 $ts = "$ts/" . posix_getpid();
115 print "[$ts] $msg\n";
119 * Purge a feed old posts.
121 * @param mixed $link A database connection.
122 * @param mixed $feed_id The id of the purged feed.
123 * @param mixed $purge_interval Olderness of purged posts.
124 * @param boolean $debug Set to True to enable the debug. False by default.
128 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
130 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
134 $result = db_query($link,
135 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
139 if (db_num_rows($result) == 1) {
140 $owner_uid = db_fetch_result($result, 0, "owner_uid");
143 if ($purge_interval == -1 ||
!$purge_interval) {
145 ccache_update($link, $feed_id, $owner_uid);
150 if (!$owner_uid) return;
152 if (FORCE_ARTICLE_PURGE
== 0) {
153 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
156 $purge_unread = true;
157 $purge_interval = FORCE_ARTICLE_PURGE
;
160 if (!$purge_unread) $query_limit = " unread = false AND ";
162 if (DB_TYPE
== "pgsql") {
163 $pg_version = get_pgsql_version($link);
165 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
167 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
168 ttrss_entries.id = ref_id AND
170 feed_id = '$feed_id' AND
172 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
176 $result = db_query($link, "DELETE FROM ttrss_user_entries
178 WHERE ttrss_entries.id = ref_id AND
180 feed_id = '$feed_id' AND
182 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
185 $rows = pg_affected_rows($result);
189 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
190 marked = false AND feed_id = '$feed_id' AND
191 (SELECT date_updated FROM ttrss_entries WHERE
192 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
194 $result = db_query($link, "DELETE FROM ttrss_user_entries
195 USING ttrss_user_entries, ttrss_entries
196 WHERE ttrss_entries.id = ref_id AND
198 feed_id = '$feed_id' AND
200 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
202 $rows = mysql_affected_rows($link);
206 ccache_update($link, $feed_id, $owner_uid);
209 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
211 } // function purge_feed
213 function feed_purge_interval($link, $feed_id) {
215 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
216 WHERE id = '$feed_id'");
218 if (db_num_rows($result) == 1) {
219 $purge_interval = db_fetch_result($result, 0, "purge_interval");
220 $owner_uid = db_fetch_result($result, 0, "owner_uid");
222 if ($purge_interval == 0) $purge_interval = get_pref($link,
223 'PURGE_OLD_DAYS', $owner_uid);
225 return $purge_interval;
232 function purge_orphans($link, $do_output = false) {
234 // purge orphaned posts in main content table
235 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
236 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
239 $rows = db_affected_rows($link, $result);
240 _debug("Purged $rows orphaned posts.");
244 function get_feed_update_interval($link, $feed_id) {
245 $result = db_query($link, "SELECT owner_uid, update_interval FROM
246 ttrss_feeds WHERE id = '$feed_id'");
248 if (db_num_rows($result) == 1) {
249 $update_interval = db_fetch_result($result, 0, "update_interval");
250 $owner_uid = db_fetch_result($result, 0, "owner_uid");
252 if ($update_interval != 0) {
253 return $update_interval;
255 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
263 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
264 $login = urlencode($login);
265 $pass = urlencode($pass);
267 if (function_exists('curl_init') && !ini_get("open_basedir")) {
268 $ch = curl_init($url);
270 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
271 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
272 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
273 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
274 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
275 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
276 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
277 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
278 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
279 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
282 curl_setopt($ch, CURLOPT_POST
, true);
283 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
287 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
289 $contents = @curl_exec
($ch);
291 if ($contents === false) {
296 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
297 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
300 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
306 if ($login && $pass ){
307 $url_parts = array();
309 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
311 if ($url_parts[1] && $url_parts[2]) {
312 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
316 return @file_get_contents
($url);
322 * Try to determine the favicon URL for a feed.
323 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
324 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
326 * @param string $url A feed or page URL
328 * @return mixed The favicon URL, or false if none was found.
330 function get_favicon_url($url) {
332 $favicon_url = false;
334 if ($html = @fetch_file_contents
($url)) {
336 libxml_use_internal_errors(true);
338 $doc = new DOMDocument();
339 $doc->loadHTML($html);
340 $xpath = new DOMXPath($doc);
342 $base = $xpath->query('/html/head/base');
343 foreach ($base as $b) {
344 $url = $b->getAttribute("href");
348 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
349 if (count($entries) > 0) {
350 foreach ($entries as $entry) {
351 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
358 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
361 } // function get_favicon_url
363 function check_feed_favicon($site_url, $feed, $link) {
364 # print "FAVICON [$site_url]: $favicon_url\n";
366 $icon_file = ICONS_DIR
. "/$feed.ico";
368 if (!file_exists($icon_file)) {
369 $favicon_url = get_favicon_url($site_url);
372 // Limiting to "image" type misses those served with text/plain
373 $contents = fetch_file_contents($favicon_url); // , "image");
376 // Crude image type matching.
377 // Patterns gleaned from the file(1) source code.
378 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
379 // 0 string \000\000\001\000 MS Windows icon resource
380 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
382 elseif (preg_match('/^GIF8/', $contents)) {
383 // 0 string GIF8 GIF image data
384 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
386 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
387 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
388 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
390 elseif (preg_match('/^\xff\xd8/', $contents)) {
391 // 0 beshort 0xffd8 JPEG image data
392 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
395 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
401 $fp = @fopen
($icon_file, "w");
404 fwrite($fp, $contents);
406 chmod($icon_file, 0644);
413 function print_select($id, $default, $values, $attributes = "") {
414 print "<select name=\"$id\" id=\"$id\" $attributes>";
415 foreach ($values as $v) {
417 $sel = "selected=\"1\"";
421 print "<option value=\"$v\" $sel>$v</option>";
426 function print_select_hash($id, $default, $values, $attributes = "") {
427 print "<select name=\"$id\" id='$id' $attributes>";
428 foreach (array_keys($values) as $v) {
430 $sel = 'selected="selected"';
434 print "<option $sel value=\"$v\">".$values[$v]."</option>";
440 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
443 if ($filters["title"]) {
444 foreach ($filters["title"] as $filter) {
445 $reg_exp = $filter["reg_exp"];
446 $inverse = $filter["inverse"];
447 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
448 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
450 array_push($matches, array($filter["action"], $filter["action_param"]));
455 if ($filters["content"]) {
456 foreach ($filters["content"] as $filter) {
457 $reg_exp = $filter["reg_exp"];
458 $inverse = $filter["inverse"];
460 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
461 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
463 array_push($matches, array($filter["action"], $filter["action_param"]));
468 if ($filters["both"]) {
469 foreach ($filters["both"] as $filter) {
470 $reg_exp = $filter["reg_exp"];
471 $inverse = $filter["inverse"];
474 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
475 array_push($matches, array($filter["action"], $filter["action_param"]));
478 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
479 array_push($matches, array($filter["action"], $filter["action_param"]));
485 if ($filters["link"]) {
486 $reg_exp = $filter["reg_exp"];
487 foreach ($filters["link"] as $filter) {
488 $reg_exp = $filter["reg_exp"];
489 $inverse = $filter["inverse"];
491 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
492 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
494 array_push($matches, array($filter["action"], $filter["action_param"]));
499 if ($filters["date"]) {
500 $reg_exp = $filter["reg_exp"];
501 foreach ($filters["date"] as $filter) {
502 $date_modifier = $filter["filter_param"];
503 $inverse = $filter["inverse"];
504 $check_timestamp = strtotime($filter["reg_exp"]);
506 # no-op when timestamp doesn't parse to prevent misfires
508 if ($check_timestamp) {
511 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
512 $date_modifier == "after" && $timestamp > $check_timestamp) {
516 if ($inverse) $match_ok = !$match_ok;
519 array_push($matches, array($filter["action"], $filter["action_param"]));
525 if ($filters["author"]) {
526 foreach ($filters["author"] as $filter) {
527 $reg_exp = $filter["reg_exp"];
528 $inverse = $filter["inverse"];
529 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
530 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
532 array_push($matches, array($filter["action"], $filter["action_param"]));
537 if ($filters["tag"]) {
539 $tag_string = join(",", $tags);
541 foreach ($filters["tag"] as $filter) {
542 $reg_exp = $filter["reg_exp"];
543 $inverse = $filter["inverse"];
545 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
546 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
548 array_push($matches, array($filter["action"], $filter["action_param"]));
557 function find_article_filter($filters, $filter_name) {
558 foreach ($filters as $f) {
559 if ($f[0] == $filter_name) {
566 function calculate_article_score($filters) {
569 foreach ($filters as $f) {
570 if ($f[0] == "score") {
577 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
578 foreach ($filters as $f) {
579 if ($f[0] == "label") {
580 label_add_article($link, $id, $f[1], $owner_uid);
585 function getmicrotime() {
586 list($usec, $sec) = explode(" ",microtime());
587 return ((float)$usec +
(float)$sec);
590 function print_radio($id, $default, $true_is, $values, $attributes = "") {
591 foreach ($values as $v) {
598 if ($v == $true_is) {
599 $sel .= " value=\"1\"";
601 $sel .= " value=\"0\"";
604 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
605 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
610 function initialize_user_prefs($link, $uid, $profile = false) {
612 $uid = db_escape_string($uid);
616 $profile_qpart = "AND profile IS NULL";
618 $profile_qpart = "AND profile = '$profile'";
621 if (get_schema_version($link) < 63) $profile_qpart = "";
623 db_query($link, "BEGIN");
625 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
627 $u_result = db_query($link, "SELECT pref_name
628 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
630 $active_prefs = array();
632 while ($line = db_fetch_assoc($u_result)) {
633 array_push($active_prefs, $line["pref_name"]);
636 while ($line = db_fetch_assoc($result)) {
637 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
638 // print "adding " . $line["pref_name"] . "<br>";
640 if (get_schema_version($link) < 63) {
641 db_query($link, "INSERT INTO ttrss_user_prefs
642 (owner_uid,pref_name,value) VALUES
643 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
646 db_query($link, "INSERT INTO ttrss_user_prefs
647 (owner_uid,pref_name,value, profile) VALUES
648 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
654 db_query($link, "COMMIT");
658 function get_ssl_certificate_id() {
659 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
660 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
661 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
662 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
663 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
668 function get_login_by_ssl_certificate($link) {
670 $cert_serial = db_escape_string(get_ssl_certificate_id());
673 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
674 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
675 owner_uid = ttrss_users.id");
677 if (db_num_rows($result) != 0) {
678 return db_escape_string(db_fetch_result($result, 0, "login"));
685 function get_remote_user($link) {
687 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
688 return db_escape_string($_SERVER["REMOTE_USER"]);
691 return db_escape_string(get_login_by_ssl_certificate($link));
694 function get_remote_fakepass($link) {
695 if (get_remote_user($link))
701 function authenticate_user($link, $login, $password, $force_auth = false) {
703 if (!SINGLE_USER_MODE
) {
705 $pwd_hash1 = encrypt_password($password);
706 $pwd_hash2 = encrypt_password($password, $login);
707 $login = db_escape_string($login);
709 $remote_user = get_remote_user($link);
711 if ($remote_user && $remote_user == $login && $login != "admin") {
713 $login = $remote_user;
715 $query = "SELECT id,login,access_level,pwd_hash
716 FROM ttrss_users WHERE
719 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
720 && $_SERVER["REMOTE_USER"]) {
721 $result = db_query($link, $query);
724 if (db_num_rows($result) == 0) {
725 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
726 $pwd_hash = encrypt_password($password, $salt, true);
728 $query2 = "INSERT INTO ttrss_users
729 (login,access_level,last_login,created,pwd_hash,salt)
730 VALUES ('$login', 0, null, NOW(), '$pwd_hash','$salt')";
731 db_query($link, $query2);
735 } else if (get_schema_version($link) > 87) {
736 $result = db_query($link, "SELECT salt FROM ttrss_users WHERE
739 if (db_num_rows($result) != 1) {
743 $salt = db_fetch_result($result, 0, "salt");
747 $query = "SELECT id,login,access_level,pwd_hash
748 FROM ttrss_users WHERE
749 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
750 pwd_hash = '$pwd_hash2')";
752 // verify and upgrade password to new salt base
754 $result = db_query($link, $query);
756 if (db_num_rows($result) == 1) {
757 // upgrade password to MODE2
759 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
760 $pwd_hash = encrypt_password($password, $salt, true);
762 db_query($link, "UPDATE ttrss_users SET
763 pwd_hash = '$pwd_hash', salt = '$salt' WHERE login = '$login'");
765 $query = "SELECT id,login,access_level,pwd_hash
766 FROM ttrss_users WHERE
767 login = '$login' AND pwd_hash = '$pwd_hash'";
775 $pwd_hash = encrypt_password($password, $salt, true);
777 $query = "SELECT id,login,access_level,pwd_hash
778 FROM ttrss_users WHERE
779 login = '$login' AND pwd_hash = '$pwd_hash'";
783 $query = "SELECT id,login,access_level,pwd_hash
784 FROM ttrss_users WHERE
785 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
786 pwd_hash = '$pwd_hash2')";
789 $result = db_query($link, $query);
791 if (db_num_rows($result) == 1) {
792 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
793 $_SESSION["name"] = db_fetch_result($result, 0, "login");
794 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
795 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
797 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
801 // LemonLDAP can send user informations via HTTP HEADER
802 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
804 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
806 $fullname = db_escape_string($fullname);
807 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
811 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
813 $email = db_escape_string($email);
814 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
819 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
820 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
822 $_SESSION["last_version_check"] = time();
824 initialize_user_prefs($link, $_SESSION["uid"]);
833 $_SESSION["uid"] = 1;
834 $_SESSION["name"] = "admin";
835 $_SESSION["access_level"] = 10;
837 if (!$_SESSION["csrf_token"]) {
838 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
841 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
843 initialize_user_prefs($link, $_SESSION["uid"]);
849 function make_password($length = 8) {
852 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
856 while ($i < $length) {
857 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
859 if (!strstr($password, $char)) {
867 // this is called after user is created to initialize default feeds, labels
870 // user preferences are checked on every login, not here
872 function initialize_user($link, $uid) {
874 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
875 values ('$uid', 'Tiny Tiny RSS: New Releases',
876 'http://tt-rss.org/releases.rss')");
878 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
879 values ('$uid', 'Tiny Tiny RSS: Forum',
880 'http://tt-rss.org/forum/rss.php')");
883 function logout_user() {
885 if (isset($_COOKIE[session_name()])) {
886 setcookie(session_name(), '', time()-42000, '/');
890 function validate_csrf($csrf_token) {
891 return $csrf_token == $_SESSION['csrf_token'];
894 function validate_session($link) {
895 if (SINGLE_USER_MODE
) return true;
897 $check_ip = $_SESSION['ip_address'];
899 switch (SESSION_CHECK_ADDRESS
) {
904 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
907 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
908 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
912 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
913 $_SESSION["login_error_msg"] =
914 __("Session failed to validate (incorrect IP)");
918 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
921 if ($_SESSION["uid"]) {
923 $result = db_query($link,
924 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
926 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
928 if ($pwd_hash != $_SESSION["pwd_hash"]) {
933 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
935 //print_r($_SESSION);
937 if (time() > $_SESSION["cookie_lifetime"]) {
945 function login_sequence($link, $mobile = false) {
946 $_SESSION["prefs_cache"] = array();
948 if (!SINGLE_USER_MODE
) {
950 $login_action = $_POST["login_action"];
952 # try to authenticate user if called from login form
953 if ($login_action == "do_login") {
954 $login = db_escape_string($_POST["login"]);
955 $password = $_POST["password"];
956 $remember_me = $_POST["remember_me"];
958 if (authenticate_user($link, $login, $password)) {
959 $_POST["password"] = "";
961 $_SESSION["language"] = $_POST["language"];
962 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
963 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
965 if ($_POST["profile"]) {
967 $profile = db_escape_string($_POST["profile"]);
969 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
970 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
972 if (db_num_rows($result) != 0) {
973 $_SESSION["profile"] = $profile;
974 $_SESSION["prefs_cache"] = array();
978 if ($_REQUEST['return']) {
979 header("Location: " . $_REQUEST['return']);
981 header("Location: " . $_SERVER["REQUEST_URI"]);
988 $_SESSION["login_error_msg"] = __("Incorrect username or password");
992 if (!$_SESSION["uid"] ||
!validate_session($link)) {
994 if (get_remote_user($link) && AUTO_LOGIN
) {
995 authenticate_user($link, get_remote_user($link), null);
996 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
998 render_login_form($link, $mobile);
999 //header("Location: login.php");
1003 /* bump login timestamp */
1004 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1007 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1008 setcookie("ttrss_lang", $_SESSION["language"],
1009 time() + SESSION_COOKIE_LIFETIME
);
1012 // try to remove possible duplicates from feed counter cache
1013 // ccache_cleanup($link, $_SESSION["uid"]);
1017 return authenticate_user($link, "admin", null);
1021 function truncate_string($str, $max_len, $suffix = '…') {
1022 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1023 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
1029 function theme_image($link, $filename) {
1031 $theme_path = get_user_theme_path($link);
1033 if ($theme_path && is_file($theme_path.$filename)) {
1034 return $theme_path.$filename;
1043 function get_user_theme($link) {
1045 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1046 $theme_name = get_pref($link, "_THEME_ID");
1047 if (is_dir("themes/$theme_name")) {
1058 function get_user_theme_path($link) {
1061 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1062 $theme_name = get_pref($link, "_THEME_ID");
1064 if ($theme_name && is_dir("themes/$theme_name")) {
1065 $theme_path = "themes/$theme_name/";
1074 if (is_file("$theme_path/theme.ini")) {
1075 $ini = parse_ini_file("$theme_path/theme.ini", true);
1076 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
1084 function get_user_theme_options($link) {
1085 $t = get_user_theme_path($link);
1088 if (is_file("$t/theme.ini")) {
1089 $ini = parse_ini_file("$t/theme.ini", true);
1090 if ($ini['theme']['version']) {
1091 return $ini['theme']['options'];
1098 function print_theme_includes($link) {
1100 $t = get_user_theme_path($link);
1104 print "<link rel=\"stylesheet\" type=\"text/css\"
1105 href=\"$t/theme.css?$time \">";
1106 if (file_exists("$t/theme.js")) {
1107 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
1113 function get_all_themes() {
1114 $themes = glob("themes/*");
1120 foreach ($themes as $t) {
1121 if (is_file("$t/theme.ini")) {
1122 $ini = parse_ini_file("$t/theme.ini", true);
1123 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
1124 !$ini['theme']['disabled']) {
1126 $entry["path"] = $t;
1127 $entry["base"] = basename($t);
1128 $entry["name"] = $ini['theme']['name'];
1129 $entry["version"] = $ini['theme']['version'];
1130 $entry["author"] = $ini['theme']['author'];
1131 $entry["options"] = $ini['theme']['options'];
1132 array_push($rv, $entry);
1140 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
1143 $source_tz = new DateTimeZone($source_tz);
1144 } catch (Exception
$e) {
1145 $source_tz = new DateTimeZone('UTC');
1149 $dest_tz = new DateTimeZone($dest_tz);
1150 } catch (Exception
$e) {
1151 $dest_tz = new DateTimeZone('UTC');
1154 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
1155 return $dt->format('U') +
$dest_tz->getOffset($dt);
1158 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
1159 $no_smart_dt = false) {
1161 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1162 if (!$timestamp) $timestamp = '1970-01-01 0:00';
1167 # We store date in UTC internally
1168 $dt = new DateTime($timestamp, $utc_tz);
1170 if ($tz_offset == -1) {
1172 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
1175 $user_tz = new DateTimeZone($user_tz_string);
1176 } catch (Exception
$e) {
1180 $tz_offset = $user_tz->getOffset($dt);
1183 $user_timestamp = $dt->format('U') +
$tz_offset;
1185 if (!$no_smart_dt) {
1186 return smart_date_time($link, $user_timestamp,
1187 $tz_offset, $owner_uid);
1190 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1192 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1194 return date($format, $user_timestamp);
1198 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
1199 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1201 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
1202 return date("G:i", $timestamp);
1203 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
1204 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1205 return date($format, $timestamp);
1207 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1208 return date($format, $timestamp);
1212 function sql_bool_to_bool($s) {
1213 if ($s == "t" ||
$s == "1" ||
$s == "true") {
1220 function bool_to_sql_bool($s) {
1228 // Session caching removed due to causing wrong redirects to upgrade
1229 // script when get_schema_version() is called on an obsolete session
1230 // created on a previous schema version.
1231 function get_schema_version($link, $nocache = false) {
1232 global $schema_version;
1234 if (!$schema_version) {
1235 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1236 $version = db_fetch_result($result, 0, "schema_version");
1237 $schema_version = $version;
1240 return $schema_version;
1244 function sanity_check($link) {
1245 require_once 'errors.php';
1248 $schema_version = get_schema_version($link, true);
1250 if ($schema_version != SCHEMA_VERSION
) {
1254 if (DB_TYPE
== "mysql") {
1255 $result = db_query($link, "SELECT true", false);
1256 if (db_num_rows($result) != 1) {
1261 if (db_escape_string("testTEST") != "testTEST") {
1265 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1268 function file_is_locked($filename) {
1269 if (function_exists('flock')) {
1270 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1272 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1273 flock($fp, LOCK_UN
);
1283 return true; // consider the file always locked and skip the test
1286 function make_lockfile($filename) {
1287 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1289 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1290 if (function_exists('posix_getpid')) {
1291 fwrite($fp, posix_getpid() . "\n");
1299 function make_stampfile($filename) {
1300 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1302 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1303 fwrite($fp, time() . "\n");
1304 flock($fp, LOCK_UN
);
1312 function sql_random_function() {
1313 if (DB_TYPE
== "mysql") {
1320 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1322 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1324 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1326 $ref_check_qpart = ($max_id &&
1327 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1329 if (is_numeric($feed)) {
1335 $cat_qpart = "cat_id = '$feed'";
1337 $cat_qpart = "cat_id IS NULL";
1340 $tmp_result = db_query($link, "SELECT id
1341 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
1343 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1345 $tmp_feed = $tmp_line["id"];
1347 db_query($link, "UPDATE ttrss_user_entries
1348 SET unread = false,last_read = NOW()
1349 WHERE feed_id = '$tmp_feed'
1350 AND $ref_check_qpart
1351 AND owner_uid = $owner_uid");
1353 } else if ($feed == -2) {
1355 db_query($link, "UPDATE ttrss_user_entries
1356 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1357 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1358 AND $ref_check_qpart
1359 AND unread = true AND owner_uid = $owner_uid");
1362 } else if ($feed > 0) {
1364 db_query($link, "UPDATE ttrss_user_entries
1365 SET unread = false,last_read = NOW()
1366 WHERE feed_id = '$feed'
1367 AND $ref_check_qpart
1368 AND owner_uid = $owner_uid");
1370 } else if ($feed < 0 && $feed > -10) { // special, like starred
1373 db_query($link, "UPDATE ttrss_user_entries
1374 SET unread = false,last_read = NOW()
1376 AND $ref_check_qpart
1377 AND owner_uid = $owner_uid");
1381 db_query($link, "UPDATE ttrss_user_entries
1382 SET unread = false,last_read = NOW()
1383 WHERE published = true
1384 AND $ref_check_qpart
1385 AND owner_uid = $owner_uid");
1390 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1392 if (DB_TYPE
== "pgsql") {
1393 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1395 $match_part = "updated > DATE_SUB(NOW(),
1396 INTERVAL $intl HOUR) ";
1399 $result = db_query($link, "SELECT id FROM ttrss_entries,
1400 ttrss_user_entries WHERE $match_part AND
1402 ttrss_user_entries.ref_id = ttrss_entries.id AND
1403 owner_uid = $owner_uid");
1405 $affected_ids = array();
1407 while ($line = db_fetch_assoc($result)) {
1408 array_push($affected_ids, $line["id"]);
1411 catchupArticlesById($link, $affected_ids, 0);
1415 db_query($link, "UPDATE ttrss_user_entries
1416 SET unread = false,last_read = NOW()
1417 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1420 } else if ($feed < -10) { // label
1422 $label_id = -$feed - 11;
1424 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1425 SET unread = false, last_read = NOW()
1426 WHERE label_id = '$label_id' AND unread = true
1427 AND $ref_check_qpart
1428 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1432 ccache_update($link, $feed, $owner_uid, $cat_view);
1435 db_query($link, "BEGIN");
1437 $tag_name = db_escape_string($feed);
1439 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1440 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1442 while ($line = db_fetch_assoc($result)) {
1443 db_query($link, "UPDATE ttrss_user_entries SET
1444 unread = false, last_read = NOW()
1445 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1447 db_query($link, "COMMIT");
1451 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1453 if (!$omode) $omode = "flc";
1455 $data = getGlobalCounters($link);
1457 $data = array_merge($data, getVirtCounters($link));
1459 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1460 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1461 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1462 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1467 function getCategoryTitle($link, $cat_id) {
1469 if ($cat_id == -1) {
1470 return __("Special");
1471 } else if ($cat_id == -2) {
1472 return __("Labels");
1475 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1478 if (db_num_rows($result) == 1) {
1479 return db_fetch_result($result, 0, "title");
1481 return "Uncategorized";
1487 function getCategoryCounters($link) {
1490 /* Labels category */
1492 $cv = array("id" => -2, "kind" => "cat",
1493 "counter" => getCategoryUnread($link, -2));
1495 array_push($ret_arr, $cv);
1497 $result = db_query($link, "SELECT id AS cat_id, value AS unread
1498 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1499 WHERE ttrss_cat_counters_cache.feed_id = id AND
1500 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1502 while ($line = db_fetch_assoc($result)) {
1503 $line["cat_id"] = (int) $line["cat_id"];
1505 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1506 "counter" => $line["unread"]);
1508 array_push($ret_arr, $cv);
1511 /* Special case: NULL category doesn't actually exist in the DB */
1513 $cv = array("id" => 0, "kind" => "cat",
1514 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
1516 array_push($ret_arr, $cv);
1521 function getCategoryUnread($link, $cat, $owner_uid = false) {
1523 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1528 $cat_query = "cat_id = '$cat'";
1530 $cat_query = "cat_id IS NULL";
1533 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1534 AND owner_uid = " . $owner_uid);
1536 $cat_feeds = array();
1537 while ($line = db_fetch_assoc($result)) {
1538 array_push($cat_feeds, "feed_id = " . $line["id"]);
1541 if (count($cat_feeds) == 0) return 0;
1543 $match_part = implode(" OR ", $cat_feeds);
1545 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1546 FROM ttrss_user_entries
1547 WHERE unread = true AND ($match_part)
1548 AND owner_uid = " . $owner_uid);
1552 # this needs to be rewritten
1553 while ($line = db_fetch_assoc($result)) {
1554 $unread +
= $line["unread"];
1558 } else if ($cat == -1) {
1559 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1560 } else if ($cat == -2) {
1562 $result = db_query($link, "
1563 SELECT COUNT(unread) AS unread FROM
1564 ttrss_user_entries, ttrss_user_labels2
1565 WHERE article_id = ref_id AND unread = true
1566 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1568 $unread = db_fetch_result($result, 0, "unread");
1575 function getFeedUnread($link, $feed, $is_cat = false) {
1576 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1579 function getLabelUnread($link, $label_id, $owner_uid = false) {
1580 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1582 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1583 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1585 if (db_num_rows($result) != 0) {
1586 return db_fetch_result($result, 0, "unread");
1592 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1593 $owner_uid = false) {
1595 $n_feed = (int) $feed;
1596 $need_entries = false;
1598 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1601 $unread_qpart = "unread = true";
1603 $unread_qpart = "true";
1607 return getCategoryUnread($link, $n_feed, $owner_uid);
1608 } if ($feed != "0" && $n_feed == 0) {
1610 $feed = db_escape_string($feed);
1612 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1613 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1614 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1615 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1616 return db_fetch_result($result, 0, "count");
1618 } else if ($n_feed == -1) {
1619 $match_part = "marked = true";
1620 } else if ($n_feed == -2) {
1621 $match_part = "published = true";
1622 } else if ($n_feed == -3) {
1623 $match_part = "unread = true AND score >= 0";
1625 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1627 if (DB_TYPE
== "pgsql") {
1628 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1630 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1633 $need_entries = true;
1635 } else if ($n_feed == -4) {
1636 $match_part = "true";
1637 } else if ($n_feed >= 0) {
1640 $match_part = "feed_id = '$n_feed'";
1642 $match_part = "feed_id IS NULL";
1645 } else if ($feed < -10) {
1647 $label_id = -$feed - 11;
1649 return getLabelUnread($link, $label_id, $owner_uid);
1655 if ($need_entries) {
1656 $from_qpart = "ttrss_user_entries,ttrss_entries";
1657 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1659 $from_qpart = "ttrss_user_entries";
1662 $query = "SELECT count(int_id) AS unread
1663 FROM $from_qpart WHERE
1664 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1666 //echo "[$feed/$query]\n";
1668 $result = db_query($link, $query);
1672 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1673 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1674 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1675 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1678 $unread = db_fetch_result($result, 0, "unread");
1683 function getGlobalUnread($link, $user_id = false) {
1686 $user_id = $_SESSION["uid"];
1689 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1690 WHERE owner_uid = '$user_id' AND feed_id > 0");
1692 $c_id = db_fetch_result($result, 0, "c_id");
1697 function getGlobalCounters($link, $global_unread = -1) {
1700 if ($global_unread == -1) {
1701 $global_unread = getGlobalUnread($link);
1704 $cv = array("id" => "global-unread",
1705 "counter" => $global_unread);
1707 array_push($ret_arr, $cv);
1709 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1710 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1712 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1714 $cv = array("id" => "subscribed-feeds",
1715 "counter" => $subscribed_feeds);
1717 array_push($ret_arr, $cv);
1722 function getTagCounters($link) {
1726 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1727 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1728 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1729 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1730 ORDER BY count DESC LIMIT 55");
1734 while ($line = db_fetch_assoc($result)) {
1735 $tags[$line["tag_name"]] +
= $line["count"];
1738 foreach (array_keys($tags) as $tag) {
1739 $unread = $tags[$tag];
1740 $tag = htmlspecialchars($tag);
1742 $cv = array("id" => $tag,
1744 "counter" => $unread);
1746 array_push($ret_arr, $cv);
1752 function getVirtCounters($link) {
1756 for ($i = 0; $i >= -4; $i--) {
1758 $count = getFeedUnread($link, $i);
1760 $cv = array("id" => $i,
1761 "counter" => $count);
1763 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1764 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1766 array_push($ret_arr, $cv);
1772 function getLabelCounters($link, $descriptions = false) {
1776 $owner_uid = $_SESSION["uid"];
1778 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1779 WHERE owner_uid = '$owner_uid'");
1781 while ($line = db_fetch_assoc($result)) {
1783 $id = -$line["id"] - 11;
1785 $label_name = $line["caption"];
1786 $count = getFeedUnread($link, $id);
1788 $cv = array("id" => $id,
1789 "counter" => $count);
1792 $cv["description"] = $label_name;
1794 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1795 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1797 array_push($ret_arr, $cv);
1803 function getFeedCounters($link, $active_feed = false) {
1807 $query = "SELECT ttrss_feeds.id,
1809 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1810 last_error, value AS count
1811 FROM ttrss_feeds, ttrss_counters_cache
1812 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1813 AND ttrss_counters_cache.feed_id = id";
1815 $result = db_query($link, $query);
1816 $fctrs_modified = false;
1818 while ($line = db_fetch_assoc($result)) {
1821 $count = $line["count"];
1822 $last_error = htmlspecialchars($line["last_error"]);
1824 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1826 $has_img = feed_has_icon($id);
1828 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1831 $cv = array("id" => $id,
1832 "updated" => $last_updated,
1833 "counter" => $count,
1834 "has_img" => (int) $has_img);
1837 $cv["error"] = $last_error;
1839 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1840 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1842 if ($active_feed && $id == $active_feed)
1843 $cv["title"] = truncate_string($line["title"], 30);
1845 array_push($ret_arr, $cv);
1852 function get_pgsql_version($link) {
1853 $result = db_query($link, "SELECT version() AS version");
1854 $version = explode(" ", db_fetch_result($result, 0, "version"));
1859 * @return integer Status code:
1860 * 0 - OK, Feed already exists
1861 * 1 - OK, Feed added
1863 * 3 - URL content is HTML, no feeds available
1864 * 4 - URL content is HTML which contains multiple feeds.
1865 * Here you should call extractfeedurls in rpc-backend
1866 * to get all possible feeds.
1867 * 5 - Couldn't download the URL content.
1869 function subscribe_to_feed($link, $url, $cat_id = 0,
1870 $auth_login = '', $auth_pass = '', $need_auth = false) {
1872 require_once "include/rssfuncs.php";
1874 $url = fix_url($url);
1876 if (!$url ||
!validate_feed_url($url)) return 2;
1880 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
1881 WHERE id = ".$_SESSION['uid']);
1883 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
1885 if (!$need_auth ||
!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
1886 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
1888 if (url_is_html($url, $auth_login, $auth_pass)) {
1889 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
1890 if (count($feedUrls) == 0) {
1892 } else if (count($feedUrls) > 1) {
1895 //use feed url as new URL
1896 $url = key($feedUrls);
1900 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
1905 if ($cat_id == "0" ||
!$cat_id) {
1906 $cat_qpart = "NULL";
1908 $cat_qpart = "'$cat_id'";
1911 $result = db_query($link,
1912 "SELECT id FROM ttrss_feeds
1913 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1915 if (db_num_rows($result) == 0) {
1916 $result = db_query($link,
1917 "INSERT INTO ttrss_feeds
1918 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1919 VALUES ('".$_SESSION["uid"]."', '$url',
1920 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1922 $result = db_query($link,
1923 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1924 AND owner_uid = " . $_SESSION["uid"]);
1926 $feed_id = db_fetch_result($result, 0, "id");
1929 update_rss_feed($link, $feed_id, true);
1938 function print_feed_select($link, $id, $default_id = "",
1939 $attributes = "", $include_all_feeds = true) {
1941 print "<select id=\"$id\" name=\"$id\" $attributes>";
1942 if ($include_all_feeds) {
1943 print "<option value=\"0\">".__('All feeds')."</option>";
1946 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1947 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1949 if (db_num_rows($result) > 0 && $include_all_feeds) {
1950 print "<option disabled>--------</option>";
1953 while ($line = db_fetch_assoc($result)) {
1954 if ($line["id"] == $default_id) {
1955 $is_selected = "selected=\"1\"";
1960 $title = truncate_string(htmlspecialchars($line["title"]), 40);
1962 printf("<option $is_selected value='%d'>%s</option>",
1963 $line["id"], $title);
1969 function print_feed_cat_select($link, $id, $default_id = "",
1970 $attributes = "", $include_all_cats = true) {
1972 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1974 if ($include_all_cats) {
1975 print "<option value=\"0\">".__('Uncategorized')."</option>";
1978 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1979 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1981 if (db_num_rows($result) > 0 && $include_all_cats) {
1982 print "<option disabled=\"1\">--------</option>";
1985 while ($line = db_fetch_assoc($result)) {
1986 if ($line["id"] == $default_id) {
1987 $is_selected = "selected=\"1\"";
1993 printf("<option $is_selected value='%d'>%s</option>",
1994 $line["id"], htmlspecialchars($line["title"]));
1997 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
2002 function checkbox_to_sql_bool($val) {
2003 return ($val == "on") ?
"true" : "false";
2006 function getFeedCatTitle($link, $id) {
2008 return __("Special");
2009 } else if ($id < -10) {
2010 return __("Labels");
2011 } else if ($id > 0) {
2012 $result = db_query($link, "SELECT ttrss_feed_categories.title
2013 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2014 cat_id = ttrss_feed_categories.id");
2015 if (db_num_rows($result) == 1) {
2016 return db_fetch_result($result, 0, "title");
2018 return __("Uncategorized");
2021 return "getFeedCatTitle($id) failed";
2026 function getFeedIcon($id) {
2029 return "images/archive.png";
2032 return "images/mark_set.png";
2035 return "images/pub_set.png";
2038 return "images/fresh.png";
2041 return "images/tag.png";
2045 return "images/label.png";
2047 if (file_exists(ICONS_DIR
. "/$id.ico"))
2048 return ICONS_URL
. "/$id.ico";
2054 function getFeedTitle($link, $id) {
2056 return __("Starred articles");
2057 } else if ($id == -2) {
2058 return __("Published articles");
2059 } else if ($id == -3) {
2060 return __("Fresh articles");
2061 } else if ($id == -4) {
2062 return __("All articles");
2063 } else if ($id === 0 ||
$id === "0") {
2064 return __("Archived articles");
2065 } else if ($id < -10) {
2066 $label_id = -$id - 11;
2067 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2068 if (db_num_rows($result) == 1) {
2069 return db_fetch_result($result, 0, "caption");
2071 return "Unknown label ($label_id)";
2074 } else if (is_numeric($id) && $id > 0) {
2075 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2076 if (db_num_rows($result) == 1) {
2077 return db_fetch_result($result, 0, "title");
2079 return "Unknown feed ($id)";
2086 function make_init_params($link) {
2089 $params["theme"] = get_user_theme($link);
2090 $params["theme_options"] = get_user_theme_options($link);
2092 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
2093 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
2094 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
2095 $params["sign_info"] = theme_image($link, "images/sign_info.png");
2097 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2098 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
2099 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
2100 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
2102 $params[strtolower($param)] = (int) get_pref($link, $param);
2105 $params["icons_url"] = ICONS_URL
;
2106 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
2107 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
2108 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
2109 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
2110 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
2112 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2113 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2115 $max_feed_id = db_fetch_result($result, 0, "mid");
2116 $num_feeds = db_fetch_result($result, 0, "nf");
2118 $params["max_feed_id"] = (int) $max_feed_id;
2119 $params["num_feeds"] = (int) $num_feeds;
2121 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
2123 $params["csrf_token"] = $_SESSION["csrf_token"];
2128 function make_runtime_info($link) {
2131 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2132 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2134 $max_feed_id = db_fetch_result($result, 0, "mid");
2135 $num_feeds = db_fetch_result($result, 0, "nf");
2137 $data["max_feed_id"] = (int) $max_feed_id;
2138 $data["num_feeds"] = (int) $num_feeds;
2140 $data['last_article_id'] = getLastArticleId($link);
2141 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2143 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
2145 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2147 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2149 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2152 $stamp_delta = time() - $stamp;
2154 if ($stamp_delta > 1800) {
2158 $_SESSION["daemon_stamp_check"] = time();
2161 $data['daemon_stamp_ok'] = $stamp_check;
2163 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2165 $data['daemon_stamp'] = $stamp_fmt;
2170 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2171 $new_version_details = @check_for_update
($link);
2173 $data['new_version_available'] = (int) ($new_version_details != false);
2175 $_SESSION["last_version_check"] = time();
2181 function search_to_sql($link, $search, $match_on) {
2183 $search_query_part = "";
2185 $keywords = explode(" ", $search);
2186 $query_keywords = array();
2188 foreach ($keywords as $k) {
2189 if (strpos($k, "-") === 0) {
2196 $commandpair = explode(":", mb_strtolower($k), 2);
2198 if ($commandpair[0] == "note" && $commandpair[1]) {
2200 if ($commandpair[1] == "true")
2201 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2203 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2205 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2207 if ($commandpair[1] == "true")
2208 array_push($query_keywords, "($not (marked = true))");
2210 array_push($query_keywords, "($not (marked = false))");
2212 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2214 if ($commandpair[1] == "true")
2215 array_push($query_keywords, "($not (published = true))");
2217 array_push($query_keywords, "($not (published = false))");
2219 } else if (strpos($k, "@") === 0) {
2221 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2222 $orig_ts = strtotime(substr($k, 1));
2223 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2225 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2227 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2228 } else if ($match_on == "both") {
2229 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2230 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2231 } else if ($match_on == "title") {
2232 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2233 } else if ($match_on == "content") {
2234 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2238 $search_query_part = implode("AND", $query_keywords);
2240 return $search_query_part;
2244 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) {
2246 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2248 $ext_tables_part = "";
2252 if (SPHINX_ENABLED
) {
2253 $ids = join(",", @sphinx_search
($search, 0, 500));
2256 $search_query_part = "ref_id IN ($ids) AND ";
2258 $search_query_part = "ref_id = -1 AND ";
2261 $search_query_part = search_to_sql($link, $search, $match_on);
2262 $search_query_part .= " AND ";
2266 $search_query_part = "";
2270 $filter_query_part = filter_to_sql($filter);
2272 $filter_query_part = "";
2276 $since_id_part = "ttrss_entries.id > $since_id AND ";
2278 $since_id_part = "";
2281 $view_query_part = "";
2283 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2285 $view_query_part = " ";
2286 } else if ($feed != -1) {
2287 $unread = getFeedUnread($link, $feed, $cat_view);
2289 $view_query_part = " unread = true AND ";
2294 if ($view_mode == "marked") {
2295 $view_query_part = " marked = true AND ";
2298 if ($view_mode == "published") {
2299 $view_query_part = " published = true AND ";
2302 if ($view_mode == "unread") {
2303 $view_query_part = " unread = true AND ";
2306 if ($view_mode == "updated") {
2307 $view_query_part = " (last_read is null and unread = false) AND ";
2311 $limit_query_part = "LIMIT " . $limit;
2314 $vfeed_query_part = "";
2316 // override query strategy and enable feed display when searching globally
2317 if ($search && $search_mode == "all_feeds") {
2318 $query_strategy_part = "ttrss_entries.id > 0";
2319 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2321 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2322 $query_strategy_part = "ttrss_entries.id > 0";
2323 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2324 id = feed_id) as feed_title,";
2325 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
2327 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2329 $tmp_result = false;
2332 $tmp_result = db_query($link, "SELECT id
2333 FROM ttrss_feeds WHERE cat_id = '$feed'");
2335 $tmp_result = db_query($link, "SELECT id
2336 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2337 WHERE id = '$feed') AND id != '$feed'");
2340 $cat_siblings = array();
2342 if (db_num_rows($tmp_result) > 0) {
2343 while ($p = db_fetch_assoc($tmp_result)) {
2344 array_push($cat_siblings, "feed_id = " . $p["id"]);
2347 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2348 $feed, implode(" OR ", $cat_siblings));
2351 $query_strategy_part = "ttrss_entries.id > 0";
2354 } else if ($feed > 0) {
2359 $query_strategy_part = "cat_id = '$feed'";
2361 $query_strategy_part = "cat_id IS NULL";
2364 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2367 $query_strategy_part = "feed_id = '$feed'";
2369 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2370 $query_strategy_part = "feed_id IS NULL";
2371 } else if ($feed == 0 && $cat_view) { // uncategorized
2372 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2373 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2374 } else if ($feed == -1) { // starred virtual feed
2375 $query_strategy_part = "marked = true";
2376 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2377 } else if ($feed == -2) { // published virtual feed OR labels category
2380 $query_strategy_part = "published = true";
2381 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2383 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2385 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2387 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2388 ttrss_user_labels2.article_id = ref_id";
2392 } else if ($feed == -3) { // fresh virtual feed
2393 $query_strategy_part = "unread = true AND score >= 0";
2395 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2397 if (DB_TYPE
== "pgsql") {
2398 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2400 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2403 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2404 } else if ($feed == -4) { // all articles virtual feed
2405 $query_strategy_part = "true";
2406 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2407 } else if ($feed <= -10) { // labels
2408 $label_id = -$feed - 11;
2410 $query_strategy_part = "label_id = '$label_id' AND
2411 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2412 ttrss_user_labels2.article_id = ref_id";
2414 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2415 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2418 $query_strategy_part = "id > 0"; // dumb
2421 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2422 $date_sort_field = "updated";
2424 $date_sort_field = "date_entered";
2427 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2428 $order_by = "$date_sort_field";
2430 $order_by = "$date_sort_field DESC";
2433 if ($view_mode != "noscores") {
2434 $order_by = "score DESC, $order_by";
2437 if ($override_order) {
2438 $order_by = $override_order;
2444 $feed_title = "Search results";
2447 $feed_title = getCategoryTitle($link, $feed);
2449 if (is_numeric($feed) && $feed > 0) {
2450 $result = db_query($link, "SELECT title,site_url,last_error
2451 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2453 $feed_title = db_fetch_result($result, 0, "title");
2454 $feed_site_url = db_fetch_result($result, 0, "site_url");
2455 $last_error = db_fetch_result($result, 0, "last_error");
2457 $feed_title = getFeedTitle($link, $feed);
2462 $content_query_part = "content as content_preview,";
2464 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2467 $feed_kind = "Feeds";
2469 $feed_kind = "Labels";
2472 if ($limit_query_part) {
2473 $offset_query_part = "OFFSET $offset";
2476 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2477 if (!$override_order) {
2478 $order_by = "ttrss_feeds.title, $order_by";
2483 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2484 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2487 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
2488 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2491 $query = "SELECT DISTINCT
2494 ttrss_entries.id,ttrss_entries.title,
2498 always_display_enclosures,
2504 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2505 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2508 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2514 ttrss_user_entries.ref_id = ttrss_entries.id AND
2515 ttrss_user_entries.owner_uid = '$owner_uid' AND
2520 $query_strategy_part ORDER BY $order_by
2521 $limit_query_part $offset_query_part";
2523 if ($_REQUEST["debug"]) print $query;
2525 $result = db_query($link, $query);
2530 $select_qpart = "SELECT DISTINCT " .
2534 "ttrss_entries.id as id," .
2547 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2550 $content_query_part .
2551 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2554 $feed_kind = "Tags";
2555 $all_tags = explode(",", $feed);
2556 if ($search_mode == 'any') {
2557 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2558 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2559 $where_qpart = " WHERE " .
2560 "ref_id = ttrss_entries.id AND " .
2561 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2562 "post_int_id = int_id AND $tag_sql AND " .
2564 $search_query_part .
2565 $query_strategy_part . " ORDER BY $order_by " .
2570 $sub_selects = array();
2571 $sub_ands = array();
2572 foreach ($all_tags as $term) {
2573 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");
2580 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2585 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2586 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2587 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2588 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2590 // error_log("TAG SQL: " . $tag_sql);
2591 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2593 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2594 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2597 return array($result, $feed_title, $feed_site_url, $last_error);
2601 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2604 if (!$owner) $owner = $_SESSION["uid"];
2606 $res = trim($str); if (!$res) return '';
2608 // create global Purifier object if needed
2610 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
2612 $config = HTMLPurifier_Config
::createDefault();
2614 $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]";
2616 $config->set('HTML.SafeObject', true);
2617 @$config->set('HTML', 'Allowed', $allowed);
2618 $config->set('Output.FlashCompat', true);
2619 $config->set('Attr.EnableID', true);
2620 if (!defined('MOBILE_VERSION')) {
2621 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
2623 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
2626 $config->set('Filter.YouTube', true);
2628 $purifier = new HTMLPurifier($config);
2631 $res = $purifier->purify($res);
2633 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2634 $res = preg_replace('/<img[^>]+>/is', '', $res);
2637 if (strpos($res, "href=") === false)
2638 $res = rewrite_urls($res);
2640 $charset_hack = '<head>
2641 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2644 $res = trim($res); if (!$res) return '';
2646 libxml_use_internal_errors(true);
2648 $doc = new DOMDocument();
2649 $doc->loadHTML($charset_hack . $res);
2650 $xpath = new DOMXPath($doc);
2652 $entries = $xpath->query('(//a[@href]|//img[@src])');
2655 foreach ($entries as $entry) {
2659 if ($entry->hasAttribute('href'))
2660 $entry->setAttribute('href',
2661 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2663 if ($entry->hasAttribute('src'))
2664 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2665 $entry->setAttribute('src',
2666 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2669 if (strtolower($entry->nodeName
) == "a") {
2670 $entry->setAttribute("target", "_blank");
2673 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2674 $br = $doc->createElement("br");
2676 if ($entry->parentNode
->nextSibling
) {
2677 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2684 $node = $doc->getElementsByTagName('body')->item(0);
2686 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2690 * Send by mail a digest of last articles.
2692 * @param mixed $link The database connection.
2693 * @param integer $limit The maximum number of articles by digest.
2694 * @return boolean Return false if digests are not enabled.
2696 function send_headlines_digests($link, $debug = false) {
2698 require_once 'lib/phpmailer/class.phpmailer.php';
2700 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2701 $limit = 1000; // maximum amount of headlines to include
2703 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2705 if (DB_TYPE
== "pgsql") {
2706 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2707 } else if (DB_TYPE
== "mysql") {
2708 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2711 $result = db_query($link, "SELECT id,email FROM ttrss_users
2712 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2714 while ($line = db_fetch_assoc($result)) {
2716 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2717 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2719 // try to send digests within 2 hours of preferred time
2720 if ($preferred_ts && time() >= $preferred_ts &&
2721 time() - $preferred_ts <= 7200) {
2723 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2725 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2729 // reset tz_offset global to prevent tz cache clash between users
2732 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2733 $digest = $tuple[0];
2734 $headlines_count = $tuple[1];
2735 $affected_ids = $tuple[2];
2736 $digest_text = $tuple[3];
2738 if ($headlines_count > 0) {
2740 $mail = new PHPMailer();
2742 $mail->PluginDir
= "lib/phpmailer/";
2743 $mail->SetLanguage("en", "lib/phpmailer/language/");
2745 $mail->CharSet
= "UTF-8";
2747 $mail->From
= SMTP_FROM_ADDRESS
;
2748 $mail->FromName
= SMTP_FROM_NAME
;
2749 $mail->AddAddress($line["email"], $line["login"]);
2752 $mail->Host
= SMTP_HOST
;
2753 $mail->Mailer
= "smtp";
2754 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2755 $mail->Username
= SMTP_LOGIN
;
2756 $mail->Password
= SMTP_PASSWORD
;
2759 $mail->IsHTML(true);
2760 $mail->Subject
= DIGEST_SUBJECT
;
2761 $mail->Body
= $digest;
2762 $mail->AltBody
= $digest_text;
2764 $rc = $mail->Send();
2766 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2768 if ($debug) print "RC=$rc\n";
2770 if ($rc && $do_catchup) {
2771 if ($debug) print "Marking affected articles as read...\n";
2772 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2775 if ($debug) print "No headlines\n";
2778 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2779 WHERE id = " . $line["id"]);
2785 if ($debug) _debug("All done.");
2789 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2791 require_once "lib/MiniTemplator.class.php";
2793 $tpl = new MiniTemplator
;
2794 $tpl_t = new MiniTemplator
;
2796 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2797 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2799 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2800 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2802 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2803 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2805 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2806 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2808 $affected_ids = array();
2810 if (DB_TYPE
== "pgsql") {
2811 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2812 } else if (DB_TYPE
== "mysql") {
2813 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2816 $result = db_query($link, "SELECT ttrss_entries.title,
2817 ttrss_feeds.title AS feed_title,
2818 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2820 ttrss_user_entries.ref_id,
2824 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2826 ttrss_user_entries,ttrss_entries,ttrss_feeds
2828 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2830 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2831 AND include_in_digest = true
2833 AND ttrss_user_entries.owner_uid = $user_id
2836 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2839 $cur_feed_title = "";
2841 $headlines_count = db_num_rows($result);
2843 $headlines = array();
2845 while ($line = db_fetch_assoc($result)) {
2846 array_push($headlines, $line);
2849 for ($i = 0; $i < sizeof($headlines); $i++
) {
2851 $line = $headlines[$i];
2853 array_push($affected_ids, $line["ref_id"]);
2855 $updated = make_local_datetime($link, $line['last_updated'], false,
2858 /* if ($line["score"] != 0) {
2859 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2861 $line["title"] .= " (".$line['score'].")";
2864 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2865 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2868 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2869 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2870 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2871 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2872 $tpl->setVariable('ARTICLE_EXCERPT',
2873 truncate_string(strip_tags($line["content"]), 300));
2874 // $tpl->setVariable('ARTICLE_CONTENT',
2875 // strip_tags($article_content));
2877 $tpl->addBlock('article');
2879 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2880 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2881 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2882 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2883 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2884 // truncate_string(strip_tags($line["excerpt"]), 100));
2886 $tpl_t->addBlock('article');
2888 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2889 $tpl->addBlock('feed');
2890 $tpl_t->addBlock('feed');
2895 $tpl->addBlock('digest');
2896 $tpl->generateOutputToString($tmp);
2898 $tpl_t->addBlock('digest');
2899 $tpl_t->generateOutputToString($tmp_t);
2901 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2904 function check_for_update($link) {
2905 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2906 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2908 $version_data = @fetch_file_contents
($version_url);
2910 if ($version_data) {
2911 $version_data = json_decode($version_data, true);
2912 if ($version_data && $version_data['version']) {
2914 if (version_compare(VERSION
, $version_data['version']) == -1) {
2915 return $version_data;
2923 function markArticlesById($link, $ids, $cmode) {
2927 foreach ($ids as $id) {
2928 array_push($tmp_ids, "ref_id = '$id'");
2931 $ids_qpart = join(" OR ", $tmp_ids);
2934 db_query($link, "UPDATE ttrss_user_entries SET
2935 marked = false,last_read = NOW()
2936 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2937 } else if ($cmode == 1) {
2938 db_query($link, "UPDATE ttrss_user_entries SET
2940 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2942 db_query($link, "UPDATE ttrss_user_entries SET
2943 marked = NOT marked,last_read = NOW()
2944 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2948 function publishArticlesById($link, $ids, $cmode) {
2952 foreach ($ids as $id) {
2953 array_push($tmp_ids, "ref_id = '$id'");
2956 $ids_qpart = join(" OR ", $tmp_ids);
2959 db_query($link, "UPDATE ttrss_user_entries SET
2960 published = false,last_read = NOW()
2961 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2962 } else if ($cmode == 1) {
2963 db_query($link, "UPDATE ttrss_user_entries SET
2965 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2967 db_query($link, "UPDATE ttrss_user_entries SET
2968 published = NOT published,last_read = NOW()
2969 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2972 if (PUBSUBHUBBUB_HUB
) {
2973 $rss_link = get_self_url_prefix() .
2974 "/public.php?op=rss&id=-2&key=" .
2975 get_feed_access_key($link, -2, false);
2977 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2979 $pubsub_result = $p->publish_update($rss_link);
2983 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2985 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2986 if (count($ids) == 0) return;
2990 foreach ($ids as $id) {
2991 array_push($tmp_ids, "ref_id = '$id'");
2994 $ids_qpart = join(" OR ", $tmp_ids);
2997 db_query($link, "UPDATE ttrss_user_entries SET
2998 unread = false,last_read = NOW()
2999 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3000 } else if ($cmode == 1) {
3001 db_query($link, "UPDATE ttrss_user_entries SET
3003 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3005 db_query($link, "UPDATE ttrss_user_entries SET
3006 unread = NOT unread,last_read = NOW()
3007 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3012 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3013 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3015 while ($line = db_fetch_assoc($result)) {
3016 ccache_update($link, $line["feed_id"], $owner_uid);
3020 function catchupArticleById($link, $id, $cmode) {
3023 db_query($link, "UPDATE ttrss_user_entries SET
3024 unread = false,last_read = NOW()
3025 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3026 } else if ($cmode == 1) {
3027 db_query($link, "UPDATE ttrss_user_entries SET
3029 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3031 db_query($link, "UPDATE ttrss_user_entries SET
3032 unread = NOT unread,last_read = NOW()
3033 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3036 $feed_id = getArticleFeed($link, $id);
3037 ccache_update($link, $feed_id, $_SESSION["uid"]);
3040 function make_guid_from_title($title) {
3041 return preg_replace("/[ \"\',.:;]/", "-",
3042 mb_strtolower(strip_tags($title), 'utf-8'));
3045 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
3047 $a_id = db_escape_string($id);
3049 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3051 $query = "SELECT DISTINCT tag_name,
3052 owner_uid as owner FROM
3053 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3054 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
3056 $obj_id = md5("TAGS:$owner_uid:$id");
3059 /* check cache first */
3061 if ($tag_cache === false) {
3062 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
3063 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3065 $tag_cache = db_fetch_result($result, 0, "tag_cache");
3069 $tags = explode(",", $tag_cache);
3072 /* do it the hard way */
3074 $tmp_result = db_query($link, $query);
3076 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3077 array_push($tags, $tmp_line["tag_name"]);
3080 /* update the cache */
3082 $tags_str = db_escape_string(join(",", $tags));
3084 db_query($link, "UPDATE ttrss_user_entries
3085 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3086 AND owner_uid = $owner_uid");
3092 function trim_array($array) {
3094 array_walk($tmp, 'trim');
3098 function tag_is_valid($tag) {
3099 if ($tag == '') return false;
3100 if (preg_match("/^[0-9]*$/", $tag)) return false;
3101 if (mb_strlen($tag) > 250) return false;
3103 if (function_exists('iconv')) {
3104 $tag = iconv("utf-8", "utf-8", $tag);
3107 if (!$tag) return false;
3112 function render_login_form($link, $mobile = 0) {
3115 require_once "login_form.php";
3118 require_once "mobile/login_form.php";
3121 require_once "mobile/classic/login_form.php";
3125 // from http://developer.apple.com/internet/safari/faq.html
3126 function no_cache_incantation() {
3127 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3128 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3129 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3130 header("Cache-Control: post-check=0, pre-check=0", false);
3131 header("Pragma: no-cache"); // HTTP/1.0
3134 function format_warning($msg, $id = "") {
3136 return "<div class=\"warning\" id=\"$id\">
3137 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3140 function format_notice($msg, $id = "") {
3142 return "<div class=\"notice\" id=\"$id\">
3143 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3146 function format_error($msg, $id = "") {
3148 return "<div class=\"error\" id=\"$id\">
3149 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3152 function print_notice($msg) {
3153 return print format_notice($msg);
3156 function print_warning($msg) {
3157 return print format_warning($msg);
3160 function print_error($msg) {
3161 return print format_error($msg);
3165 function T_sprintf() {
3166 $args = func_get_args();
3167 return vsprintf(__(array_shift($args)), $args);
3170 function format_inline_player($link, $url, $ctype) {
3174 if (strpos($ctype, "audio/") === 0) {
3176 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3177 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3178 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3180 $id = 'AUDIO-' . uniqid();
3182 $entry .= "<audio id=\"$id\"\">
3183 <source src=\"$url\"></source>
3186 $entry .= "<span onclick=\"player(this)\"
3187 title=\"".__("Click to play")."\" status=\"0\"
3188 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3192 $entry .= "<object type=\"application/x-shockwave-flash\"
3193 data=\"lib/button/musicplayer.swf?song_url=$url\"
3194 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3195 <param name=\"movie\"
3196 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3201 $filename = substr($url, strrpos($url, "/")+
1);
3203 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3204 $filename . " (" . $ctype . ")" . "</a>";
3209 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3211 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3217 /* we can figure out feed_id from article id anyway, why do we
3218 * pass feed_id here? let's ignore the argument :( */
3220 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3221 WHERE ref_id = '$id'");
3223 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3225 $rv['feed_id'] = $feed_id;
3227 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3229 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3230 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3232 if (db_num_rows($result) == 1) {
3233 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3234 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3236 $rtl_content = false;
3237 $always_display_enclosures = false;
3241 $rtl_tag = "dir=\"RTL\"";
3248 if ($mark_as_read) {
3249 $result = db_query($link, "UPDATE ttrss_user_entries
3250 SET unread = false,last_read = NOW()
3251 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3253 ccache_update($link, $feed_id, $owner_uid);
3256 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3257 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3258 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3259 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3265 FROM ttrss_entries,ttrss_user_entries
3266 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3270 $line = db_fetch_assoc($result);
3272 if ($line["icon_url"]) {
3273 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3275 $feed_icon = " ";
3278 $feed_site_url = $line['site_url'];
3280 $num_comments = $line["num_comments"];
3281 $entry_comments = "";
3283 if ($num_comments > 0) {
3284 if ($line["comments"]) {
3285 $comments_url = $line["comments"];
3287 $comments_url = $line["link"];
3289 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3291 if ($line["comments"] && $line["link"] != $line["comments"]) {
3292 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
3297 header("Content-Type: text/html");
3298 $rv['content'] .= "<html><head>
3299 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3300 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3301 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3305 $title_escaped = db_escape_string($line['title']);
3307 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3308 truncate_string(strip_tags($line['title']), 15) . "</div>";
3310 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3311 strip_tags($line['title']) . "</div>";
3313 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3315 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3316 class=\"postHeader\" id=\"POSTHDR-$id\">";
3318 $entry_author = $line["author"];
3320 if ($entry_author) {
3321 $entry_author = __(" - ") . $entry_author;
3324 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3327 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3329 if ($line["link"]) {
3330 $rv['content'] .= "<div class='postTitle' clear='both'><a target='_blank'
3331 title=\"".htmlspecialchars($line['title'])."\"
3333 $line["link"] . "\">" .
3334 truncate_string($line["title"], 100) .
3335 "<span class='author'>$entry_author</span></a></div>";
3337 $rv['content'] .= "<div class='postTitle' clear='both'>" . $line["title"] . "$entry_author</div>";
3340 $tag_cache = $line["tag_cache"];
3343 $tags = get_article_tags($link, $id, $owner_uid);
3345 $tags = explode(",", $tag_cache);
3347 $tags_str = format_tags_string($tags, $id);
3348 $tags_str_full = join(", ", $tags);
3350 if (!$tags_str_full) $tags_str_full = __("no tags");
3352 if (!$entry_comments) $entry_comments = " "; # placeholder
3354 $rv['content'] .= "<div class='postTags' style='float : right'>
3355 <img src='".theme_image($link, 'images/tag.png')."'
3356 class='tagsPic' alt='Tags' title='Tags'> ";
3359 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3360 <a title=\"".__('Edit tags for this article')."\"
3361 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3363 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3364 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3365 position=\"below\">$tags_str_full</div>";
3367 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3368 class='tagsPic' style=\"cursor : pointer\"
3369 onclick=\"postOpenInNewTab(event, $id)\"
3370 alt='Zoom' title='".__('Open article in new tab')."'>";
3372 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3374 foreach ($button_plugins as $p) {
3375 $pclass = trim("${p}_button");
3377 if (class_exists($pclass)) {
3378 $plugin = new $pclass($link);
3379 $rv['content'] .= $plugin->render($id, $line);
3383 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3384 class='tagsPic' style=\"cursor : pointer\"
3385 onclick=\"closeArticlePanel($id)\"
3386 title='".__('Close article')."'>";
3389 $tags_str = strip_tags($tags_str);
3390 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3392 $rv['content'] .= "</div>";
3393 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3395 if ($line["orig_feed_id"]) {
3397 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3398 WHERE id = ".$line["orig_feed_id"]);
3400 if (db_num_rows($tmp_result) != 0) {
3402 $rv['content'] .= "<div clear='both'>";
3403 $rv['content'] .= __("Originally from:");
3405 $rv['content'] .= " ";
3407 $tmp_line = db_fetch_assoc($tmp_result);
3409 $rv['content'] .= "<a target='_blank'
3410 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3411 $tmp_line['title'] . "</a>";
3413 $rv['content'] .= " ";
3415 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3416 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3418 $rv['content'] .= "</div>";
3422 $rv['content'] .= "</div>";
3424 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3425 if ($line['note']) {
3426 $rv['content'] .= format_article_note($id, $line['note']);
3428 $rv['content'] .= "</div>";
3430 $rv['content'] .= "<div class=\"postIcon\">" .
3431 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3432 href=\"".htmlspecialchars($feed_site_url)."\">".
3433 $feed_icon . "</a></div>";
3435 $rv['content'] .= "<div class=\"postContent\">";
3439 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3441 $ngram_result = db_query($link, "SELECT id,title FROM
3442 ttrss_entries,ttrss_user_entries
3443 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3444 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3445 AND title != '$title_escaped'
3446 AND owner_uid = $owner_uid");
3448 if (db_num_rows($ngram_result) > 0) {
3449 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3450 "<span>" . __('Related')."</span>";
3451 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3453 while ($nline = db_fetch_assoc($ngram_result)) {
3454 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3455 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3458 $rv['content'] .= "</div></div><br/";
3462 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3465 $rv['content'] .= $article_content;
3467 $rv['content'] .= format_article_enclosures($link, $id,
3468 $always_display_enclosures, $article_content);
3470 $rv['content'] .= "</div>";
3472 $rv['content'] .= "</div>";
3478 <div style=\"text-align : center\">
3479 <button onclick=\"return window.close()\">".
3480 __("Close this window")."</button></div>";
3481 $rv['content'] .= "</body></html>";
3488 function print_checkpoint($n, $s) {
3489 $ts = getmicrotime();
3490 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3494 function sanitize_tag($tag) {
3497 $tag = mb_strtolower($tag, 'utf-8');
3499 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3501 // $tag = str_replace('"', "", $tag);
3502 // $tag = str_replace("+", " ", $tag);
3503 $tag = str_replace("technorati tag: ", "", $tag);
3508 function get_self_url_prefix() {
3509 return SELF_URL_PATH
;
3512 function opml_publish_url($link){
3514 $url_path = get_self_url_prefix();
3515 $url_path .= "/opml.php?op=publish&key=" .
3516 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3522 * Purge a feed contents, marked articles excepted.
3524 * @param mixed $link The database connection.
3525 * @param integer $id The id of the feed to purge.
3528 function clear_feed_articles($link, $id) {
3531 $result = db_query($link, "DELETE FROM ttrss_user_entries
3532 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3534 $result = db_query($link, "DELETE FROM ttrss_user_entries
3535 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3538 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3539 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3541 ccache_update($link, $id, $_SESSION['uid']);
3542 } // function clear_feed_articles
3545 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3547 * @return string The Mozilla Firefox feed adding URL.
3549 function add_feed_url() {
3550 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3552 $url_path = get_self_url_prefix() .
3553 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
3555 } // function add_feed_url
3557 function encrypt_password($pass, $salt = '', $mode2 = false) {
3558 if ($salt && $mode2) {
3559 return "MODE2:" . hash('sha256', $salt . $pass);
3561 return "SHA1X:" . sha1("$salt:$pass");
3563 return "SHA1:" . sha1($pass);
3565 } // function encrypt_password
3567 function sanitize_article_content($text) {
3568 # we don't support CDATA sections in articles, they break our own escaping
3569 $text = preg_replace("/\[\[CDATA/", "", $text);
3570 $text = preg_replace("/\]\]\>/", "", $text);
3574 function load_filters($link, $feed, $owner_uid, $action_id = false) {
3578 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
3580 $result = db_query($link, "SELECT reg_exp,
3581 ttrss_filter_types.name AS name,
3582 ttrss_filter_actions.name AS action,
3587 LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
3588 ttrss_filter_types,ttrss_filter_actions
3592 ttrss_filters.owner_uid = $owner_uid AND
3593 ttrss_filter_types.id = filter_type AND
3594 ttrss_filter_actions.id = action_id AND
3595 ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
3596 (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
3597 ttrss_filters.cat_id IS NULL) OR
3598 (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
3601 while ($line = db_fetch_assoc($result)) {
3603 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
3604 $filter["reg_exp"] = $line["reg_exp"];
3605 $filter["action"] = $line["action"];
3606 $filter["action_param"] = $line["action_param"];
3607 $filter["filter_param"] = $line["filter_param"];
3608 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3610 array_push($filters[$line["name"]], $filter);
3617 function get_score_pic($score) {
3619 return "score_high.png";
3620 } else if ($score > 0) {
3621 return "score_half_high.png";
3622 } else if ($score < -100) {
3623 return "score_low.png";
3624 } else if ($score < 0) {
3625 return "score_half_low.png";
3627 return "score_neutral.png";
3631 function feed_has_icon($id) {
3632 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3635 function init_connection($link) {
3638 if (DB_TYPE
== "pgsql") {
3639 pg_query($link, "set client_encoding = 'UTF-8'");
3640 pg_set_client_encoding("UNICODE");
3641 pg_query($link, "set datestyle = 'ISO, european'");
3642 pg_query($link, "set TIME ZONE 0");
3644 db_query($link, "SET time_zone = '+0:0'");
3646 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3647 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3652 print "Unable to connect to database:" . db_last_error();
3657 /* function ccache_zero($link, $feed_id, $owner_uid) {
3658 db_query($link, "UPDATE ttrss_counters_cache SET
3659 value = 0, updated = NOW() WHERE
3660 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3663 function ccache_zero_all($link, $owner_uid) {
3664 db_query($link, "UPDATE ttrss_counters_cache SET
3665 value = 0 WHERE owner_uid = '$owner_uid'");
3667 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3668 value = 0 WHERE owner_uid = '$owner_uid'");
3671 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3674 $table = "ttrss_counters_cache";
3676 $table = "ttrss_cat_counters_cache";
3679 db_query($link, "DELETE FROM $table WHERE
3680 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3684 function ccache_update_all($link, $owner_uid) {
3686 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3688 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3689 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3691 while ($line = db_fetch_assoc($result)) {
3692 ccache_update($link, $line["feed_id"], $owner_uid, true);
3695 /* We have to manually include category 0 */
3697 ccache_update($link, 0, $owner_uid, true);
3700 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3701 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3703 while ($line = db_fetch_assoc($result)) {
3704 print ccache_update($link, $line["feed_id"], $owner_uid);
3711 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3712 $no_update = false) {
3714 if (!is_numeric($feed_id)) return;
3717 $table = "ttrss_counters_cache";
3719 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3720 WHERE id = '$feed_id'");
3721 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3724 $table = "ttrss_cat_counters_cache";
3727 if (DB_TYPE
== "pgsql") {
3728 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3729 } else if (DB_TYPE
== "mysql") {
3730 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3733 $result = db_query($link, "SELECT value FROM $table
3734 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3737 if (db_num_rows($result) == 1) {
3738 return db_fetch_result($result, 0, "value");
3743 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3749 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3750 $update_pcat = true) {
3752 if (!is_numeric($feed_id)) return;
3754 if (!$is_cat && $feed_id > 0) {
3755 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3756 WHERE id = '$feed_id'");
3757 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3760 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3762 /* When updating a label, all we need to do is recalculate feed counters
3763 * because labels are not cached */
3766 ccache_update_all($link, $owner_uid);
3771 $table = "ttrss_counters_cache";
3773 $table = "ttrss_cat_counters_cache";
3776 if ($is_cat && $feed_id >= 0) {
3777 if ($feed_id != 0) {
3778 $cat_qpart = "cat_id = '$feed_id'";
3780 $cat_qpart = "cat_id IS NULL";
3783 /* Recalculate counters for child feeds */
3785 $result = db_query($link, "SELECT id FROM ttrss_feeds
3786 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3788 while ($line = db_fetch_assoc($result)) {
3789 ccache_update($link, $line["id"], $owner_uid, false, false);
3792 $result = db_query($link, "SELECT SUM(value) AS sv
3793 FROM ttrss_counters_cache, ttrss_feeds
3794 WHERE id = feed_id AND $cat_qpart AND
3795 ttrss_feeds.owner_uid = '$owner_uid'");
3797 $unread = (int) db_fetch_result($result, 0, "sv");
3800 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3803 db_query($link, "BEGIN");
3805 $result = db_query($link, "SELECT feed_id FROM $table
3806 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3808 if (db_num_rows($result) == 1) {
3809 db_query($link, "UPDATE $table SET
3810 value = '$unread', updated = NOW() WHERE
3811 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3814 db_query($link, "INSERT INTO $table
3815 (feed_id, value, owner_uid, updated)
3817 ($feed_id, $unread, $owner_uid, NOW())");
3820 db_query($link, "COMMIT");
3822 if ($feed_id > 0 && $prev_unread != $unread) {
3826 /* Update parent category */
3830 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3831 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3833 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3835 ccache_update($link, $cat_id, $owner_uid, true);
3839 } else if ($feed_id < 0) {
3840 ccache_update_all($link, $owner_uid);
3846 /* function ccache_cleanup($link, $owner_uid) {
3848 if (DB_TYPE == "pgsql") {
3849 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3850 (SELECT count(*) FROM ttrss_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'");
3854 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3855 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3856 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3857 AND owner_uid = '$owner_uid'");
3859 db_query($link, "DELETE c1 FROM
3860 ttrss_counters_cache AS c1,
3861 ttrss_counters_cache AS c2
3863 c1.owner_uid = '$owner_uid' AND
3864 c1.owner_uid = c2.owner_uid AND
3865 c1.feed_id = c2.feed_id");
3867 db_query($link, "DELETE c1 FROM
3868 ttrss_cat_counters_cache AS c1,
3869 ttrss_cat_counters_cache AS c2
3871 c1.owner_uid = '$owner_uid' AND
3872 c1.owner_uid = c2.owner_uid AND
3873 c1.feed_id = c2.feed_id");
3878 function label_find_id($link, $label, $owner_uid) {
3879 $result = db_query($link,
3880 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3881 AND owner_uid = '$owner_uid' LIMIT 1");
3883 if (db_num_rows($result) == 1) {
3884 return db_fetch_result($result, 0, "id");
3890 function get_article_labels($link, $id) {
3894 $result = db_query($link, "SELECT label_cache FROM
3895 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3898 $label_cache = db_fetch_result($result, 0, "label_cache");
3902 $label_cache = json_decode($label_cache, true);
3904 if ($label_cache["no-labels"] == 1)
3907 return $label_cache;
3910 $result = db_query($link,
3911 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3912 FROM ttrss_labels2, ttrss_user_labels2
3914 AND article_id = '$id'
3915 AND owner_uid = ".$_SESSION["uid"] . "
3918 while ($line = db_fetch_assoc($result)) {
3919 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3921 array_push($rv, $rk);
3925 label_update_cache($link, $id, $rv);
3927 label_update_cache($link, $id, array("no-labels" => 1));
3933 function label_find_caption($link, $label, $owner_uid) {
3934 $result = db_query($link,
3935 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3936 AND owner_uid = '$owner_uid' LIMIT 1");
3938 if (db_num_rows($result) == 1) {
3939 return db_fetch_result($result, 0, "caption");
3945 function label_update_cache($link, $id, $labels = false, $force = false) {
3948 label_clear_cache($link, $id);
3951 $labels = get_article_labels($link, $id);
3953 $labels = db_escape_string(json_encode($labels));
3955 db_query($link, "UPDATE ttrss_user_entries SET
3956 label_cache = '$labels' WHERE ref_id = '$id'");
3960 function label_clear_cache($link, $id) {
3962 db_query($link, "UPDATE ttrss_user_entries SET
3963 label_cache = '' WHERE ref_id = '$id'");
3967 function label_remove_article($link, $id, $label, $owner_uid) {
3969 $label_id = label_find_id($link, $label, $owner_uid);
3971 if (!$label_id) return;
3973 $result = db_query($link,
3974 "DELETE FROM ttrss_user_labels2
3976 label_id = '$label_id' AND
3977 article_id = '$id'");
3979 label_clear_cache($link, $id);
3982 function label_add_article($link, $id, $label, $owner_uid) {
3984 $label_id = label_find_id($link, $label, $owner_uid);
3986 if (!$label_id) return;
3988 $result = db_query($link,
3990 article_id FROM ttrss_labels2, ttrss_user_labels2
3993 label_id = '$label_id' AND
3994 article_id = '$id' AND owner_uid = '$owner_uid'
3997 if (db_num_rows($result) == 0) {
3998 db_query($link, "INSERT INTO ttrss_user_labels2
3999 (label_id, article_id) VALUES ('$label_id', '$id')");
4002 label_clear_cache($link, $id);
4006 function label_remove($link, $id, $owner_uid) {
4007 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4009 db_query($link, "BEGIN");
4011 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4014 $caption = db_fetch_result($result, 0, "caption");
4016 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
4017 AND owner_uid = " . $owner_uid);
4019 if (db_affected_rows($link, $result) != 0 && $caption) {
4021 /* Remove access key for the label */
4023 $ext_id = -11 - $id;
4025 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4026 feed_id = '$ext_id' AND owner_uid = $owner_uid");
4028 /* Disable filters that reference label being removed */
4030 db_query($link, "UPDATE ttrss_filters SET
4031 enabled = false WHERE action_param = '$caption'
4033 AND owner_uid = " . $owner_uid);
4035 /* Remove cached data */
4037 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
4038 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
4042 db_query($link, "COMMIT");
4045 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
4047 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
4049 db_query($link, "BEGIN");
4053 $result = db_query($link, "SELECT id FROM ttrss_labels2
4054 WHERE caption = '$caption' AND owner_uid = $owner_uid");
4056 if (db_num_rows($result) == 0) {
4057 $result = db_query($link,
4058 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
4059 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
4061 $result = db_affected_rows($link, $result) != 0;
4064 db_query($link, "COMMIT");
4069 function format_tags_string($tags, $id) {
4072 $tags_nolinks_str = "";
4078 $formatted_tags = array();
4080 foreach ($tags as $tag) {
4082 $tag_escaped = str_replace("'", "\\'", $tag);
4084 if (mb_strlen($tag) > 30) {
4085 $tag = truncate_string($tag, 30);
4088 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4090 array_push($formatted_tags, $tag_str);
4092 $tmp_tags_str = implode(", ", $formatted_tags);
4094 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4099 $tags_str = implode(", ", $formatted_tags);
4101 if ($num_tags < count($tags)) {
4102 $tags_str .= ", …";
4105 if ($num_tags == 0) {
4106 $tags_str = __("no tags");
4113 function format_article_labels($labels, $id) {
4117 foreach ($labels as $l) {
4118 $labels_str .= sprintf("<span class='hlLabelRef'
4119 style='color : %s; background-color : %s'>%s</span>",
4120 $l[2], $l[3], $l[1]);
4127 function format_article_note($id, $note) {
4129 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4130 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4131 __('(edit note)')."</div>$note</div>";
4136 function toggle_collapse_cat($link, $cat_id, $mode) {
4138 $mode = bool_to_sql_bool($mode);
4140 db_query($link, "UPDATE ttrss_feed_categories SET
4141 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4148 $pref_name = '_COLLAPSED_SPECIAL';
4151 $pref_name = '_COLLAPSED_LABELS';
4154 $pref_name = '_COLLAPSED_UNCAT';
4160 set_pref($link, $pref_name, 'true');
4162 set_pref($link, $pref_name, 'false');
4168 function remove_feed($link, $id, $owner_uid) {
4172 /* save starred articles in Archived feed */
4174 db_query($link, "BEGIN");
4176 /* prepare feed if necessary */
4178 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4181 if (db_num_rows($result) == 0) {
4182 db_query($link, "INSERT INTO ttrss_archived_feeds
4183 (id, owner_uid, title, feed_url, site_url)
4184 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4188 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4189 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4190 marked = true AND owner_uid = $owner_uid");
4192 /* Remove access key for the feed */
4194 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4195 feed_id = '$id' AND owner_uid = $owner_uid");
4197 /* remove the feed */
4199 db_query($link, "DELETE FROM ttrss_feeds
4200 WHERE id = '$id' AND owner_uid = $owner_uid");
4202 db_query($link, "COMMIT");
4204 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4205 unlink(ICONS_DIR
. "/$id.ico");
4208 ccache_remove($link, $id, $owner_uid);
4211 label_remove($link, -11-$id, $owner_uid);
4212 ccache_remove($link, -11-$id, $owner_uid);
4216 function add_feed_category($link, $feed_cat) {
4218 if (!$feed_cat) return false;
4220 db_query($link, "BEGIN");
4222 $result = db_query($link,
4223 "SELECT id FROM ttrss_feed_categories
4224 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4226 if (db_num_rows($result) == 0) {
4228 $result = db_query($link,
4229 "INSERT INTO ttrss_feed_categories (owner_uid,title)
4230 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
4232 db_query($link, "COMMIT");
4240 function remove_feed_category($link, $id, $owner_uid) {
4242 db_query($link, "DELETE FROM ttrss_feed_categories
4243 WHERE id = '$id' AND owner_uid = $owner_uid");
4245 ccache_remove($link, $id, $owner_uid, true);
4248 function archive_article($link, $id, $owner_uid) {
4249 db_query($link, "BEGIN");
4251 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4252 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4254 if (db_num_rows($result) != 0) {
4256 /* prepare the archived table */
4258 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4261 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4262 WHERE id = '$feed_id'");
4264 if (db_num_rows($result) == 0) {
4265 db_query($link, "INSERT INTO ttrss_archived_feeds
4266 (id, owner_uid, title, feed_url, site_url)
4267 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4268 WHERE id = '$feed_id'");
4271 db_query($link, "UPDATE ttrss_user_entries
4272 SET orig_feed_id = feed_id, feed_id = NULL
4273 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4277 db_query($link, "COMMIT");
4280 function getArticleFeed($link, $id) {
4281 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4282 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4284 if (db_num_rows($result) != 0) {
4285 return db_fetch_result($result, 0, "feed_id");
4292 * Fixes incomplete URLs by prepending "http://".
4293 * Also replaces feed:// with http://, and
4294 * prepends a trailing slash if the url is a domain name only.
4296 * @param string $url Possibly incomplete URL
4298 * @return string Fixed URL.
4300 function fix_url($url) {
4301 if (strpos($url, '://') === false) {
4302 $url = 'http://' . $url;
4303 } else if (substr($url, 0, 5) == 'feed:') {
4304 $url = 'http:' . substr($url, 5);
4307 //prepend slash if the URL has no slash in it
4308 // "http://www.example" -> "http://www.example/"
4309 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4313 if ($url != "http:///")
4319 function validate_feed_url($url) {
4320 $parts = parse_url($url);
4322 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4326 function get_article_enclosures($link, $id) {
4328 $query = "SELECT * FROM ttrss_enclosures
4329 WHERE post_id = '$id' AND content_url != ''";
4333 $result = db_query($link, $query);
4335 if (db_num_rows($result) > 0) {
4336 while ($line = db_fetch_assoc($result)) {
4337 array_push($rv, $line);
4344 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
4350 if ($cat_id == -4 ||
$cat_id == -2) {
4351 $counters = getLabelCounters($link, true);
4353 foreach (array_values($counters) as $cv) {
4355 $unread = $cv["counter"];
4357 if ($unread ||
!$unread_only) {
4361 "title" => $cv["description"],
4362 "unread" => $cv["counter"],
4366 array_push($feeds, $row);
4373 if ($cat_id == -4 ||
$cat_id == -1) {
4374 foreach (array(-1, -2, -3, -4, 0) as $i) {
4375 $unread = getFeedUnread($link, $i);
4377 if ($unread ||
!$unread_only) {
4378 $title = getFeedTitle($link, $i);
4383 "unread" => $unread,
4386 array_push($feeds, $row);
4395 $limit_qpart = "LIMIT $limit OFFSET $offset";
4400 if ($cat_id == -4 ||
$cat_id == -3) {
4401 $result = db_query($link, "SELECT
4402 id, feed_url, cat_id, title, order_id, ".
4403 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4404 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4405 " ORDER BY cat_id, title " . $limit_qpart);
4409 $cat_qpart = "cat_id = '$cat_id'";
4411 $cat_qpart = "cat_id IS NULL";
4413 $result = db_query($link, "SELECT
4414 id, feed_url, cat_id, title, order_id, ".
4415 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4416 FROM ttrss_feeds WHERE
4417 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4418 " ORDER BY cat_id, title " . $limit_qpart);
4421 while ($line = db_fetch_assoc($result)) {
4423 $unread = getFeedUnread($link, $line["id"]);
4425 $has_icon = feed_has_icon($line['id']);
4427 if ($unread ||
!$unread_only) {
4430 "feed_url" => $line["feed_url"],
4431 "title" => $line["title"],
4432 "id" => (int)$line["id"],
4433 "unread" => (int)$unread,
4434 "has_icon" => $has_icon,
4435 "cat_id" => (int)$line["cat_id"],
4436 "last_updated" => strtotime($line["last_updated"]),
4437 "order_id" => (int) $line["order_id"],
4440 array_push($feeds, $row);
4447 function api_get_headlines($link, $feed_id, $limit, $offset,
4448 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4449 $include_attachments, $since_id,
4450 $search = "", $search_mode = "", $match_on = "") {
4452 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4453 $view_mode, $is_cat, $search, $search_mode, $match_on,
4454 $order, $offset, 0, false, $since_id);
4456 $result = $qfh_ret[0];
4457 $feed_title = $qfh_ret[1];
4459 $headlines = array();
4461 while ($line = db_fetch_assoc($result)) {
4462 $is_updated = ($line["last_read"] == "" &&
4463 ($line["unread"] != "t" && $line["unread"] != "1"));
4465 $tags = explode(",", $line["tag_cache"]);
4466 $labels = json_decode($line["label_cache"], true);
4468 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4469 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4471 $headline_row = array(
4472 "id" => (int)$line["id"],
4473 "unread" => sql_bool_to_bool($line["unread"]),
4474 "marked" => sql_bool_to_bool($line["marked"]),
4475 "published" => sql_bool_to_bool($line["published"]),
4476 "updated" => strtotime($line["updated"]),
4477 "is_updated" => $is_updated,
4478 "title" => $line["title"],
4479 "link" => $line["link"],
4480 "feed_id" => $line["feed_id"],
4484 if ($include_attachments)
4485 $headline_row['attachments'] = get_article_enclosures($link,
4488 if ($show_excerpt) {
4489 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4490 $headline_row["excerpt"] = $excerpt;
4493 if ($show_content) {
4494 $headline_row["content"] = $line["content_preview"];
4497 // unify label output to ease parsing
4498 if ($labels["no-labels"] == 1) $labels = array();
4500 $headline_row["labels"] = $labels;
4502 $headline_row["feed_title"] = $line["feed_title"];
4504 array_push($headlines, $headline_row);
4510 function generate_error_feed($link, $error) {
4513 $reply['headlines']['id'] = -6;
4514 $reply['headlines']['is_cat'] = false;
4516 $reply['headlines']['toolbar'] = '';
4517 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4519 $reply['headlines-info'] = array("count" => 0,
4520 "vgroup_last_feed" => '',
4522 "disable_cache" => true);
4528 function generate_dashboard_feed($link) {
4531 $reply['headlines']['id'] = -5;
4532 $reply['headlines']['is_cat'] = false;
4534 $reply['headlines']['toolbar'] = '';
4535 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4537 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4539 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4540 WHERE owner_uid = " . $_SESSION['uid']);
4542 $last_updated = db_fetch_result($result, 0, "last_updated");
4543 $last_updated = make_local_datetime($link, $last_updated, false);
4545 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4547 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4548 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4550 $num_errors = db_fetch_result($result, 0, "num_errors");
4552 if ($num_errors > 0) {
4553 $reply['headlines']['content'] .= "<br/>";
4554 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4555 __('Some feeds have update errors (click for details)')."</a>";
4557 $reply['headlines']['content'] .= "</span></p>";
4559 $reply['headlines-info'] = array("count" => 0,
4560 "vgroup_last_feed" => '',
4562 "disable_cache" => true);
4567 function save_email_address($link, $email) {
4568 // FIXME: implement persistent storage of emails
4570 if (!$_SESSION['stored_emails'])
4571 $_SESSION['stored_emails'] = array();
4573 if (!in_array($email, $_SESSION['stored_emails']))
4574 array_push($_SESSION['stored_emails'], $email);
4577 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4578 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4580 $sql_is_cat = bool_to_sql_bool($is_cat);
4582 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4583 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4584 AND owner_uid = " . $owner_uid);
4586 if (db_num_rows($result) == 1) {
4587 $key = db_escape_string(sha1(uniqid(rand(), true)));
4589 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4590 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4591 AND owner_uid = " . $owner_uid);
4596 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4600 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4602 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4604 $sql_is_cat = bool_to_sql_bool($is_cat);
4606 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4607 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4608 AND owner_uid = " . $owner_uid);
4610 if (db_num_rows($result) == 1) {
4611 return db_fetch_result($result, 0, "access_key");
4613 $key = db_escape_string(sha1(uniqid(rand(), true)));
4615 $result = db_query($link, "INSERT INTO ttrss_access_keys
4616 (access_key, feed_id, is_cat, owner_uid)
4617 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4625 * Extracts RSS/Atom feed URLs from the given HTML URL.
4627 * @param string $url HTML page URL
4629 * @return array Array of feeds. Key is the full URL, value the title
4631 function get_feeds_from_html($url, $login = false, $pass = false)
4633 $url = fix_url($url);
4634 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4636 libxml_use_internal_errors(true);
4638 $content = @fetch_file_contents
($url, false, $login, $pass);
4640 $doc = new DOMDocument();
4641 $doc->loadHTML($content);
4642 $xpath = new DOMXPath($doc);
4643 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4644 $feedUrls = array();
4645 foreach ($entries as $entry) {
4646 if ($entry->hasAttribute('href')) {
4647 $title = $entry->getAttribute('title');
4649 $title = $entry->getAttribute('type');
4651 $feedUrl = rewrite_relative_url(
4652 $baseUrl, $entry->getAttribute('href')
4654 $feedUrls[$feedUrl] = $title;
4661 * Checks if the content behind the given URL is a HTML file
4663 * @param string $url URL to check
4665 * @return boolean True if the URL contains HTML content
4667 function url_is_html($url, $login = false, $pass = false) {
4668 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
4670 if (stripos($content, '<html>') === false
4671 && stripos($content, '<html ') === false
4679 function print_label_select($link, $name, $value, $attributes = "") {
4681 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4682 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4684 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4685 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4687 while ($line = db_fetch_assoc($result)) {
4689 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4691 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4692 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4696 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4703 function format_article_enclosures($link, $id, $always_display_enclosures,
4706 $result = get_article_enclosures($link, $id);
4709 if (count($result) > 0) {
4711 $entries_html = array();
4714 foreach ($result as $line) {
4716 $url = $line["content_url"];
4717 $ctype = $line["content_type"];
4719 if (!$ctype) $ctype = __("unknown type");
4721 $filename = substr($url, strrpos($url, "/")+
1);
4723 # $player = format_inline_player($link, $url, $ctype);
4725 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4726 # $filename . " (" . $ctype . ")" . "</a>";
4728 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4729 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4731 array_push($entries_html, $entry);
4735 $entry["type"] = $ctype;
4736 $entry["filename"] = $filename;
4737 $entry["url"] = $url;
4739 array_push($entries, $entry);
4742 if (!get_pref($link, "STRIP_IMAGES")) {
4743 if ($always_display_enclosures ||
4744 !preg_match("/<img/i", $article_content)) {
4746 foreach ($entries as $entry) {
4748 if (preg_match("/image/", $entry["type"]) ||
4749 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4752 alt=\"".htmlspecialchars($entry["filename"])."\"
4753 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4760 $rv .= "<div dojoType=\"dijit.form.DropDownButton\">".
4761 "<span>" . __('Attachments')."</span>";
4762 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4764 foreach ($entries_html as $entry) { $rv .= $entry; };
4766 $rv .= "</div></div>";
4772 function getLastArticleId($link) {
4773 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4774 WHERE owner_uid = " . $_SESSION["uid"]);
4776 if (db_num_rows($result) == 1) {
4777 return db_fetch_result($result, 0, "id");
4783 function build_url($parts) {
4784 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4788 * Converts a (possibly) relative URL to a absolute one.
4790 * @param string $url Base URL (i.e. from where the document is)
4791 * @param string $rel_url Possibly relative URL in the document
4793 * @return string Absolute URL
4795 function rewrite_relative_url($url, $rel_url) {
4796 if (strpos($rel_url, "magnet:") === 0) {
4798 } else if (strpos($rel_url, "://") !== false) {
4800 } else if (strpos($rel_url, "/") === 0)
4802 $parts = parse_url($url);
4803 $parts['path'] = $rel_url;
4805 return build_url($parts);
4808 $parts = parse_url($url);
4809 if (!isset($parts['path'])) {
4810 $parts['path'] = '/';
4812 $dir = $parts['path'];
4813 if (substr($dir, -1) !== '/') {
4814 $dir = dirname($parts['path']);
4815 $dir !== '/' && $dir .= '/';
4817 $parts['path'] = $dir . $rel_url;
4819 return build_url($parts);
4823 function sphinx_search($query, $offset = 0, $limit = 30) {
4824 require_once 'lib/sphinxapi.php';
4826 $sphinxClient = new SphinxClient();
4828 $sphinxClient->SetServer('localhost', 9312);
4829 $sphinxClient->SetConnectTimeout(1);
4831 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4832 'feed_title' => 20));
4834 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4835 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4836 $sphinxClient->SetLimits($offset, $limit, 1000);
4837 $sphinxClient->SetArrayResult(false);
4838 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4840 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4844 if (is_array($result['matches'])) {
4845 foreach (array_keys($result['matches']) as $int_id) {
4846 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4847 array_push($ids, $ref_id);
4854 function cleanup_tags($link, $days = 14, $limit = 1000) {
4856 if (DB_TYPE
== "pgsql") {
4857 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4858 } else if (DB_TYPE
== "mysql") {
4859 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4864 while ($limit > 0) {
4867 $query = "SELECT ttrss_tags.id AS id
4868 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4869 WHERE post_int_id = int_id AND $interval_query AND
4870 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4872 $result = db_query($link, $query);
4876 while ($line = db_fetch_assoc($result)) {
4877 array_push($ids, $line['id']);
4880 if (count($ids) > 0) {
4881 $ids = join(",", $ids);
4884 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4885 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4890 $limit -= $limit_part;
4895 return $tags_deleted;
4898 function print_user_stylesheet($link) {
4899 $value = get_pref($link, 'USER_STYLESHEET');
4902 print "<style type=\"text/css\">";
4903 print str_replace("<br/>", "\n", $value);
4909 /* function rewrite_urls($line) {
4914 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4915 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4920 function rewrite_urls($html) {
4921 libxml_use_internal_errors(true);
4923 $charset_hack = '<head>
4924 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4927 $doc = new DOMDocument();
4928 $doc->loadHTML($charset_hack . $html);
4929 $xpath = new DOMXPath($doc);
4931 $entries = $xpath->query('//*/text()');
4933 foreach ($entries as $entry) {
4934 if (strstr($entry->wholeText
, "://") !== false) {
4935 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4936 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4938 if ($text != $entry->wholeText
) {
4939 $cdoc = new DOMDocument();
4940 $cdoc->loadHTML($charset_hack . $text);
4943 foreach ($cdoc->childNodes
as $cnode) {
4944 $cnode = $doc->importNode($cnode, true);
4947 $entry->parentNode
->insertBefore($cnode);
4951 $entry->parentNode
->removeChild($entry);
4957 $node = $doc->getElementsByTagName('body')->item(0);
4959 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4961 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4966 function filter_to_sql($filter) {
4969 $regexp_valid = preg_match('/' . $filter['reg_exp'] . '/',
4970 $filter['reg_exp']) !== FALSE;
4972 if ($regexp_valid) {
4974 if (DB_TYPE
== "pgsql")
4977 $reg_qpart = "REGEXP";
4979 switch ($filter["type"]) {
4981 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4982 $filter['reg_exp'] . "')";
4985 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4986 $filter['reg_exp'] . "')";
4989 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4990 $filter['reg_exp'] . "') OR LOWER(" .
4991 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
4994 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4995 $filter['reg_exp'] . "')";
4998 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4999 $filter['reg_exp'] . "')";
5003 if ($filter["filter_param"] == "before")
5008 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
5009 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
5012 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
5013 $filter['reg_exp'] . "')";
5017 if ($filter["inverse"])
5018 $query = "NOT ($query)";
5021 if (DB_TYPE
== "pgsql") {
5022 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
5024 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
5036 // -1 - never connected
5037 // 0 - no data received
5038 // 1 - data received successfully
5039 // 2 - did not receive valid data
5040 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5042 function get_linked_feeds($link, $instance_id = false) {
5044 $instance_qpart = "id = '$instance_id' AND ";
5046 $instance_qpart = "";
5048 if (DB_TYPE
== "pgsql") {
5049 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5051 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5054 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5055 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5057 while ($line = db_fetch_assoc($result)) {
5060 _debug("Updating: " . $line['access_url'] . " ($id)");
5062 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5063 $post_query = 'key=' . $line['access_key'];
5065 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5067 // try doing it the old way
5069 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5070 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5074 $feeds = json_decode($feeds, true);
5077 if ($feeds['error']) {
5078 $status = $feeds['error']['code'] +
10;
5082 if (count($feeds['feeds']) > 0) {
5084 db_query($link, "DELETE FROM ttrss_linked_feeds
5085 WHERE instance_id = '$id'");
5087 foreach ($feeds['feeds'] as $feed) {
5088 $feed_url = db_escape_string($feed['feed_url']);
5089 $title = db_escape_string($feed['title']);
5090 $subscribers = db_escape_string($feed['subscribers']);
5091 $site_url = db_escape_string($feed['site_url']);
5093 db_query($link, "INSERT INTO ttrss_linked_feeds
5094 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5096 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5099 // received 0 feeds, this might indicate that
5100 // the instance on the other hand is rebuilding feedbrowser cache
5101 // we will try again later
5103 // TODO: maybe perform expiration based on updated here?
5106 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5116 _debug("Status: $status");
5118 db_query($link, "UPDATE ttrss_linked_instances SET
5119 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5124 function make_feed_browser($link, $search, $limit, $mode = 1) {
5126 $owner_uid = $_SESSION["uid"];
5130 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5131 UPPER(title) LIKE UPPER('%$search%'))";
5137 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5138 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5139 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5140 AND owner_uid = '$owner_uid') $search_qpart
5141 ORDER BY subscribers DESC LIMIT $limit"); */
5143 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5144 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5145 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5147 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5148 WHERE tf.feed_url = qqq.feed_url
5149 AND owner_uid = '$owner_uid') $search_qpart
5150 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5152 } else if ($mode == 2) {
5153 $result = db_query($link, "SELECT *,
5154 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5155 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5157 ttrss_archived_feeds
5159 (SELECT COUNT(*) FROM ttrss_feeds
5160 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5161 owner_uid = '$owner_uid') = 0 AND
5162 owner_uid = '$owner_uid' $search_qpart
5163 ORDER BY id DESC LIMIT $limit");
5168 while ($line = db_fetch_assoc($result)) {
5172 $feed_url = htmlspecialchars($line["feed_url"]);
5173 $site_url = htmlspecialchars($line["site_url"]);
5174 $subscribers = $line["subscribers"];
5176 $check_box = "<input onclick='toggleSelectListRow2(this)'
5177 dojoType=\"dijit.form.CheckBox\"
5178 type=\"checkbox\" \">";
5180 $class = ($feedctr %
2) ?
"even" : "odd";
5182 $site_url = "<a target=\"_blank\"
5184 <span class=\"fb_feedTitle\">".
5185 htmlspecialchars($line["title"])."</span></a>";
5187 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5188 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5189 style='vertical-align : middle'></a>";
5191 $rv .= "<li>$check_box $feed_url $site_url".
5192 " <span class='subscribers'>($subscribers)</span></li>";
5194 } else if ($mode == 2) {
5195 $feed_url = htmlspecialchars($line["feed_url"]);
5196 $site_url = htmlspecialchars($line["site_url"]);
5197 $title = htmlspecialchars($line["title"]);
5199 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5200 type=\"checkbox\">";
5202 $class = ($feedctr %
2) ?
"even" : "odd";
5204 if ($line['articles_archived'] > 0) {
5205 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5206 $archived = " <span class='subscribers'>($archived)</span>";
5211 $site_url = "<a target=\"_blank\"
5213 <span class=\"fb_feedTitle\">".
5214 htmlspecialchars($line["title"])."</span></a>";
5216 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5217 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5218 style='vertical-align : middle'></a>";
5221 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5222 "$check_box $feed_url $site_url $archived</li>";
5228 if ($feedctr == 0) {
5229 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5235 if (!function_exists('gzdecode')) {
5236 function gzdecode($string) { // no support for 2nd argument
5237 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5238 base64_encode($string));
5242 function perform_data_import($link, $filename, $owner_uid) {
5246 $num_feeds_created = 0;
5248 $doc = @DOMDocument
::load($filename);
5251 $contents = file_get_contents($filename);
5254 $data = @gzuncompress
($contents);
5258 $data = @gzdecode
($contents);
5262 $doc = DOMDocument
::loadXML($data);
5267 $xpath = new DOMXpath($doc);
5269 $container = $doc->firstChild
;
5271 if ($container && $container->hasAttribute('schema-version')) {
5272 $schema_version = $container->getAttribute('schema-version');
5274 if ($schema_version != SCHEMA_VERSION
) {
5275 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5280 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5284 $articles = $xpath->query("//article");
5286 foreach ($articles as $article_node) {
5287 if ($article_node->childNodes
) {
5293 foreach ($article_node->childNodes
as $child) {
5294 if ($child->nodeName
!= 'label_cache')
5295 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5297 $article[$child->nodeName
] = $child->nodeValue
;
5300 //print_r($article);
5302 if ($article['guid']) {
5306 //db_query($link, "BEGIN");
5308 //print 'GUID:' . $article['guid'] . "\n";
5310 $result = db_query($link, "SELECT id FROM ttrss_entries
5311 WHERE guid = '".$article['guid']."'");
5313 if (db_num_rows($result) == 0) {
5315 $result = db_query($link,
5316 "INSERT INTO ttrss_entries
5330 ('".$article['title']."',
5331 '".$article['guid']."',
5332 '".$article['link']."',
5333 '".$article['updated']."',
5334 '".$article['content']."',
5335 '".sha1($article['content'])."',
5343 $result = db_query($link, "SELECT id FROM ttrss_entries
5344 WHERE guid = '".$article['guid']."'");
5346 if (db_num_rows($result) != 0) {
5347 $ref_id = db_fetch_result($result, 0, "id");
5351 $ref_id = db_fetch_result($result, 0, "id");
5354 //print "Got ref ID: $ref_id\n";
5358 $feed_url = $article['feed_url'];
5359 $feed_title = $article['feed_title'];
5363 if ($feed_url && $feed_title) {
5364 $result = db_query($link, "SELECT id FROM ttrss_feeds
5365 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5367 if (db_num_rows($result) != 0) {
5368 $feed = db_fetch_result($result, 0, "id");
5370 // try autocreating feed in Uncategorized...
5372 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5373 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5375 $result = db_query($link, "SELECT id FROM ttrss_feeds
5376 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5378 if (db_num_rows($result) != 0) {
5379 ++
$num_feeds_created;
5381 $feed = db_fetch_result($result, 0, "id");
5386 if ($feed != 'NULL')
5387 $feed_qpart = "feed_id = $feed";
5389 $feed_qpart = "feed_id IS NULL";
5391 //print "$ref_id / $feed / " . $article['title'] . "\n";
5393 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5394 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5396 if (db_num_rows($result) == 0) {
5398 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5399 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5400 $score = (int) $article['score'];
5402 $tag_cache = $article['tag_cache'];
5403 $label_cache = db_escape_string($article['label_cache']);
5404 $note = $article['note'];
5406 //print "Importing " . $article['title'] . "<br/>";
5410 $result = db_query($link,
5411 "INSERT INTO ttrss_user_entries
5412 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5413 published, score, tag_cache, label_cache, uuid, note)
5414 VALUES ($ref_id, $owner_uid, $feed, false,
5415 NULL, $marked, $published, $score, '$tag_cache',
5416 '$label_cache', '', '$note')");
5418 $label_cache = json_decode($label_cache, true);
5420 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5421 foreach ($label_cache as $label) {
5423 label_create($link, $label[1],
5424 $label[2], $label[3], $owner_uid);
5426 label_add_article($link, $ref_id, $label[1], $owner_uid);
5431 //db_query($link, "COMMIT");
5439 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5440 $num_processed, $num_imported, $num_feeds_created) .
5445 print "<p>" . __("Could not load XML document.") . "</p>";
5450 function get_random_bytes($length) {
5451 if (function_exists('openssl_random_pseudo_bytes')) {
5452 return openssl_random_pseudo_bytes($length);
5456 for ($i = 0; $i < $length; $i++
)
5457 $output .= chr(mt_rand(0, 255));