2 define('EXPECTED_CONFIG_VERSION', 25);
3 define('SCHEMA_VERSION', 94);
5 function __autoload($class) {
6 $class_file = str_replace("_", "/", strtolower(basename($class)));
8 $file = dirname(__FILE__
)."/../classes/$class_file.php";
10 if (file_exists($file)) {
15 mb_internal_encoding("UTF-8");
16 date_default_timezone_set('UTC');
17 if (defined('E_DEPRECATED')) {
18 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
20 error_reporting(E_ALL
& ~E_NOTICE
);
23 require_once 'config.php';
25 if (DB_TYPE
== "pgsql") {
26 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
28 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
31 define('THEME_VERSION_REQUIRED', 1.1);
34 * Return available translations names.
37 * @return array A array of available translations.
39 function get_translations() {
41 "auto" => "Detect automatically",
46 "fr_FR" => "Français",
47 "hu_HU" => "Magyar (Hungarian)",
48 "it_IT" => "Italiano",
49 "ja_JP" => "日本語 (Japanese)",
50 "nb_NO" => "Norwegian bokmål",
52 "pt_BR" => "Portuguese/Brazil",
53 "zh_CN" => "Simplified Chinese");
58 require_once "lib/accept-to-gettext.php";
59 require_once "lib/gettext/gettext.inc";
61 function startup_gettext() {
63 # Get locale from Accept-Language header
64 $lang = al2gt(array_keys(get_translations()), "text/html");
66 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
67 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
70 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
71 $lang = $_COOKIE["ttrss_lang"];
74 /* In login action of mobile version */
75 if ($_POST["language"] && defined('MOBILE_VERSION')) {
76 $lang = $_POST["language"];
77 $_COOKIE["ttrss_lang"] = $lang;
81 if (defined('LC_MESSAGES')) {
82 _setlocale(LC_MESSAGES
, $lang);
83 } else if (defined('LC_ALL')) {
84 _setlocale(LC_ALL
, $lang);
87 if (defined('MOBILE_VERSION')) {
88 _bindtextdomain("messages", "../locale");
90 _bindtextdomain("messages", "locale");
93 _textdomain("messages");
94 _bind_textdomain_codeset("messages", "UTF-8");
100 require_once 'db-prefs.php';
101 require_once 'version.php';
103 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
105 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
106 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
108 ini_set('user_agent', SELF_USER_AGENT
);
110 require_once 'lib/pubsubhubbub/publisher.php';
115 $utc_tz = new DateTimeZone('UTC');
116 $schema_version = false;
119 * Print a timestamped debug message.
121 * @param string $msg The debug message.
124 function _debug($msg) {
125 if (defined('QUIET') && QUIET
) {
128 $ts = strftime("%H:%M:%S", time());
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
132 print "[$ts] $msg\n";
136 * Purge a feed old posts.
138 * @param mixed $link A database connection.
139 * @param mixed $feed_id The id of the purged feed.
140 * @param mixed $purge_interval Olderness of purged posts.
141 * @param boolean $debug Set to True to enable the debug. False by default.
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
151 $result = db_query($link,
152 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
156 if (db_num_rows($result) == 1) {
157 $owner_uid = db_fetch_result($result, 0, "owner_uid");
160 if ($purge_interval == -1 ||
!$purge_interval) {
162 ccache_update($link, $feed_id, $owner_uid);
167 if (!$owner_uid) return;
169 if (FORCE_ARTICLE_PURGE
== 0) {
170 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
173 $purge_unread = true;
174 $purge_interval = FORCE_ARTICLE_PURGE
;
177 if (!$purge_unread) $query_limit = " unread = false AND ";
179 if (DB_TYPE
== "pgsql") {
180 $pg_version = get_pgsql_version($link);
182 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
184 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
185 ttrss_entries.id = ref_id AND
187 feed_id = '$feed_id' AND
189 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
193 $result = db_query($link, "DELETE FROM ttrss_user_entries
195 WHERE ttrss_entries.id = ref_id AND
197 feed_id = '$feed_id' AND
199 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
202 $rows = pg_affected_rows($result);
206 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
207 marked = false AND feed_id = '$feed_id' AND
208 (SELECT date_updated FROM ttrss_entries WHERE
209 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
211 $result = db_query($link, "DELETE FROM ttrss_user_entries
212 USING ttrss_user_entries, ttrss_entries
213 WHERE ttrss_entries.id = ref_id AND
215 feed_id = '$feed_id' AND
217 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
219 $rows = mysql_affected_rows($link);
223 ccache_update($link, $feed_id, $owner_uid);
226 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
228 } // function purge_feed
230 function feed_purge_interval($link, $feed_id) {
232 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
233 WHERE id = '$feed_id'");
235 if (db_num_rows($result) == 1) {
236 $purge_interval = db_fetch_result($result, 0, "purge_interval");
237 $owner_uid = db_fetch_result($result, 0, "owner_uid");
239 if ($purge_interval == 0) $purge_interval = get_pref($link,
240 'PURGE_OLD_DAYS', $owner_uid);
242 return $purge_interval;
249 function purge_orphans($link, $do_output = false) {
251 // purge orphaned posts in main content table
252 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
253 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
256 $rows = db_affected_rows($link, $result);
257 _debug("Purged $rows orphaned posts.");
261 function get_feed_update_interval($link, $feed_id) {
262 $result = db_query($link, "SELECT owner_uid, update_interval FROM
263 ttrss_feeds WHERE id = '$feed_id'");
265 if (db_num_rows($result) == 1) {
266 $update_interval = db_fetch_result($result, 0, "update_interval");
267 $owner_uid = db_fetch_result($result, 0, "owner_uid");
269 if ($update_interval != 0) {
270 return $update_interval;
272 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
280 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
281 $login = urlencode($login);
282 $pass = urlencode($pass);
284 if (function_exists('curl_init') && !ini_get("open_basedir")) {
285 $ch = curl_init($url);
287 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
288 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
289 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
290 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
291 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
292 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
293 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
294 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
295 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
296 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
299 curl_setopt($ch, CURLOPT_POST
, true);
300 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
304 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
306 $contents = @curl_exec
($ch);
308 if ($contents === false) {
313 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
314 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
317 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
323 if ($login && $pass ){
324 $url_parts = array();
326 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
328 if ($url_parts[1] && $url_parts[2]) {
329 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
333 return @file_get_contents
($url);
339 * Try to determine the favicon URL for a feed.
340 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
341 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
343 * @param string $url A feed or page URL
345 * @return mixed The favicon URL, or false if none was found.
347 function get_favicon_url($url) {
349 $favicon_url = false;
351 if ($html = @fetch_file_contents
($url)) {
353 libxml_use_internal_errors(true);
355 $doc = new DOMDocument();
356 $doc->loadHTML($html);
357 $xpath = new DOMXPath($doc);
359 $base = $xpath->query('/html/head/base');
360 foreach ($base as $b) {
361 $url = $b->getAttribute("href");
365 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
366 if (count($entries) > 0) {
367 foreach ($entries as $entry) {
368 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
375 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
378 } // function get_favicon_url
380 function check_feed_favicon($site_url, $feed, $link) {
381 # print "FAVICON [$site_url]: $favicon_url\n";
383 $icon_file = ICONS_DIR
. "/$feed.ico";
385 if (!file_exists($icon_file)) {
386 $favicon_url = get_favicon_url($site_url);
389 // Limiting to "image" type misses those served with text/plain
390 $contents = fetch_file_contents($favicon_url); // , "image");
393 // Crude image type matching.
394 // Patterns gleaned from the file(1) source code.
395 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
396 // 0 string \000\000\001\000 MS Windows icon resource
397 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
399 elseif (preg_match('/^GIF8/', $contents)) {
400 // 0 string GIF8 GIF image data
401 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
403 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
404 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
405 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
407 elseif (preg_match('/^\xff\xd8/', $contents)) {
408 // 0 beshort 0xffd8 JPEG image data
409 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
412 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
418 $fp = @fopen
($icon_file, "w");
421 fwrite($fp, $contents);
423 chmod($icon_file, 0644);
430 function print_select($id, $default, $values, $attributes = "") {
431 print "<select name=\"$id\" id=\"$id\" $attributes>";
432 foreach ($values as $v) {
434 $sel = "selected=\"1\"";
438 print "<option value=\"$v\" $sel>$v</option>";
443 function print_select_hash($id, $default, $values, $attributes = "") {
444 print "<select name=\"$id\" id='$id' $attributes>";
445 foreach (array_keys($values) as $v) {
447 $sel = 'selected="selected"';
451 print "<option $sel value=\"$v\">".$values[$v]."</option>";
457 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
460 if ($filters["title"]) {
461 foreach ($filters["title"] as $filter) {
462 $reg_exp = $filter["reg_exp"];
463 $inverse = $filter["inverse"];
464 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
465 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
467 array_push($matches, array($filter["action"], $filter["action_param"]));
472 if ($filters["content"]) {
473 foreach ($filters["content"] as $filter) {
474 $reg_exp = $filter["reg_exp"];
475 $inverse = $filter["inverse"];
477 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
478 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
480 array_push($matches, array($filter["action"], $filter["action_param"]));
485 if ($filters["both"]) {
486 foreach ($filters["both"] as $filter) {
487 $reg_exp = $filter["reg_exp"];
488 $inverse = $filter["inverse"];
491 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
492 array_push($matches, array($filter["action"], $filter["action_param"]));
495 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
496 array_push($matches, array($filter["action"], $filter["action_param"]));
502 if ($filters["link"]) {
503 $reg_exp = $filter["reg_exp"];
504 foreach ($filters["link"] as $filter) {
505 $reg_exp = $filter["reg_exp"];
506 $inverse = $filter["inverse"];
508 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
509 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
511 array_push($matches, array($filter["action"], $filter["action_param"]));
516 if ($filters["date"]) {
517 $reg_exp = $filter["reg_exp"];
518 foreach ($filters["date"] as $filter) {
519 $date_modifier = $filter["filter_param"];
520 $inverse = $filter["inverse"];
521 $check_timestamp = strtotime($filter["reg_exp"]);
523 # no-op when timestamp doesn't parse to prevent misfires
525 if ($check_timestamp) {
528 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
529 $date_modifier == "after" && $timestamp > $check_timestamp) {
533 if ($inverse) $match_ok = !$match_ok;
536 array_push($matches, array($filter["action"], $filter["action_param"]));
542 if ($filters["author"]) {
543 foreach ($filters["author"] as $filter) {
544 $reg_exp = $filter["reg_exp"];
545 $inverse = $filter["inverse"];
546 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
547 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
549 array_push($matches, array($filter["action"], $filter["action_param"]));
554 if ($filters["tag"]) {
556 $tag_string = join(",", $tags);
558 foreach ($filters["tag"] as $filter) {
559 $reg_exp = $filter["reg_exp"];
560 $inverse = $filter["inverse"];
562 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
563 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
565 array_push($matches, array($filter["action"], $filter["action_param"]));
574 function find_article_filter($filters, $filter_name) {
575 foreach ($filters as $f) {
576 if ($f[0] == $filter_name) {
583 function calculate_article_score($filters) {
586 foreach ($filters as $f) {
587 if ($f[0] == "score") {
594 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
595 foreach ($filters as $f) {
596 if ($f[0] == "label") {
597 label_add_article($link, $id, $f[1], $owner_uid);
602 function getmicrotime() {
603 list($usec, $sec) = explode(" ",microtime());
604 return ((float)$usec +
(float)$sec);
607 function print_radio($id, $default, $true_is, $values, $attributes = "") {
608 foreach ($values as $v) {
615 if ($v == $true_is) {
616 $sel .= " value=\"1\"";
618 $sel .= " value=\"0\"";
621 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
622 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
627 function initialize_user_prefs($link, $uid, $profile = false) {
629 $uid = db_escape_string($uid);
633 $profile_qpart = "AND profile IS NULL";
635 $profile_qpart = "AND profile = '$profile'";
638 if (get_schema_version($link) < 63) $profile_qpart = "";
640 db_query($link, "BEGIN");
642 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
644 $u_result = db_query($link, "SELECT pref_name
645 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
647 $active_prefs = array();
649 while ($line = db_fetch_assoc($u_result)) {
650 array_push($active_prefs, $line["pref_name"]);
653 while ($line = db_fetch_assoc($result)) {
654 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
655 // print "adding " . $line["pref_name"] . "<br>";
657 if (get_schema_version($link) < 63) {
658 db_query($link, "INSERT INTO ttrss_user_prefs
659 (owner_uid,pref_name,value) VALUES
660 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
663 db_query($link, "INSERT INTO ttrss_user_prefs
664 (owner_uid,pref_name,value, profile) VALUES
665 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
671 db_query($link, "COMMIT");
675 function get_ssl_certificate_id() {
676 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
677 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
678 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
679 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
680 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
685 function authenticate_user($link, $login, $password, $check_only = false) {
687 if (!SINGLE_USER_MODE
) {
690 $modules = explode(",", AUTH_MODULES
);
692 foreach ($modules as $module) {
693 $module_class = "auth_$module";
694 if (class_exists($module_class)) {
695 $authenticator = new $module_class($link);
697 $user_id = (int) $authenticator->authenticate($login, $password);
700 $_SESSION["auth_module"] = $module;
705 print T_sprintf("Fatal: authentication module %s not found.", $module);
710 if ($user_id && !$check_only) {
711 $_SESSION["uid"] = $user_id;
713 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
714 WHERE id = '$user_id'");
716 $_SESSION["name"] = db_fetch_result($result, 0, "login");
717 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
718 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
720 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
723 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
724 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
726 $_SESSION["last_version_check"] = time();
728 initialize_user_prefs($link, $_SESSION["uid"]);
737 $_SESSION["uid"] = 1;
738 $_SESSION["name"] = "admin";
739 $_SESSION["access_level"] = 10;
741 $_SESSION["hide_hello"] = true;
742 $_SESSION["hide_logout"] = true;
744 $_SESSION["auth_module"] = false;
746 if (!$_SESSION["csrf_token"]) {
747 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
750 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
752 initialize_user_prefs($link, $_SESSION["uid"]);
758 function make_password($length = 8) {
761 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
765 while ($i < $length) {
766 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
768 if (!strstr($password, $char)) {
776 // this is called after user is created to initialize default feeds, labels
779 // user preferences are checked on every login, not here
781 function initialize_user($link, $uid) {
783 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
784 values ('$uid', 'Tiny Tiny RSS: New Releases',
785 'http://tt-rss.org/releases.rss')");
787 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
788 values ('$uid', 'Tiny Tiny RSS: Forum',
789 'http://tt-rss.org/forum/rss.php')");
792 function logout_user() {
794 if (isset($_COOKIE[session_name()])) {
795 setcookie(session_name(), '', time()-42000, '/');
799 function validate_csrf($csrf_token) {
800 return $csrf_token == $_SESSION['csrf_token'];
803 function validate_session($link) {
804 if (SINGLE_USER_MODE
) return true;
806 $check_ip = $_SESSION['ip_address'];
808 switch (SESSION_CHECK_ADDRESS
) {
813 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
816 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
817 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
821 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
822 $_SESSION["login_error_msg"] =
823 __("Session failed to validate (incorrect IP)");
827 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
830 if ($_SESSION["uid"]) {
832 $result = db_query($link,
833 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
835 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
837 if ($pwd_hash != $_SESSION["pwd_hash"]) {
842 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
844 //print_r($_SESSION);
846 if (time() > $_SESSION["cookie_lifetime"]) {
854 function login_sequence($link, $mobile = false) {
855 $_SESSION["prefs_cache"] = array();
857 if (!SINGLE_USER_MODE
) {
859 $login_action = $_POST["login_action"];
861 # try to authenticate user if called from login form
862 if ($login_action == "do_login") {
863 $login = db_escape_string($_POST["login"]);
864 $password = $_POST["password"];
865 $remember_me = $_POST["remember_me"];
867 if (authenticate_user($link, $login, $password)) {
868 $_POST["password"] = "";
870 $_SESSION["language"] = $_POST["language"];
871 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
872 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
874 if ($_POST["profile"]) {
876 $profile = db_escape_string($_POST["profile"]);
878 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
879 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
881 if (db_num_rows($result) != 0) {
882 $_SESSION["profile"] = $profile;
883 $_SESSION["prefs_cache"] = array();
887 if ($_REQUEST['return']) {
888 header("Location: " . $_REQUEST['return']);
890 header("Location: " . $_SERVER["REQUEST_URI"]);
897 $_SESSION["login_error_msg"] = __("Incorrect username or password");
901 if (!$_SESSION["uid"] ||
!validate_session($link)) {
903 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
904 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
906 authenticate_user($link, null, null, true);
907 render_login_form($link, $mobile);
911 /* bump login timestamp */
912 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
915 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
916 setcookie("ttrss_lang", $_SESSION["language"],
917 time() + SESSION_COOKIE_LIFETIME
);
920 // try to remove possible duplicates from feed counter cache
921 // ccache_cleanup($link, $_SESSION["uid"]);
925 return authenticate_user($link, "admin", null);
929 function truncate_string($str, $max_len, $suffix = '…') {
930 if (mb_strlen($str, "utf-8") > $max_len - 3) {
931 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
937 function theme_image($link, $filename) {
939 $theme_path = get_user_theme_path($link);
941 if ($theme_path && is_file($theme_path.$filename)) {
942 return $theme_path.$filename;
951 function get_user_theme($link) {
953 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
954 $theme_name = get_pref($link, "_THEME_ID");
955 if (is_dir("themes/$theme_name")) {
966 function get_user_theme_path($link) {
969 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
970 $theme_name = get_pref($link, "_THEME_ID");
972 if ($theme_name && is_dir("themes/$theme_name")) {
973 $theme_path = "themes/$theme_name/";
982 if (is_file("$theme_path/theme.ini")) {
983 $ini = parse_ini_file("$theme_path/theme.ini", true);
984 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
992 function get_user_theme_options($link) {
993 $t = get_user_theme_path($link);
996 if (is_file("$t/theme.ini")) {
997 $ini = parse_ini_file("$t/theme.ini", true);
998 if ($ini['theme']['version']) {
999 return $ini['theme']['options'];
1006 function print_theme_includes($link) {
1008 $t = get_user_theme_path($link);
1012 print "<link rel=\"stylesheet\" type=\"text/css\"
1013 href=\"$t/theme.css?$time \">";
1014 if (file_exists("$t/theme.js")) {
1015 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
1021 function get_all_themes() {
1022 $themes = glob("themes/*");
1028 foreach ($themes as $t) {
1029 if (is_file("$t/theme.ini")) {
1030 $ini = parse_ini_file("$t/theme.ini", true);
1031 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
1032 !$ini['theme']['disabled']) {
1034 $entry["path"] = $t;
1035 $entry["base"] = basename($t);
1036 $entry["name"] = $ini['theme']['name'];
1037 $entry["version"] = $ini['theme']['version'];
1038 $entry["author"] = $ini['theme']['author'];
1039 $entry["options"] = $ini['theme']['options'];
1040 array_push($rv, $entry);
1048 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
1051 $source_tz = new DateTimeZone($source_tz);
1052 } catch (Exception
$e) {
1053 $source_tz = new DateTimeZone('UTC');
1057 $dest_tz = new DateTimeZone($dest_tz);
1058 } catch (Exception
$e) {
1059 $dest_tz = new DateTimeZone('UTC');
1062 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
1063 return $dt->format('U') +
$dest_tz->getOffset($dt);
1066 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
1067 $no_smart_dt = false) {
1069 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1070 if (!$timestamp) $timestamp = '1970-01-01 0:00';
1075 # We store date in UTC internally
1076 $dt = new DateTime($timestamp, $utc_tz);
1078 if ($tz_offset == -1) {
1080 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
1083 $user_tz = new DateTimeZone($user_tz_string);
1084 } catch (Exception
$e) {
1088 $tz_offset = $user_tz->getOffset($dt);
1091 $user_timestamp = $dt->format('U') +
$tz_offset;
1093 if (!$no_smart_dt) {
1094 return smart_date_time($link, $user_timestamp,
1095 $tz_offset, $owner_uid);
1098 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1100 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1102 return date($format, $user_timestamp);
1106 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
1107 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1109 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
1110 return date("G:i", $timestamp);
1111 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
1112 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1113 return date($format, $timestamp);
1115 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1116 return date($format, $timestamp);
1120 function sql_bool_to_bool($s) {
1121 if ($s == "t" ||
$s == "1" ||
$s == "true") {
1128 function bool_to_sql_bool($s) {
1136 // Session caching removed due to causing wrong redirects to upgrade
1137 // script when get_schema_version() is called on an obsolete session
1138 // created on a previous schema version.
1139 function get_schema_version($link, $nocache = false) {
1140 global $schema_version;
1142 if (!$schema_version) {
1143 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1144 $version = db_fetch_result($result, 0, "schema_version");
1145 $schema_version = $version;
1148 return $schema_version;
1152 function sanity_check($link) {
1153 require_once 'errors.php';
1156 $schema_version = get_schema_version($link, true);
1158 if ($schema_version != SCHEMA_VERSION
) {
1162 if (DB_TYPE
== "mysql") {
1163 $result = db_query($link, "SELECT true", false);
1164 if (db_num_rows($result) != 1) {
1169 if (db_escape_string("testTEST") != "testTEST") {
1173 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1176 function file_is_locked($filename) {
1177 if (function_exists('flock')) {
1178 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1180 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1181 flock($fp, LOCK_UN
);
1191 return true; // consider the file always locked and skip the test
1194 function make_lockfile($filename) {
1195 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1197 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1198 if (function_exists('posix_getpid')) {
1199 fwrite($fp, posix_getpid() . "\n");
1207 function make_stampfile($filename) {
1208 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1210 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1211 fwrite($fp, time() . "\n");
1212 flock($fp, LOCK_UN
);
1220 function sql_random_function() {
1221 if (DB_TYPE
== "mysql") {
1228 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1230 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1232 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1234 $ref_check_qpart = ($max_id &&
1235 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1237 if (is_numeric($feed)) {
1243 $cat_qpart = "cat_id = '$feed'";
1245 $cat_qpart = "cat_id IS NULL";
1248 $tmp_result = db_query($link, "SELECT id
1249 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
1251 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1253 $tmp_feed = $tmp_line["id"];
1255 db_query($link, "UPDATE ttrss_user_entries
1256 SET unread = false,last_read = NOW()
1257 WHERE feed_id = '$tmp_feed'
1258 AND $ref_check_qpart
1259 AND owner_uid = $owner_uid");
1261 } else if ($feed == -2) {
1263 db_query($link, "UPDATE ttrss_user_entries
1264 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1265 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1266 AND $ref_check_qpart
1267 AND unread = true AND owner_uid = $owner_uid");
1270 } else if ($feed > 0) {
1272 db_query($link, "UPDATE ttrss_user_entries
1273 SET unread = false,last_read = NOW()
1274 WHERE feed_id = '$feed'
1275 AND $ref_check_qpart
1276 AND owner_uid = $owner_uid");
1278 } else if ($feed < 0 && $feed > -10) { // special, like starred
1281 db_query($link, "UPDATE ttrss_user_entries
1282 SET unread = false,last_read = NOW()
1284 AND $ref_check_qpart
1285 AND owner_uid = $owner_uid");
1289 db_query($link, "UPDATE ttrss_user_entries
1290 SET unread = false,last_read = NOW()
1291 WHERE published = true
1292 AND $ref_check_qpart
1293 AND owner_uid = $owner_uid");
1298 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1300 if (DB_TYPE
== "pgsql") {
1301 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1303 $match_part = "updated > DATE_SUB(NOW(),
1304 INTERVAL $intl HOUR) ";
1307 $result = db_query($link, "SELECT id FROM ttrss_entries,
1308 ttrss_user_entries WHERE $match_part AND
1310 ttrss_user_entries.ref_id = ttrss_entries.id AND
1311 owner_uid = $owner_uid");
1313 $affected_ids = array();
1315 while ($line = db_fetch_assoc($result)) {
1316 array_push($affected_ids, $line["id"]);
1319 catchupArticlesById($link, $affected_ids, 0);
1323 db_query($link, "UPDATE ttrss_user_entries
1324 SET unread = false,last_read = NOW()
1325 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1328 } else if ($feed < -10) { // label
1330 $label_id = -$feed - 11;
1332 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1333 SET unread = false, last_read = NOW()
1334 WHERE label_id = '$label_id' AND unread = true
1335 AND $ref_check_qpart
1336 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1340 ccache_update($link, $feed, $owner_uid, $cat_view);
1343 db_query($link, "BEGIN");
1345 $tag_name = db_escape_string($feed);
1347 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1348 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1350 while ($line = db_fetch_assoc($result)) {
1351 db_query($link, "UPDATE ttrss_user_entries SET
1352 unread = false, last_read = NOW()
1353 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1355 db_query($link, "COMMIT");
1359 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1361 if (!$omode) $omode = "flc";
1363 $data = getGlobalCounters($link);
1365 $data = array_merge($data, getVirtCounters($link));
1367 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1368 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1369 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1370 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1375 function getCategoryTitle($link, $cat_id) {
1377 if ($cat_id == -1) {
1378 return __("Special");
1379 } else if ($cat_id == -2) {
1380 return __("Labels");
1383 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1386 if (db_num_rows($result) == 1) {
1387 return db_fetch_result($result, 0, "title");
1389 return "Uncategorized";
1395 function getCategoryCounters($link) {
1398 /* Labels category */
1400 $cv = array("id" => -2, "kind" => "cat",
1401 "counter" => getCategoryUnread($link, -2));
1403 array_push($ret_arr, $cv);
1405 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1406 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1407 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1408 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1409 WHERE ttrss_cat_counters_cache.feed_id = id AND
1410 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1411 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1413 while ($line = db_fetch_assoc($result)) {
1414 $line["cat_id"] = (int) $line["cat_id"];
1416 if ($line["num_children"] > 0) {
1417 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1422 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1423 "child_counter" => $child_counter,
1424 "counter" => $line["unread"]);
1426 array_push($ret_arr, $cv);
1429 /* Special case: NULL category doesn't actually exist in the DB */
1431 $cv = array("id" => 0, "kind" => "cat",
1432 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
1434 array_push($ret_arr, $cv);
1439 // only accepts real cats (>= 0)
1440 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1441 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1443 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1444 AND owner_uid = $owner_uid");
1448 while ($line = db_fetch_assoc($result)) {
1449 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1450 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1456 function getCategoryUnread($link, $cat, $owner_uid = false) {
1458 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1463 $cat_query = "cat_id = '$cat'";
1465 $cat_query = "cat_id IS NULL";
1468 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1469 AND owner_uid = " . $owner_uid);
1471 $cat_feeds = array();
1472 while ($line = db_fetch_assoc($result)) {
1473 array_push($cat_feeds, "feed_id = " . $line["id"]);
1476 if (count($cat_feeds) == 0) return 0;
1478 $match_part = implode(" OR ", $cat_feeds);
1480 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1481 FROM ttrss_user_entries
1482 WHERE unread = true AND ($match_part)
1483 AND owner_uid = " . $owner_uid);
1487 # this needs to be rewritten
1488 while ($line = db_fetch_assoc($result)) {
1489 $unread +
= $line["unread"];
1493 } else if ($cat == -1) {
1494 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1495 } else if ($cat == -2) {
1497 $result = db_query($link, "
1498 SELECT COUNT(unread) AS unread FROM
1499 ttrss_user_entries, ttrss_user_labels2
1500 WHERE article_id = ref_id AND unread = true
1501 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1503 $unread = db_fetch_result($result, 0, "unread");
1510 function getFeedUnread($link, $feed, $is_cat = false) {
1511 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1514 function getLabelUnread($link, $label_id, $owner_uid = false) {
1515 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1517 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1518 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1520 if (db_num_rows($result) != 0) {
1521 return db_fetch_result($result, 0, "unread");
1527 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1528 $owner_uid = false) {
1530 $n_feed = (int) $feed;
1531 $need_entries = false;
1533 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1536 $unread_qpart = "unread = true";
1538 $unread_qpart = "true";
1542 return getCategoryUnread($link, $n_feed, $owner_uid);
1543 } if ($feed != "0" && $n_feed == 0) {
1545 $feed = db_escape_string($feed);
1547 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1548 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1549 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1550 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1551 return db_fetch_result($result, 0, "count");
1553 } else if ($n_feed == -1) {
1554 $match_part = "marked = true";
1555 } else if ($n_feed == -2) {
1556 $match_part = "published = true";
1557 } else if ($n_feed == -3) {
1558 $match_part = "unread = true AND score >= 0";
1560 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1562 if (DB_TYPE
== "pgsql") {
1563 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1565 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1568 $need_entries = true;
1570 } else if ($n_feed == -4) {
1571 $match_part = "true";
1572 } else if ($n_feed >= 0) {
1575 $match_part = "feed_id = '$n_feed'";
1577 $match_part = "feed_id IS NULL";
1580 } else if ($feed < -10) {
1582 $label_id = -$feed - 11;
1584 return getLabelUnread($link, $label_id, $owner_uid);
1590 if ($need_entries) {
1591 $from_qpart = "ttrss_user_entries,ttrss_entries";
1592 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1594 $from_qpart = "ttrss_user_entries";
1597 $query = "SELECT count(int_id) AS unread
1598 FROM $from_qpart WHERE
1599 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1601 //echo "[$feed/$query]\n";
1603 $result = db_query($link, $query);
1607 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1608 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1609 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1610 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1613 $unread = db_fetch_result($result, 0, "unread");
1618 function getGlobalUnread($link, $user_id = false) {
1621 $user_id = $_SESSION["uid"];
1624 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1625 WHERE owner_uid = '$user_id' AND feed_id > 0");
1627 $c_id = db_fetch_result($result, 0, "c_id");
1632 function getGlobalCounters($link, $global_unread = -1) {
1635 if ($global_unread == -1) {
1636 $global_unread = getGlobalUnread($link);
1639 $cv = array("id" => "global-unread",
1640 "counter" => $global_unread);
1642 array_push($ret_arr, $cv);
1644 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1645 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1647 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1649 $cv = array("id" => "subscribed-feeds",
1650 "counter" => $subscribed_feeds);
1652 array_push($ret_arr, $cv);
1657 function getTagCounters($link) {
1661 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1662 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1663 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1664 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1665 ORDER BY count DESC LIMIT 55");
1669 while ($line = db_fetch_assoc($result)) {
1670 $tags[$line["tag_name"]] +
= $line["count"];
1673 foreach (array_keys($tags) as $tag) {
1674 $unread = $tags[$tag];
1675 $tag = htmlspecialchars($tag);
1677 $cv = array("id" => $tag,
1679 "counter" => $unread);
1681 array_push($ret_arr, $cv);
1687 function getVirtCounters($link) {
1691 for ($i = 0; $i >= -4; $i--) {
1693 $count = getFeedUnread($link, $i);
1695 $cv = array("id" => $i,
1696 "counter" => $count);
1698 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1699 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1701 array_push($ret_arr, $cv);
1707 function getLabelCounters($link, $descriptions = false) {
1711 $owner_uid = $_SESSION["uid"];
1713 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1714 WHERE owner_uid = '$owner_uid'");
1716 while ($line = db_fetch_assoc($result)) {
1718 $id = -$line["id"] - 11;
1720 $label_name = $line["caption"];
1721 $count = getFeedUnread($link, $id);
1723 $cv = array("id" => $id,
1724 "counter" => $count);
1727 $cv["description"] = $label_name;
1729 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1730 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1732 array_push($ret_arr, $cv);
1738 function getFeedCounters($link, $active_feed = false) {
1742 $query = "SELECT ttrss_feeds.id,
1744 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1745 last_error, value AS count
1746 FROM ttrss_feeds, ttrss_counters_cache
1747 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1748 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1749 AND ttrss_counters_cache.feed_id = id";
1751 $result = db_query($link, $query);
1752 $fctrs_modified = false;
1754 while ($line = db_fetch_assoc($result)) {
1757 $count = $line["count"];
1758 $last_error = htmlspecialchars($line["last_error"]);
1760 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1762 $has_img = feed_has_icon($id);
1764 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1767 $cv = array("id" => $id,
1768 "updated" => $last_updated,
1769 "counter" => $count,
1770 "has_img" => (int) $has_img);
1773 $cv["error"] = $last_error;
1775 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1776 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1778 if ($active_feed && $id == $active_feed)
1779 $cv["title"] = truncate_string($line["title"], 30);
1781 array_push($ret_arr, $cv);
1788 function get_pgsql_version($link) {
1789 $result = db_query($link, "SELECT version() AS version");
1790 $version = explode(" ", db_fetch_result($result, 0, "version"));
1795 * @return integer Status code:
1796 * 0 - OK, Feed already exists
1797 * 1 - OK, Feed added
1799 * 3 - URL content is HTML, no feeds available
1800 * 4 - URL content is HTML which contains multiple feeds.
1801 * Here you should call extractfeedurls in rpc-backend
1802 * to get all possible feeds.
1803 * 5 - Couldn't download the URL content.
1805 function subscribe_to_feed($link, $url, $cat_id = 0,
1806 $auth_login = '', $auth_pass = '', $need_auth = false) {
1808 require_once "include/rssfuncs.php";
1810 $url = fix_url($url);
1812 if (!$url ||
!validate_feed_url($url)) return 2;
1816 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
1817 WHERE id = ".$_SESSION['uid']);
1819 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
1821 if (!$need_auth ||
!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
1822 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
1824 if (url_is_html($url, $auth_login, $auth_pass)) {
1825 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
1826 if (count($feedUrls) == 0) {
1828 } else if (count($feedUrls) > 1) {
1831 //use feed url as new URL
1832 $url = key($feedUrls);
1836 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
1841 if ($cat_id == "0" ||
!$cat_id) {
1842 $cat_qpart = "NULL";
1844 $cat_qpart = "'$cat_id'";
1847 $result = db_query($link,
1848 "SELECT id FROM ttrss_feeds
1849 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1851 if (db_num_rows($result) == 0) {
1852 $result = db_query($link,
1853 "INSERT INTO ttrss_feeds
1854 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1855 VALUES ('".$_SESSION["uid"]."', '$url',
1856 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1858 $result = db_query($link,
1859 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1860 AND owner_uid = " . $_SESSION["uid"]);
1862 $feed_id = db_fetch_result($result, 0, "id");
1865 update_rss_feed($link, $feed_id, true);
1874 function print_feed_select($link, $id, $default_id = "",
1875 $attributes = "", $include_all_feeds = true) {
1877 print "<select id=\"$id\" name=\"$id\" $attributes>";
1878 if ($include_all_feeds) {
1879 print "<option value=\"0\">".__('All feeds')."</option>";
1882 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1883 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1885 if (db_num_rows($result) > 0 && $include_all_feeds) {
1886 print "<option disabled>--------</option>";
1889 while ($line = db_fetch_assoc($result)) {
1890 if ($line["id"] == $default_id) {
1891 $is_selected = "selected=\"1\"";
1896 $title = truncate_string(htmlspecialchars($line["title"]), 40);
1898 printf("<option $is_selected value='%d'>%s</option>",
1899 $line["id"], $title);
1905 function print_feed_cat_select($link, $id, $default_id,
1906 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1909 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1913 $parent_qpart = "parent_cat = '$root_id'";
1915 $parent_qpart = "parent_cat IS NULL";
1917 $result = db_query($link, "SELECT id,title,
1918 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1919 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1920 FROM ttrss_feed_categories
1921 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1923 while ($line = db_fetch_assoc($result)) {
1924 if ($line["id"] == $default_id) {
1925 $is_selected = "selected=\"1\"";
1930 for ($i = 0; $i < $nest_level; $i++
)
1931 $line["title"] = " - " . $line["title"];
1934 printf("<option $is_selected value='%d'>%s</option>",
1935 $line["id"], htmlspecialchars($line["title"]));
1937 if ($line["num_children"] > 0)
1938 print_feed_cat_select($link, $id, $default_id, $attributes,
1939 $include_all_cats, $line["id"], $nest_level+
1);
1943 if ($include_all_cats) {
1944 if (db_num_rows($result) > 0) {
1945 print "<option disabled=\"1\">--------</option>";
1948 if ($default_id == 0) {
1949 $is_selected = "selected=\"1\"";
1954 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1960 function checkbox_to_sql_bool($val) {
1961 return ($val == "on") ?
"true" : "false";
1964 function getFeedCatTitle($link, $id) {
1966 return __("Special");
1967 } else if ($id < -10) {
1968 return __("Labels");
1969 } else if ($id > 0) {
1970 $result = db_query($link, "SELECT ttrss_feed_categories.title
1971 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1972 cat_id = ttrss_feed_categories.id");
1973 if (db_num_rows($result) == 1) {
1974 return db_fetch_result($result, 0, "title");
1976 return __("Uncategorized");
1979 return "getFeedCatTitle($id) failed";
1984 function getFeedIcon($id) {
1987 return "images/archive.png";
1990 return "images/mark_set.png";
1993 return "images/pub_set.png";
1996 return "images/fresh.png";
1999 return "images/tag.png";
2003 return "images/label.png";
2005 if (file_exists(ICONS_DIR
. "/$id.ico"))
2006 return ICONS_URL
. "/$id.ico";
2012 function getFeedTitle($link, $id) {
2014 return __("Starred articles");
2015 } else if ($id == -2) {
2016 return __("Published articles");
2017 } else if ($id == -3) {
2018 return __("Fresh articles");
2019 } else if ($id == -4) {
2020 return __("All articles");
2021 } else if ($id === 0 ||
$id === "0") {
2022 return __("Archived articles");
2023 } else if ($id < -10) {
2024 $label_id = -$id - 11;
2025 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2026 if (db_num_rows($result) == 1) {
2027 return db_fetch_result($result, 0, "caption");
2029 return "Unknown label ($label_id)";
2032 } else if (is_numeric($id) && $id > 0) {
2033 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2034 if (db_num_rows($result) == 1) {
2035 return db_fetch_result($result, 0, "title");
2037 return "Unknown feed ($id)";
2044 function make_init_params($link) {
2047 $params["theme"] = get_user_theme($link);
2048 $params["theme_options"] = get_user_theme_options($link);
2050 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
2051 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
2052 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
2053 $params["sign_info"] = theme_image($link, "images/sign_info.png");
2055 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2056 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
2057 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
2058 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
2060 $params[strtolower($param)] = (int) get_pref($link, $param);
2063 $params["icons_url"] = ICONS_URL
;
2064 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
2065 $params["default_include_children"] = get_pref($link, "_DEFAULT_INCLUDE_CHILDREN");
2066 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
2067 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
2068 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
2069 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
2071 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2072 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2074 $max_feed_id = db_fetch_result($result, 0, "mid");
2075 $num_feeds = db_fetch_result($result, 0, "nf");
2077 $params["max_feed_id"] = (int) $max_feed_id;
2078 $params["num_feeds"] = (int) $num_feeds;
2080 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
2082 $params["csrf_token"] = $_SESSION["csrf_token"];
2087 function make_runtime_info($link) {
2090 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2091 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2093 $max_feed_id = db_fetch_result($result, 0, "mid");
2094 $num_feeds = db_fetch_result($result, 0, "nf");
2096 $data["max_feed_id"] = (int) $max_feed_id;
2097 $data["num_feeds"] = (int) $num_feeds;
2099 $data['last_article_id'] = getLastArticleId($link);
2100 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2102 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
2104 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2106 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2108 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2111 $stamp_delta = time() - $stamp;
2113 if ($stamp_delta > 1800) {
2117 $_SESSION["daemon_stamp_check"] = time();
2120 $data['daemon_stamp_ok'] = $stamp_check;
2122 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2124 $data['daemon_stamp'] = $stamp_fmt;
2129 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2130 $new_version_details = @check_for_update
($link);
2132 $data['new_version_available'] = (int) ($new_version_details != false);
2134 $_SESSION["last_version_check"] = time();
2140 function search_to_sql($link, $search, $match_on) {
2142 $search_query_part = "";
2144 $keywords = explode(" ", $search);
2145 $query_keywords = array();
2147 foreach ($keywords as $k) {
2148 if (strpos($k, "-") === 0) {
2155 $commandpair = explode(":", mb_strtolower($k), 2);
2157 if ($commandpair[0] == "note" && $commandpair[1]) {
2159 if ($commandpair[1] == "true")
2160 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2162 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2164 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2166 if ($commandpair[1] == "true")
2167 array_push($query_keywords, "($not (marked = true))");
2169 array_push($query_keywords, "($not (marked = false))");
2171 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2173 if ($commandpair[1] == "true")
2174 array_push($query_keywords, "($not (published = true))");
2176 array_push($query_keywords, "($not (published = false))");
2178 } else if (strpos($k, "@") === 0) {
2180 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2181 $orig_ts = strtotime(substr($k, 1));
2182 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2184 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2186 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2187 } else if ($match_on == "both") {
2188 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2189 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2190 } else if ($match_on == "title") {
2191 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2192 } else if ($match_on == "content") {
2193 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2197 $search_query_part = implode("AND", $query_keywords);
2199 return $search_query_part;
2202 function getChildCategories($link, $cat, $owner_uid) {
2205 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2206 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2208 while ($line = db_fetch_assoc($result)) {
2209 array_push($rv, $line["id"]);
2210 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2216 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false) {
2218 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2220 $ext_tables_part = "";
2224 if (SPHINX_ENABLED
) {
2225 $ids = join(",", @sphinx_search
($search, 0, 500));
2228 $search_query_part = "ref_id IN ($ids) AND ";
2230 $search_query_part = "ref_id = -1 AND ";
2233 $search_query_part = search_to_sql($link, $search, $match_on);
2234 $search_query_part .= " AND ";
2238 $search_query_part = "";
2242 $filter_query_part = filter_to_sql($filter);
2244 $filter_query_part = "";
2248 $since_id_part = "ttrss_entries.id > $since_id AND ";
2250 $since_id_part = "";
2253 $view_query_part = "";
2255 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2257 $view_query_part = " ";
2258 } else if ($feed != -1) {
2259 $unread = getFeedUnread($link, $feed, $cat_view);
2261 if ($cat_view && $feed > 0 && $include_children)
2262 $unread +
= getCategoryChildrenUnread($link, $feed);
2265 $view_query_part = " unread = true AND ";
2270 if ($view_mode == "marked") {
2271 $view_query_part = " marked = true AND ";
2274 if ($view_mode == "published") {
2275 $view_query_part = " published = true AND ";
2278 if ($view_mode == "unread") {
2279 $view_query_part = " unread = true AND ";
2282 if ($view_mode == "updated") {
2283 $view_query_part = " (last_read is null and unread = false) AND ";
2287 $limit_query_part = "LIMIT " . $limit;
2290 $vfeed_query_part = "";
2292 // override query strategy and enable feed display when searching globally
2293 if ($search && $search_mode == "all_feeds") {
2294 $query_strategy_part = "ttrss_entries.id > 0";
2295 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2297 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2298 $query_strategy_part = "ttrss_entries.id > 0";
2299 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2300 id = feed_id) as feed_title,";
2301 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
2303 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2305 $tmp_result = false;
2308 $tmp_result = db_query($link, "SELECT id
2309 FROM ttrss_feeds WHERE cat_id = '$feed'");
2311 $tmp_result = db_query($link, "SELECT id
2312 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2313 WHERE id = '$feed') AND id != '$feed'");
2316 $cat_siblings = array();
2318 if (db_num_rows($tmp_result) > 0) {
2319 while ($p = db_fetch_assoc($tmp_result)) {
2320 array_push($cat_siblings, "feed_id = " . $p["id"]);
2323 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2324 $feed, implode(" OR ", $cat_siblings));
2327 $query_strategy_part = "ttrss_entries.id > 0";
2330 } else if ($feed > 0) {
2335 if ($include_children) {
2337 $subcats = getChildCategories($link, $feed, $owner_uid);
2339 if (count($subcats) == 0) {
2340 $query_strategy_part = "cat_id = '$feed'";
2342 array_push($subcats, $feed);
2343 $query_strategy_part = "cat_id IN (".
2344 implode(",", $subcats).")";
2347 $query_strategy_part = "cat_id = '$feed'";
2351 $query_strategy_part = "cat_id IS NULL";
2354 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2357 $query_strategy_part = "feed_id = '$feed'";
2359 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2360 $query_strategy_part = "feed_id IS NULL";
2361 } else if ($feed == 0 && $cat_view) { // uncategorized
2362 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2363 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2364 } else if ($feed == -1) { // starred virtual feed
2365 $query_strategy_part = "marked = true";
2366 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2367 } else if ($feed == -2) { // published virtual feed OR labels category
2370 $query_strategy_part = "published = true";
2371 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2373 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2375 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2377 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2378 ttrss_user_labels2.article_id = ref_id";
2382 } else if ($feed == -3) { // fresh virtual feed
2383 $query_strategy_part = "unread = true AND score >= 0";
2385 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2387 if (DB_TYPE
== "pgsql") {
2388 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2390 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2393 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2394 } else if ($feed == -4) { // all articles virtual feed
2395 $query_strategy_part = "true";
2396 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2397 } else if ($feed <= -10) { // labels
2398 $label_id = -$feed - 11;
2400 $query_strategy_part = "label_id = '$label_id' AND
2401 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2402 ttrss_user_labels2.article_id = ref_id";
2404 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2405 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2408 $query_strategy_part = "id > 0"; // dumb
2411 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2412 $date_sort_field = "updated";
2414 $date_sort_field = "date_entered";
2417 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2418 $order_by = "$date_sort_field";
2420 $order_by = "$date_sort_field DESC";
2423 if ($view_mode != "noscores") {
2424 $order_by = "score DESC, $order_by";
2427 if ($override_order) {
2428 $order_by = $override_order;
2434 $feed_title = "Search results";
2437 $feed_title = getCategoryTitle($link, $feed);
2439 if (is_numeric($feed) && $feed > 0) {
2440 $result = db_query($link, "SELECT title,site_url,last_error
2441 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2443 $feed_title = db_fetch_result($result, 0, "title");
2444 $feed_site_url = db_fetch_result($result, 0, "site_url");
2445 $last_error = db_fetch_result($result, 0, "last_error");
2447 $feed_title = getFeedTitle($link, $feed);
2452 $content_query_part = "content as content_preview,";
2454 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2457 $feed_kind = "Feeds";
2459 $feed_kind = "Labels";
2462 if ($limit_query_part) {
2463 $offset_query_part = "OFFSET $offset";
2466 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2467 if (!$override_order) {
2468 $order_by = "ttrss_feeds.title, $order_by";
2473 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2474 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2477 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
2478 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2481 $query = "SELECT DISTINCT
2484 ttrss_entries.id,ttrss_entries.title,
2488 always_display_enclosures,
2494 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2495 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2498 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2504 ttrss_user_entries.ref_id = ttrss_entries.id AND
2505 ttrss_user_entries.owner_uid = '$owner_uid' AND
2510 $query_strategy_part ORDER BY $order_by
2511 $limit_query_part $offset_query_part";
2513 if ($_REQUEST["debug"]) print $query;
2515 $result = db_query($link, $query);
2520 $select_qpart = "SELECT DISTINCT " .
2524 "ttrss_entries.id as id," .
2537 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2540 $content_query_part .
2541 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2544 $feed_kind = "Tags";
2545 $all_tags = explode(",", $feed);
2546 if ($search_mode == 'any') {
2547 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2548 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2549 $where_qpart = " WHERE " .
2550 "ref_id = ttrss_entries.id AND " .
2551 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2552 "post_int_id = int_id AND $tag_sql AND " .
2554 $search_query_part .
2555 $query_strategy_part . " ORDER BY $order_by " .
2560 $sub_selects = array();
2561 $sub_ands = array();
2562 foreach ($all_tags as $term) {
2563 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2570 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2575 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2576 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2577 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2578 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2580 // error_log("TAG SQL: " . $tag_sql);
2581 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2583 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2584 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2587 return array($result, $feed_title, $feed_site_url, $last_error);
2591 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2594 if (!$owner) $owner = $_SESSION["uid"];
2596 $res = trim($str); if (!$res) return '';
2598 // create global Purifier object if needed
2600 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
2602 $config = HTMLPurifier_Config
::createDefault();
2604 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title|align|hspace],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td,span[class]";
2606 $config->set('HTML.SafeObject', true);
2607 @$config->set('HTML', 'Allowed', $allowed);
2608 $config->set('Output.FlashCompat', true);
2609 $config->set('Attr.EnableID', true);
2610 if (!defined('MOBILE_VERSION')) {
2611 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
2613 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
2616 $config->set('Filter.YouTube', true);
2618 $purifier = new HTMLPurifier($config);
2621 $res = $purifier->purify($res);
2623 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2624 $res = preg_replace('/<img[^>]+>/is', '', $res);
2627 if (strpos($res, "href=") === false)
2628 $res = rewrite_urls($res);
2630 $charset_hack = '<head>
2631 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2634 $res = trim($res); if (!$res) return '';
2636 libxml_use_internal_errors(true);
2638 $doc = new DOMDocument();
2639 $doc->loadHTML($charset_hack . $res);
2640 $xpath = new DOMXPath($doc);
2642 $entries = $xpath->query('(//a[@href]|//img[@src])');
2645 foreach ($entries as $entry) {
2649 if ($entry->hasAttribute('href'))
2650 $entry->setAttribute('href',
2651 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2653 if ($entry->hasAttribute('src'))
2654 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2655 $entry->setAttribute('src',
2656 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2659 if (strtolower($entry->nodeName
) == "a") {
2660 $entry->setAttribute("target", "_blank");
2663 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2664 $br = $doc->createElement("br");
2666 if ($entry->parentNode
->nextSibling
) {
2667 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2674 $node = $doc->getElementsByTagName('body')->item(0);
2676 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2680 * Send by mail a digest of last articles.
2682 * @param mixed $link The database connection.
2683 * @param integer $limit The maximum number of articles by digest.
2684 * @return boolean Return false if digests are not enabled.
2686 function send_headlines_digests($link, $debug = false) {
2688 require_once 'lib/phpmailer/class.phpmailer.php';
2690 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2691 $limit = 1000; // maximum amount of headlines to include
2693 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2695 if (DB_TYPE
== "pgsql") {
2696 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2697 } else if (DB_TYPE
== "mysql") {
2698 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2701 $result = db_query($link, "SELECT id,email FROM ttrss_users
2702 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2704 while ($line = db_fetch_assoc($result)) {
2706 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2707 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2709 // try to send digests within 2 hours of preferred time
2710 if ($preferred_ts && time() >= $preferred_ts &&
2711 time() - $preferred_ts <= 7200) {
2713 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2715 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2719 // reset tz_offset global to prevent tz cache clash between users
2722 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2723 $digest = $tuple[0];
2724 $headlines_count = $tuple[1];
2725 $affected_ids = $tuple[2];
2726 $digest_text = $tuple[3];
2728 if ($headlines_count > 0) {
2730 $mail = new PHPMailer();
2732 $mail->PluginDir
= "lib/phpmailer/";
2733 $mail->SetLanguage("en", "lib/phpmailer/language/");
2735 $mail->CharSet
= "UTF-8";
2737 $mail->From
= SMTP_FROM_ADDRESS
;
2738 $mail->FromName
= SMTP_FROM_NAME
;
2739 $mail->AddAddress($line["email"], $line["login"]);
2742 $mail->Host
= SMTP_HOST
;
2743 $mail->Mailer
= "smtp";
2744 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2745 $mail->Username
= SMTP_LOGIN
;
2746 $mail->Password
= SMTP_PASSWORD
;
2749 $mail->IsHTML(true);
2750 $mail->Subject
= DIGEST_SUBJECT
;
2751 $mail->Body
= $digest;
2752 $mail->AltBody
= $digest_text;
2754 $rc = $mail->Send();
2756 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2758 if ($debug) print "RC=$rc\n";
2760 if ($rc && $do_catchup) {
2761 if ($debug) print "Marking affected articles as read...\n";
2762 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2765 if ($debug) print "No headlines\n";
2768 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2769 WHERE id = " . $line["id"]);
2775 if ($debug) _debug("All done.");
2779 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2781 require_once "lib/MiniTemplator.class.php";
2783 $tpl = new MiniTemplator
;
2784 $tpl_t = new MiniTemplator
;
2786 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2787 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2789 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2790 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2792 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2793 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2795 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2796 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2798 $affected_ids = array();
2800 if (DB_TYPE
== "pgsql") {
2801 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2802 } else if (DB_TYPE
== "mysql") {
2803 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2806 $result = db_query($link, "SELECT ttrss_entries.title,
2807 ttrss_feeds.title AS feed_title,
2808 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2810 ttrss_user_entries.ref_id,
2814 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2816 ttrss_user_entries,ttrss_entries,ttrss_feeds
2818 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2820 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2821 AND include_in_digest = true
2823 AND ttrss_user_entries.owner_uid = $user_id
2826 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2829 $cur_feed_title = "";
2831 $headlines_count = db_num_rows($result);
2833 $headlines = array();
2835 while ($line = db_fetch_assoc($result)) {
2836 array_push($headlines, $line);
2839 for ($i = 0; $i < sizeof($headlines); $i++
) {
2841 $line = $headlines[$i];
2843 array_push($affected_ids, $line["ref_id"]);
2845 $updated = make_local_datetime($link, $line['last_updated'], false,
2848 /* if ($line["score"] != 0) {
2849 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2851 $line["title"] .= " (".$line['score'].")";
2854 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2855 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2858 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2859 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2860 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2861 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2862 $tpl->setVariable('ARTICLE_EXCERPT',
2863 truncate_string(strip_tags($line["content"]), 300));
2864 // $tpl->setVariable('ARTICLE_CONTENT',
2865 // strip_tags($article_content));
2867 $tpl->addBlock('article');
2869 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2870 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2871 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2872 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2873 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2874 // truncate_string(strip_tags($line["excerpt"]), 100));
2876 $tpl_t->addBlock('article');
2878 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2879 $tpl->addBlock('feed');
2880 $tpl_t->addBlock('feed');
2885 $tpl->addBlock('digest');
2886 $tpl->generateOutputToString($tmp);
2888 $tpl_t->addBlock('digest');
2889 $tpl_t->generateOutputToString($tmp_t);
2891 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2894 function check_for_update($link) {
2895 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2896 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2898 $version_data = @fetch_file_contents
($version_url);
2900 if ($version_data) {
2901 $version_data = json_decode($version_data, true);
2902 if ($version_data && $version_data['version']) {
2904 if (version_compare(VERSION
, $version_data['version']) == -1) {
2905 return $version_data;
2913 function markArticlesById($link, $ids, $cmode) {
2917 foreach ($ids as $id) {
2918 array_push($tmp_ids, "ref_id = '$id'");
2921 $ids_qpart = join(" OR ", $tmp_ids);
2924 db_query($link, "UPDATE ttrss_user_entries SET
2925 marked = false,last_read = NOW()
2926 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2927 } else if ($cmode == 1) {
2928 db_query($link, "UPDATE ttrss_user_entries SET
2930 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2932 db_query($link, "UPDATE ttrss_user_entries SET
2933 marked = NOT marked,last_read = NOW()
2934 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2938 function publishArticlesById($link, $ids, $cmode) {
2942 foreach ($ids as $id) {
2943 array_push($tmp_ids, "ref_id = '$id'");
2946 $ids_qpart = join(" OR ", $tmp_ids);
2949 db_query($link, "UPDATE ttrss_user_entries SET
2950 published = false,last_read = NOW()
2951 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2952 } else if ($cmode == 1) {
2953 db_query($link, "UPDATE ttrss_user_entries SET
2955 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2957 db_query($link, "UPDATE ttrss_user_entries SET
2958 published = NOT published,last_read = NOW()
2959 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2962 if (PUBSUBHUBBUB_HUB
) {
2963 $rss_link = get_self_url_prefix() .
2964 "/public.php?op=rss&id=-2&key=" .
2965 get_feed_access_key($link, -2, false);
2967 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2969 $pubsub_result = $p->publish_update($rss_link);
2973 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2975 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2976 if (count($ids) == 0) return;
2980 foreach ($ids as $id) {
2981 array_push($tmp_ids, "ref_id = '$id'");
2984 $ids_qpart = join(" OR ", $tmp_ids);
2987 db_query($link, "UPDATE ttrss_user_entries SET
2988 unread = false,last_read = NOW()
2989 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2990 } else if ($cmode == 1) {
2991 db_query($link, "UPDATE ttrss_user_entries SET
2993 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2995 db_query($link, "UPDATE ttrss_user_entries SET
2996 unread = NOT unread,last_read = NOW()
2997 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3002 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3003 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3005 while ($line = db_fetch_assoc($result)) {
3006 ccache_update($link, $line["feed_id"], $owner_uid);
3010 function catchupArticleById($link, $id, $cmode) {
3013 db_query($link, "UPDATE ttrss_user_entries SET
3014 unread = false,last_read = NOW()
3015 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3016 } else if ($cmode == 1) {
3017 db_query($link, "UPDATE ttrss_user_entries SET
3019 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3021 db_query($link, "UPDATE ttrss_user_entries SET
3022 unread = NOT unread,last_read = NOW()
3023 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3026 $feed_id = getArticleFeed($link, $id);
3027 ccache_update($link, $feed_id, $_SESSION["uid"]);
3030 function make_guid_from_title($title) {
3031 return preg_replace("/[ \"\',.:;]/", "-",
3032 mb_strtolower(strip_tags($title), 'utf-8'));
3035 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
3037 $a_id = db_escape_string($id);
3039 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3041 $query = "SELECT DISTINCT tag_name,
3042 owner_uid as owner FROM
3043 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3044 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
3046 $obj_id = md5("TAGS:$owner_uid:$id");
3049 /* check cache first */
3051 if ($tag_cache === false) {
3052 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
3053 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3055 $tag_cache = db_fetch_result($result, 0, "tag_cache");
3059 $tags = explode(",", $tag_cache);
3062 /* do it the hard way */
3064 $tmp_result = db_query($link, $query);
3066 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3067 array_push($tags, $tmp_line["tag_name"]);
3070 /* update the cache */
3072 $tags_str = db_escape_string(join(",", $tags));
3074 db_query($link, "UPDATE ttrss_user_entries
3075 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3076 AND owner_uid = $owner_uid");
3082 function trim_array($array) {
3084 array_walk($tmp, 'trim');
3088 function tag_is_valid($tag) {
3089 if ($tag == '') return false;
3090 if (preg_match("/^[0-9]*$/", $tag)) return false;
3091 if (mb_strlen($tag) > 250) return false;
3093 if (function_exists('iconv')) {
3094 $tag = iconv("utf-8", "utf-8", $tag);
3097 if (!$tag) return false;
3102 function render_login_form($link, $mobile = 0) {
3105 require_once "login_form.php";
3108 require_once "mobile/login_form.php";
3111 require_once "mobile/classic/login_form.php";
3115 // from http://developer.apple.com/internet/safari/faq.html
3116 function no_cache_incantation() {
3117 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3118 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3119 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3120 header("Cache-Control: post-check=0, pre-check=0", false);
3121 header("Pragma: no-cache"); // HTTP/1.0
3124 function format_warning($msg, $id = "") {
3126 return "<div class=\"warning\" id=\"$id\">
3127 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3130 function format_notice($msg, $id = "") {
3132 return "<div class=\"notice\" id=\"$id\">
3133 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3136 function format_error($msg, $id = "") {
3138 return "<div class=\"error\" id=\"$id\">
3139 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3142 function print_notice($msg) {
3143 return print format_notice($msg);
3146 function print_warning($msg) {
3147 return print format_warning($msg);
3150 function print_error($msg) {
3151 return print format_error($msg);
3155 function T_sprintf() {
3156 $args = func_get_args();
3157 return vsprintf(__(array_shift($args)), $args);
3160 function format_inline_player($link, $url, $ctype) {
3164 if (strpos($ctype, "audio/") === 0) {
3166 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3167 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3168 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3170 $id = 'AUDIO-' . uniqid();
3172 $entry .= "<audio id=\"$id\"\">
3173 <source src=\"$url\"></source>
3176 $entry .= "<span onclick=\"player(this)\"
3177 title=\"".__("Click to play")."\" status=\"0\"
3178 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3182 $entry .= "<object type=\"application/x-shockwave-flash\"
3183 data=\"lib/button/musicplayer.swf?song_url=$url\"
3184 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3185 <param name=\"movie\"
3186 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3191 $filename = substr($url, strrpos($url, "/")+
1);
3193 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3194 $filename . " (" . $ctype . ")" . "</a>";
3199 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3202 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3208 /* we can figure out feed_id from article id anyway, why do we
3209 * pass feed_id here? let's ignore the argument :( */
3211 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3212 WHERE ref_id = '$id'");
3214 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3216 $rv['feed_id'] = $feed_id;
3218 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3220 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3221 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3223 if (db_num_rows($result) == 1) {
3224 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3225 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3227 $rtl_content = false;
3228 $always_display_enclosures = false;
3232 $rtl_tag = "dir=\"RTL\"";
3239 if ($mark_as_read) {
3240 $result = db_query($link, "UPDATE ttrss_user_entries
3241 SET unread = false,last_read = NOW()
3242 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3244 ccache_update($link, $feed_id, $owner_uid);
3247 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3248 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3249 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3250 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3256 FROM ttrss_entries,ttrss_user_entries
3257 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3261 $line = db_fetch_assoc($result);
3263 $plugins->hook('article_before', $line);
3265 if ($line["icon_url"]) {
3266 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3268 $feed_icon = " ";
3271 $feed_site_url = $line['site_url'];
3273 $num_comments = $line["num_comments"];
3274 $entry_comments = "";
3276 if ($num_comments > 0) {
3277 if ($line["comments"]) {
3278 $comments_url = $line["comments"];
3280 $comments_url = $line["link"];
3282 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3284 if ($line["comments"] && $line["link"] != $line["comments"]) {
3285 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
3290 header("Content-Type: text/html");
3291 $rv['content'] .= "<html><head>
3292 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3293 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3294 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3298 $title_escaped = db_escape_string($line['title']);
3300 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3301 truncate_string(strip_tags($line['title']), 15) . "</div>";
3303 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3304 strip_tags($line['title']) . "</div>";
3306 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3308 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3309 class=\"postHeader\" id=\"POSTHDR-$id\">";
3311 $entry_author = $line["author"];
3313 if ($entry_author) {
3314 $entry_author = __(" - ") . $entry_author;
3317 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3320 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3322 if ($line["link"]) {
3323 $rv['content'] .= "<div class='postTitle' clear='both'><a target='_blank'
3324 title=\"".htmlspecialchars($line['title'])."\"
3326 $line["link"] . "\">" .
3327 truncate_string($line["title"], 100) .
3328 "<span class='author'>$entry_author</span></a></div>";
3330 $rv['content'] .= "<div class='postTitle' clear='both'>" . $line["title"] . "$entry_author</div>";
3333 $tag_cache = $line["tag_cache"];
3336 $tags = get_article_tags($link, $id, $owner_uid);
3338 $tags = explode(",", $tag_cache);
3340 $tags_str = format_tags_string($tags, $id);
3341 $tags_str_full = join(", ", $tags);
3343 if (!$tags_str_full) $tags_str_full = __("no tags");
3345 if (!$entry_comments) $entry_comments = " "; # placeholder
3347 $rv['content'] .= "<div class='postTags' style='float : right'>
3348 <img src='".theme_image($link, 'images/tag.png')."'
3349 class='tagsPic' alt='Tags' title='Tags'> ";
3352 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3353 <a title=\"".__('Edit tags for this article')."\"
3354 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3356 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3357 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3358 position=\"below\">$tags_str_full</div>";
3360 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3361 class='tagsPic' style=\"cursor : pointer\"
3362 onclick=\"postOpenInNewTab(event, $id)\"
3363 alt='Zoom' title='".__('Open article in new tab')."'>";
3365 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3367 foreach ($button_plugins as $p) {
3368 $pclass = trim("button_${p}");
3370 if (class_exists($pclass)) {
3371 $plugin = new $pclass($link);
3372 $rv['content'] .= $plugin->render($id, $line);
3376 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3377 class='tagsPic' style=\"cursor : pointer\"
3378 onclick=\"closeArticlePanel($id)\"
3379 title='".__('Close article')."'>";
3382 $tags_str = strip_tags($tags_str);
3383 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3385 $rv['content'] .= "</div>";
3386 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3388 if ($line["orig_feed_id"]) {
3390 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3391 WHERE id = ".$line["orig_feed_id"]);
3393 if (db_num_rows($tmp_result) != 0) {
3395 $rv['content'] .= "<div clear='both'>";
3396 $rv['content'] .= __("Originally from:");
3398 $rv['content'] .= " ";
3400 $tmp_line = db_fetch_assoc($tmp_result);
3402 $rv['content'] .= "<a target='_blank'
3403 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3404 $tmp_line['title'] . "</a>";
3406 $rv['content'] .= " ";
3408 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3409 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3411 $rv['content'] .= "</div>";
3415 $rv['content'] .= "</div>";
3417 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3418 if ($line['note']) {
3419 $rv['content'] .= format_article_note($id, $line['note']);
3421 $rv['content'] .= "</div>";
3423 $rv['content'] .= "<div class=\"postIcon\">" .
3424 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3425 href=\"".htmlspecialchars($feed_site_url)."\">".
3426 $feed_icon . "</a></div>";
3428 $rv['content'] .= "<div class=\"postContent\">";
3432 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3434 $ngram_result = db_query($link, "SELECT id,title FROM
3435 ttrss_entries,ttrss_user_entries
3436 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3437 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3438 AND title != '$title_escaped'
3439 AND owner_uid = $owner_uid");
3441 if (db_num_rows($ngram_result) > 0) {
3442 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3443 "<span>" . __('Related')."</span>";
3444 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3446 while ($nline = db_fetch_assoc($ngram_result)) {
3447 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3448 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3451 $rv['content'] .= "</div></div><br/";
3455 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3458 $rv['content'] .= $article_content;
3460 $rv['content'] .= format_article_enclosures($link, $id,
3461 $always_display_enclosures, $article_content);
3463 $rv['content'] .= "</div>";
3465 $rv['content'] .= "</div>";
3471 <div style=\"text-align : center\">
3472 <button onclick=\"return window.close()\">".
3473 __("Close this window")."</button></div>";
3474 $rv['content'] .= "</body></html>";
3477 $plugins->hook('article_after', $rv);
3483 function print_checkpoint($n, $s) {
3484 $ts = getmicrotime();
3485 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3489 function sanitize_tag($tag) {
3492 $tag = mb_strtolower($tag, 'utf-8');
3494 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3496 // $tag = str_replace('"', "", $tag);
3497 // $tag = str_replace("+", " ", $tag);
3498 $tag = str_replace("technorati tag: ", "", $tag);
3503 function get_self_url_prefix() {
3504 return SELF_URL_PATH
;
3507 function opml_publish_url($link){
3509 $url_path = get_self_url_prefix();
3510 $url_path .= "/opml.php?op=publish&key=" .
3511 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3517 * Purge a feed contents, marked articles excepted.
3519 * @param mixed $link The database connection.
3520 * @param integer $id The id of the feed to purge.
3523 function clear_feed_articles($link, $id) {
3526 $result = db_query($link, "DELETE FROM ttrss_user_entries
3527 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3529 $result = db_query($link, "DELETE FROM ttrss_user_entries
3530 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3533 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3534 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3536 ccache_update($link, $id, $_SESSION['uid']);
3537 } // function clear_feed_articles
3540 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3542 * @return string The Mozilla Firefox feed adding URL.
3544 function add_feed_url() {
3545 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3547 $url_path = get_self_url_prefix() .
3548 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
3550 } // function add_feed_url
3552 function encrypt_password($pass, $salt = '', $mode2 = false) {
3553 if ($salt && $mode2) {
3554 return "MODE2:" . hash('sha256', $salt . $pass);
3556 return "SHA1X:" . sha1("$salt:$pass");
3558 return "SHA1:" . sha1($pass);
3560 } // function encrypt_password
3562 function sanitize_article_content($text) {
3563 # we don't support CDATA sections in articles, they break our own escaping
3564 $text = preg_replace("/\[\[CDATA/", "", $text);
3565 $text = preg_replace("/\]\]\>/", "", $text);
3569 function load_filters($link, $feed, $owner_uid, $action_id = false) {
3573 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
3575 $result = db_query($link, "SELECT reg_exp,
3576 ttrss_filter_types.name AS name,
3577 ttrss_filter_actions.name AS action,
3582 LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
3583 ttrss_filter_types,ttrss_filter_actions
3587 ttrss_filters.owner_uid = $owner_uid AND
3588 ttrss_filter_types.id = filter_type AND
3589 ttrss_filter_actions.id = action_id AND
3590 ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
3591 (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
3592 ttrss_filters.cat_id IS NULL) OR
3593 (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
3596 while ($line = db_fetch_assoc($result)) {
3598 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
3599 $filter["reg_exp"] = $line["reg_exp"];
3600 $filter["action"] = $line["action"];
3601 $filter["action_param"] = $line["action_param"];
3602 $filter["filter_param"] = $line["filter_param"];
3603 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3605 array_push($filters[$line["name"]], $filter);
3612 function get_score_pic($score) {
3614 return "score_high.png";
3615 } else if ($score > 0) {
3616 return "score_half_high.png";
3617 } else if ($score < -100) {
3618 return "score_low.png";
3619 } else if ($score < 0) {
3620 return "score_half_low.png";
3622 return "score_neutral.png";
3626 function feed_has_icon($id) {
3627 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3630 function init_connection($link) {
3633 if (DB_TYPE
== "pgsql") {
3634 pg_query($link, "set client_encoding = 'UTF-8'");
3635 pg_set_client_encoding("UNICODE");
3636 pg_query($link, "set datestyle = 'ISO, european'");
3637 pg_query($link, "set TIME ZONE 0");
3639 db_query($link, "SET time_zone = '+0:0'");
3641 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3642 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3647 print "Unable to connect to database:" . db_last_error();
3652 /* function ccache_zero($link, $feed_id, $owner_uid) {
3653 db_query($link, "UPDATE ttrss_counters_cache SET
3654 value = 0, updated = NOW() WHERE
3655 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3658 function ccache_zero_all($link, $owner_uid) {
3659 db_query($link, "UPDATE ttrss_counters_cache SET
3660 value = 0 WHERE owner_uid = '$owner_uid'");
3662 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3663 value = 0 WHERE owner_uid = '$owner_uid'");
3666 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3669 $table = "ttrss_counters_cache";
3671 $table = "ttrss_cat_counters_cache";
3674 db_query($link, "DELETE FROM $table WHERE
3675 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3679 function ccache_update_all($link, $owner_uid) {
3681 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3683 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3684 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3686 while ($line = db_fetch_assoc($result)) {
3687 ccache_update($link, $line["feed_id"], $owner_uid, true);
3690 /* We have to manually include category 0 */
3692 ccache_update($link, 0, $owner_uid, true);
3695 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3696 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3698 while ($line = db_fetch_assoc($result)) {
3699 print ccache_update($link, $line["feed_id"], $owner_uid);
3706 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3707 $no_update = false) {
3709 if (!is_numeric($feed_id)) return;
3712 $table = "ttrss_counters_cache";
3714 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3715 WHERE id = '$feed_id'");
3716 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3719 $table = "ttrss_cat_counters_cache";
3722 if (DB_TYPE
== "pgsql") {
3723 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3724 } else if (DB_TYPE
== "mysql") {
3725 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3728 $result = db_query($link, "SELECT value FROM $table
3729 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3732 if (db_num_rows($result) == 1) {
3733 return db_fetch_result($result, 0, "value");
3738 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3744 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3745 $update_pcat = true) {
3747 if (!is_numeric($feed_id)) return;
3749 if (!$is_cat && $feed_id > 0) {
3750 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3751 WHERE id = '$feed_id'");
3752 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3755 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3757 /* When updating a label, all we need to do is recalculate feed counters
3758 * because labels are not cached */
3761 ccache_update_all($link, $owner_uid);
3766 $table = "ttrss_counters_cache";
3768 $table = "ttrss_cat_counters_cache";
3771 if ($is_cat && $feed_id >= 0) {
3772 if ($feed_id != 0) {
3773 $cat_qpart = "cat_id = '$feed_id'";
3775 $cat_qpart = "cat_id IS NULL";
3778 /* Recalculate counters for child feeds */
3780 $result = db_query($link, "SELECT id FROM ttrss_feeds
3781 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3783 while ($line = db_fetch_assoc($result)) {
3784 ccache_update($link, $line["id"], $owner_uid, false, false);
3787 $result = db_query($link, "SELECT SUM(value) AS sv
3788 FROM ttrss_counters_cache, ttrss_feeds
3789 WHERE id = feed_id AND $cat_qpart AND
3790 ttrss_feeds.owner_uid = '$owner_uid'");
3792 $unread = (int) db_fetch_result($result, 0, "sv");
3795 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3798 db_query($link, "BEGIN");
3800 $result = db_query($link, "SELECT feed_id FROM $table
3801 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3803 if (db_num_rows($result) == 1) {
3804 db_query($link, "UPDATE $table SET
3805 value = '$unread', updated = NOW() WHERE
3806 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3809 db_query($link, "INSERT INTO $table
3810 (feed_id, value, owner_uid, updated)
3812 ($feed_id, $unread, $owner_uid, NOW())");
3815 db_query($link, "COMMIT");
3817 if ($feed_id > 0 && $prev_unread != $unread) {
3821 /* Update parent category */
3825 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3826 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3828 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3830 ccache_update($link, $cat_id, $owner_uid, true);
3834 } else if ($feed_id < 0) {
3835 ccache_update_all($link, $owner_uid);
3841 /* function ccache_cleanup($link, $owner_uid) {
3843 if (DB_TYPE == "pgsql") {
3844 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3845 (SELECT count(*) FROM ttrss_counters_cache AS c2
3846 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3847 AND owner_uid = '$owner_uid'");
3849 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3850 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3851 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3852 AND owner_uid = '$owner_uid'");
3854 db_query($link, "DELETE c1 FROM
3855 ttrss_counters_cache AS c1,
3856 ttrss_counters_cache AS c2
3858 c1.owner_uid = '$owner_uid' AND
3859 c1.owner_uid = c2.owner_uid AND
3860 c1.feed_id = c2.feed_id");
3862 db_query($link, "DELETE c1 FROM
3863 ttrss_cat_counters_cache AS c1,
3864 ttrss_cat_counters_cache AS c2
3866 c1.owner_uid = '$owner_uid' AND
3867 c1.owner_uid = c2.owner_uid AND
3868 c1.feed_id = c2.feed_id");
3873 function label_find_id($link, $label, $owner_uid) {
3874 $result = db_query($link,
3875 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3876 AND owner_uid = '$owner_uid' LIMIT 1");
3878 if (db_num_rows($result) == 1) {
3879 return db_fetch_result($result, 0, "id");
3885 function get_article_labels($link, $id) {
3889 $result = db_query($link, "SELECT label_cache FROM
3890 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3893 $label_cache = db_fetch_result($result, 0, "label_cache");
3897 $label_cache = json_decode($label_cache, true);
3899 if ($label_cache["no-labels"] == 1)
3902 return $label_cache;
3905 $result = db_query($link,
3906 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3907 FROM ttrss_labels2, ttrss_user_labels2
3909 AND article_id = '$id'
3910 AND owner_uid = ".$_SESSION["uid"] . "
3913 while ($line = db_fetch_assoc($result)) {
3914 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3916 array_push($rv, $rk);
3920 label_update_cache($link, $id, $rv);
3922 label_update_cache($link, $id, array("no-labels" => 1));
3928 function label_find_caption($link, $label, $owner_uid) {
3929 $result = db_query($link,
3930 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3931 AND owner_uid = '$owner_uid' LIMIT 1");
3933 if (db_num_rows($result) == 1) {
3934 return db_fetch_result($result, 0, "caption");
3940 function label_update_cache($link, $id, $labels = false, $force = false) {
3943 label_clear_cache($link, $id);
3946 $labels = get_article_labels($link, $id);
3948 $labels = db_escape_string(json_encode($labels));
3950 db_query($link, "UPDATE ttrss_user_entries SET
3951 label_cache = '$labels' WHERE ref_id = '$id'");
3955 function label_clear_cache($link, $id) {
3957 db_query($link, "UPDATE ttrss_user_entries SET
3958 label_cache = '' WHERE ref_id = '$id'");
3962 function label_remove_article($link, $id, $label, $owner_uid) {
3964 $label_id = label_find_id($link, $label, $owner_uid);
3966 if (!$label_id) return;
3968 $result = db_query($link,
3969 "DELETE FROM ttrss_user_labels2
3971 label_id = '$label_id' AND
3972 article_id = '$id'");
3974 label_clear_cache($link, $id);
3977 function label_add_article($link, $id, $label, $owner_uid) {
3979 $label_id = label_find_id($link, $label, $owner_uid);
3981 if (!$label_id) return;
3983 $result = db_query($link,
3985 article_id FROM ttrss_labels2, ttrss_user_labels2
3988 label_id = '$label_id' AND
3989 article_id = '$id' AND owner_uid = '$owner_uid'
3992 if (db_num_rows($result) == 0) {
3993 db_query($link, "INSERT INTO ttrss_user_labels2
3994 (label_id, article_id) VALUES ('$label_id', '$id')");
3997 label_clear_cache($link, $id);
4001 function label_remove($link, $id, $owner_uid) {
4002 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4004 db_query($link, "BEGIN");
4006 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4009 $caption = db_fetch_result($result, 0, "caption");
4011 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
4012 AND owner_uid = " . $owner_uid);
4014 if (db_affected_rows($link, $result) != 0 && $caption) {
4016 /* Remove access key for the label */
4018 $ext_id = -11 - $id;
4020 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4021 feed_id = '$ext_id' AND owner_uid = $owner_uid");
4023 /* Disable filters that reference label being removed */
4025 db_query($link, "UPDATE ttrss_filters SET
4026 enabled = false WHERE action_param = '$caption'
4028 AND owner_uid = " . $owner_uid);
4030 /* Remove cached data */
4032 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
4033 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
4037 db_query($link, "COMMIT");
4040 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
4042 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
4044 db_query($link, "BEGIN");
4048 $result = db_query($link, "SELECT id FROM ttrss_labels2
4049 WHERE caption = '$caption' AND owner_uid = $owner_uid");
4051 if (db_num_rows($result) == 0) {
4052 $result = db_query($link,
4053 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
4054 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
4056 $result = db_affected_rows($link, $result) != 0;
4059 db_query($link, "COMMIT");
4064 function format_tags_string($tags, $id) {
4067 $tags_nolinks_str = "";
4073 $formatted_tags = array();
4075 foreach ($tags as $tag) {
4077 $tag_escaped = str_replace("'", "\\'", $tag);
4079 if (mb_strlen($tag) > 30) {
4080 $tag = truncate_string($tag, 30);
4083 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4085 array_push($formatted_tags, $tag_str);
4087 $tmp_tags_str = implode(", ", $formatted_tags);
4089 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4094 $tags_str = implode(", ", $formatted_tags);
4096 if ($num_tags < count($tags)) {
4097 $tags_str .= ", …";
4100 if ($num_tags == 0) {
4101 $tags_str = __("no tags");
4108 function format_article_labels($labels, $id) {
4112 foreach ($labels as $l) {
4113 $labels_str .= sprintf("<span class='hlLabelRef'
4114 style='color : %s; background-color : %s'>%s</span>",
4115 $l[2], $l[3], $l[1]);
4122 function format_article_note($id, $note) {
4124 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4125 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4126 __('(edit note)')."</div>$note</div>";
4131 function toggle_collapse_cat($link, $cat_id, $mode) {
4133 $mode = bool_to_sql_bool($mode);
4135 db_query($link, "UPDATE ttrss_feed_categories SET
4136 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4143 $pref_name = '_COLLAPSED_SPECIAL';
4146 $pref_name = '_COLLAPSED_LABELS';
4149 $pref_name = '_COLLAPSED_UNCAT';
4155 set_pref($link, $pref_name, 'true');
4157 set_pref($link, $pref_name, 'false');
4163 function remove_feed($link, $id, $owner_uid) {
4167 /* save starred articles in Archived feed */
4169 db_query($link, "BEGIN");
4171 /* prepare feed if necessary */
4173 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4176 if (db_num_rows($result) == 0) {
4177 db_query($link, "INSERT INTO ttrss_archived_feeds
4178 (id, owner_uid, title, feed_url, site_url)
4179 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4183 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4184 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4185 marked = true AND owner_uid = $owner_uid");
4187 /* Remove access key for the feed */
4189 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4190 feed_id = '$id' AND owner_uid = $owner_uid");
4192 /* remove the feed */
4194 db_query($link, "DELETE FROM ttrss_feeds
4195 WHERE id = '$id' AND owner_uid = $owner_uid");
4197 db_query($link, "COMMIT");
4199 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4200 unlink(ICONS_DIR
. "/$id.ico");
4203 ccache_remove($link, $id, $owner_uid);
4206 label_remove($link, -11-$id, $owner_uid);
4207 ccache_remove($link, -11-$id, $owner_uid);
4211 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
4212 if ($parent_cat_id) {
4213 $parent_qpart = "parent_cat = '$parent_cat_id'";
4214 $parent_insert = "'$parent_cat_id'";
4216 $parent_qpart = "parent_cat IS NULL";
4217 $parent_insert = "NULL";
4220 $result = db_query($link,
4221 "SELECT id FROM ttrss_feed_categories
4222 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4224 if (db_num_rows($result) == 0) {
4227 return db_fetch_result($result, 0, "id");
4231 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
4233 if (!$feed_cat) return false;
4235 db_query($link, "BEGIN");
4237 if ($parent_cat_id) {
4238 $parent_qpart = "parent_cat = '$parent_cat_id'";
4239 $parent_insert = "'$parent_cat_id'";
4241 $parent_qpart = "parent_cat IS NULL";
4242 $parent_insert = "NULL";
4245 $result = db_query($link,
4246 "SELECT id FROM ttrss_feed_categories
4247 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4249 if (db_num_rows($result) == 0) {
4251 $result = db_query($link,
4252 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4253 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
4255 db_query($link, "COMMIT");
4263 function remove_feed_category($link, $id, $owner_uid) {
4265 db_query($link, "DELETE FROM ttrss_feed_categories
4266 WHERE id = '$id' AND owner_uid = $owner_uid");
4268 ccache_remove($link, $id, $owner_uid, true);
4271 function archive_article($link, $id, $owner_uid) {
4272 db_query($link, "BEGIN");
4274 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4275 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4277 if (db_num_rows($result) != 0) {
4279 /* prepare the archived table */
4281 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4284 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4285 WHERE id = '$feed_id'");
4287 if (db_num_rows($result) == 0) {
4288 db_query($link, "INSERT INTO ttrss_archived_feeds
4289 (id, owner_uid, title, feed_url, site_url)
4290 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4291 WHERE id = '$feed_id'");
4294 db_query($link, "UPDATE ttrss_user_entries
4295 SET orig_feed_id = feed_id, feed_id = NULL
4296 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4300 db_query($link, "COMMIT");
4303 function getArticleFeed($link, $id) {
4304 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4305 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4307 if (db_num_rows($result) != 0) {
4308 return db_fetch_result($result, 0, "feed_id");
4315 * Fixes incomplete URLs by prepending "http://".
4316 * Also replaces feed:// with http://, and
4317 * prepends a trailing slash if the url is a domain name only.
4319 * @param string $url Possibly incomplete URL
4321 * @return string Fixed URL.
4323 function fix_url($url) {
4324 if (strpos($url, '://') === false) {
4325 $url = 'http://' . $url;
4326 } else if (substr($url, 0, 5) == 'feed:') {
4327 $url = 'http:' . substr($url, 5);
4330 //prepend slash if the URL has no slash in it
4331 // "http://www.example" -> "http://www.example/"
4332 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4336 if ($url != "http:///")
4342 function validate_feed_url($url) {
4343 $parts = parse_url($url);
4345 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4349 function get_article_enclosures($link, $id) {
4351 $query = "SELECT * FROM ttrss_enclosures
4352 WHERE post_id = '$id' AND content_url != ''";
4356 $result = db_query($link, $query);
4358 if (db_num_rows($result) > 0) {
4359 while ($line = db_fetch_assoc($result)) {
4360 array_push($rv, $line);
4367 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
4373 if ($cat_id == -4 ||
$cat_id == -2) {
4374 $counters = getLabelCounters($link, true);
4376 foreach (array_values($counters) as $cv) {
4378 $unread = $cv["counter"];
4380 if ($unread ||
!$unread_only) {
4384 "title" => $cv["description"],
4385 "unread" => $cv["counter"],
4389 array_push($feeds, $row);
4396 if ($cat_id == -4 ||
$cat_id == -1) {
4397 foreach (array(-1, -2, -3, -4, 0) as $i) {
4398 $unread = getFeedUnread($link, $i);
4400 if ($unread ||
!$unread_only) {
4401 $title = getFeedTitle($link, $i);
4406 "unread" => $unread,
4409 array_push($feeds, $row);
4418 $limit_qpart = "LIMIT $limit OFFSET $offset";
4423 if ($cat_id == -4 ||
$cat_id == -3) {
4424 $result = db_query($link, "SELECT
4425 id, feed_url, cat_id, title, order_id, ".
4426 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4427 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4428 " ORDER BY cat_id, title " . $limit_qpart);
4432 $cat_qpart = "cat_id = '$cat_id'";
4434 $cat_qpart = "cat_id IS NULL";
4436 $result = db_query($link, "SELECT
4437 id, feed_url, cat_id, title, order_id, ".
4438 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4439 FROM ttrss_feeds WHERE
4440 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4441 " ORDER BY cat_id, title " . $limit_qpart);
4444 while ($line = db_fetch_assoc($result)) {
4446 $unread = getFeedUnread($link, $line["id"]);
4448 $has_icon = feed_has_icon($line['id']);
4450 if ($unread ||
!$unread_only) {
4453 "feed_url" => $line["feed_url"],
4454 "title" => $line["title"],
4455 "id" => (int)$line["id"],
4456 "unread" => (int)$unread,
4457 "has_icon" => $has_icon,
4458 "cat_id" => (int)$line["cat_id"],
4459 "last_updated" => strtotime($line["last_updated"]),
4460 "order_id" => (int) $line["order_id"],
4463 array_push($feeds, $row);
4470 function api_get_headlines($link, $feed_id, $limit, $offset,
4471 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4472 $include_attachments, $since_id,
4473 $search = "", $search_mode = "", $match_on = "") {
4475 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4476 $view_mode, $is_cat, $search, $search_mode, $match_on,
4477 $order, $offset, 0, false, $since_id);
4479 $result = $qfh_ret[0];
4480 $feed_title = $qfh_ret[1];
4482 $headlines = array();
4484 while ($line = db_fetch_assoc($result)) {
4485 $is_updated = ($line["last_read"] == "" &&
4486 ($line["unread"] != "t" && $line["unread"] != "1"));
4488 $tags = explode(",", $line["tag_cache"]);
4489 $labels = json_decode($line["label_cache"], true);
4491 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4492 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4494 $headline_row = array(
4495 "id" => (int)$line["id"],
4496 "unread" => sql_bool_to_bool($line["unread"]),
4497 "marked" => sql_bool_to_bool($line["marked"]),
4498 "published" => sql_bool_to_bool($line["published"]),
4499 "updated" => strtotime($line["updated"]),
4500 "is_updated" => $is_updated,
4501 "title" => $line["title"],
4502 "link" => $line["link"],
4503 "feed_id" => $line["feed_id"],
4507 if ($include_attachments)
4508 $headline_row['attachments'] = get_article_enclosures($link,
4511 if ($show_excerpt) {
4512 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4513 $headline_row["excerpt"] = $excerpt;
4516 if ($show_content) {
4517 $headline_row["content"] = $line["content_preview"];
4520 // unify label output to ease parsing
4521 if ($labels["no-labels"] == 1) $labels = array();
4523 $headline_row["labels"] = $labels;
4525 $headline_row["feed_title"] = $line["feed_title"];
4527 array_push($headlines, $headline_row);
4533 function generate_error_feed($link, $error) {
4536 $reply['headlines']['id'] = -6;
4537 $reply['headlines']['is_cat'] = false;
4539 $reply['headlines']['toolbar'] = '';
4540 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4542 $reply['headlines-info'] = array("count" => 0,
4543 "vgroup_last_feed" => '',
4545 "disable_cache" => true);
4551 function generate_dashboard_feed($link) {
4554 $reply['headlines']['id'] = -5;
4555 $reply['headlines']['is_cat'] = false;
4557 $reply['headlines']['toolbar'] = '';
4558 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4560 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4562 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4563 WHERE owner_uid = " . $_SESSION['uid']);
4565 $last_updated = db_fetch_result($result, 0, "last_updated");
4566 $last_updated = make_local_datetime($link, $last_updated, false);
4568 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4570 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4571 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4573 $num_errors = db_fetch_result($result, 0, "num_errors");
4575 if ($num_errors > 0) {
4576 $reply['headlines']['content'] .= "<br/>";
4577 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4578 __('Some feeds have update errors (click for details)')."</a>";
4580 $reply['headlines']['content'] .= "</span></p>";
4582 $reply['headlines-info'] = array("count" => 0,
4583 "vgroup_last_feed" => '',
4585 "disable_cache" => true);
4590 function save_email_address($link, $email) {
4591 // FIXME: implement persistent storage of emails
4593 if (!$_SESSION['stored_emails'])
4594 $_SESSION['stored_emails'] = array();
4596 if (!in_array($email, $_SESSION['stored_emails']))
4597 array_push($_SESSION['stored_emails'], $email);
4600 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4601 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4603 $sql_is_cat = bool_to_sql_bool($is_cat);
4605 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4606 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4607 AND owner_uid = " . $owner_uid);
4609 if (db_num_rows($result) == 1) {
4610 $key = db_escape_string(sha1(uniqid(rand(), true)));
4612 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4613 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4614 AND owner_uid = " . $owner_uid);
4619 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4623 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4625 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4627 $sql_is_cat = bool_to_sql_bool($is_cat);
4629 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4630 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4631 AND owner_uid = " . $owner_uid);
4633 if (db_num_rows($result) == 1) {
4634 return db_fetch_result($result, 0, "access_key");
4636 $key = db_escape_string(sha1(uniqid(rand(), true)));
4638 $result = db_query($link, "INSERT INTO ttrss_access_keys
4639 (access_key, feed_id, is_cat, owner_uid)
4640 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4648 * Extracts RSS/Atom feed URLs from the given HTML URL.
4650 * @param string $url HTML page URL
4652 * @return array Array of feeds. Key is the full URL, value the title
4654 function get_feeds_from_html($url, $login = false, $pass = false)
4656 $url = fix_url($url);
4657 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4659 libxml_use_internal_errors(true);
4661 $content = @fetch_file_contents
($url, false, $login, $pass);
4663 $doc = new DOMDocument();
4664 $doc->loadHTML($content);
4665 $xpath = new DOMXPath($doc);
4666 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4667 $feedUrls = array();
4668 foreach ($entries as $entry) {
4669 if ($entry->hasAttribute('href')) {
4670 $title = $entry->getAttribute('title');
4672 $title = $entry->getAttribute('type');
4674 $feedUrl = rewrite_relative_url(
4675 $baseUrl, $entry->getAttribute('href')
4677 $feedUrls[$feedUrl] = $title;
4684 * Checks if the content behind the given URL is a HTML file
4686 * @param string $url URL to check
4688 * @return boolean True if the URL contains HTML content
4690 function url_is_html($url, $login = false, $pass = false) {
4691 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
4693 if (stripos($content, '<html>') === false
4694 && stripos($content, '<html ') === false
4702 function print_label_select($link, $name, $value, $attributes = "") {
4704 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4705 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4707 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4708 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4710 while ($line = db_fetch_assoc($result)) {
4712 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4714 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4715 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4719 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4726 function format_article_enclosures($link, $id, $always_display_enclosures,
4729 $result = get_article_enclosures($link, $id);
4732 if (count($result) > 0) {
4734 $entries_html = array();
4737 foreach ($result as $line) {
4739 $url = $line["content_url"];
4740 $ctype = $line["content_type"];
4742 if (!$ctype) $ctype = __("unknown type");
4744 $filename = substr($url, strrpos($url, "/")+
1);
4746 # $player = format_inline_player($link, $url, $ctype);
4748 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4749 # $filename . " (" . $ctype . ")" . "</a>";
4751 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4752 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4754 array_push($entries_html, $entry);
4758 $entry["type"] = $ctype;
4759 $entry["filename"] = $filename;
4760 $entry["url"] = $url;
4762 array_push($entries, $entry);
4765 if (!get_pref($link, "STRIP_IMAGES")) {
4766 if ($always_display_enclosures ||
4767 !preg_match("/<img/i", $article_content)) {
4769 foreach ($entries as $entry) {
4771 if (preg_match("/image/", $entry["type"]) ||
4772 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4775 alt=\"".htmlspecialchars($entry["filename"])."\"
4776 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4783 $rv .= "<div dojoType=\"dijit.form.DropDownButton\">".
4784 "<span>" . __('Attachments')."</span>";
4785 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4787 foreach ($entries_html as $entry) { $rv .= $entry; };
4789 $rv .= "</div></div>";
4795 function getLastArticleId($link) {
4796 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4797 WHERE owner_uid = " . $_SESSION["uid"]);
4799 if (db_num_rows($result) == 1) {
4800 return db_fetch_result($result, 0, "id");
4806 function build_url($parts) {
4807 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4811 * Converts a (possibly) relative URL to a absolute one.
4813 * @param string $url Base URL (i.e. from where the document is)
4814 * @param string $rel_url Possibly relative URL in the document
4816 * @return string Absolute URL
4818 function rewrite_relative_url($url, $rel_url) {
4819 if (strpos($rel_url, "magnet:") === 0) {
4821 } else if (strpos($rel_url, "://") !== false) {
4823 } else if (strpos($rel_url, "//") === 0) {
4824 # protocol-relative URL (rare but they exist)
4826 } else if (strpos($rel_url, "/") === 0)
4828 $parts = parse_url($url);
4829 $parts['path'] = $rel_url;
4831 return build_url($parts);
4834 $parts = parse_url($url);
4835 if (!isset($parts['path'])) {
4836 $parts['path'] = '/';
4838 $dir = $parts['path'];
4839 if (substr($dir, -1) !== '/') {
4840 $dir = dirname($parts['path']);
4841 $dir !== '/' && $dir .= '/';
4843 $parts['path'] = $dir . $rel_url;
4845 return build_url($parts);
4849 function sphinx_search($query, $offset = 0, $limit = 30) {
4850 require_once 'lib/sphinxapi.php';
4852 $sphinxClient = new SphinxClient();
4854 $sphinxClient->SetServer('localhost', 9312);
4855 $sphinxClient->SetConnectTimeout(1);
4857 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4858 'feed_title' => 20));
4860 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4861 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4862 $sphinxClient->SetLimits($offset, $limit, 1000);
4863 $sphinxClient->SetArrayResult(false);
4864 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4866 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4870 if (is_array($result['matches'])) {
4871 foreach (array_keys($result['matches']) as $int_id) {
4872 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4873 array_push($ids, $ref_id);
4880 function cleanup_tags($link, $days = 14, $limit = 1000) {
4882 if (DB_TYPE
== "pgsql") {
4883 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4884 } else if (DB_TYPE
== "mysql") {
4885 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4890 while ($limit > 0) {
4893 $query = "SELECT ttrss_tags.id AS id
4894 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4895 WHERE post_int_id = int_id AND $interval_query AND
4896 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4898 $result = db_query($link, $query);
4902 while ($line = db_fetch_assoc($result)) {
4903 array_push($ids, $line['id']);
4906 if (count($ids) > 0) {
4907 $ids = join(",", $ids);
4910 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4911 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4916 $limit -= $limit_part;
4921 return $tags_deleted;
4924 function print_user_stylesheet($link) {
4925 $value = get_pref($link, 'USER_STYLESHEET');
4928 print "<style type=\"text/css\">";
4929 print str_replace("<br/>", "\n", $value);
4935 /* function rewrite_urls($line) {
4940 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4941 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4946 function rewrite_urls($html) {
4947 libxml_use_internal_errors(true);
4949 $charset_hack = '<head>
4950 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4953 $doc = new DOMDocument();
4954 $doc->loadHTML($charset_hack . $html);
4955 $xpath = new DOMXPath($doc);
4957 $entries = $xpath->query('//*/text()');
4959 foreach ($entries as $entry) {
4960 if (strstr($entry->wholeText
, "://") !== false) {
4961 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4962 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4964 if ($text != $entry->wholeText
) {
4965 $cdoc = new DOMDocument();
4966 $cdoc->loadHTML($charset_hack . $text);
4969 foreach ($cdoc->childNodes
as $cnode) {
4970 $cnode = $doc->importNode($cnode, true);
4973 $entry->parentNode
->insertBefore($cnode);
4977 $entry->parentNode
->removeChild($entry);
4983 $node = $doc->getElementsByTagName('body')->item(0);
4985 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4987 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4992 function filter_to_sql($filter) {
4995 $regexp_valid = preg_match('/' . $filter['reg_exp'] . '/',
4996 $filter['reg_exp']) !== FALSE;
4998 if ($regexp_valid) {
5000 if (DB_TYPE
== "pgsql")
5003 $reg_qpart = "REGEXP";
5005 switch ($filter["type"]) {
5007 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
5008 $filter['reg_exp'] . "')";
5011 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
5012 $filter['reg_exp'] . "')";
5015 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
5016 $filter['reg_exp'] . "') OR LOWER(" .
5017 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
5020 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
5021 $filter['reg_exp'] . "')";
5024 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
5025 $filter['reg_exp'] . "')";
5029 if ($filter["filter_param"] == "before")
5034 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
5035 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
5038 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
5039 $filter['reg_exp'] . "')";
5043 if ($filter["inverse"])
5044 $query = "NOT ($query)";
5047 if (DB_TYPE
== "pgsql") {
5048 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
5050 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
5062 // -1 - never connected
5063 // 0 - no data received
5064 // 1 - data received successfully
5065 // 2 - did not receive valid data
5066 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5068 function get_linked_feeds($link, $instance_id = false) {
5070 $instance_qpart = "id = '$instance_id' AND ";
5072 $instance_qpart = "";
5074 if (DB_TYPE
== "pgsql") {
5075 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5077 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5080 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5081 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5083 while ($line = db_fetch_assoc($result)) {
5086 _debug("Updating: " . $line['access_url'] . " ($id)");
5088 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5089 $post_query = 'key=' . $line['access_key'];
5091 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5093 // try doing it the old way
5095 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5096 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5100 $feeds = json_decode($feeds, true);
5103 if ($feeds['error']) {
5104 $status = $feeds['error']['code'] +
10;
5108 if (count($feeds['feeds']) > 0) {
5110 db_query($link, "DELETE FROM ttrss_linked_feeds
5111 WHERE instance_id = '$id'");
5113 foreach ($feeds['feeds'] as $feed) {
5114 $feed_url = db_escape_string($feed['feed_url']);
5115 $title = db_escape_string($feed['title']);
5116 $subscribers = db_escape_string($feed['subscribers']);
5117 $site_url = db_escape_string($feed['site_url']);
5119 db_query($link, "INSERT INTO ttrss_linked_feeds
5120 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5122 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5125 // received 0 feeds, this might indicate that
5126 // the instance on the other hand is rebuilding feedbrowser cache
5127 // we will try again later
5129 // TODO: maybe perform expiration based on updated here?
5132 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5142 _debug("Status: $status");
5144 db_query($link, "UPDATE ttrss_linked_instances SET
5145 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5150 function make_feed_browser($link, $search, $limit, $mode = 1) {
5152 $owner_uid = $_SESSION["uid"];
5156 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5157 UPPER(title) LIKE UPPER('%$search%'))";
5163 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5164 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5165 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5166 AND owner_uid = '$owner_uid') $search_qpart
5167 ORDER BY subscribers DESC LIMIT $limit"); */
5169 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5170 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5171 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5173 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5174 WHERE tf.feed_url = qqq.feed_url
5175 AND owner_uid = '$owner_uid') $search_qpart
5176 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5178 } else if ($mode == 2) {
5179 $result = db_query($link, "SELECT *,
5180 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5181 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5183 ttrss_archived_feeds
5185 (SELECT COUNT(*) FROM ttrss_feeds
5186 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5187 owner_uid = '$owner_uid') = 0 AND
5188 owner_uid = '$owner_uid' $search_qpart
5189 ORDER BY id DESC LIMIT $limit");
5194 while ($line = db_fetch_assoc($result)) {
5198 $feed_url = htmlspecialchars($line["feed_url"]);
5199 $site_url = htmlspecialchars($line["site_url"]);
5200 $subscribers = $line["subscribers"];
5202 $check_box = "<input onclick='toggleSelectListRow2(this)'
5203 dojoType=\"dijit.form.CheckBox\"
5204 type=\"checkbox\" \">";
5206 $class = ($feedctr %
2) ?
"even" : "odd";
5208 $site_url = "<a target=\"_blank\"
5210 <span class=\"fb_feedTitle\">".
5211 htmlspecialchars($line["title"])."</span></a>";
5213 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5214 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5215 style='vertical-align : middle'></a>";
5217 $rv .= "<li>$check_box $feed_url $site_url".
5218 " <span class='subscribers'>($subscribers)</span></li>";
5220 } else if ($mode == 2) {
5221 $feed_url = htmlspecialchars($line["feed_url"]);
5222 $site_url = htmlspecialchars($line["site_url"]);
5223 $title = htmlspecialchars($line["title"]);
5225 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5226 type=\"checkbox\">";
5228 $class = ($feedctr %
2) ?
"even" : "odd";
5230 if ($line['articles_archived'] > 0) {
5231 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5232 $archived = " <span class='subscribers'>($archived)</span>";
5237 $site_url = "<a target=\"_blank\"
5239 <span class=\"fb_feedTitle\">".
5240 htmlspecialchars($line["title"])."</span></a>";
5242 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5243 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5244 style='vertical-align : middle'></a>";
5247 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5248 "$check_box $feed_url $site_url $archived</li>";
5254 if ($feedctr == 0) {
5255 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5261 if (!function_exists('gzdecode')) {
5262 function gzdecode($string) { // no support for 2nd argument
5263 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5264 base64_encode($string));
5268 function perform_data_import($link, $filename, $owner_uid) {
5272 $num_feeds_created = 0;
5274 $doc = @DOMDocument
::load($filename);
5277 $contents = file_get_contents($filename);
5280 $data = @gzuncompress
($contents);
5284 $data = @gzdecode
($contents);
5288 $doc = DOMDocument
::loadXML($data);
5293 $xpath = new DOMXpath($doc);
5295 $container = $doc->firstChild
;
5297 if ($container && $container->hasAttribute('schema-version')) {
5298 $schema_version = $container->getAttribute('schema-version');
5300 if ($schema_version != SCHEMA_VERSION
) {
5301 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5306 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5310 $articles = $xpath->query("//article");
5312 foreach ($articles as $article_node) {
5313 if ($article_node->childNodes
) {
5319 foreach ($article_node->childNodes
as $child) {
5320 if ($child->nodeName
!= 'label_cache')
5321 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5323 $article[$child->nodeName
] = $child->nodeValue
;
5326 //print_r($article);
5328 if ($article['guid']) {
5332 //db_query($link, "BEGIN");
5334 //print 'GUID:' . $article['guid'] . "\n";
5336 $result = db_query($link, "SELECT id FROM ttrss_entries
5337 WHERE guid = '".$article['guid']."'");
5339 if (db_num_rows($result) == 0) {
5341 $result = db_query($link,
5342 "INSERT INTO ttrss_entries
5356 ('".$article['title']."',
5357 '".$article['guid']."',
5358 '".$article['link']."',
5359 '".$article['updated']."',
5360 '".$article['content']."',
5361 '".sha1($article['content'])."',
5369 $result = db_query($link, "SELECT id FROM ttrss_entries
5370 WHERE guid = '".$article['guid']."'");
5372 if (db_num_rows($result) != 0) {
5373 $ref_id = db_fetch_result($result, 0, "id");
5377 $ref_id = db_fetch_result($result, 0, "id");
5380 //print "Got ref ID: $ref_id\n";
5384 $feed_url = $article['feed_url'];
5385 $feed_title = $article['feed_title'];
5389 if ($feed_url && $feed_title) {
5390 $result = db_query($link, "SELECT id FROM ttrss_feeds
5391 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5393 if (db_num_rows($result) != 0) {
5394 $feed = db_fetch_result($result, 0, "id");
5396 // try autocreating feed in Uncategorized...
5398 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5399 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5401 $result = db_query($link, "SELECT id FROM ttrss_feeds
5402 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5404 if (db_num_rows($result) != 0) {
5405 ++
$num_feeds_created;
5407 $feed = db_fetch_result($result, 0, "id");
5412 if ($feed != 'NULL')
5413 $feed_qpart = "feed_id = $feed";
5415 $feed_qpart = "feed_id IS NULL";
5417 //print "$ref_id / $feed / " . $article['title'] . "\n";
5419 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5420 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5422 if (db_num_rows($result) == 0) {
5424 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5425 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5426 $score = (int) $article['score'];
5428 $tag_cache = $article['tag_cache'];
5429 $label_cache = db_escape_string($article['label_cache']);
5430 $note = $article['note'];
5432 //print "Importing " . $article['title'] . "<br/>";
5436 $result = db_query($link,
5437 "INSERT INTO ttrss_user_entries
5438 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5439 published, score, tag_cache, label_cache, uuid, note)
5440 VALUES ($ref_id, $owner_uid, $feed, false,
5441 NULL, $marked, $published, $score, '$tag_cache',
5442 '$label_cache', '', '$note')");
5444 $label_cache = json_decode($label_cache, true);
5446 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5447 foreach ($label_cache as $label) {
5449 label_create($link, $label[1],
5450 $label[2], $label[3], $owner_uid);
5452 label_add_article($link, $ref_id, $label[1], $owner_uid);
5457 //db_query($link, "COMMIT");
5465 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5466 $num_processed, $num_imported, $num_feeds_created) .
5471 print "<p>" . __("Could not load XML document.") . "</p>";
5476 function get_random_bytes($length) {
5477 if (function_exists('openssl_random_pseudo_bytes')) {
5478 return openssl_random_pseudo_bytes($length);
5482 for ($i = 0; $i < $length; $i++
)
5483 $output .= chr(mt_rand(0, 255));
5489 function read_stdin() {
5490 $fp = fopen("php://stdin", "r");
5493 $line = trim(fgets($fp));