2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 100);
5 $fetch_last_error = false;
8 function __autoload($class) {
9 $class_file = str_replace("_", "/", strtolower(basename($class)));
11 $file = dirname(__FILE__
)."/../classes/$class_file.php";
13 if (file_exists($file)) {
19 mb_internal_encoding("UTF-8");
20 date_default_timezone_set('UTC');
21 if (defined('E_DEPRECATED')) {
22 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
24 error_reporting(E_ALL
& ~E_NOTICE
);
27 require_once 'config.php';
29 if (DB_TYPE
== "pgsql") {
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
32 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
35 define('THEME_VERSION_REQUIRED', 1.1);
38 * Return available translations names.
41 * @return array A array of available translations.
43 function get_translations() {
45 "auto" => "Detect automatically",
50 "fr_FR" => "Français",
51 "hu_HU" => "Magyar (Hungarian)",
52 "it_IT" => "Italiano",
53 "ja_JP" => "日本語 (Japanese)",
54 "nb_NO" => "Norwegian bokmål",
57 "pt_BR" => "Portuguese/Brazil",
58 "zh_CN" => "Simplified Chinese");
63 require_once "lib/accept-to-gettext.php";
64 require_once "lib/gettext/gettext.inc";
66 function startup_gettext() {
68 # Get locale from Accept-Language header
69 $lang = al2gt(array_keys(get_translations()), "text/html");
71 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
72 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
75 /* In login action of mobile version */
76 if ($_POST["language"] && defined('MOBILE_VERSION')) {
77 $lang = $_POST["language"];
79 $lang = $_SESSION["language"];
83 if (defined('LC_MESSAGES')) {
84 _setlocale(LC_MESSAGES
, $lang);
85 } else if (defined('LC_ALL')) {
86 _setlocale(LC_ALL
, $lang);
89 if (defined('MOBILE_VERSION')) {
90 _bindtextdomain("messages", "../locale");
92 _bindtextdomain("messages", "locale");
95 _textdomain("messages");
96 _bind_textdomain_codeset("messages", "UTF-8");
102 require_once 'db-prefs.php';
103 require_once 'version.php';
105 ini_set('user_agent', SELF_USER_AGENT
);
107 require_once 'lib/pubsubhubbub/publisher.php';
108 require_once 'lib/htmLawed.php';
111 $utc_tz = new DateTimeZone('UTC');
112 $schema_version = false;
115 * Print a timestamped debug message.
117 * @param string $msg The debug message.
120 function _debug($msg) {
121 if (defined('QUIET') && QUIET
) {
124 $ts = strftime("%H:%M:%S", time());
125 if (function_exists('posix_getpid')) {
126 $ts = "$ts/" . posix_getpid();
128 print "[$ts] $msg\n";
132 * Purge a feed old posts.
134 * @param mixed $link A database connection.
135 * @param mixed $feed_id The id of the purged feed.
136 * @param mixed $purge_interval Olderness of purged posts.
137 * @param boolean $debug Set to True to enable the debug. False by default.
141 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
143 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
147 $result = db_query($link,
148 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
152 if (db_num_rows($result) == 1) {
153 $owner_uid = db_fetch_result($result, 0, "owner_uid");
156 if ($purge_interval == -1 ||
!$purge_interval) {
158 ccache_update($link, $feed_id, $owner_uid);
163 if (!$owner_uid) return;
165 if (FORCE_ARTICLE_PURGE
== 0) {
166 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
169 $purge_unread = true;
170 $purge_interval = FORCE_ARTICLE_PURGE
;
173 if (!$purge_unread) $query_limit = " unread = false AND ";
175 if (DB_TYPE
== "pgsql") {
176 $pg_version = get_pgsql_version($link);
178 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
180 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
181 ttrss_entries.id = ref_id AND
183 feed_id = '$feed_id' AND
185 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
189 $result = db_query($link, "DELETE FROM ttrss_user_entries
191 WHERE ttrss_entries.id = ref_id AND
193 feed_id = '$feed_id' AND
195 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
198 $rows = pg_affected_rows($result);
202 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
203 marked = false AND feed_id = '$feed_id' AND
204 (SELECT date_updated FROM ttrss_entries WHERE
205 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
207 $result = db_query($link, "DELETE FROM ttrss_user_entries
208 USING ttrss_user_entries, ttrss_entries
209 WHERE ttrss_entries.id = ref_id AND
211 feed_id = '$feed_id' AND
213 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
215 $rows = mysql_affected_rows($link);
219 ccache_update($link, $feed_id, $owner_uid);
222 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
224 } // function purge_feed
226 function feed_purge_interval($link, $feed_id) {
228 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
229 WHERE id = '$feed_id'");
231 if (db_num_rows($result) == 1) {
232 $purge_interval = db_fetch_result($result, 0, "purge_interval");
233 $owner_uid = db_fetch_result($result, 0, "owner_uid");
235 if ($purge_interval == 0) $purge_interval = get_pref($link,
236 'PURGE_OLD_DAYS', $owner_uid);
238 return $purge_interval;
245 function purge_orphans($link, $do_output = false) {
247 // purge orphaned posts in main content table
248 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
249 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
252 $rows = db_affected_rows($link, $result);
253 _debug("Purged $rows orphaned posts.");
257 function get_feed_update_interval($link, $feed_id) {
258 $result = db_query($link, "SELECT owner_uid, update_interval FROM
259 ttrss_feeds WHERE id = '$feed_id'");
261 if (db_num_rows($result) == 1) {
262 $update_interval = db_fetch_result($result, 0, "update_interval");
263 $owner_uid = db_fetch_result($result, 0, "owner_uid");
265 if ($update_interval != 0) {
266 return $update_interval;
268 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
276 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
277 $login = urlencode($login);
278 $pass = urlencode($pass);
280 global $fetch_last_error;
282 if (function_exists('curl_init') && !ini_get("open_basedir")) {
283 $ch = curl_init($url);
285 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
286 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
287 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
288 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
289 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
290 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
291 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
292 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
293 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
294 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
297 curl_setopt($ch, CURLOPT_POST
, true);
298 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
302 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
304 $contents = @curl_exec
($ch);
306 if ($contents === false) {
307 $fetch_last_error = curl_error($ch);
312 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
313 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
316 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
322 if ($login && $pass ){
323 $url_parts = array();
325 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
327 if ($url_parts[1] && $url_parts[2]) {
328 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
332 $data = @file_get_contents
($url);
334 if (!$data && function_exists('error_get_last')) {
335 $error = error_get_last();
336 $fetch_last_error = $error["message"];
344 * Try to determine the favicon URL for a feed.
345 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
346 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
348 * @param string $url A feed or page URL
350 * @return mixed The favicon URL, or false if none was found.
352 function get_favicon_url($url) {
354 $favicon_url = false;
356 if ($html = @fetch_file_contents
($url)) {
358 libxml_use_internal_errors(true);
360 $doc = new DOMDocument();
361 $doc->loadHTML($html);
362 $xpath = new DOMXPath($doc);
364 $base = $xpath->query('/html/head/base');
365 foreach ($base as $b) {
366 $url = $b->getAttribute("href");
370 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
371 if (count($entries) > 0) {
372 foreach ($entries as $entry) {
373 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
380 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
383 } // function get_favicon_url
385 function check_feed_favicon($site_url, $feed, $link) {
386 # print "FAVICON [$site_url]: $favicon_url\n";
388 $icon_file = ICONS_DIR
. "/$feed.ico";
390 if (!file_exists($icon_file)) {
391 $favicon_url = get_favicon_url($site_url);
394 // Limiting to "image" type misses those served with text/plain
395 $contents = fetch_file_contents($favicon_url); // , "image");
398 // Crude image type matching.
399 // Patterns gleaned from the file(1) source code.
400 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
401 // 0 string \000\000\001\000 MS Windows icon resource
402 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
404 elseif (preg_match('/^GIF8/', $contents)) {
405 // 0 string GIF8 GIF image data
406 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
408 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
409 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
410 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
412 elseif (preg_match('/^\xff\xd8/', $contents)) {
413 // 0 beshort 0xffd8 JPEG image data
414 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
423 $fp = @fopen
($icon_file, "w");
426 fwrite($fp, $contents);
428 chmod($icon_file, 0644);
435 function print_select($id, $default, $values, $attributes = "") {
436 print "<select name=\"$id\" id=\"$id\" $attributes>";
437 foreach ($values as $v) {
439 $sel = "selected=\"1\"";
443 print "<option value=\"$v\" $sel>$v</option>";
448 function print_select_hash($id, $default, $values, $attributes = "") {
449 print "<select name=\"$id\" id='$id' $attributes>";
450 foreach (array_keys($values) as $v) {
452 $sel = 'selected="selected"';
456 print "<option $sel value=\"$v\">".$values[$v]."</option>";
462 function getmicrotime() {
463 list($usec, $sec) = explode(" ",microtime());
464 return ((float)$usec +
(float)$sec);
467 function print_radio($id, $default, $true_is, $values, $attributes = "") {
468 foreach ($values as $v) {
475 if ($v == $true_is) {
476 $sel .= " value=\"1\"";
478 $sel .= " value=\"0\"";
481 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
482 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
487 function initialize_user_prefs($link, $uid, $profile = false) {
489 $uid = db_escape_string($uid);
493 $profile_qpart = "AND profile IS NULL";
495 $profile_qpart = "AND profile = '$profile'";
498 if (get_schema_version($link) < 63) $profile_qpart = "";
500 db_query($link, "BEGIN");
502 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
504 $u_result = db_query($link, "SELECT pref_name
505 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
507 $active_prefs = array();
509 while ($line = db_fetch_assoc($u_result)) {
510 array_push($active_prefs, $line["pref_name"]);
513 while ($line = db_fetch_assoc($result)) {
514 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
515 // print "adding " . $line["pref_name"] . "<br>";
517 if (get_schema_version($link) < 63) {
518 db_query($link, "INSERT INTO ttrss_user_prefs
519 (owner_uid,pref_name,value) VALUES
520 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
523 db_query($link, "INSERT INTO ttrss_user_prefs
524 (owner_uid,pref_name,value, profile) VALUES
525 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
531 db_query($link, "COMMIT");
535 function get_ssl_certificate_id() {
536 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
537 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
538 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
539 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
540 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
545 function authenticate_user($link, $login, $password, $check_only = false) {
547 if (!SINGLE_USER_MODE
) {
550 $modules = explode(",", AUTH_MODULES
);
552 foreach ($modules as $module) {
553 $module_class = "auth_$module";
554 if (class_exists($module_class)) {
555 $authenticator = new $module_class($link);
557 $user_id = (int) $authenticator->authenticate($login, $password);
560 $_SESSION["auth_module"] = $module;
565 print T_sprintf("Fatal: authentication module %s not found.", $module);
570 if ($user_id && !$check_only) {
571 $_SESSION["uid"] = $user_id;
573 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
574 WHERE id = '$user_id'");
576 $_SESSION["name"] = db_fetch_result($result, 0, "login");
577 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
578 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
580 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
583 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
584 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
586 $_SESSION["last_version_check"] = time();
588 initialize_user_prefs($link, $_SESSION["uid"]);
597 $_SESSION["uid"] = 1;
598 $_SESSION["name"] = "admin";
599 $_SESSION["access_level"] = 10;
601 $_SESSION["hide_hello"] = true;
602 $_SESSION["hide_logout"] = true;
604 $_SESSION["auth_module"] = false;
606 if (!$_SESSION["csrf_token"]) {
607 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
610 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
612 initialize_user_prefs($link, $_SESSION["uid"]);
618 function make_password($length = 8) {
621 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
625 while ($i < $length) {
626 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
628 if (!strstr($password, $char)) {
636 // this is called after user is created to initialize default feeds, labels
639 // user preferences are checked on every login, not here
641 function initialize_user($link, $uid) {
643 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
644 values ('$uid', 'Tiny Tiny RSS: New Releases',
645 'http://tt-rss.org/releases.rss')");
647 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
648 values ('$uid', 'Tiny Tiny RSS: Forum',
649 'http://tt-rss.org/forum/rss.php')");
652 function logout_user() {
654 if (isset($_COOKIE[session_name()])) {
655 setcookie(session_name(), '', time()-42000, '/');
659 function validate_csrf($csrf_token) {
660 return $csrf_token == $_SESSION['csrf_token'];
663 function validate_session($link) {
664 if (SINGLE_USER_MODE
) return true;
666 $check_ip = $_SESSION['ip_address'];
668 switch (SESSION_CHECK_ADDRESS
) {
673 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
676 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
677 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
681 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
682 $_SESSION["login_error_msg"] =
683 __("Session failed to validate (incorrect IP)");
687 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
690 if ($_SESSION["uid"]) {
692 $result = db_query($link,
693 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
695 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
697 if ($pwd_hash != $_SESSION["pwd_hash"]) {
702 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
704 //print_r($_SESSION);
706 if (time() > $_SESSION["cookie_lifetime"]) {
714 function load_user_plugins($link, $owner_uid) {
716 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
719 $pluginhost->load($plugins);
723 function login_sequence($link, $login_form = 0) {
724 if (SINGLE_USER_MODE
) {
725 authenticate_user($link, "admin", null);
726 load_user_plugins($link, $_SESSION["uid"]);
728 if (!$_SESSION["uid"] ||
!validate_session($link)) {
730 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
731 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
733 authenticate_user($link, null, null, true);
736 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
739 /* bump login timestamp */
740 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
744 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
745 setcookie("ttrss_lang", $_SESSION["language"],
746 time() + SESSION_COOKIE_LIFETIME
);
749 if ($_SESSION["uid"]) {
750 load_user_plugins($link, $_SESSION["uid"]);
755 function truncate_string($str, $max_len, $suffix = '…') {
756 if (mb_strlen($str, "utf-8") > $max_len - 3) {
757 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
763 function theme_image($link, $filename) {
765 $theme_path = get_user_theme_path($link);
767 if ($theme_path && is_file($theme_path.$filename)) {
768 return $theme_path.$filename;
777 function get_user_theme($link) {
779 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
780 $theme_name = get_pref($link, "_THEME_ID");
781 if (is_dir("themes/$theme_name")) {
792 function get_user_theme_path($link) {
795 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
796 $theme_name = get_pref($link, "_THEME_ID");
798 if ($theme_name && is_dir("themes/$theme_name")) {
799 $theme_path = "themes/$theme_name/";
808 if (is_file("$theme_path/theme.ini")) {
809 $ini = parse_ini_file("$theme_path/theme.ini", true);
810 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
818 function get_user_theme_options($link) {
819 $t = get_user_theme_path($link);
822 if (is_file("$t/theme.ini")) {
823 $ini = parse_ini_file("$t/theme.ini", true);
824 if ($ini['theme']['version']) {
825 return $ini['theme']['options'];
832 function print_theme_includes($link) {
834 $t = get_user_theme_path($link);
838 print "<link rel=\"stylesheet\" type=\"text/css\"
839 href=\"$t/theme.css?$time \">";
840 if (file_exists("$t/theme.js")) {
841 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
847 function get_all_themes() {
848 $themes = glob("themes/*");
854 foreach ($themes as $t) {
855 if (is_file("$t/theme.ini")) {
856 $ini = parse_ini_file("$t/theme.ini", true);
857 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
858 !$ini['theme']['disabled']) {
861 $entry["base"] = basename($t);
862 $entry["name"] = $ini['theme']['name'];
863 $entry["version"] = $ini['theme']['version'];
864 $entry["author"] = $ini['theme']['author'];
865 $entry["options"] = $ini['theme']['options'];
866 array_push($rv, $entry);
874 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
877 $source_tz = new DateTimeZone($source_tz);
878 } catch (Exception
$e) {
879 $source_tz = new DateTimeZone('UTC');
883 $dest_tz = new DateTimeZone($dest_tz);
884 } catch (Exception
$e) {
885 $dest_tz = new DateTimeZone('UTC');
888 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
889 return $dt->format('U') +
$dest_tz->getOffset($dt);
892 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
893 $no_smart_dt = false) {
895 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
896 if (!$timestamp) $timestamp = '1970-01-01 0:00';
901 # We store date in UTC internally
902 $dt = new DateTime($timestamp, $utc_tz);
904 if ($tz_offset == -1) {
906 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
909 $user_tz = new DateTimeZone($user_tz_string);
910 } catch (Exception
$e) {
914 $tz_offset = $user_tz->getOffset($dt);
917 $user_timestamp = $dt->format('U') +
$tz_offset;
920 return smart_date_time($link, $user_timestamp,
921 $tz_offset, $owner_uid);
924 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
926 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
928 return date($format, $user_timestamp);
932 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
933 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
935 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
936 return date("G:i", $timestamp);
937 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
938 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
939 return date($format, $timestamp);
941 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
942 return date($format, $timestamp);
946 function sql_bool_to_bool($s) {
947 if ($s == "t" ||
$s == "1" ||
$s == "true") {
954 function bool_to_sql_bool($s) {
962 // Session caching removed due to causing wrong redirects to upgrade
963 // script when get_schema_version() is called on an obsolete session
964 // created on a previous schema version.
965 function get_schema_version($link, $nocache = false) {
966 global $schema_version;
968 if (!$schema_version) {
969 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
970 $version = db_fetch_result($result, 0, "schema_version");
971 $schema_version = $version;
974 return $schema_version;
978 function sanity_check($link) {
979 require_once 'errors.php';
982 $schema_version = get_schema_version($link, true);
984 if ($schema_version != SCHEMA_VERSION
) {
988 if (DB_TYPE
== "mysql") {
989 $result = db_query($link, "SELECT true", false);
990 if (db_num_rows($result) != 1) {
995 if (db_escape_string("testTEST") != "testTEST") {
999 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1002 function file_is_locked($filename) {
1003 if (function_exists('flock')) {
1004 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1006 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1007 flock($fp, LOCK_UN
);
1017 return true; // consider the file always locked and skip the test
1020 function make_lockfile($filename) {
1021 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1023 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1024 if (function_exists('posix_getpid')) {
1025 fwrite($fp, posix_getpid() . "\n");
1033 function make_stampfile($filename) {
1034 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1036 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1037 fwrite($fp, time() . "\n");
1038 flock($fp, LOCK_UN
);
1046 function sql_random_function() {
1047 if (DB_TYPE
== "mysql") {
1054 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1056 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1058 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1060 $ref_check_qpart = ($max_id &&
1061 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1063 if (is_numeric($feed)) {
1069 $children = getChildCategories($link, $feed, $owner_uid);
1070 array_push($children, $feed);
1072 $children = join(",", $children);
1074 $cat_qpart = "cat_id IN ($children)";
1076 $cat_qpart = "cat_id IS NULL";
1079 db_query($link, "UPDATE ttrss_user_entries
1080 SET unread = false,last_read = NOW()
1081 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1082 AND $ref_check_qpart
1083 AND owner_uid = $owner_uid");
1085 } else if ($feed == -2) {
1087 db_query($link, "UPDATE ttrss_user_entries
1088 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1089 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1090 AND $ref_check_qpart
1091 AND unread = true AND owner_uid = $owner_uid");
1094 } else if ($feed > 0) {
1096 db_query($link, "UPDATE ttrss_user_entries
1097 SET unread = false,last_read = NOW()
1098 WHERE feed_id = '$feed'
1099 AND $ref_check_qpart
1100 AND owner_uid = $owner_uid");
1102 } else if ($feed < 0 && $feed > -10) { // special, like starred
1105 db_query($link, "UPDATE ttrss_user_entries
1106 SET unread = false,last_read = NOW()
1108 AND $ref_check_qpart
1109 AND owner_uid = $owner_uid");
1113 db_query($link, "UPDATE ttrss_user_entries
1114 SET unread = false,last_read = NOW()
1115 WHERE published = true
1116 AND $ref_check_qpart
1117 AND owner_uid = $owner_uid");
1122 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1124 if (DB_TYPE
== "pgsql") {
1125 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1127 $match_part = "updated > DATE_SUB(NOW(),
1128 INTERVAL $intl HOUR) ";
1131 $result = db_query($link, "SELECT id FROM ttrss_entries,
1132 ttrss_user_entries WHERE $match_part AND
1134 ttrss_user_entries.ref_id = ttrss_entries.id AND
1135 owner_uid = $owner_uid");
1137 $affected_ids = array();
1139 while ($line = db_fetch_assoc($result)) {
1140 array_push($affected_ids, $line["id"]);
1143 catchupArticlesById($link, $affected_ids, 0);
1147 db_query($link, "UPDATE ttrss_user_entries
1148 SET unread = false,last_read = NOW()
1149 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1152 } else if ($feed < -10) { // label
1154 $label_id = -$feed - 11;
1156 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1157 SET unread = false, last_read = NOW()
1158 WHERE label_id = '$label_id' AND unread = true
1159 AND $ref_check_qpart
1160 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1164 ccache_update($link, $feed, $owner_uid, $cat_view);
1167 db_query($link, "BEGIN");
1169 $tag_name = db_escape_string($feed);
1171 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1172 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1174 while ($line = db_fetch_assoc($result)) {
1175 db_query($link, "UPDATE ttrss_user_entries SET
1176 unread = false, last_read = NOW()
1177 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1179 db_query($link, "COMMIT");
1183 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1185 if (!$omode) $omode = "flc";
1187 $data = getGlobalCounters($link);
1189 $data = array_merge($data, getVirtCounters($link));
1191 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1192 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1193 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1194 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1199 function getCategoryTitle($link, $cat_id) {
1201 if ($cat_id == -1) {
1202 return __("Special");
1203 } else if ($cat_id == -2) {
1204 return __("Labels");
1207 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1210 if (db_num_rows($result) == 1) {
1211 return db_fetch_result($result, 0, "title");
1213 return __("Uncategorized");
1219 function getCategoryCounters($link) {
1222 /* Labels category */
1224 $cv = array("id" => -2, "kind" => "cat",
1225 "counter" => getCategoryUnread($link, -2));
1227 array_push($ret_arr, $cv);
1229 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1230 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1231 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1232 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1233 WHERE ttrss_cat_counters_cache.feed_id = id AND
1234 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1235 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1237 while ($line = db_fetch_assoc($result)) {
1238 $line["cat_id"] = (int) $line["cat_id"];
1240 if ($line["num_children"] > 0) {
1241 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1246 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1247 "counter" => $line["unread"] +
$child_counter);
1249 array_push($ret_arr, $cv);
1252 /* Special case: NULL category doesn't actually exist in the DB */
1254 $cv = array("id" => 0, "kind" => "cat",
1255 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1257 array_push($ret_arr, $cv);
1262 // only accepts real cats (>= 0)
1263 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1264 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1266 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1267 AND owner_uid = $owner_uid");
1271 while ($line = db_fetch_assoc($result)) {
1272 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1273 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1279 function getCategoryUnread($link, $cat, $owner_uid = false) {
1281 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1286 $cat_query = "cat_id = '$cat'";
1288 $cat_query = "cat_id IS NULL";
1291 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1292 AND owner_uid = " . $owner_uid);
1294 $cat_feeds = array();
1295 while ($line = db_fetch_assoc($result)) {
1296 array_push($cat_feeds, "feed_id = " . $line["id"]);
1299 if (count($cat_feeds) == 0) return 0;
1301 $match_part = implode(" OR ", $cat_feeds);
1303 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1304 FROM ttrss_user_entries
1305 WHERE unread = true AND ($match_part)
1306 AND owner_uid = " . $owner_uid);
1310 # this needs to be rewritten
1311 while ($line = db_fetch_assoc($result)) {
1312 $unread +
= $line["unread"];
1316 } else if ($cat == -1) {
1317 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1318 } else if ($cat == -2) {
1320 $result = db_query($link, "
1321 SELECT COUNT(unread) AS unread FROM
1322 ttrss_user_entries, ttrss_user_labels2
1323 WHERE article_id = ref_id AND unread = true
1324 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1326 $unread = db_fetch_result($result, 0, "unread");
1333 function getFeedUnread($link, $feed, $is_cat = false) {
1334 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1337 function getLabelUnread($link, $label_id, $owner_uid = false) {
1338 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1340 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1341 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1343 if (db_num_rows($result) != 0) {
1344 return db_fetch_result($result, 0, "unread");
1350 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1351 $owner_uid = false) {
1353 $n_feed = (int) $feed;
1354 $need_entries = false;
1356 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1359 $unread_qpart = "unread = true";
1361 $unread_qpart = "true";
1365 return getCategoryUnread($link, $n_feed, $owner_uid);
1366 } else if ($n_feed == -6) {
1368 } else if ($feed != "0" && $n_feed == 0) {
1370 $feed = db_escape_string($feed);
1372 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1373 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1374 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1375 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1376 return db_fetch_result($result, 0, "count");
1378 } else if ($n_feed == -1) {
1379 $match_part = "marked = true";
1380 } else if ($n_feed == -2) {
1381 $match_part = "published = true";
1382 } else if ($n_feed == -3) {
1383 $match_part = "unread = true AND score >= 0";
1385 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1387 if (DB_TYPE
== "pgsql") {
1388 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1390 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1393 $need_entries = true;
1395 } else if ($n_feed == -4) {
1396 $match_part = "true";
1397 } else if ($n_feed >= 0) {
1400 $match_part = "feed_id = '$n_feed'";
1402 $match_part = "feed_id IS NULL";
1405 } else if ($feed < -10) {
1407 $label_id = -$feed - 11;
1409 return getLabelUnread($link, $label_id, $owner_uid);
1415 if ($need_entries) {
1416 $from_qpart = "ttrss_user_entries,ttrss_entries";
1417 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1419 $from_qpart = "ttrss_user_entries";
1422 $query = "SELECT count(int_id) AS unread
1423 FROM $from_qpart WHERE
1424 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1426 //echo "[$feed/$query]\n";
1428 $result = db_query($link, $query);
1432 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1433 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1434 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1435 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1438 $unread = db_fetch_result($result, 0, "unread");
1443 function getGlobalUnread($link, $user_id = false) {
1446 $user_id = $_SESSION["uid"];
1449 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1450 WHERE owner_uid = '$user_id' AND feed_id > 0");
1452 $c_id = db_fetch_result($result, 0, "c_id");
1457 function getGlobalCounters($link, $global_unread = -1) {
1460 if ($global_unread == -1) {
1461 $global_unread = getGlobalUnread($link);
1464 $cv = array("id" => "global-unread",
1465 "counter" => (int) $global_unread);
1467 array_push($ret_arr, $cv);
1469 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1470 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1472 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1474 $cv = array("id" => "subscribed-feeds",
1475 "counter" => (int) $subscribed_feeds);
1477 array_push($ret_arr, $cv);
1482 function getTagCounters($link) {
1486 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1487 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1488 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1489 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1490 ORDER BY count DESC LIMIT 55");
1494 while ($line = db_fetch_assoc($result)) {
1495 $tags[$line["tag_name"]] +
= $line["count"];
1498 foreach (array_keys($tags) as $tag) {
1499 $unread = $tags[$tag];
1500 $tag = htmlspecialchars($tag);
1502 $cv = array("id" => $tag,
1504 "counter" => $unread);
1506 array_push($ret_arr, $cv);
1512 function getVirtCounters($link) {
1516 for ($i = 0; $i >= -4; $i--) {
1518 $count = getFeedUnread($link, $i);
1520 $cv = array("id" => $i,
1521 "counter" => (int) $count);
1523 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1524 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1526 array_push($ret_arr, $cv);
1532 function getLabelCounters($link, $descriptions = false) {
1536 $owner_uid = $_SESSION["uid"];
1538 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1539 WHERE owner_uid = '$owner_uid'");
1541 while ($line = db_fetch_assoc($result)) {
1543 $id = -$line["id"] - 11;
1545 $label_name = $line["caption"];
1546 $count = getFeedUnread($link, $id);
1548 $cv = array("id" => $id,
1549 "counter" => (int) $count);
1552 $cv["description"] = $label_name;
1554 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1555 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1557 array_push($ret_arr, $cv);
1563 function getFeedCounters($link, $active_feed = false) {
1567 $query = "SELECT ttrss_feeds.id,
1569 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1570 last_error, value AS count
1571 FROM ttrss_feeds, ttrss_counters_cache
1572 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1573 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1574 AND ttrss_counters_cache.feed_id = id";
1576 $result = db_query($link, $query);
1577 $fctrs_modified = false;
1579 while ($line = db_fetch_assoc($result)) {
1582 $count = $line["count"];
1583 $last_error = htmlspecialchars($line["last_error"]);
1585 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1587 $has_img = feed_has_icon($id);
1589 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1592 $cv = array("id" => $id,
1593 "updated" => $last_updated,
1594 "counter" => (int) $count,
1595 "has_img" => (int) $has_img);
1598 $cv["error"] = $last_error;
1600 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1601 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1603 if ($active_feed && $id == $active_feed)
1604 $cv["title"] = truncate_string($line["title"], 30);
1606 array_push($ret_arr, $cv);
1613 function get_pgsql_version($link) {
1614 $result = db_query($link, "SELECT version() AS version");
1615 $version = explode(" ", db_fetch_result($result, 0, "version"));
1620 * @return array (code => Status code, message => error message if available)
1622 * 0 - OK, Feed already exists
1623 * 1 - OK, Feed added
1625 * 3 - URL content is HTML, no feeds available
1626 * 4 - URL content is HTML which contains multiple feeds.
1627 * Here you should call extractfeedurls in rpc-backend
1628 * to get all possible feeds.
1629 * 5 - Couldn't download the URL content.
1631 function subscribe_to_feed($link, $url, $cat_id = 0,
1632 $auth_login = '', $auth_pass = '', $need_auth = false) {
1634 global $fetch_last_error;
1636 require_once "include/rssfuncs.php";
1638 $url = fix_url($url);
1640 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1642 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1645 return array("code" => 5, "message" => $fetch_last_error);
1648 if (is_html($contents)) {
1649 $feedUrls = get_feeds_from_html($url, $contents);
1651 if (count($feedUrls) == 0) {
1652 return array("code" => 3);
1653 } else if (count($feedUrls) > 1) {
1654 return array("code" => 4, "feeds" => $feedUrls);
1656 //use feed url as new URL
1657 $url = key($feedUrls);
1660 if ($cat_id == "0" ||
!$cat_id) {
1661 $cat_qpart = "NULL";
1663 $cat_qpart = "'$cat_id'";
1666 $result = db_query($link,
1667 "SELECT id FROM ttrss_feeds
1668 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1670 if (db_num_rows($result) == 0) {
1671 $result = db_query($link,
1672 "INSERT INTO ttrss_feeds
1673 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1674 VALUES ('".$_SESSION["uid"]."', '$url',
1675 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1677 $result = db_query($link,
1678 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1679 AND owner_uid = " . $_SESSION["uid"]);
1681 $feed_id = db_fetch_result($result, 0, "id");
1684 update_rss_feed($link, $feed_id, true);
1687 return array("code" => 1);
1689 return array("code" => 0);
1693 function print_feed_select($link, $id, $default_id = "",
1694 $attributes = "", $include_all_feeds = true,
1695 $root_id = false, $nest_level = 0) {
1698 print "<select id=\"$id\" name=\"$id\" $attributes>";
1699 if ($include_all_feeds) {
1700 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1701 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1705 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1708 $parent_qpart = "parent_cat = '$root_id'";
1710 $parent_qpart = "parent_cat IS NULL";
1712 $result = db_query($link, "SELECT id,title,
1713 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1714 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1715 FROM ttrss_feed_categories
1716 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1718 while ($line = db_fetch_assoc($result)) {
1720 for ($i = 0; $i < $nest_level; $i++
)
1721 $line["title"] = " - " . $line["title"];
1723 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1725 printf("<option $is_selected value='CAT:%d'>%s</option>",
1726 $line["id"], htmlspecialchars($line["title"]));
1728 if ($line["num_children"] > 0)
1729 print_feed_select($link, $id, $default_id, $attributes,
1730 $include_all_feeds, $line["id"], $nest_level+
1);
1732 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1733 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1735 while ($fline = db_fetch_assoc($feed_result)) {
1736 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1738 $fline["title"] = " + " . $fline["title"];
1740 for ($i = 0; $i < $nest_level; $i++
)
1741 $fline["title"] = " - " . $fline["title"];
1743 printf("<option $is_selected value='%d'>%s</option>",
1744 $fline["id"], htmlspecialchars($fline["title"]));
1749 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1751 printf("<option $is_selected value='CAT:0'>%s</option>",
1752 __("Uncategorized"));
1754 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1755 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1757 while ($fline = db_fetch_assoc($feed_result)) {
1758 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1760 $fline["title"] = " + " . $fline["title"];
1762 for ($i = 0; $i < $nest_level; $i++
)
1763 $fline["title"] = " - " . $fline["title"];
1765 printf("<option $is_selected value='%d'>%s</option>",
1766 $fline["id"], htmlspecialchars($fline["title"]));
1771 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1772 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1774 while ($line = db_fetch_assoc($result)) {
1776 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1778 printf("<option $is_selected value='%d'>%s</option>",
1779 $line["id"], htmlspecialchars($line["title"]));
1788 function print_feed_cat_select($link, $id, $default_id,
1789 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1792 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1796 $parent_qpart = "parent_cat = '$root_id'";
1798 $parent_qpart = "parent_cat IS NULL";
1800 $result = db_query($link, "SELECT id,title,
1801 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1802 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1803 FROM ttrss_feed_categories
1804 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1806 while ($line = db_fetch_assoc($result)) {
1807 if ($line["id"] == $default_id) {
1808 $is_selected = "selected=\"1\"";
1813 for ($i = 0; $i < $nest_level; $i++
)
1814 $line["title"] = " - " . $line["title"];
1817 printf("<option $is_selected value='%d'>%s</option>",
1818 $line["id"], htmlspecialchars($line["title"]));
1820 if ($line["num_children"] > 0)
1821 print_feed_cat_select($link, $id, $default_id, $attributes,
1822 $include_all_cats, $line["id"], $nest_level+
1);
1826 if ($include_all_cats) {
1827 if (db_num_rows($result) > 0) {
1828 print "<option disabled=\"1\">--------</option>";
1831 if ($default_id == 0) {
1832 $is_selected = "selected=\"1\"";
1837 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1843 function checkbox_to_sql_bool($val) {
1844 return ($val == "on") ?
"true" : "false";
1847 function getFeedCatTitle($link, $id) {
1849 return __("Special");
1850 } else if ($id < -10) {
1851 return __("Labels");
1852 } else if ($id > 0) {
1853 $result = db_query($link, "SELECT ttrss_feed_categories.title
1854 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1855 cat_id = ttrss_feed_categories.id");
1856 if (db_num_rows($result) == 1) {
1857 return db_fetch_result($result, 0, "title");
1859 return __("Uncategorized");
1862 return "getFeedCatTitle($id) failed";
1867 function getFeedIcon($id) {
1870 return "images/archive.png";
1873 return "images/mark_set.png";
1876 return "images/pub_set.png";
1879 return "images/fresh.png";
1882 return "images/tag.png";
1885 return "images/recently_read.png";
1889 return "images/label.png";
1891 if (file_exists(ICONS_DIR
. "/$id.ico"))
1892 return ICONS_URL
. "/$id.ico";
1898 function getFeedTitle($link, $id, $cat = false) {
1900 return getCategoryTitle($link, $id);
1901 } else if ($id == -1) {
1902 return __("Starred articles");
1903 } else if ($id == -2) {
1904 return __("Published articles");
1905 } else if ($id == -3) {
1906 return __("Fresh articles");
1907 } else if ($id == -4) {
1908 return __("All articles");
1909 } else if ($id === 0 ||
$id === "0") {
1910 return __("Archived articles");
1911 } else if ($id == -6) {
1912 return __("Recently read");
1913 } else if ($id < -10) {
1914 $label_id = -$id - 11;
1915 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1916 if (db_num_rows($result) == 1) {
1917 return db_fetch_result($result, 0, "caption");
1919 return "Unknown label ($label_id)";
1922 } else if (is_numeric($id) && $id > 0) {
1923 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1924 if (db_num_rows($result) == 1) {
1925 return db_fetch_result($result, 0, "title");
1927 return "Unknown feed ($id)";
1934 function make_init_params($link) {
1937 $params["theme"] = get_user_theme($link);
1938 $params["theme_options"] = get_user_theme_options($link);
1940 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1941 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1942 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
1943 $params["sign_info"] = theme_image($link, "images/sign_info.png");
1945 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1946 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1947 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1948 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1950 $params[strtolower($param)] = (int) get_pref($link, $param);
1953 $params["icons_url"] = ICONS_URL
;
1954 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1955 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1956 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1957 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1958 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1960 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1961 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1963 $max_feed_id = db_fetch_result($result, 0, "mid");
1964 $num_feeds = db_fetch_result($result, 0, "nf");
1966 $params["max_feed_id"] = (int) $max_feed_id;
1967 $params["num_feeds"] = (int) $num_feeds;
1969 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1971 $params["csrf_token"] = $_SESSION["csrf_token"];
1976 function make_runtime_info($link) {
1979 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1980 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1982 $max_feed_id = db_fetch_result($result, 0, "mid");
1983 $num_feeds = db_fetch_result($result, 0, "nf");
1985 $data["max_feed_id"] = (int) $max_feed_id;
1986 $data["num_feeds"] = (int) $num_feeds;
1988 $data['last_article_id'] = getLastArticleId($link);
1989 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1991 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1993 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1995 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1997 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2000 $stamp_delta = time() - $stamp;
2002 if ($stamp_delta > 1800) {
2006 $_SESSION["daemon_stamp_check"] = time();
2009 $data['daemon_stamp_ok'] = $stamp_check;
2011 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2013 $data['daemon_stamp'] = $stamp_fmt;
2018 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2019 $new_version_details = @check_for_update
($link);
2021 $data['new_version_available'] = (int) ($new_version_details != false);
2023 $_SESSION["last_version_check"] = time();
2024 $_SESSION["version_data"] = $new_version_details;
2030 function search_to_sql($link, $search, $match_on) {
2032 $search_query_part = "";
2034 $keywords = explode(" ", $search);
2035 $query_keywords = array();
2037 foreach ($keywords as $k) {
2038 if (strpos($k, "-") === 0) {
2045 $commandpair = explode(":", mb_strtolower($k), 2);
2047 if ($commandpair[0] == "note" && $commandpair[1]) {
2049 if ($commandpair[1] == "true")
2050 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2052 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2054 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2056 if ($commandpair[1] == "true")
2057 array_push($query_keywords, "($not (marked = true))");
2059 array_push($query_keywords, "($not (marked = false))");
2061 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2063 if ($commandpair[1] == "true")
2064 array_push($query_keywords, "($not (published = true))");
2066 array_push($query_keywords, "($not (published = false))");
2068 } else if (strpos($k, "@") === 0) {
2070 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2071 $orig_ts = strtotime(substr($k, 1));
2072 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2074 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2076 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2077 } else if ($match_on == "both") {
2078 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2079 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2080 } else if ($match_on == "title") {
2081 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2082 } else if ($match_on == "content") {
2083 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2087 $search_query_part = implode("AND", $query_keywords);
2089 return $search_query_part;
2092 function getParentCategories($link, $cat, $owner_uid) {
2095 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2096 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2098 while ($line = db_fetch_assoc($result)) {
2099 array_push($rv, $line["parent_cat"]);
2100 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2106 function getChildCategories($link, $cat, $owner_uid) {
2109 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2110 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2112 while ($line = db_fetch_assoc($result)) {
2113 array_push($rv, $line["id"]);
2114 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2120 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) {
2122 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2124 $ext_tables_part = "";
2128 if (SPHINX_ENABLED
) {
2129 $ids = join(",", @sphinx_search
($search, 0, 500));
2132 $search_query_part = "ref_id IN ($ids) AND ";
2134 $search_query_part = "ref_id = -1 AND ";
2137 $search_query_part = search_to_sql($link, $search, $match_on);
2138 $search_query_part .= " AND ";
2142 $search_query_part = "";
2147 if (DB_TYPE
== "pgsql") {
2148 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2150 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2153 $override_order = "updated DESC";
2155 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2157 // Try to check if SQL regexp implementation chokes on a valid regexp
2158 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2159 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2160 WHERE $filter_query_part LIMIT 1", false);
2162 $test = db_fetch_result($result, 0, "true");
2165 $filter_query_part = "false AND";
2167 $filter_query_part .= " AND";
2171 $filter_query_part = "";
2175 $since_id_part = "ttrss_entries.id > $since_id AND ";
2177 $since_id_part = "";
2180 $view_query_part = "";
2182 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2184 $view_query_part = " ";
2185 } else if ($feed != -1) {
2186 $unread = getFeedUnread($link, $feed, $cat_view);
2188 if ($cat_view && $feed > 0 && $include_children)
2189 $unread +
= getCategoryChildrenUnread($link, $feed);
2192 $view_query_part = " unread = true AND ";
2197 if ($view_mode == "marked") {
2198 $view_query_part = " marked = true AND ";
2201 if ($view_mode == "published") {
2202 $view_query_part = " published = true AND ";
2205 if ($view_mode == "unread") {
2206 $view_query_part = " unread = true AND ";
2209 if ($view_mode == "updated") {
2210 $view_query_part = " (last_read is null and unread = false) AND ";
2214 $limit_query_part = "LIMIT " . $limit;
2217 $allow_archived = false;
2219 $vfeed_query_part = "";
2221 // override query strategy and enable feed display when searching globally
2222 if ($search && $search_mode == "all_feeds") {
2223 $query_strategy_part = "true";
2224 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2226 } else if (!is_numeric($feed)) {
2227 $query_strategy_part = "true";
2228 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2229 id = feed_id) as feed_title,";
2230 } else if ($search && $search_mode == "this_cat") {
2231 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2234 if ($include_children) {
2235 $subcats = getChildCategories($link, $feed, $owner_uid);
2236 array_push($subcats, $feed);
2237 $cats_qpart = join(",", $subcats);
2239 $cats_qpart = $feed;
2242 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2245 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2248 } else if ($feed > 0) {
2253 if ($include_children) {
2255 $subcats = getChildCategories($link, $feed, $owner_uid);
2257 array_push($subcats, $feed);
2258 $query_strategy_part = "cat_id IN (".
2259 implode(",", $subcats).")";
2262 $query_strategy_part = "cat_id = '$feed'";
2266 $query_strategy_part = "cat_id IS NULL";
2269 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2272 $query_strategy_part = "feed_id = '$feed'";
2274 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2275 $query_strategy_part = "feed_id IS NULL";
2276 $allow_archived = true;
2277 } else if ($feed == 0 && $cat_view) { // uncategorized
2278 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2279 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2280 } else if ($feed == -1) { // starred virtual feed
2281 $query_strategy_part = "marked = true";
2282 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2283 $allow_archived = true;
2285 } else if ($feed == -2) { // published virtual feed OR labels category
2288 $query_strategy_part = "published = true";
2289 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2290 $allow_archived = true;
2292 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2294 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2296 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2298 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2299 ttrss_user_labels2.article_id = ref_id";
2302 } else if ($feed == -6) { // recently read
2303 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2304 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2305 $allow_archived = true;
2307 if (!$override_order) $override_order = "last_read DESC";
2308 } else if ($feed == -3) { // fresh virtual feed
2309 $query_strategy_part = "unread = true AND score >= 0";
2311 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2313 if (DB_TYPE
== "pgsql") {
2314 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2316 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2319 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2320 } else if ($feed == -4) { // all articles virtual feed
2321 $query_strategy_part = "true";
2322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2323 } else if ($feed <= -10) { // labels
2324 $label_id = -$feed - 11;
2326 $query_strategy_part = "label_id = '$label_id' AND
2327 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2328 ttrss_user_labels2.article_id = ref_id";
2330 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2331 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2332 $allow_archived = true;
2335 $query_strategy_part = "true";
2338 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2339 $date_sort_field = "updated";
2341 $date_sort_field = "date_entered";
2344 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2345 $order_by = "$date_sort_field";
2347 $order_by = "$date_sort_field DESC";
2350 if ($view_mode != "noscores") {
2351 $order_by = "score DESC, $order_by";
2354 if ($override_order) {
2355 $order_by = $override_order;
2361 $feed_title = T_sprintf("Search results: %s", $search);
2364 $feed_title = getCategoryTitle($link, $feed);
2366 if (is_numeric($feed) && $feed > 0) {
2367 $result = db_query($link, "SELECT title,site_url,last_error
2368 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2370 $feed_title = db_fetch_result($result, 0, "title");
2371 $feed_site_url = db_fetch_result($result, 0, "site_url");
2372 $last_error = db_fetch_result($result, 0, "last_error");
2374 $feed_title = getFeedTitle($link, $feed);
2379 $content_query_part = "content as content_preview, cached_content, ";
2381 if (is_numeric($feed)) {
2384 $feed_kind = "Feeds";
2386 $feed_kind = "Labels";
2389 if ($limit_query_part) {
2390 $offset_query_part = "OFFSET $offset";
2393 // proper override_order applied above
2394 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2395 if (!$override_order) {
2396 $order_by = "ttrss_feeds.title, $order_by";
2398 $order_by = "ttrss_feeds.title, $override_order";
2402 if (!$allow_archived) {
2403 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2404 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2407 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2408 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2411 $query = "SELECT DISTINCT
2414 ttrss_entries.id,ttrss_entries.title,
2418 always_display_enclosures,
2424 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2425 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2428 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2434 ttrss_user_entries.ref_id = ttrss_entries.id AND
2435 ttrss_user_entries.owner_uid = '$owner_uid' AND
2440 $query_strategy_part ORDER BY $order_by
2441 $limit_query_part $offset_query_part";
2443 if ($_REQUEST["debug"]) print $query;
2445 $result = db_query($link, $query);
2450 $select_qpart = "SELECT DISTINCT " .
2454 "ttrss_entries.id as id," .
2467 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2470 $content_query_part .
2471 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2474 $feed_kind = "Tags";
2475 $all_tags = explode(",", $feed);
2476 if ($search_mode == 'any') {
2477 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2478 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2479 $where_qpart = " WHERE " .
2480 "ref_id = ttrss_entries.id AND " .
2481 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2482 "post_int_id = int_id AND $tag_sql AND " .
2484 $search_query_part .
2485 $query_strategy_part . " ORDER BY $order_by " .
2490 $sub_selects = array();
2491 $sub_ands = array();
2492 foreach ($all_tags as $term) {
2493 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");
2500 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2505 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2506 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2507 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2508 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2510 // error_log("TAG SQL: " . $tag_sql);
2511 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2513 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2514 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2517 return array($result, $feed_title, $feed_site_url, $last_error);
2521 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2522 if (!$owner) $owner = $_SESSION["uid"];
2524 $res = trim($str); if (!$res) return '';
2526 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
2527 $res = htmLawed($res, $config);
2529 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2530 $res = preg_replace('/<img[^>]+>/is', '', $res);
2533 if (strpos($res, "href=") === false)
2534 $res = rewrite_urls($res);
2536 $charset_hack = '<head>
2537 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2540 $res = trim($res); if (!$res) return '';
2542 libxml_use_internal_errors(true);
2544 $doc = new DOMDocument();
2545 $doc->loadHTML($charset_hack . $res);
2546 $xpath = new DOMXPath($doc);
2548 $entries = $xpath->query('(//a[@href]|//img[@src])');
2551 foreach ($entries as $entry) {
2555 if ($entry->hasAttribute('href'))
2556 $entry->setAttribute('href',
2557 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2559 if ($entry->hasAttribute('src'))
2560 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2561 $entry->setAttribute('src',
2562 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2565 if (strtolower($entry->nodeName
) == "a") {
2566 $entry->setAttribute("target", "_blank");
2569 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2570 $br = $doc->createElement("br");
2572 if ($entry->parentNode
->nextSibling
) {
2573 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2580 $node = $doc->getElementsByTagName('body')->item(0);
2582 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2585 function check_for_update($link) {
2586 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2587 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2589 $version_data = @fetch_file_contents
($version_url);
2591 if ($version_data) {
2592 $version_data = json_decode($version_data, true);
2593 if ($version_data && $version_data['version']) {
2595 if (version_compare(VERSION
, $version_data['version']) == -1) {
2596 return $version_data;
2604 function markArticlesById($link, $ids, $cmode) {
2608 foreach ($ids as $id) {
2609 array_push($tmp_ids, "ref_id = '$id'");
2612 $ids_qpart = join(" OR ", $tmp_ids);
2615 db_query($link, "UPDATE ttrss_user_entries SET
2616 marked = false,last_read = NOW()
2617 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2618 } else if ($cmode == 1) {
2619 db_query($link, "UPDATE ttrss_user_entries SET
2621 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2623 db_query($link, "UPDATE ttrss_user_entries SET
2624 marked = NOT marked,last_read = NOW()
2625 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2629 function publishArticlesById($link, $ids, $cmode) {
2633 foreach ($ids as $id) {
2634 array_push($tmp_ids, "ref_id = '$id'");
2637 $ids_qpart = join(" OR ", $tmp_ids);
2640 db_query($link, "UPDATE ttrss_user_entries SET
2641 published = false,last_read = NOW()
2642 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2643 } else if ($cmode == 1) {
2644 db_query($link, "UPDATE ttrss_user_entries SET
2645 published = true,last_read = NOW()
2646 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2648 db_query($link, "UPDATE ttrss_user_entries SET
2649 published = NOT published,last_read = NOW()
2650 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2653 if (PUBSUBHUBBUB_HUB
) {
2654 $rss_link = get_self_url_prefix() .
2655 "/public.php?op=rss&id=-2&key=" .
2656 get_feed_access_key($link, -2, false);
2658 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2660 $pubsub_result = $p->publish_update($rss_link);
2664 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2666 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2667 if (count($ids) == 0) return;
2671 foreach ($ids as $id) {
2672 array_push($tmp_ids, "ref_id = '$id'");
2675 $ids_qpart = join(" OR ", $tmp_ids);
2678 db_query($link, "UPDATE ttrss_user_entries SET
2679 unread = false,last_read = NOW()
2680 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2681 } else if ($cmode == 1) {
2682 db_query($link, "UPDATE ttrss_user_entries SET
2684 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2686 db_query($link, "UPDATE ttrss_user_entries SET
2687 unread = NOT unread,last_read = NOW()
2688 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2693 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2694 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2696 while ($line = db_fetch_assoc($result)) {
2697 ccache_update($link, $line["feed_id"], $owner_uid);
2701 function catchupArticleById($link, $id, $cmode) {
2704 db_query($link, "UPDATE ttrss_user_entries SET
2705 unread = false,last_read = NOW()
2706 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2707 } else if ($cmode == 1) {
2708 db_query($link, "UPDATE ttrss_user_entries SET
2710 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2712 db_query($link, "UPDATE ttrss_user_entries SET
2713 unread = NOT unread,last_read = NOW()
2714 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2717 $feed_id = getArticleFeed($link, $id);
2718 ccache_update($link, $feed_id, $_SESSION["uid"]);
2721 function make_guid_from_title($title) {
2722 return preg_replace("/[ \"\',.:;]/", "-",
2723 mb_strtolower(strip_tags($title), 'utf-8'));
2726 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2728 $a_id = db_escape_string($id);
2730 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2732 $query = "SELECT DISTINCT tag_name,
2733 owner_uid as owner FROM
2734 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2735 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2737 $obj_id = md5("TAGS:$owner_uid:$id");
2740 /* check cache first */
2742 if ($tag_cache === false) {
2743 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2744 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2746 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2750 $tags = explode(",", $tag_cache);
2753 /* do it the hard way */
2755 $tmp_result = db_query($link, $query);
2757 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2758 array_push($tags, $tmp_line["tag_name"]);
2761 /* update the cache */
2763 $tags_str = db_escape_string(join(",", $tags));
2765 db_query($link, "UPDATE ttrss_user_entries
2766 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2767 AND owner_uid = $owner_uid");
2773 function trim_array($array) {
2775 array_walk($tmp, 'trim');
2779 function tag_is_valid($tag) {
2780 if ($tag == '') return false;
2781 if (preg_match("/^[0-9]*$/", $tag)) return false;
2782 if (mb_strlen($tag) > 250) return false;
2784 if (function_exists('iconv')) {
2785 $tag = iconv("utf-8", "utf-8", $tag);
2788 if (!$tag) return false;
2793 function render_login_form($link, $form_id = 0) {
2796 require_once "login_form.php";
2799 require_once "mobile/login_form.php";
2805 // from http://developer.apple.com/internet/safari/faq.html
2806 function no_cache_incantation() {
2807 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2808 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2809 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2810 header("Cache-Control: post-check=0, pre-check=0", false);
2811 header("Pragma: no-cache"); // HTTP/1.0
2814 function format_warning($msg, $id = "") {
2816 return "<div class=\"warning\" id=\"$id\">
2817 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
2820 function format_notice($msg, $id = "") {
2822 return "<div class=\"notice\" id=\"$id\">
2823 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
2826 function format_error($msg, $id = "") {
2828 return "<div class=\"error\" id=\"$id\">
2829 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
2832 function print_notice($msg) {
2833 return print format_notice($msg);
2836 function print_warning($msg) {
2837 return print format_warning($msg);
2840 function print_error($msg) {
2841 return print format_error($msg);
2845 function T_sprintf() {
2846 $args = func_get_args();
2847 return vsprintf(__(array_shift($args)), $args);
2850 function format_inline_player($link, $url, $ctype) {
2854 if (strpos($ctype, "audio/") === 0) {
2856 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2857 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2858 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2860 $id = 'AUDIO-' . uniqid();
2862 $entry .= "<audio id=\"$id\"\">
2863 <source src=\"$url\"></source>
2866 $entry .= "<span onclick=\"player(this)\"
2867 title=\"".__("Click to play")."\" status=\"0\"
2868 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2872 $entry .= "<object type=\"application/x-shockwave-flash\"
2873 data=\"lib/button/musicplayer.swf?song_url=$url\"
2874 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2875 <param name=\"movie\"
2876 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2881 $filename = substr($url, strrpos($url, "/")+
1);
2883 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2884 $filename . " (" . $ctype . ")" . "</a>";
2889 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2890 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2896 /* we can figure out feed_id from article id anyway, why do we
2897 * pass feed_id here? let's ignore the argument :( */
2899 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2900 WHERE ref_id = '$id'");
2902 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2904 $rv['feed_id'] = $feed_id;
2906 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2908 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2909 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2911 if (db_num_rows($result) == 1) {
2912 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2913 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2914 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2916 $rtl_content = false;
2917 $always_display_enclosures = false;
2918 $cache_content = false;
2922 $rtl_tag = "dir=\"RTL\"";
2929 if ($mark_as_read) {
2930 $result = db_query($link, "UPDATE ttrss_user_entries
2931 SET unread = false,last_read = NOW()
2932 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2934 ccache_update($link, $feed_id, $owner_uid);
2937 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2938 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
2939 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
2940 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2947 FROM ttrss_entries,ttrss_user_entries
2948 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
2952 $line = db_fetch_assoc($result);
2954 if ($line["icon_url"]) {
2955 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
2957 $feed_icon = " ";
2960 $feed_site_url = $line['site_url'];
2962 $num_comments = $line["num_comments"];
2963 $entry_comments = "";
2965 if ($num_comments > 0) {
2966 if ($line["comments"]) {
2967 $comments_url = htmlspecialchars($line["comments"]);
2969 $comments_url = htmlspecialchars($line["link"]);
2971 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
2973 if ($line["comments"] && $line["link"] != $line["comments"]) {
2974 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
2979 header("Content-Type: text/html");
2980 $rv['content'] .= "<html><head>
2981 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
2982 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2983 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2987 $title_escaped = htmlspecialchars($line['title']);
2989 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
2990 truncate_string(strip_tags($line['title']), 15) . "</div>";
2992 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2993 strip_tags($line['title']) . "</div>";
2995 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
2997 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
2998 class=\"postHeader\" id=\"POSTHDR-$id\">";
3000 $entry_author = $line["author"];
3002 if ($entry_author) {
3003 $entry_author = __(" - ") . $entry_author;
3006 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3009 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3011 if ($line["link"]) {
3012 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3013 title=\"".htmlspecialchars($line['title'])."\"
3015 htmlspecialchars($line["link"]) . "\">" .
3017 "<span class='author'>$entry_author</span></a></div>";
3019 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3022 $tag_cache = $line["tag_cache"];
3025 $tags = get_article_tags($link, $id, $owner_uid);
3027 $tags = explode(",", $tag_cache);
3029 $tags_str = format_tags_string($tags, $id);
3030 $tags_str_full = join(", ", $tags);
3032 if (!$tags_str_full) $tags_str_full = __("no tags");
3034 if (!$entry_comments) $entry_comments = " "; # placeholder
3036 $rv['content'] .= "<div class='postTags' style='float : right'>
3037 <img src='".theme_image($link, 'images/tag.png')."'
3038 class='tagsPic' alt='Tags' title='Tags'> ";
3041 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3042 <a title=\"".__('Edit tags for this article')."\"
3043 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3045 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3046 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3047 position=\"below\">$tags_str_full</div>";
3049 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3050 class='tagsPic' style=\"cursor : pointer\"
3051 onclick=\"postOpenInNewTab(event, $id)\"
3052 alt='Zoom' title='".__('Open article in new tab')."'>";
3056 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
3057 $rv['content'] .= $p->hook_article_button($line);
3060 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3061 class='tagsPic' style=\"cursor : pointer\"
3062 onclick=\"closeArticlePanel($id)\"
3063 title='".__('Close article')."'>";
3066 $tags_str = strip_tags($tags_str);
3067 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3069 $rv['content'] .= "</div>";
3070 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3072 if ($line["orig_feed_id"]) {
3074 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3075 WHERE id = ".$line["orig_feed_id"]);
3077 if (db_num_rows($tmp_result) != 0) {
3079 $rv['content'] .= "<div clear='both'>";
3080 $rv['content'] .= __("Originally from:");
3082 $rv['content'] .= " ";
3084 $tmp_line = db_fetch_assoc($tmp_result);
3086 $rv['content'] .= "<a target='_blank'
3087 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3088 $tmp_line['title'] . "</a>";
3090 $rv['content'] .= " ";
3092 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3093 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3095 $rv['content'] .= "</div>";
3099 $rv['content'] .= "</div>";
3101 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3102 if ($line['note']) {
3103 $rv['content'] .= format_article_note($id, $line['note']);
3105 $rv['content'] .= "</div>";
3107 $rv['content'] .= "<div class=\"postIcon\">" .
3108 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3109 href=\"".htmlspecialchars($feed_site_url)."\">".
3110 $feed_icon . "</a></div>";
3112 $rv['content'] .= "<div class=\"postContent\">";
3116 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3118 $ngram_result = db_query($link, "SELECT id,title FROM
3119 ttrss_entries,ttrss_user_entries
3120 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3121 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3122 AND title != '$title_escaped'
3123 AND owner_uid = $owner_uid");
3125 if (db_num_rows($ngram_result) > 0) {
3126 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3127 "<span>" . __('Related')."</span>";
3128 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3130 while ($nline = db_fetch_assoc($ngram_result)) {
3131 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3132 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3135 $rv['content'] .= "</div></div><br/";
3139 if ($cache_content && $line["cached_content"] != "") {
3140 $line["content"] =& $line["cached_content"];
3143 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3146 $rv['content'] .= $article_content;
3148 $rv['content'] .= format_article_enclosures($link, $id,
3149 $always_display_enclosures, $article_content);
3151 $rv['content'] .= "</div>";
3153 $rv['content'] .= "</div>";
3159 <div style=\"text-align : center\">
3160 <button onclick=\"return window.close()\">".
3161 __("Close this window")."</button></div>";
3162 $rv['content'] .= "</body></html>";
3169 function print_checkpoint($n, $s) {
3170 $ts = getmicrotime();
3171 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3175 function sanitize_tag($tag) {
3178 $tag = mb_strtolower($tag, 'utf-8');
3180 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3182 // $tag = str_replace('"', "", $tag);
3183 // $tag = str_replace("+", " ", $tag);
3184 $tag = str_replace("technorati tag: ", "", $tag);
3189 function get_self_url_prefix() {
3190 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3191 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3193 return SELF_URL_PATH
;
3197 function opml_publish_url($link){
3199 $url_path = get_self_url_prefix();
3200 $url_path .= "/opml.php?op=publish&key=" .
3201 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3207 * Purge a feed contents, marked articles excepted.
3209 * @param mixed $link The database connection.
3210 * @param integer $id The id of the feed to purge.
3213 function clear_feed_articles($link, $id) {
3216 $result = db_query($link, "DELETE FROM ttrss_user_entries
3217 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3219 $result = db_query($link, "DELETE FROM ttrss_user_entries
3220 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3223 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3224 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3226 ccache_update($link, $id, $_SESSION['uid']);
3227 } // function clear_feed_articles
3230 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3232 * @return string The Mozilla Firefox feed adding URL.
3234 function add_feed_url() {
3235 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3237 $url_path = get_self_url_prefix() .
3238 "/public.php?op=subscribe&feed_url=%s";
3240 } // function add_feed_url
3242 function encrypt_password($pass, $salt = '', $mode2 = false) {
3243 if ($salt && $mode2) {
3244 return "MODE2:" . hash('sha256', $salt . $pass);
3246 return "SHA1X:" . sha1("$salt:$pass");
3248 return "SHA1:" . sha1($pass);
3250 } // function encrypt_password
3252 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3255 $cat_id = (int)getFeedCategory($link, $feed_id);
3257 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3258 owner_uid = $owner_uid AND enabled = true");
3260 $check_cats = join(",", array_merge(
3261 getParentCategories($link, $cat_id, $owner_uid),
3264 while ($line = db_fetch_assoc($result)) {
3265 $filter_id = $line["id"];
3267 $result2 = db_query($link, "SELECT
3268 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3269 FROM ttrss_filters2_rules AS r,
3270 ttrss_filter_types AS t
3272 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3273 (feed_id IS NULL OR feed_id = '$feed_id') AND
3274 filter_type = t.id AND filter_id = '$filter_id'");
3279 while ($rule_line = db_fetch_assoc($result2)) {
3280 # print_r($rule_line);
3283 $rule["reg_exp"] = $rule_line["reg_exp"];
3284 $rule["type"] = $rule_line["type_name"];
3286 array_push($rules, $rule);
3289 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3290 FROM ttrss_filters2_actions AS a,
3291 ttrss_filter_actions AS t
3293 action_id = t.id AND filter_id = '$filter_id'");
3295 while ($action_line = db_fetch_assoc($result2)) {
3296 # print_r($action_line);
3299 $action["type"] = $action_line["type_name"];
3300 $action["param"] = $action_line["action_param"];
3302 array_push($actions, $action);
3307 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3308 $filter["rules"] = $rules;
3309 $filter["actions"] = $actions;
3311 if (count($rules) > 0 && count($actions) > 0) {
3312 array_push($filters, $filter);
3319 function get_score_pic($score) {
3321 return "score_high.png";
3322 } else if ($score > 0) {
3323 return "score_half_high.png";
3324 } else if ($score < -100) {
3325 return "score_low.png";
3326 } else if ($score < 0) {
3327 return "score_half_low.png";
3329 return "score_neutral.png";
3333 function feed_has_icon($id) {
3334 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3337 function init_connection($link) {
3340 if (DB_TYPE
== "pgsql") {
3341 pg_query($link, "set client_encoding = 'UTF-8'");
3342 pg_set_client_encoding("UNICODE");
3343 pg_query($link, "set datestyle = 'ISO, european'");
3344 pg_query($link, "set TIME ZONE 0");
3346 db_query($link, "SET time_zone = '+0:0'");
3348 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3349 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3355 $pluginhost = new PluginHost($link);
3356 $pluginhost->load(PLUGINS
);
3360 print "Unable to connect to database:" . db_last_error();
3365 /* function ccache_zero($link, $feed_id, $owner_uid) {
3366 db_query($link, "UPDATE ttrss_counters_cache SET
3367 value = 0, updated = NOW() WHERE
3368 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3371 function ccache_zero_all($link, $owner_uid) {
3372 db_query($link, "UPDATE ttrss_counters_cache SET
3373 value = 0 WHERE owner_uid = '$owner_uid'");
3375 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3376 value = 0 WHERE owner_uid = '$owner_uid'");
3379 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3382 $table = "ttrss_counters_cache";
3384 $table = "ttrss_cat_counters_cache";
3387 db_query($link, "DELETE FROM $table WHERE
3388 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3392 function ccache_update_all($link, $owner_uid) {
3394 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3396 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3397 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3399 while ($line = db_fetch_assoc($result)) {
3400 ccache_update($link, $line["feed_id"], $owner_uid, true);
3403 /* We have to manually include category 0 */
3405 ccache_update($link, 0, $owner_uid, true);
3408 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3409 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3411 while ($line = db_fetch_assoc($result)) {
3412 print ccache_update($link, $line["feed_id"], $owner_uid);
3419 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3420 $no_update = false) {
3422 if (!is_numeric($feed_id)) return;
3425 $table = "ttrss_counters_cache";
3427 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3428 WHERE id = '$feed_id'");
3429 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3432 $table = "ttrss_cat_counters_cache";
3435 if (DB_TYPE
== "pgsql") {
3436 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3437 } else if (DB_TYPE
== "mysql") {
3438 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3441 $result = db_query($link, "SELECT value FROM $table
3442 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3445 if (db_num_rows($result) == 1) {
3446 return db_fetch_result($result, 0, "value");
3451 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3457 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3458 $update_pcat = true) {
3460 if (!is_numeric($feed_id)) return;
3462 if (!$is_cat && $feed_id > 0) {
3463 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3464 WHERE id = '$feed_id'");
3465 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3468 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3470 /* When updating a label, all we need to do is recalculate feed counters
3471 * because labels are not cached */
3474 ccache_update_all($link, $owner_uid);
3479 $table = "ttrss_counters_cache";
3481 $table = "ttrss_cat_counters_cache";
3484 if ($is_cat && $feed_id >= 0) {
3485 if ($feed_id != 0) {
3486 $cat_qpart = "cat_id = '$feed_id'";
3488 $cat_qpart = "cat_id IS NULL";
3491 /* Recalculate counters for child feeds */
3493 $result = db_query($link, "SELECT id FROM ttrss_feeds
3494 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3496 while ($line = db_fetch_assoc($result)) {
3497 ccache_update($link, $line["id"], $owner_uid, false, false);
3500 $result = db_query($link, "SELECT SUM(value) AS sv
3501 FROM ttrss_counters_cache, ttrss_feeds
3502 WHERE id = feed_id AND $cat_qpart AND
3503 ttrss_feeds.owner_uid = '$owner_uid'");
3505 $unread = (int) db_fetch_result($result, 0, "sv");
3508 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3511 db_query($link, "BEGIN");
3513 $result = db_query($link, "SELECT feed_id FROM $table
3514 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3516 if (db_num_rows($result) == 1) {
3517 db_query($link, "UPDATE $table SET
3518 value = '$unread', updated = NOW() WHERE
3519 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3522 db_query($link, "INSERT INTO $table
3523 (feed_id, value, owner_uid, updated)
3525 ($feed_id, $unread, $owner_uid, NOW())");
3528 db_query($link, "COMMIT");
3530 if ($feed_id > 0 && $prev_unread != $unread) {
3534 /* Update parent category */
3538 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3539 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3541 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3543 ccache_update($link, $cat_id, $owner_uid, true);
3547 } else if ($feed_id < 0) {
3548 ccache_update_all($link, $owner_uid);
3554 /* function ccache_cleanup($link, $owner_uid) {
3556 if (DB_TYPE == "pgsql") {
3557 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3558 (SELECT count(*) FROM ttrss_counters_cache AS c2
3559 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3560 AND owner_uid = '$owner_uid'");
3562 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3563 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3564 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3565 AND owner_uid = '$owner_uid'");
3567 db_query($link, "DELETE c1 FROM
3568 ttrss_counters_cache AS c1,
3569 ttrss_counters_cache AS c2
3571 c1.owner_uid = '$owner_uid' AND
3572 c1.owner_uid = c2.owner_uid AND
3573 c1.feed_id = c2.feed_id");
3575 db_query($link, "DELETE c1 FROM
3576 ttrss_cat_counters_cache AS c1,
3577 ttrss_cat_counters_cache AS c2
3579 c1.owner_uid = '$owner_uid' AND
3580 c1.owner_uid = c2.owner_uid AND
3581 c1.feed_id = c2.feed_id");
3586 function label_find_id($link, $label, $owner_uid) {
3587 $result = db_query($link,
3588 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3589 AND owner_uid = '$owner_uid' LIMIT 1");
3591 if (db_num_rows($result) == 1) {
3592 return db_fetch_result($result, 0, "id");
3598 function get_article_labels($link, $id, $owner_uid = false) {
3601 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3603 $result = db_query($link, "SELECT label_cache FROM
3604 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3607 if (db_num_rows($result) > 0) {
3608 $label_cache = db_fetch_result($result, 0, "label_cache");
3611 $label_cache = json_decode($label_cache, true);
3613 if ($label_cache["no-labels"] == 1)
3616 return $label_cache;
3620 $result = db_query($link,
3621 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3622 FROM ttrss_labels2, ttrss_user_labels2
3624 AND article_id = '$id'
3625 AND owner_uid = ". $owner_uid . "
3628 while ($line = db_fetch_assoc($result)) {
3629 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3631 array_push($rv, $rk);
3635 label_update_cache($link, $owner_uid, $id, $rv);
3637 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3643 function label_find_caption($link, $label, $owner_uid) {
3644 $result = db_query($link,
3645 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3646 AND owner_uid = '$owner_uid' LIMIT 1");
3648 if (db_num_rows($result) == 1) {
3649 return db_fetch_result($result, 0, "caption");
3655 function get_all_labels($link, $owner_uid) {
3658 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3660 while ($line = db_fetch_assoc($result)) {
3661 array_push($rv, $line);
3667 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3670 label_clear_cache($link, $id);
3673 $labels = get_article_labels($link, $id);
3675 $labels = db_escape_string(json_encode($labels));
3677 db_query($link, "UPDATE ttrss_user_entries SET
3678 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3682 function label_clear_cache($link, $id) {
3684 db_query($link, "UPDATE ttrss_user_entries SET
3685 label_cache = '' WHERE ref_id = '$id'");
3689 function label_remove_article($link, $id, $label, $owner_uid) {
3691 $label_id = label_find_id($link, $label, $owner_uid);
3693 if (!$label_id) return;
3695 $result = db_query($link,
3696 "DELETE FROM ttrss_user_labels2
3698 label_id = '$label_id' AND
3699 article_id = '$id'");
3701 label_clear_cache($link, $id);
3704 function label_add_article($link, $id, $label, $owner_uid) {
3706 $label_id = label_find_id($link, $label, $owner_uid);
3708 if (!$label_id) return;
3710 $result = db_query($link,
3712 article_id FROM ttrss_labels2, ttrss_user_labels2
3715 label_id = '$label_id' AND
3716 article_id = '$id' AND owner_uid = '$owner_uid'
3719 if (db_num_rows($result) == 0) {
3720 db_query($link, "INSERT INTO ttrss_user_labels2
3721 (label_id, article_id) VALUES ('$label_id', '$id')");
3724 label_clear_cache($link, $id);
3728 function label_remove($link, $id, $owner_uid) {
3729 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3731 db_query($link, "BEGIN");
3733 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3736 $caption = db_fetch_result($result, 0, "caption");
3738 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3739 AND owner_uid = " . $owner_uid);
3741 if (db_affected_rows($link, $result) != 0 && $caption) {
3743 /* Remove access key for the label */
3745 $ext_id = -11 - $id;
3747 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3748 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3750 /* Disable filters that reference label being removed */
3752 db_query($link, "UPDATE ttrss_filters SET
3753 enabled = false WHERE action_param = '$caption'
3755 AND owner_uid = " . $owner_uid);
3757 /* Remove cached data */
3759 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3760 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3764 db_query($link, "COMMIT");
3767 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3769 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3771 db_query($link, "BEGIN");
3775 $result = db_query($link, "SELECT id FROM ttrss_labels2
3776 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3778 if (db_num_rows($result) == 0) {
3779 $result = db_query($link,
3780 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3781 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3783 $result = db_affected_rows($link, $result) != 0;
3786 db_query($link, "COMMIT");
3791 function format_tags_string($tags, $id) {
3794 $tags_nolinks_str = "";
3800 $formatted_tags = array();
3802 foreach ($tags as $tag) {
3804 $tag_escaped = str_replace("'", "\\'", $tag);
3806 if (mb_strlen($tag) > 30) {
3807 $tag = truncate_string($tag, 30);
3810 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3812 array_push($formatted_tags, $tag_str);
3814 $tmp_tags_str = implode(", ", $formatted_tags);
3816 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
3821 $tags_str = implode(", ", $formatted_tags);
3823 if ($num_tags < count($tags)) {
3824 $tags_str .= ", …";
3827 if ($num_tags == 0) {
3828 $tags_str = __("no tags");
3835 function format_article_labels($labels, $id) {
3839 foreach ($labels as $l) {
3840 $labels_str .= sprintf("<span class='hlLabelRef'
3841 style='color : %s; background-color : %s'>%s</span>",
3842 $l[2], $l[3], $l[1]);
3849 function format_article_note($id, $note) {
3851 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3852 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3853 __('(edit note)')."</div>$note</div>";
3858 function toggle_collapse_cat($link, $cat_id, $mode) {
3860 $mode = bool_to_sql_bool($mode);
3862 db_query($link, "UPDATE ttrss_feed_categories SET
3863 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3870 $pref_name = '_COLLAPSED_SPECIAL';
3873 $pref_name = '_COLLAPSED_LABELS';
3876 $pref_name = '_COLLAPSED_UNCAT';
3882 set_pref($link, $pref_name, 'true');
3884 set_pref($link, $pref_name, 'false');
3890 function remove_feed($link, $id, $owner_uid) {
3894 /* save starred articles in Archived feed */
3896 db_query($link, "BEGIN");
3898 /* prepare feed if necessary */
3900 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
3903 if (db_num_rows($result) == 0) {
3904 db_query($link, "INSERT INTO ttrss_archived_feeds
3905 (id, owner_uid, title, feed_url, site_url)
3906 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
3910 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
3911 orig_feed_id = '$id' WHERE feed_id = '$id' AND
3912 marked = true AND owner_uid = $owner_uid");
3914 /* Remove access key for the feed */
3916 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3917 feed_id = '$id' AND owner_uid = $owner_uid");
3919 /* remove the feed */
3921 db_query($link, "DELETE FROM ttrss_feeds
3922 WHERE id = '$id' AND owner_uid = $owner_uid");
3924 db_query($link, "COMMIT");
3926 if (file_exists(ICONS_DIR
. "/$id.ico")) {
3927 unlink(ICONS_DIR
. "/$id.ico");
3930 ccache_remove($link, $id, $owner_uid);
3933 label_remove($link, -11-$id, $owner_uid);
3934 ccache_remove($link, -11-$id, $owner_uid);
3938 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3939 if ($parent_cat_id) {
3940 $parent_qpart = "parent_cat = '$parent_cat_id'";
3941 $parent_insert = "'$parent_cat_id'";
3943 $parent_qpart = "parent_cat IS NULL";
3944 $parent_insert = "NULL";
3947 $result = db_query($link,
3948 "SELECT id FROM ttrss_feed_categories
3949 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3951 if (db_num_rows($result) == 0) {
3954 return db_fetch_result($result, 0, "id");
3958 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3960 if (!$feed_cat) return false;
3962 db_query($link, "BEGIN");
3964 if ($parent_cat_id) {
3965 $parent_qpart = "parent_cat = '$parent_cat_id'";
3966 $parent_insert = "'$parent_cat_id'";
3968 $parent_qpart = "parent_cat IS NULL";
3969 $parent_insert = "NULL";
3972 $result = db_query($link,
3973 "SELECT id FROM ttrss_feed_categories
3974 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3976 if (db_num_rows($result) == 0) {
3978 $result = db_query($link,
3979 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3980 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3982 db_query($link, "COMMIT");
3990 function remove_feed_category($link, $id, $owner_uid) {
3992 db_query($link, "DELETE FROM ttrss_feed_categories
3993 WHERE id = '$id' AND owner_uid = $owner_uid");
3995 ccache_remove($link, $id, $owner_uid, true);
3998 function archive_article($link, $id, $owner_uid) {
3999 db_query($link, "BEGIN");
4001 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4002 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4004 if (db_num_rows($result) != 0) {
4006 /* prepare the archived table */
4008 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4011 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4012 WHERE id = '$feed_id'");
4014 if (db_num_rows($result) == 0) {
4015 db_query($link, "INSERT INTO ttrss_archived_feeds
4016 (id, owner_uid, title, feed_url, site_url)
4017 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4018 WHERE id = '$feed_id'");
4021 db_query($link, "UPDATE ttrss_user_entries
4022 SET orig_feed_id = feed_id, feed_id = NULL
4023 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4027 db_query($link, "COMMIT");
4030 function getArticleFeed($link, $id) {
4031 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4032 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4034 if (db_num_rows($result) != 0) {
4035 return db_fetch_result($result, 0, "feed_id");
4042 * Fixes incomplete URLs by prepending "http://".
4043 * Also replaces feed:// with http://, and
4044 * prepends a trailing slash if the url is a domain name only.
4046 * @param string $url Possibly incomplete URL
4048 * @return string Fixed URL.
4050 function fix_url($url) {
4051 if (strpos($url, '://') === false) {
4052 $url = 'http://' . $url;
4053 } else if (substr($url, 0, 5) == 'feed:') {
4054 $url = 'http:' . substr($url, 5);
4057 //prepend slash if the URL has no slash in it
4058 // "http://www.example" -> "http://www.example/"
4059 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4063 if ($url != "http:///")
4069 function validate_feed_url($url) {
4070 $parts = parse_url($url);
4072 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4076 function get_article_enclosures($link, $id) {
4078 $query = "SELECT * FROM ttrss_enclosures
4079 WHERE post_id = '$id' AND content_url != ''";
4083 $result = db_query($link, $query);
4085 if (db_num_rows($result) > 0) {
4086 while ($line = db_fetch_assoc($result)) {
4087 array_push($rv, $line);
4094 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4100 if ($cat_id == -4 ||
$cat_id == -2) {
4101 $counters = getLabelCounters($link, true);
4103 foreach (array_values($counters) as $cv) {
4105 $unread = $cv["counter"];
4107 if ($unread ||
!$unread_only) {
4111 "title" => $cv["description"],
4112 "unread" => $cv["counter"],
4116 array_push($feeds, $row);
4123 if ($cat_id == -4 ||
$cat_id == -1) {
4124 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4125 $unread = getFeedUnread($link, $i);
4127 if ($unread ||
!$unread_only) {
4128 $title = getFeedTitle($link, $i);
4133 "unread" => $unread,
4136 array_push($feeds, $row);
4144 if ($include_nested && $cat_id) {
4145 $result = db_query($link, "SELECT
4146 id, title FROM ttrss_feed_categories
4147 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4148 " ORDER BY id, title");
4150 while ($line = db_fetch_assoc($result)) {
4151 $unread = getFeedUnread($link, $line["id"], true) +
4152 getCategoryChildrenUnread($link, $line["id"]);
4154 if ($unread ||
!$unread_only) {
4156 "id" => $line["id"],
4157 "title" => $line["title"],
4158 "unread" => $unread,
4161 array_push($feeds, $row);
4169 $limit_qpart = "LIMIT $limit OFFSET $offset";
4174 if ($cat_id == -4 ||
$cat_id == -3) {
4175 $result = db_query($link, "SELECT
4176 id, feed_url, cat_id, title, order_id, ".
4177 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4178 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4179 " ORDER BY cat_id, title " . $limit_qpart);
4183 $cat_qpart = "cat_id = '$cat_id'";
4185 $cat_qpart = "cat_id IS NULL";
4187 $result = db_query($link, "SELECT
4188 id, feed_url, cat_id, title, order_id, ".
4189 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4190 FROM ttrss_feeds WHERE
4191 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4192 " ORDER BY cat_id, title " . $limit_qpart);
4195 while ($line = db_fetch_assoc($result)) {
4197 $unread = getFeedUnread($link, $line["id"]);
4199 $has_icon = feed_has_icon($line['id']);
4201 if ($unread ||
!$unread_only) {
4204 "feed_url" => $line["feed_url"],
4205 "title" => $line["title"],
4206 "id" => (int)$line["id"],
4207 "unread" => (int)$unread,
4208 "has_icon" => $has_icon,
4209 "cat_id" => (int)$line["cat_id"],
4210 "last_updated" => strtotime($line["last_updated"]),
4211 "order_id" => (int) $line["order_id"],
4214 array_push($feeds, $row);
4221 function api_get_headlines($link, $feed_id, $limit, $offset,
4222 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4223 $include_attachments, $since_id,
4224 $search = "", $search_mode = "", $match_on = "",
4225 $include_nested = false, $sanitize_content = true) {
4227 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4228 $view_mode, $is_cat, $search, $search_mode, $match_on,
4229 $order, $offset, 0, false, $since_id, $include_nested);
4231 $result = $qfh_ret[0];
4232 $feed_title = $qfh_ret[1];
4234 $headlines = array();
4236 while ($line = db_fetch_assoc($result)) {
4237 $is_updated = ($line["last_read"] == "" &&
4238 ($line["unread"] != "t" && $line["unread"] != "1"));
4240 $tags = explode(",", $line["tag_cache"]);
4241 $labels = json_decode($line["label_cache"], true);
4243 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4244 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4246 $headline_row = array(
4247 "id" => (int)$line["id"],
4248 "unread" => sql_bool_to_bool($line["unread"]),
4249 "marked" => sql_bool_to_bool($line["marked"]),
4250 "published" => sql_bool_to_bool($line["published"]),
4251 "updated" => strtotime($line["updated"]),
4252 "is_updated" => $is_updated,
4253 "title" => $line["title"],
4254 "link" => $line["link"],
4255 "feed_id" => $line["feed_id"],
4259 if ($include_attachments)
4260 $headline_row['attachments'] = get_article_enclosures($link,
4263 if ($show_excerpt) {
4264 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4265 $headline_row["excerpt"] = $excerpt;
4268 if ($show_content) {
4270 if ($line["cached_content"] != "") {
4271 $line["content_preview"] =& $line["cached_content"];
4274 if ($sanitize_content) {
4275 $headline_row["content"] = sanitize($link,
4276 $line["content_preview"], false, false, $line["site_url"]);
4278 $headline_row["content"] = $line["content_preview"];
4282 // unify label output to ease parsing
4283 if ($labels["no-labels"] == 1) $labels = array();
4285 $headline_row["labels"] = $labels;
4287 $headline_row["feed_title"] = $line["feed_title"];
4289 $headline_row["comments_count"] = (int)$line["num_comments"];
4290 $headline_row["comments_link"] = $line["comments"];
4292 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4294 array_push($headlines, $headline_row);
4300 function generate_error_feed($link, $error) {
4303 $reply['headlines']['id'] = -6;
4304 $reply['headlines']['is_cat'] = false;
4306 $reply['headlines']['toolbar'] = '';
4307 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4309 $reply['headlines-info'] = array("count" => 0,
4310 "vgroup_last_feed" => '',
4312 "disable_cache" => true);
4318 function generate_dashboard_feed($link) {
4321 $reply['headlines']['id'] = -5;
4322 $reply['headlines']['is_cat'] = false;
4324 $reply['headlines']['toolbar'] = '';
4325 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4327 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4329 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4330 WHERE owner_uid = " . $_SESSION['uid']);
4332 $last_updated = db_fetch_result($result, 0, "last_updated");
4333 $last_updated = make_local_datetime($link, $last_updated, false);
4335 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4337 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4338 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4340 $num_errors = db_fetch_result($result, 0, "num_errors");
4342 if ($num_errors > 0) {
4343 $reply['headlines']['content'] .= "<br/>";
4344 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4345 __('Some feeds have update errors (click for details)')."</a>";
4347 $reply['headlines']['content'] .= "</span></p>";
4349 $reply['headlines-info'] = array("count" => 0,
4350 "vgroup_last_feed" => '',
4352 "disable_cache" => true);
4357 function save_email_address($link, $email) {
4358 // FIXME: implement persistent storage of emails
4360 if (!$_SESSION['stored_emails'])
4361 $_SESSION['stored_emails'] = array();
4363 if (!in_array($email, $_SESSION['stored_emails']))
4364 array_push($_SESSION['stored_emails'], $email);
4367 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4368 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4370 $sql_is_cat = bool_to_sql_bool($is_cat);
4372 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4373 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4374 AND owner_uid = " . $owner_uid);
4376 if (db_num_rows($result) == 1) {
4377 $key = db_escape_string(sha1(uniqid(rand(), true)));
4379 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4380 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4381 AND owner_uid = " . $owner_uid);
4386 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4390 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4392 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4394 $sql_is_cat = bool_to_sql_bool($is_cat);
4396 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4397 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4398 AND owner_uid = " . $owner_uid);
4400 if (db_num_rows($result) == 1) {
4401 return db_fetch_result($result, 0, "access_key");
4403 $key = db_escape_string(sha1(uniqid(rand(), true)));
4405 $result = db_query($link, "INSERT INTO ttrss_access_keys
4406 (access_key, feed_id, is_cat, owner_uid)
4407 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4414 function get_feeds_from_html($url, $content)
4416 $url = fix_url($url);
4417 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4419 libxml_use_internal_errors(true);
4421 $doc = new DOMDocument();
4422 $doc->loadHTML($content);
4423 $xpath = new DOMXPath($doc);
4424 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4425 $feedUrls = array();
4426 foreach ($entries as $entry) {
4427 if ($entry->hasAttribute('href')) {
4428 $title = $entry->getAttribute('title');
4430 $title = $entry->getAttribute('type');
4432 $feedUrl = rewrite_relative_url(
4433 $baseUrl, $entry->getAttribute('href')
4435 $feedUrls[$feedUrl] = $title;
4441 function is_html($content) {
4442 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4445 function url_is_html($url, $login = false, $pass = false) {
4446 return is_html(fetch_file_contents($url, false, $login, $pass));
4449 function print_label_select($link, $name, $value, $attributes = "") {
4451 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4452 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4454 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4455 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4457 while ($line = db_fetch_assoc($result)) {
4459 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4461 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4462 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4466 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4473 function format_article_enclosures($link, $id, $always_display_enclosures,
4476 $result = get_article_enclosures($link, $id);
4479 if (count($result) > 0) {
4481 $entries_html = array();
4484 foreach ($result as $line) {
4486 $url = $line["content_url"];
4487 $ctype = $line["content_type"];
4489 if (!$ctype) $ctype = __("unknown type");
4491 $filename = substr($url, strrpos($url, "/")+
1);
4493 # $player = format_inline_player($link, $url, $ctype);
4495 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4496 # $filename . " (" . $ctype . ")" . "</a>";
4498 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4499 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4501 array_push($entries_html, $entry);
4505 $entry["type"] = $ctype;
4506 $entry["filename"] = $filename;
4507 $entry["url"] = $url;
4509 array_push($entries, $entry);
4512 if (!get_pref($link, "STRIP_IMAGES")) {
4513 if ($always_display_enclosures ||
4514 !preg_match("/<img/i", $article_content)) {
4516 foreach ($entries as $entry) {
4518 if (preg_match("/image/", $entry["type"]) ||
4519 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4522 alt=\"".htmlspecialchars($entry["filename"])."\"
4523 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4530 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4531 "<span>" . __('Attachments')."</span>";
4532 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4534 foreach ($entries_html as $entry) { $rv .= $entry; };
4536 $rv .= "</div></div>";
4542 function getLastArticleId($link) {
4543 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4544 WHERE owner_uid = " . $_SESSION["uid"]);
4546 if (db_num_rows($result) == 1) {
4547 return db_fetch_result($result, 0, "id");
4553 function build_url($parts) {
4554 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4558 * Converts a (possibly) relative URL to a absolute one.
4560 * @param string $url Base URL (i.e. from where the document is)
4561 * @param string $rel_url Possibly relative URL in the document
4563 * @return string Absolute URL
4565 function rewrite_relative_url($url, $rel_url) {
4566 if (strpos($rel_url, "magnet:") === 0) {
4568 } else if (strpos($rel_url, "://") !== false) {
4570 } else if (strpos($rel_url, "//") === 0) {
4571 # protocol-relative URL (rare but they exist)
4573 } else if (strpos($rel_url, "/") === 0)
4575 $parts = parse_url($url);
4576 $parts['path'] = $rel_url;
4578 return build_url($parts);
4581 $parts = parse_url($url);
4582 if (!isset($parts['path'])) {
4583 $parts['path'] = '/';
4585 $dir = $parts['path'];
4586 if (substr($dir, -1) !== '/') {
4587 $dir = dirname($parts['path']);
4588 $dir !== '/' && $dir .= '/';
4590 $parts['path'] = $dir . $rel_url;
4592 return build_url($parts);
4596 function sphinx_search($query, $offset = 0, $limit = 30) {
4597 require_once 'lib/sphinxapi.php';
4599 $sphinxClient = new SphinxClient();
4601 $sphinxClient->SetServer('localhost', 9312);
4602 $sphinxClient->SetConnectTimeout(1);
4604 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4605 'feed_title' => 20));
4607 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4608 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4609 $sphinxClient->SetLimits($offset, $limit, 1000);
4610 $sphinxClient->SetArrayResult(false);
4611 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4613 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4617 if (is_array($result['matches'])) {
4618 foreach (array_keys($result['matches']) as $int_id) {
4619 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4620 array_push($ids, $ref_id);
4627 function cleanup_tags($link, $days = 14, $limit = 1000) {
4629 if (DB_TYPE
== "pgsql") {
4630 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4631 } else if (DB_TYPE
== "mysql") {
4632 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4637 while ($limit > 0) {
4640 $query = "SELECT ttrss_tags.id AS id
4641 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4642 WHERE post_int_id = int_id AND $interval_query AND
4643 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4645 $result = db_query($link, $query);
4649 while ($line = db_fetch_assoc($result)) {
4650 array_push($ids, $line['id']);
4653 if (count($ids) > 0) {
4654 $ids = join(",", $ids);
4657 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4658 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4663 $limit -= $limit_part;
4668 return $tags_deleted;
4671 function print_user_stylesheet($link) {
4672 $value = get_pref($link, 'USER_STYLESHEET');
4675 print "<style type=\"text/css\">";
4676 print str_replace("<br/>", "\n", $value);
4682 /* function rewrite_urls($line) {
4687 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4688 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4693 function rewrite_urls($html) {
4694 libxml_use_internal_errors(true);
4696 $charset_hack = '<head>
4697 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4700 $doc = new DOMDocument();
4701 $doc->loadHTML($charset_hack . $html);
4702 $xpath = new DOMXPath($doc);
4704 $entries = $xpath->query('//*/text()');
4706 foreach ($entries as $entry) {
4707 if (strstr($entry->wholeText
, "://") !== false) {
4708 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4709 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4711 if ($text != $entry->wholeText
) {
4712 $cdoc = new DOMDocument();
4713 $cdoc->loadHTML($charset_hack . $text);
4716 foreach ($cdoc->childNodes
as $cnode) {
4717 $cnode = $doc->importNode($cnode, true);
4720 $entry->parentNode
->insertBefore($cnode);
4724 $entry->parentNode
->removeChild($entry);
4730 $node = $doc->getElementsByTagName('body')->item(0);
4732 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4734 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4739 function filter_to_sql($link, $filter, $owner_uid) {
4742 if (DB_TYPE
== "pgsql")
4745 $reg_qpart = "REGEXP";
4747 foreach ($filter["rules"] AS $rule) {
4748 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4749 $rule['reg_exp']) !== FALSE;
4751 if ($regexp_valid) {
4753 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4755 switch ($rule["type"]) {
4757 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4758 $rule['reg_exp'] . "')";
4761 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4762 $rule['reg_exp'] . "')";
4765 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4766 $rule['reg_exp'] . "') OR LOWER(" .
4767 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4770 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4771 $rule['reg_exp'] . "')";
4774 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4775 $rule['reg_exp'] . "')";
4778 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4779 $rule['reg_exp'] . "')";
4783 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4784 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4787 if (isset($rule["cat_id"])) {
4789 if ($rule["cat_id"] > 0) {
4790 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4791 array_push($children, $rule["cat_id"]);
4793 $children = join(",", $children);
4795 $cat_qpart = "cat_id IN ($children)";
4797 $cat_qpart = "cat_id IS NULL";
4800 $qpart .= " AND $cat_qpart";
4803 array_push($query, "($qpart)");
4808 if (count($query) > 0) {
4809 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
4815 if (!function_exists('gzdecode')) {
4816 function gzdecode($string) { // no support for 2nd argument
4817 return file_get_contents('compress.zlib://data:who/cares;base64,'.
4818 base64_encode($string));
4822 function get_random_bytes($length) {
4823 if (function_exists('openssl_random_pseudo_bytes')) {
4824 return openssl_random_pseudo_bytes($length);
4828 for ($i = 0; $i < $length; $i++
)
4829 $output .= chr(mt_rand(0, 255));
4835 function read_stdin() {
4836 $fp = fopen("php://stdin", "r");
4839 $line = trim(fgets($fp));
4847 function tmpdirname($path, $prefix) {
4848 // Use PHP's tmpfile function to create a temporary
4849 // directory name. Delete the file and keep the name.
4850 $tempname = tempnam($path,$prefix);
4854 if (!unlink($tempname))
4860 function getFeedCategory($link, $feed) {
4861 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
4862 WHERE id = '$feed'");
4864 if (db_num_rows($result) > 0) {
4865 return db_fetch_result($result, 0, "cat_id");
4872 function create_published_article($link, $title, $url, $content, $labels_str,
4875 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
4876 $content_hash = sha1($content);
4878 if ($labels_str != "") {
4879 $labels = explode(",", $labels_str);
4886 if (!$title) $title = $url;
4887 if (!$title && !$url) return false;
4889 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
4891 db_query($link, "BEGIN");
4893 // only check for our user data here, others might have shared this with different content etc
4894 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
4895 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
4897 if (db_num_rows($result) != 0) {
4898 $ref_id = db_fetch_result($result, 0, "id");
4900 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
4901 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
4903 if (db_num_rows($result) != 0) {
4904 $int_id = db_fetch_result($result, 0, "int_id");
4906 db_query($link, "UPDATE ttrss_entries SET
4907 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
4909 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
4910 int_id = '$int_id' AND owner_uid = '$owner_uid'");
4913 db_query($link, "INSERT INTO ttrss_user_entries
4914 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4916 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4919 if (count($labels) != 0) {
4920 foreach ($labels as $label) {
4921 label_add_article($link, $ref_id, trim($label), $owner_uid);
4928 $result = db_query($link, "INSERT INTO ttrss_entries
4929 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
4931 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
4933 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
4935 if (db_num_rows($result) != 0) {
4936 $ref_id = db_fetch_result($result, 0, "id");
4938 db_query($link, "INSERT INTO ttrss_user_entries
4939 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4941 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4943 if (count($labels) != 0) {
4944 foreach ($labels as $label) {
4945 label_add_article($link, $ref_id, trim($label), $owner_uid);
4953 db_query($link, "COMMIT");
4958 function implements_interface($class, $interface) {
4959 return in_array($interface, class_implements($class));