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);
571 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER
) as $plugin) {
573 $user_id = (int) $plugin->authenticate($login, $password);
576 $_SESSION["auth_module"] = strtolower(get_class($plugin));
581 if ($user_id && !$check_only) {
582 $_SESSION["uid"] = $user_id;
584 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
585 WHERE id = '$user_id'");
587 $_SESSION["name"] = db_fetch_result($result, 0, "login");
588 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
589 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
591 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
594 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
595 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
597 $_SESSION["last_version_check"] = time();
599 initialize_user_prefs($link, $_SESSION["uid"]);
608 $_SESSION["uid"] = 1;
609 $_SESSION["name"] = "admin";
610 $_SESSION["access_level"] = 10;
612 $_SESSION["hide_hello"] = true;
613 $_SESSION["hide_logout"] = true;
615 $_SESSION["auth_module"] = false;
617 if (!$_SESSION["csrf_token"]) {
618 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
621 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
623 initialize_user_prefs($link, $_SESSION["uid"]);
629 function make_password($length = 8) {
632 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
636 while ($i < $length) {
637 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
639 if (!strstr($password, $char)) {
647 // this is called after user is created to initialize default feeds, labels
650 // user preferences are checked on every login, not here
652 function initialize_user($link, $uid) {
654 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
655 values ('$uid', 'Tiny Tiny RSS: New Releases',
656 'http://tt-rss.org/releases.rss')");
658 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
659 values ('$uid', 'Tiny Tiny RSS: Forum',
660 'http://tt-rss.org/forum/rss.php')");
663 function logout_user() {
665 if (isset($_COOKIE[session_name()])) {
666 setcookie(session_name(), '', time()-42000, '/');
670 function validate_csrf($csrf_token) {
671 return $csrf_token == $_SESSION['csrf_token'];
674 function validate_session($link) {
675 if (SINGLE_USER_MODE
) return true;
677 $check_ip = $_SESSION['ip_address'];
679 switch (SESSION_CHECK_ADDRESS
) {
684 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
687 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
688 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
692 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
693 $_SESSION["login_error_msg"] =
694 __("Session failed to validate (incorrect IP)");
698 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
701 if ($_SESSION["uid"]) {
703 $result = db_query($link,
704 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
706 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
708 if ($pwd_hash != $_SESSION["pwd_hash"]) {
713 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
715 //print_r($_SESSION);
717 if (time() > $_SESSION["cookie_lifetime"]) {
725 function load_user_plugins($link, $owner_uid) {
727 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
730 $pluginhost->load($plugins, $pluginhost::KIND_USER
, $owner_uid);
731 $pluginhost->load_data();
735 function login_sequence($link, $login_form = 0) {
736 if (SINGLE_USER_MODE
) {
737 authenticate_user($link, "admin", null);
738 load_user_plugins($link, $_SESSION["uid"]);
740 if (!$_SESSION["uid"] ||
!validate_session($link)) {
742 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
743 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
745 authenticate_user($link, null, null, true);
748 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
751 /* bump login timestamp */
752 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
756 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
757 setcookie("ttrss_lang", $_SESSION["language"],
758 time() + SESSION_COOKIE_LIFETIME
);
761 if ($_SESSION["uid"]) {
762 load_user_plugins($link, $_SESSION["uid"]);
767 function truncate_string($str, $max_len, $suffix = '…') {
768 if (mb_strlen($str, "utf-8") > $max_len - 3) {
769 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
775 function theme_image($link, $filename) {
777 $theme_path = get_user_theme_path($link);
779 if ($theme_path && is_file($theme_path.$filename)) {
780 return $theme_path.$filename;
789 function get_user_theme($link) {
791 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
792 $theme_name = get_pref($link, "_THEME_ID");
793 if (is_dir("themes/$theme_name")) {
804 function get_user_theme_path($link) {
807 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
808 $theme_name = get_pref($link, "_THEME_ID");
810 if ($theme_name && is_dir("themes/$theme_name")) {
811 $theme_path = "themes/$theme_name/";
820 if (is_file("$theme_path/theme.ini")) {
821 $ini = parse_ini_file("$theme_path/theme.ini", true);
822 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
830 function get_user_theme_options($link) {
831 $t = get_user_theme_path($link);
834 if (is_file("$t/theme.ini")) {
835 $ini = parse_ini_file("$t/theme.ini", true);
836 if ($ini['theme']['version']) {
837 return $ini['theme']['options'];
844 function print_theme_includes($link) {
846 $t = get_user_theme_path($link);
850 print "<link rel=\"stylesheet\" type=\"text/css\"
851 href=\"$t/theme.css?$time \">";
852 if (file_exists("$t/theme.js")) {
853 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
859 function get_all_themes() {
860 $themes = glob("themes/*");
866 foreach ($themes as $t) {
867 if (is_file("$t/theme.ini")) {
868 $ini = parse_ini_file("$t/theme.ini", true);
869 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
870 !$ini['theme']['disabled']) {
873 $entry["base"] = basename($t);
874 $entry["name"] = $ini['theme']['name'];
875 $entry["version"] = $ini['theme']['version'];
876 $entry["author"] = $ini['theme']['author'];
877 $entry["options"] = $ini['theme']['options'];
878 array_push($rv, $entry);
886 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
889 $source_tz = new DateTimeZone($source_tz);
890 } catch (Exception
$e) {
891 $source_tz = new DateTimeZone('UTC');
895 $dest_tz = new DateTimeZone($dest_tz);
896 } catch (Exception
$e) {
897 $dest_tz = new DateTimeZone('UTC');
900 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
901 return $dt->format('U') +
$dest_tz->getOffset($dt);
904 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
905 $no_smart_dt = false) {
907 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
908 if (!$timestamp) $timestamp = '1970-01-01 0:00';
913 # We store date in UTC internally
914 $dt = new DateTime($timestamp, $utc_tz);
916 if ($tz_offset == -1) {
918 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
921 $user_tz = new DateTimeZone($user_tz_string);
922 } catch (Exception
$e) {
926 $tz_offset = $user_tz->getOffset($dt);
929 $user_timestamp = $dt->format('U') +
$tz_offset;
932 return smart_date_time($link, $user_timestamp,
933 $tz_offset, $owner_uid);
936 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
938 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
940 return date($format, $user_timestamp);
944 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
945 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
947 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
948 return date("G:i", $timestamp);
949 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
950 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
951 return date($format, $timestamp);
953 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
954 return date($format, $timestamp);
958 function sql_bool_to_bool($s) {
959 if ($s == "t" ||
$s == "1" ||
$s == "true") {
966 function bool_to_sql_bool($s) {
974 // Session caching removed due to causing wrong redirects to upgrade
975 // script when get_schema_version() is called on an obsolete session
976 // created on a previous schema version.
977 function get_schema_version($link, $nocache = false) {
978 global $schema_version;
980 if (!$schema_version) {
981 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
982 $version = db_fetch_result($result, 0, "schema_version");
983 $schema_version = $version;
986 return $schema_version;
990 function sanity_check($link) {
991 require_once 'errors.php';
994 $schema_version = get_schema_version($link, true);
996 if ($schema_version != SCHEMA_VERSION
) {
1000 if (DB_TYPE
== "mysql") {
1001 $result = db_query($link, "SELECT true", false);
1002 if (db_num_rows($result) != 1) {
1007 if (db_escape_string("testTEST") != "testTEST") {
1011 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1014 function file_is_locked($filename) {
1015 if (function_exists('flock')) {
1016 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1018 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1019 flock($fp, LOCK_UN
);
1029 return true; // consider the file always locked and skip the test
1032 function make_lockfile($filename) {
1033 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1035 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1036 if (function_exists('posix_getpid')) {
1037 fwrite($fp, posix_getpid() . "\n");
1045 function make_stampfile($filename) {
1046 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1048 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1049 fwrite($fp, time() . "\n");
1050 flock($fp, LOCK_UN
);
1058 function sql_random_function() {
1059 if (DB_TYPE
== "mysql") {
1066 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1068 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1070 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1072 $ref_check_qpart = ($max_id &&
1073 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1075 if (is_numeric($feed)) {
1081 $children = getChildCategories($link, $feed, $owner_uid);
1082 array_push($children, $feed);
1084 $children = join(",", $children);
1086 $cat_qpart = "cat_id IN ($children)";
1088 $cat_qpart = "cat_id IS NULL";
1091 db_query($link, "UPDATE ttrss_user_entries
1092 SET unread = false,last_read = NOW()
1093 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1094 AND $ref_check_qpart
1095 AND owner_uid = $owner_uid");
1097 } else if ($feed == -2) {
1099 db_query($link, "UPDATE ttrss_user_entries
1100 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1101 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1102 AND $ref_check_qpart
1103 AND unread = true AND owner_uid = $owner_uid");
1106 } else if ($feed > 0) {
1108 db_query($link, "UPDATE ttrss_user_entries
1109 SET unread = false,last_read = NOW()
1110 WHERE feed_id = '$feed'
1111 AND $ref_check_qpart
1112 AND owner_uid = $owner_uid");
1114 } else if ($feed < 0 && $feed > -10) { // special, like starred
1117 db_query($link, "UPDATE ttrss_user_entries
1118 SET unread = false,last_read = NOW()
1120 AND $ref_check_qpart
1121 AND owner_uid = $owner_uid");
1125 db_query($link, "UPDATE ttrss_user_entries
1126 SET unread = false,last_read = NOW()
1127 WHERE published = true
1128 AND $ref_check_qpart
1129 AND owner_uid = $owner_uid");
1134 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1136 if (DB_TYPE
== "pgsql") {
1137 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1139 $match_part = "updated > DATE_SUB(NOW(),
1140 INTERVAL $intl HOUR) ";
1143 $result = db_query($link, "SELECT id FROM ttrss_entries,
1144 ttrss_user_entries WHERE $match_part AND
1146 ttrss_user_entries.ref_id = ttrss_entries.id AND
1147 owner_uid = $owner_uid");
1149 $affected_ids = array();
1151 while ($line = db_fetch_assoc($result)) {
1152 array_push($affected_ids, $line["id"]);
1155 catchupArticlesById($link, $affected_ids, 0);
1159 db_query($link, "UPDATE ttrss_user_entries
1160 SET unread = false,last_read = NOW()
1161 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1164 } else if ($feed < -10) { // label
1166 $label_id = -$feed - 11;
1168 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1169 SET unread = false, last_read = NOW()
1170 WHERE label_id = '$label_id' AND unread = true
1171 AND $ref_check_qpart
1172 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1176 ccache_update($link, $feed, $owner_uid, $cat_view);
1179 db_query($link, "BEGIN");
1181 $tag_name = db_escape_string($feed);
1183 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1184 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1186 while ($line = db_fetch_assoc($result)) {
1187 db_query($link, "UPDATE ttrss_user_entries SET
1188 unread = false, last_read = NOW()
1189 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1191 db_query($link, "COMMIT");
1195 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1197 if (!$omode) $omode = "flc";
1199 $data = getGlobalCounters($link);
1201 $data = array_merge($data, getVirtCounters($link));
1203 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1204 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1205 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1206 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1211 function getCategoryTitle($link, $cat_id) {
1213 if ($cat_id == -1) {
1214 return __("Special");
1215 } else if ($cat_id == -2) {
1216 return __("Labels");
1219 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1222 if (db_num_rows($result) == 1) {
1223 return db_fetch_result($result, 0, "title");
1225 return __("Uncategorized");
1231 function getCategoryCounters($link) {
1234 /* Labels category */
1236 $cv = array("id" => -2, "kind" => "cat",
1237 "counter" => getCategoryUnread($link, -2));
1239 array_push($ret_arr, $cv);
1241 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1242 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1243 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1244 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1245 WHERE ttrss_cat_counters_cache.feed_id = id AND
1246 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1247 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1249 while ($line = db_fetch_assoc($result)) {
1250 $line["cat_id"] = (int) $line["cat_id"];
1252 if ($line["num_children"] > 0) {
1253 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1258 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1259 "counter" => $line["unread"] +
$child_counter);
1261 array_push($ret_arr, $cv);
1264 /* Special case: NULL category doesn't actually exist in the DB */
1266 $cv = array("id" => 0, "kind" => "cat",
1267 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1269 array_push($ret_arr, $cv);
1274 // only accepts real cats (>= 0)
1275 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1276 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1278 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1279 AND owner_uid = $owner_uid");
1283 while ($line = db_fetch_assoc($result)) {
1284 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1285 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1291 function getCategoryUnread($link, $cat, $owner_uid = false) {
1293 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1298 $cat_query = "cat_id = '$cat'";
1300 $cat_query = "cat_id IS NULL";
1303 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1304 AND owner_uid = " . $owner_uid);
1306 $cat_feeds = array();
1307 while ($line = db_fetch_assoc($result)) {
1308 array_push($cat_feeds, "feed_id = " . $line["id"]);
1311 if (count($cat_feeds) == 0) return 0;
1313 $match_part = implode(" OR ", $cat_feeds);
1315 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1316 FROM ttrss_user_entries
1317 WHERE unread = true AND ($match_part)
1318 AND owner_uid = " . $owner_uid);
1322 # this needs to be rewritten
1323 while ($line = db_fetch_assoc($result)) {
1324 $unread +
= $line["unread"];
1328 } else if ($cat == -1) {
1329 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1330 } else if ($cat == -2) {
1332 $result = db_query($link, "
1333 SELECT COUNT(unread) AS unread FROM
1334 ttrss_user_entries, ttrss_user_labels2
1335 WHERE article_id = ref_id AND unread = true
1336 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1338 $unread = db_fetch_result($result, 0, "unread");
1345 function getFeedUnread($link, $feed, $is_cat = false) {
1346 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1349 function getLabelUnread($link, $label_id, $owner_uid = false) {
1350 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1352 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1353 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1355 if (db_num_rows($result) != 0) {
1356 return db_fetch_result($result, 0, "unread");
1362 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1363 $owner_uid = false) {
1365 $n_feed = (int) $feed;
1366 $need_entries = false;
1368 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1371 $unread_qpart = "unread = true";
1373 $unread_qpart = "true";
1377 return getCategoryUnread($link, $n_feed, $owner_uid);
1378 } else if ($n_feed == -6) {
1380 } else if ($feed != "0" && $n_feed == 0) {
1382 $feed = db_escape_string($feed);
1384 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1385 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1386 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1387 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1388 return db_fetch_result($result, 0, "count");
1390 } else if ($n_feed == -1) {
1391 $match_part = "marked = true";
1392 } else if ($n_feed == -2) {
1393 $match_part = "published = true";
1394 } else if ($n_feed == -3) {
1395 $match_part = "unread = true AND score >= 0";
1397 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1399 if (DB_TYPE
== "pgsql") {
1400 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1402 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1405 $need_entries = true;
1407 } else if ($n_feed == -4) {
1408 $match_part = "true";
1409 } else if ($n_feed >= 0) {
1412 $match_part = "feed_id = '$n_feed'";
1414 $match_part = "feed_id IS NULL";
1417 } else if ($feed < -10) {
1419 $label_id = -$feed - 11;
1421 return getLabelUnread($link, $label_id, $owner_uid);
1427 if ($need_entries) {
1428 $from_qpart = "ttrss_user_entries,ttrss_entries";
1429 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1431 $from_qpart = "ttrss_user_entries";
1434 $query = "SELECT count(int_id) AS unread
1435 FROM $from_qpart WHERE
1436 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1438 //echo "[$feed/$query]\n";
1440 $result = db_query($link, $query);
1444 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1445 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1446 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1447 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1450 $unread = db_fetch_result($result, 0, "unread");
1455 function getGlobalUnread($link, $user_id = false) {
1458 $user_id = $_SESSION["uid"];
1461 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1462 WHERE owner_uid = '$user_id' AND feed_id > 0");
1464 $c_id = db_fetch_result($result, 0, "c_id");
1469 function getGlobalCounters($link, $global_unread = -1) {
1472 if ($global_unread == -1) {
1473 $global_unread = getGlobalUnread($link);
1476 $cv = array("id" => "global-unread",
1477 "counter" => (int) $global_unread);
1479 array_push($ret_arr, $cv);
1481 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1482 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1484 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1486 $cv = array("id" => "subscribed-feeds",
1487 "counter" => (int) $subscribed_feeds);
1489 array_push($ret_arr, $cv);
1494 function getTagCounters($link) {
1498 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1499 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1500 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1501 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1502 ORDER BY count DESC LIMIT 55");
1506 while ($line = db_fetch_assoc($result)) {
1507 $tags[$line["tag_name"]] +
= $line["count"];
1510 foreach (array_keys($tags) as $tag) {
1511 $unread = $tags[$tag];
1512 $tag = htmlspecialchars($tag);
1514 $cv = array("id" => $tag,
1516 "counter" => $unread);
1518 array_push($ret_arr, $cv);
1524 function getVirtCounters($link) {
1528 for ($i = 0; $i >= -4; $i--) {
1530 $count = getFeedUnread($link, $i);
1532 $cv = array("id" => $i,
1533 "counter" => (int) $count);
1535 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1536 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1538 array_push($ret_arr, $cv);
1544 function getLabelCounters($link, $descriptions = false) {
1548 $owner_uid = $_SESSION["uid"];
1550 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1551 WHERE owner_uid = '$owner_uid'");
1553 while ($line = db_fetch_assoc($result)) {
1555 $id = -$line["id"] - 11;
1557 $label_name = $line["caption"];
1558 $count = getFeedUnread($link, $id);
1560 $cv = array("id" => $id,
1561 "counter" => (int) $count);
1564 $cv["description"] = $label_name;
1566 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1567 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1569 array_push($ret_arr, $cv);
1575 function getFeedCounters($link, $active_feed = false) {
1579 $query = "SELECT ttrss_feeds.id,
1581 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1582 last_error, value AS count
1583 FROM ttrss_feeds, ttrss_counters_cache
1584 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1585 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1586 AND ttrss_counters_cache.feed_id = id";
1588 $result = db_query($link, $query);
1589 $fctrs_modified = false;
1591 while ($line = db_fetch_assoc($result)) {
1594 $count = $line["count"];
1595 $last_error = htmlspecialchars($line["last_error"]);
1597 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1599 $has_img = feed_has_icon($id);
1601 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1604 $cv = array("id" => $id,
1605 "updated" => $last_updated,
1606 "counter" => (int) $count,
1607 "has_img" => (int) $has_img);
1610 $cv["error"] = $last_error;
1612 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1613 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1615 if ($active_feed && $id == $active_feed)
1616 $cv["title"] = truncate_string($line["title"], 30);
1618 array_push($ret_arr, $cv);
1625 function get_pgsql_version($link) {
1626 $result = db_query($link, "SELECT version() AS version");
1627 $version = explode(" ", db_fetch_result($result, 0, "version"));
1632 * @return array (code => Status code, message => error message if available)
1634 * 0 - OK, Feed already exists
1635 * 1 - OK, Feed added
1637 * 3 - URL content is HTML, no feeds available
1638 * 4 - URL content is HTML which contains multiple feeds.
1639 * Here you should call extractfeedurls in rpc-backend
1640 * to get all possible feeds.
1641 * 5 - Couldn't download the URL content.
1643 function subscribe_to_feed($link, $url, $cat_id = 0,
1644 $auth_login = '', $auth_pass = '', $need_auth = false) {
1646 global $fetch_last_error;
1648 require_once "include/rssfuncs.php";
1650 $url = fix_url($url);
1652 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1654 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1657 return array("code" => 5, "message" => $fetch_last_error);
1660 if (is_html($contents)) {
1661 $feedUrls = get_feeds_from_html($url, $contents);
1663 if (count($feedUrls) == 0) {
1664 return array("code" => 3);
1665 } else if (count($feedUrls) > 1) {
1666 return array("code" => 4, "feeds" => $feedUrls);
1668 //use feed url as new URL
1669 $url = key($feedUrls);
1672 if ($cat_id == "0" ||
!$cat_id) {
1673 $cat_qpart = "NULL";
1675 $cat_qpart = "'$cat_id'";
1678 $result = db_query($link,
1679 "SELECT id FROM ttrss_feeds
1680 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1682 if (db_num_rows($result) == 0) {
1683 $result = db_query($link,
1684 "INSERT INTO ttrss_feeds
1685 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1686 VALUES ('".$_SESSION["uid"]."', '$url',
1687 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1689 $result = db_query($link,
1690 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1691 AND owner_uid = " . $_SESSION["uid"]);
1693 $feed_id = db_fetch_result($result, 0, "id");
1696 update_rss_feed($link, $feed_id, true);
1699 return array("code" => 1);
1701 return array("code" => 0);
1705 function print_feed_select($link, $id, $default_id = "",
1706 $attributes = "", $include_all_feeds = true,
1707 $root_id = false, $nest_level = 0) {
1710 print "<select id=\"$id\" name=\"$id\" $attributes>";
1711 if ($include_all_feeds) {
1712 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1713 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1717 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1720 $parent_qpart = "parent_cat = '$root_id'";
1722 $parent_qpart = "parent_cat IS NULL";
1724 $result = db_query($link, "SELECT id,title,
1725 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1726 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1727 FROM ttrss_feed_categories
1728 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1730 while ($line = db_fetch_assoc($result)) {
1732 for ($i = 0; $i < $nest_level; $i++
)
1733 $line["title"] = " - " . $line["title"];
1735 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1737 printf("<option $is_selected value='CAT:%d'>%s</option>",
1738 $line["id"], htmlspecialchars($line["title"]));
1740 if ($line["num_children"] > 0)
1741 print_feed_select($link, $id, $default_id, $attributes,
1742 $include_all_feeds, $line["id"], $nest_level+
1);
1744 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1745 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1747 while ($fline = db_fetch_assoc($feed_result)) {
1748 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1750 $fline["title"] = " + " . $fline["title"];
1752 for ($i = 0; $i < $nest_level; $i++
)
1753 $fline["title"] = " - " . $fline["title"];
1755 printf("<option $is_selected value='%d'>%s</option>",
1756 $fline["id"], htmlspecialchars($fline["title"]));
1761 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1763 printf("<option $is_selected value='CAT:0'>%s</option>",
1764 __("Uncategorized"));
1766 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1767 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1769 while ($fline = db_fetch_assoc($feed_result)) {
1770 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1772 $fline["title"] = " + " . $fline["title"];
1774 for ($i = 0; $i < $nest_level; $i++
)
1775 $fline["title"] = " - " . $fline["title"];
1777 printf("<option $is_selected value='%d'>%s</option>",
1778 $fline["id"], htmlspecialchars($fline["title"]));
1783 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1784 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1786 while ($line = db_fetch_assoc($result)) {
1788 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1790 printf("<option $is_selected value='%d'>%s</option>",
1791 $line["id"], htmlspecialchars($line["title"]));
1800 function print_feed_cat_select($link, $id, $default_id,
1801 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1804 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1808 $parent_qpart = "parent_cat = '$root_id'";
1810 $parent_qpart = "parent_cat IS NULL";
1812 $result = db_query($link, "SELECT id,title,
1813 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1814 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1815 FROM ttrss_feed_categories
1816 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1818 while ($line = db_fetch_assoc($result)) {
1819 if ($line["id"] == $default_id) {
1820 $is_selected = "selected=\"1\"";
1825 for ($i = 0; $i < $nest_level; $i++
)
1826 $line["title"] = " - " . $line["title"];
1829 printf("<option $is_selected value='%d'>%s</option>",
1830 $line["id"], htmlspecialchars($line["title"]));
1832 if ($line["num_children"] > 0)
1833 print_feed_cat_select($link, $id, $default_id, $attributes,
1834 $include_all_cats, $line["id"], $nest_level+
1);
1838 if ($include_all_cats) {
1839 if (db_num_rows($result) > 0) {
1840 print "<option disabled=\"1\">--------</option>";
1843 if ($default_id == 0) {
1844 $is_selected = "selected=\"1\"";
1849 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1855 function checkbox_to_sql_bool($val) {
1856 return ($val == "on") ?
"true" : "false";
1859 function getFeedCatTitle($link, $id) {
1861 return __("Special");
1862 } else if ($id < -10) {
1863 return __("Labels");
1864 } else if ($id > 0) {
1865 $result = db_query($link, "SELECT ttrss_feed_categories.title
1866 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1867 cat_id = ttrss_feed_categories.id");
1868 if (db_num_rows($result) == 1) {
1869 return db_fetch_result($result, 0, "title");
1871 return __("Uncategorized");
1874 return "getFeedCatTitle($id) failed";
1879 function getFeedIcon($id) {
1882 return "images/archive.png";
1885 return "images/mark_set.svg";
1888 return "images/pub_set.svg";
1891 return "images/fresh.png";
1894 return "images/tag.png";
1897 return "images/recently_read.png";
1901 return "images/label.png";
1903 if (file_exists(ICONS_DIR
. "/$id.ico"))
1904 return ICONS_URL
. "/$id.ico";
1910 function getFeedTitle($link, $id, $cat = false) {
1912 return getCategoryTitle($link, $id);
1913 } else if ($id == -1) {
1914 return __("Starred articles");
1915 } else if ($id == -2) {
1916 return __("Published articles");
1917 } else if ($id == -3) {
1918 return __("Fresh articles");
1919 } else if ($id == -4) {
1920 return __("All articles");
1921 } else if ($id === 0 ||
$id === "0") {
1922 return __("Archived articles");
1923 } else if ($id == -6) {
1924 return __("Recently read");
1925 } else if ($id < -10) {
1926 $label_id = -$id - 11;
1927 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1928 if (db_num_rows($result) == 1) {
1929 return db_fetch_result($result, 0, "caption");
1931 return "Unknown label ($label_id)";
1934 } else if (is_numeric($id) && $id > 0) {
1935 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1936 if (db_num_rows($result) == 1) {
1937 return db_fetch_result($result, 0, "title");
1939 return "Unknown feed ($id)";
1946 function make_init_params($link) {
1949 $params["theme"] = get_user_theme($link);
1950 $params["theme_options"] = get_user_theme_options($link);
1952 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1953 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1954 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1955 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
1957 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1958 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1959 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1960 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1962 $params[strtolower($param)] = (int) get_pref($link, $param);
1965 $params["icons_url"] = ICONS_URL
;
1966 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1967 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1968 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1969 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1970 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1972 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1973 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1975 $max_feed_id = db_fetch_result($result, 0, "mid");
1976 $num_feeds = db_fetch_result($result, 0, "nf");
1978 $params["max_feed_id"] = (int) $max_feed_id;
1979 $params["num_feeds"] = (int) $num_feeds;
1981 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1983 $params["csrf_token"] = $_SESSION["csrf_token"];
1988 function make_runtime_info($link) {
1991 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1992 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1994 $max_feed_id = db_fetch_result($result, 0, "mid");
1995 $num_feeds = db_fetch_result($result, 0, "nf");
1997 $data["max_feed_id"] = (int) $max_feed_id;
1998 $data["num_feeds"] = (int) $num_feeds;
2000 $data['last_article_id'] = getLastArticleId($link);
2001 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2003 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
2005 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2007 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2009 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2012 $stamp_delta = time() - $stamp;
2014 if ($stamp_delta > 1800) {
2018 $_SESSION["daemon_stamp_check"] = time();
2021 $data['daemon_stamp_ok'] = $stamp_check;
2023 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2025 $data['daemon_stamp'] = $stamp_fmt;
2030 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2031 $new_version_details = @check_for_update
($link);
2033 $data['new_version_available'] = (int) ($new_version_details != false);
2035 $_SESSION["last_version_check"] = time();
2036 $_SESSION["version_data"] = $new_version_details;
2042 function search_to_sql($link, $search, $match_on) {
2044 $search_query_part = "";
2046 $keywords = explode(" ", $search);
2047 $query_keywords = array();
2049 foreach ($keywords as $k) {
2050 if (strpos($k, "-") === 0) {
2057 $commandpair = explode(":", mb_strtolower($k), 2);
2059 if ($commandpair[0] == "note" && $commandpair[1]) {
2061 if ($commandpair[1] == "true")
2062 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2064 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2066 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2068 if ($commandpair[1] == "true")
2069 array_push($query_keywords, "($not (marked = true))");
2071 array_push($query_keywords, "($not (marked = false))");
2073 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2075 if ($commandpair[1] == "true")
2076 array_push($query_keywords, "($not (published = true))");
2078 array_push($query_keywords, "($not (published = false))");
2080 } else if (strpos($k, "@") === 0) {
2082 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2083 $orig_ts = strtotime(substr($k, 1));
2084 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2086 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2088 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2089 } else if ($match_on == "both") {
2090 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2091 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2092 } else if ($match_on == "title") {
2093 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2094 } else if ($match_on == "content") {
2095 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2099 $search_query_part = implode("AND", $query_keywords);
2101 return $search_query_part;
2104 function getParentCategories($link, $cat, $owner_uid) {
2107 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2108 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2110 while ($line = db_fetch_assoc($result)) {
2111 array_push($rv, $line["parent_cat"]);
2112 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2118 function getChildCategories($link, $cat, $owner_uid) {
2121 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2122 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2124 while ($line = db_fetch_assoc($result)) {
2125 array_push($rv, $line["id"]);
2126 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2132 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) {
2134 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2136 $ext_tables_part = "";
2140 if (SPHINX_ENABLED
) {
2141 $ids = join(",", @sphinx_search
($search, 0, 500));
2144 $search_query_part = "ref_id IN ($ids) AND ";
2146 $search_query_part = "ref_id = -1 AND ";
2149 $search_query_part = search_to_sql($link, $search, $match_on);
2150 $search_query_part .= " AND ";
2154 $search_query_part = "";
2159 if (DB_TYPE
== "pgsql") {
2160 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2162 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2165 $override_order = "updated DESC";
2167 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2169 // Try to check if SQL regexp implementation chokes on a valid regexp
2170 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2171 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2172 WHERE $filter_query_part LIMIT 1", false);
2174 $test = db_fetch_result($result, 0, "true");
2177 $filter_query_part = "false AND";
2179 $filter_query_part .= " AND";
2183 $filter_query_part = "";
2187 $since_id_part = "ttrss_entries.id > $since_id AND ";
2189 $since_id_part = "";
2192 $view_query_part = "";
2194 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2196 $view_query_part = " ";
2197 } else if ($feed != -1) {
2198 $unread = getFeedUnread($link, $feed, $cat_view);
2200 if ($cat_view && $feed > 0 && $include_children)
2201 $unread +
= getCategoryChildrenUnread($link, $feed);
2204 $view_query_part = " unread = true AND ";
2209 if ($view_mode == "marked") {
2210 $view_query_part = " marked = true AND ";
2213 if ($view_mode == "published") {
2214 $view_query_part = " published = true AND ";
2217 if ($view_mode == "unread") {
2218 $view_query_part = " unread = true AND ";
2221 if ($view_mode == "updated") {
2222 $view_query_part = " (last_read is null and unread = false) AND ";
2226 $limit_query_part = "LIMIT " . $limit;
2229 $allow_archived = false;
2231 $vfeed_query_part = "";
2233 // override query strategy and enable feed display when searching globally
2234 if ($search && $search_mode == "all_feeds") {
2235 $query_strategy_part = "true";
2236 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2238 } else if (!is_numeric($feed)) {
2239 $query_strategy_part = "true";
2240 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2241 id = feed_id) as feed_title,";
2242 } else if ($search && $search_mode == "this_cat") {
2243 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2246 if ($include_children) {
2247 $subcats = getChildCategories($link, $feed, $owner_uid);
2248 array_push($subcats, $feed);
2249 $cats_qpart = join(",", $subcats);
2251 $cats_qpart = $feed;
2254 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2257 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2260 } else if ($feed > 0) {
2265 if ($include_children) {
2267 $subcats = getChildCategories($link, $feed, $owner_uid);
2269 array_push($subcats, $feed);
2270 $query_strategy_part = "cat_id IN (".
2271 implode(",", $subcats).")";
2274 $query_strategy_part = "cat_id = '$feed'";
2278 $query_strategy_part = "cat_id IS NULL";
2281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2284 $query_strategy_part = "feed_id = '$feed'";
2286 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2287 $query_strategy_part = "feed_id IS NULL";
2288 $allow_archived = true;
2289 } else if ($feed == 0 && $cat_view) { // uncategorized
2290 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2291 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2292 } else if ($feed == -1) { // starred virtual feed
2293 $query_strategy_part = "marked = true";
2294 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2295 $allow_archived = true;
2297 } else if ($feed == -2) { // published virtual feed OR labels category
2300 $query_strategy_part = "published = true";
2301 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2302 $allow_archived = true;
2304 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2306 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2308 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2310 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2311 ttrss_user_labels2.article_id = ref_id";
2314 } else if ($feed == -6) { // recently read
2315 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2316 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2317 $allow_archived = true;
2319 if (!$override_order) $override_order = "last_read DESC";
2320 } else if ($feed == -3) { // fresh virtual feed
2321 $query_strategy_part = "unread = true AND score >= 0";
2323 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2325 if (DB_TYPE
== "pgsql") {
2326 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2328 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2331 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2332 } else if ($feed == -4) { // all articles virtual feed
2333 $query_strategy_part = "true";
2334 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2335 } else if ($feed <= -10) { // labels
2336 $label_id = -$feed - 11;
2338 $query_strategy_part = "label_id = '$label_id' AND
2339 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2340 ttrss_user_labels2.article_id = ref_id";
2342 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2343 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2344 $allow_archived = true;
2347 $query_strategy_part = "true";
2350 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2351 $date_sort_field = "updated";
2353 $date_sort_field = "date_entered";
2356 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2357 $order_by = "$date_sort_field";
2359 $order_by = "$date_sort_field DESC";
2362 if ($view_mode != "noscores") {
2363 $order_by = "score DESC, $order_by";
2366 if ($override_order) {
2367 $order_by = $override_order;
2373 $feed_title = T_sprintf("Search results: %s", $search);
2376 $feed_title = getCategoryTitle($link, $feed);
2378 if (is_numeric($feed) && $feed > 0) {
2379 $result = db_query($link, "SELECT title,site_url,last_error
2380 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2382 $feed_title = db_fetch_result($result, 0, "title");
2383 $feed_site_url = db_fetch_result($result, 0, "site_url");
2384 $last_error = db_fetch_result($result, 0, "last_error");
2386 $feed_title = getFeedTitle($link, $feed);
2391 $content_query_part = "content as content_preview, cached_content, ";
2393 if (is_numeric($feed)) {
2396 $feed_kind = "Feeds";
2398 $feed_kind = "Labels";
2401 if ($limit_query_part) {
2402 $offset_query_part = "OFFSET $offset";
2405 // proper override_order applied above
2406 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2407 if (!$override_order) {
2408 $order_by = "ttrss_feeds.title, $order_by";
2410 $order_by = "ttrss_feeds.title, $override_order";
2414 if (!$allow_archived) {
2415 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2416 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2419 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2420 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2423 $query = "SELECT DISTINCT
2426 ttrss_entries.id,ttrss_entries.title,
2430 always_display_enclosures,
2436 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2437 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2440 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2446 ttrss_user_entries.ref_id = ttrss_entries.id AND
2447 ttrss_user_entries.owner_uid = '$owner_uid' AND
2452 $query_strategy_part ORDER BY $order_by
2453 $limit_query_part $offset_query_part";
2455 if ($_REQUEST["debug"]) print $query;
2457 $result = db_query($link, $query);
2462 $select_qpart = "SELECT DISTINCT " .
2466 "ttrss_entries.id as id," .
2479 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2482 $content_query_part .
2483 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2486 $feed_kind = "Tags";
2487 $all_tags = explode(",", $feed);
2488 if ($search_mode == 'any') {
2489 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2490 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2491 $where_qpart = " WHERE " .
2492 "ref_id = ttrss_entries.id AND " .
2493 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2494 "post_int_id = int_id AND $tag_sql AND " .
2496 $search_query_part .
2497 $query_strategy_part . " ORDER BY $order_by " .
2502 $sub_selects = array();
2503 $sub_ands = array();
2504 foreach ($all_tags as $term) {
2505 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");
2512 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2517 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2518 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2519 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2520 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2522 // error_log("TAG SQL: " . $tag_sql);
2523 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2525 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2526 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2529 return array($result, $feed_title, $feed_site_url, $last_error);
2533 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2534 if (!$owner) $owner = $_SESSION["uid"];
2536 $res = trim($str); if (!$res) return '';
2538 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
2539 $res = htmLawed($res, $config);
2541 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2542 $res = preg_replace('/<img[^>]+>/is', '', $res);
2545 if (strpos($res, "href=") === false)
2546 $res = rewrite_urls($res);
2548 $charset_hack = '<head>
2549 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2552 $res = trim($res); if (!$res) return '';
2554 libxml_use_internal_errors(true);
2556 $doc = new DOMDocument();
2557 $doc->loadHTML($charset_hack . $res);
2558 $xpath = new DOMXPath($doc);
2560 $entries = $xpath->query('(//a[@href]|//img[@src])');
2563 foreach ($entries as $entry) {
2567 if ($entry->hasAttribute('href'))
2568 $entry->setAttribute('href',
2569 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2571 if ($entry->hasAttribute('src'))
2572 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2573 $entry->setAttribute('src',
2574 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2577 if (strtolower($entry->nodeName
) == "a") {
2578 $entry->setAttribute("target", "_blank");
2581 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2582 $br = $doc->createElement("br");
2584 if ($entry->parentNode
->nextSibling
) {
2585 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2592 $node = $doc->getElementsByTagName('body')->item(0);
2594 return $doc->saveXML($node); //LIBXML_NOEMPTYTAG
2597 function check_for_update($link) {
2598 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2599 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2601 $version_data = @fetch_file_contents
($version_url);
2603 if ($version_data) {
2604 $version_data = json_decode($version_data, true);
2605 if ($version_data && $version_data['version']) {
2607 if (version_compare(VERSION
, $version_data['version']) == -1) {
2608 return $version_data;
2616 function markArticlesById($link, $ids, $cmode) {
2620 foreach ($ids as $id) {
2621 array_push($tmp_ids, "ref_id = '$id'");
2624 $ids_qpart = join(" OR ", $tmp_ids);
2627 db_query($link, "UPDATE ttrss_user_entries SET
2628 marked = false,last_read = NOW()
2629 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2630 } else if ($cmode == 1) {
2631 db_query($link, "UPDATE ttrss_user_entries SET
2633 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2635 db_query($link, "UPDATE ttrss_user_entries SET
2636 marked = NOT marked,last_read = NOW()
2637 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2641 function publishArticlesById($link, $ids, $cmode) {
2645 foreach ($ids as $id) {
2646 array_push($tmp_ids, "ref_id = '$id'");
2649 $ids_qpart = join(" OR ", $tmp_ids);
2652 db_query($link, "UPDATE ttrss_user_entries SET
2653 published = false,last_read = NOW()
2654 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2655 } else if ($cmode == 1) {
2656 db_query($link, "UPDATE ttrss_user_entries SET
2657 published = true,last_read = NOW()
2658 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2660 db_query($link, "UPDATE ttrss_user_entries SET
2661 published = NOT published,last_read = NOW()
2662 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2665 if (PUBSUBHUBBUB_HUB
) {
2666 $rss_link = get_self_url_prefix() .
2667 "/public.php?op=rss&id=-2&key=" .
2668 get_feed_access_key($link, -2, false);
2670 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2672 $pubsub_result = $p->publish_update($rss_link);
2676 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2678 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2679 if (count($ids) == 0) return;
2683 foreach ($ids as $id) {
2684 array_push($tmp_ids, "ref_id = '$id'");
2687 $ids_qpart = join(" OR ", $tmp_ids);
2690 db_query($link, "UPDATE ttrss_user_entries SET
2691 unread = false,last_read = NOW()
2692 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2693 } else if ($cmode == 1) {
2694 db_query($link, "UPDATE ttrss_user_entries SET
2696 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2698 db_query($link, "UPDATE ttrss_user_entries SET
2699 unread = NOT unread,last_read = NOW()
2700 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2705 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2706 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2708 while ($line = db_fetch_assoc($result)) {
2709 ccache_update($link, $line["feed_id"], $owner_uid);
2713 function catchupArticleById($link, $id, $cmode) {
2716 db_query($link, "UPDATE ttrss_user_entries SET
2717 unread = false,last_read = NOW()
2718 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2719 } else if ($cmode == 1) {
2720 db_query($link, "UPDATE ttrss_user_entries SET
2722 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2724 db_query($link, "UPDATE ttrss_user_entries SET
2725 unread = NOT unread,last_read = NOW()
2726 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2729 $feed_id = getArticleFeed($link, $id);
2730 ccache_update($link, $feed_id, $_SESSION["uid"]);
2733 function make_guid_from_title($title) {
2734 return preg_replace("/[ \"\',.:;]/", "-",
2735 mb_strtolower(strip_tags($title), 'utf-8'));
2738 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2740 $a_id = db_escape_string($id);
2742 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2744 $query = "SELECT DISTINCT tag_name,
2745 owner_uid as owner FROM
2746 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2747 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2749 $obj_id = md5("TAGS:$owner_uid:$id");
2752 /* check cache first */
2754 if ($tag_cache === false) {
2755 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2756 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2758 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2762 $tags = explode(",", $tag_cache);
2765 /* do it the hard way */
2767 $tmp_result = db_query($link, $query);
2769 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2770 array_push($tags, $tmp_line["tag_name"]);
2773 /* update the cache */
2775 $tags_str = db_escape_string(join(",", $tags));
2777 db_query($link, "UPDATE ttrss_user_entries
2778 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2779 AND owner_uid = $owner_uid");
2785 function trim_array($array) {
2787 array_walk($tmp, 'trim');
2791 function tag_is_valid($tag) {
2792 if ($tag == '') return false;
2793 if (preg_match("/^[0-9]*$/", $tag)) return false;
2794 if (mb_strlen($tag) > 250) return false;
2796 if (function_exists('iconv')) {
2797 $tag = iconv("utf-8", "utf-8", $tag);
2800 if (!$tag) return false;
2805 function render_login_form($link, $form_id = 0) {
2808 require_once "login_form.php";
2811 require_once "mobile/login_form.php";
2817 // from http://developer.apple.com/internet/safari/faq.html
2818 function no_cache_incantation() {
2819 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2820 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2821 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2822 header("Cache-Control: post-check=0, pre-check=0", false);
2823 header("Pragma: no-cache"); // HTTP/1.0
2826 function format_warning($msg, $id = "") {
2828 return "<div class=\"warning\" id=\"$id\">
2829 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2832 function format_notice($msg, $id = "") {
2834 return "<div class=\"notice\" id=\"$id\">
2835 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
2838 function format_error($msg, $id = "") {
2840 return "<div class=\"error\" id=\"$id\">
2841 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2844 function print_notice($msg) {
2845 return print format_notice($msg);
2848 function print_warning($msg) {
2849 return print format_warning($msg);
2852 function print_error($msg) {
2853 return print format_error($msg);
2857 function T_sprintf() {
2858 $args = func_get_args();
2859 return vsprintf(__(array_shift($args)), $args);
2862 function format_inline_player($link, $url, $ctype) {
2866 if (strpos($ctype, "audio/") === 0) {
2868 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2869 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2870 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2872 $id = 'AUDIO-' . uniqid();
2874 $entry .= "<audio id=\"$id\"\">
2875 <source src=\"$url\"></source>
2878 $entry .= "<span onclick=\"player(this)\"
2879 title=\"".__("Click to play")."\" status=\"0\"
2880 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2884 $entry .= "<object type=\"application/x-shockwave-flash\"
2885 data=\"lib/button/musicplayer.swf?song_url=$url\"
2886 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2887 <param name=\"movie\"
2888 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2893 $filename = substr($url, strrpos($url, "/")+
1);
2895 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2896 $filename . " (" . $ctype . ")" . "</a>";
2901 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2902 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2908 /* we can figure out feed_id from article id anyway, why do we
2909 * pass feed_id here? let's ignore the argument :( */
2911 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2912 WHERE ref_id = '$id'");
2914 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2916 $rv['feed_id'] = $feed_id;
2918 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2920 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2921 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2923 if (db_num_rows($result) == 1) {
2924 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2925 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2926 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2928 $rtl_content = false;
2929 $always_display_enclosures = false;
2930 $cache_content = false;
2934 $rtl_tag = "dir=\"RTL\"";
2941 if ($mark_as_read) {
2942 $result = db_query($link, "UPDATE ttrss_user_entries
2943 SET unread = false,last_read = NOW()
2944 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2946 ccache_update($link, $feed_id, $owner_uid);
2949 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2950 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
2951 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
2952 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2959 FROM ttrss_entries,ttrss_user_entries
2960 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
2964 $line = db_fetch_assoc($result);
2966 if ($line["icon_url"]) {
2967 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
2969 $feed_icon = " ";
2972 $feed_site_url = $line['site_url'];
2974 $num_comments = $line["num_comments"];
2975 $entry_comments = "";
2977 if ($num_comments > 0) {
2978 if ($line["comments"]) {
2979 $comments_url = htmlspecialchars($line["comments"]);
2981 $comments_url = htmlspecialchars($line["link"]);
2983 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
2985 if ($line["comments"] && $line["link"] != $line["comments"]) {
2986 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
2991 header("Content-Type: text/html");
2992 $rv['content'] .= "<html><head>
2993 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
2994 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2995 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2999 $title_escaped = htmlspecialchars($line['title']);
3001 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3002 truncate_string(strip_tags($line['title']), 15) . "</div>";
3004 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3005 strip_tags($line['title']) . "</div>";
3007 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3009 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3010 class=\"postHeader\" id=\"POSTHDR-$id\">";
3012 $entry_author = $line["author"];
3014 if ($entry_author) {
3015 $entry_author = __(" - ") . $entry_author;
3018 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3021 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3023 if ($line["link"]) {
3024 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3025 title=\"".htmlspecialchars($line['title'])."\"
3027 htmlspecialchars($line["link"]) . "\">" .
3029 "<span class='author'>$entry_author</span></a></div>";
3031 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3034 $tag_cache = $line["tag_cache"];
3037 $tags = get_article_tags($link, $id, $owner_uid);
3039 $tags = explode(",", $tag_cache);
3041 $tags_str = format_tags_string($tags, $id);
3042 $tags_str_full = join(", ", $tags);
3044 if (!$tags_str_full) $tags_str_full = __("no tags");
3046 if (!$entry_comments) $entry_comments = " "; # placeholder
3048 $rv['content'] .= "<div class='postTags' style='float : right'>
3049 <img src='".theme_image($link, 'images/tag.png')."'
3050 class='tagsPic' alt='Tags' title='Tags'> ";
3053 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3054 <a title=\"".__('Edit tags for this article')."\"
3055 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3057 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3058 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3059 position=\"below\">$tags_str_full</div>";
3061 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3062 class='tagsPic' style=\"cursor : pointer\"
3063 onclick=\"postOpenInNewTab(event, $id)\"
3064 alt='Zoom' title='".__('Open article in new tab')."'>";
3068 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
3069 $rv['content'] .= $p->hook_article_button($line);
3072 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3073 class='tagsPic' style=\"cursor : pointer\"
3074 onclick=\"closeArticlePanel($id)\"
3075 title='".__('Close article')."'>";
3078 $tags_str = strip_tags($tags_str);
3079 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3081 $rv['content'] .= "</div>";
3082 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3084 if ($line["orig_feed_id"]) {
3086 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3087 WHERE id = ".$line["orig_feed_id"]);
3089 if (db_num_rows($tmp_result) != 0) {
3091 $rv['content'] .= "<div clear='both'>";
3092 $rv['content'] .= __("Originally from:");
3094 $rv['content'] .= " ";
3096 $tmp_line = db_fetch_assoc($tmp_result);
3098 $rv['content'] .= "<a target='_blank'
3099 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3100 $tmp_line['title'] . "</a>";
3102 $rv['content'] .= " ";
3104 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3105 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
3107 $rv['content'] .= "</div>";
3111 $rv['content'] .= "</div>";
3113 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3114 if ($line['note']) {
3115 $rv['content'] .= format_article_note($id, $line['note']);
3117 $rv['content'] .= "</div>";
3119 $rv['content'] .= "<div class=\"postIcon\">" .
3120 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3121 href=\"".htmlspecialchars($feed_site_url)."\">".
3122 $feed_icon . "</a></div>";
3124 $rv['content'] .= "<div class=\"postContent\">";
3128 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3130 $ngram_result = db_query($link, "SELECT id,title FROM
3131 ttrss_entries,ttrss_user_entries
3132 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3133 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3134 AND title != '$title_escaped'
3135 AND owner_uid = $owner_uid");
3137 if (db_num_rows($ngram_result) > 0) {
3138 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3139 "<span>" . __('Related')."</span>";
3140 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3142 while ($nline = db_fetch_assoc($ngram_result)) {
3143 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3144 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3147 $rv['content'] .= "</div></div><br/";
3151 if ($cache_content && $line["cached_content"] != "") {
3152 $line["content"] =& $line["cached_content"];
3155 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3158 $rv['content'] .= $article_content;
3160 $rv['content'] .= format_article_enclosures($link, $id,
3161 $always_display_enclosures, $article_content);
3163 $rv['content'] .= "</div>";
3165 $rv['content'] .= "</div>";
3171 <div style=\"text-align : center\">
3172 <button onclick=\"return window.close()\">".
3173 __("Close this window")."</button></div>";
3174 $rv['content'] .= "</body></html>";
3181 function print_checkpoint($n, $s) {
3182 $ts = getmicrotime();
3183 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3187 function sanitize_tag($tag) {
3190 $tag = mb_strtolower($tag, 'utf-8');
3192 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3194 // $tag = str_replace('"', "", $tag);
3195 // $tag = str_replace("+", " ", $tag);
3196 $tag = str_replace("technorati tag: ", "", $tag);
3201 function get_self_url_prefix() {
3202 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3203 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3205 return SELF_URL_PATH
;
3209 function opml_publish_url($link){
3211 $url_path = get_self_url_prefix();
3212 $url_path .= "/opml.php?op=publish&key=" .
3213 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3219 * Purge a feed contents, marked articles excepted.
3221 * @param mixed $link The database connection.
3222 * @param integer $id The id of the feed to purge.
3225 function clear_feed_articles($link, $id) {
3228 $result = db_query($link, "DELETE FROM ttrss_user_entries
3229 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3231 $result = db_query($link, "DELETE FROM ttrss_user_entries
3232 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3235 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3236 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3238 ccache_update($link, $id, $_SESSION['uid']);
3239 } // function clear_feed_articles
3242 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3244 * @return string The Mozilla Firefox feed adding URL.
3246 function add_feed_url() {
3247 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3249 $url_path = get_self_url_prefix() .
3250 "/public.php?op=subscribe&feed_url=%s";
3252 } // function add_feed_url
3254 function encrypt_password($pass, $salt = '', $mode2 = false) {
3255 if ($salt && $mode2) {
3256 return "MODE2:" . hash('sha256', $salt . $pass);
3258 return "SHA1X:" . sha1("$salt:$pass");
3260 return "SHA1:" . sha1($pass);
3262 } // function encrypt_password
3264 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3267 $cat_id = (int)getFeedCategory($link, $feed_id);
3269 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3270 owner_uid = $owner_uid AND enabled = true");
3272 $check_cats = join(",", array_merge(
3273 getParentCategories($link, $cat_id, $owner_uid),
3276 while ($line = db_fetch_assoc($result)) {
3277 $filter_id = $line["id"];
3279 $result2 = db_query($link, "SELECT
3280 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3281 FROM ttrss_filters2_rules AS r,
3282 ttrss_filter_types AS t
3284 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3285 (feed_id IS NULL OR feed_id = '$feed_id') AND
3286 filter_type = t.id AND filter_id = '$filter_id'");
3291 while ($rule_line = db_fetch_assoc($result2)) {
3292 # print_r($rule_line);
3295 $rule["reg_exp"] = $rule_line["reg_exp"];
3296 $rule["type"] = $rule_line["type_name"];
3298 array_push($rules, $rule);
3301 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3302 FROM ttrss_filters2_actions AS a,
3303 ttrss_filter_actions AS t
3305 action_id = t.id AND filter_id = '$filter_id'");
3307 while ($action_line = db_fetch_assoc($result2)) {
3308 # print_r($action_line);
3311 $action["type"] = $action_line["type_name"];
3312 $action["param"] = $action_line["action_param"];
3314 array_push($actions, $action);
3319 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3320 $filter["rules"] = $rules;
3321 $filter["actions"] = $actions;
3323 if (count($rules) > 0 && count($actions) > 0) {
3324 array_push($filters, $filter);
3331 function get_score_pic($score) {
3333 return "score_high.png";
3334 } else if ($score > 0) {
3335 return "score_half_high.png";
3336 } else if ($score < -100) {
3337 return "score_low.png";
3338 } else if ($score < 0) {
3339 return "score_half_low.png";
3341 return "score_neutral.png";
3345 function feed_has_icon($id) {
3346 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3349 function init_connection($link) {
3352 if (DB_TYPE
== "pgsql") {
3353 pg_query($link, "set client_encoding = 'UTF-8'");
3354 pg_set_client_encoding("UNICODE");
3355 pg_query($link, "set datestyle = 'ISO, european'");
3356 pg_query($link, "set TIME ZONE 0");
3358 db_query($link, "SET time_zone = '+0:0'");
3360 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3361 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3367 $pluginhost = new PluginHost($link);
3368 $pluginhost->load(PLUGINS
, $pluginhost::KIND_ALL
);
3372 print "Unable to connect to database:" . db_last_error();
3377 /* function ccache_zero($link, $feed_id, $owner_uid) {
3378 db_query($link, "UPDATE ttrss_counters_cache SET
3379 value = 0, updated = NOW() WHERE
3380 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3383 function ccache_zero_all($link, $owner_uid) {
3384 db_query($link, "UPDATE ttrss_counters_cache SET
3385 value = 0 WHERE owner_uid = '$owner_uid'");
3387 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3388 value = 0 WHERE owner_uid = '$owner_uid'");
3391 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3394 $table = "ttrss_counters_cache";
3396 $table = "ttrss_cat_counters_cache";
3399 db_query($link, "DELETE FROM $table WHERE
3400 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3404 function ccache_update_all($link, $owner_uid) {
3406 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3408 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3409 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3411 while ($line = db_fetch_assoc($result)) {
3412 ccache_update($link, $line["feed_id"], $owner_uid, true);
3415 /* We have to manually include category 0 */
3417 ccache_update($link, 0, $owner_uid, true);
3420 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3421 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3423 while ($line = db_fetch_assoc($result)) {
3424 print ccache_update($link, $line["feed_id"], $owner_uid);
3431 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3432 $no_update = false) {
3434 if (!is_numeric($feed_id)) return;
3437 $table = "ttrss_counters_cache";
3439 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3440 WHERE id = '$feed_id'");
3441 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3444 $table = "ttrss_cat_counters_cache";
3447 if (DB_TYPE
== "pgsql") {
3448 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3449 } else if (DB_TYPE
== "mysql") {
3450 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3453 $result = db_query($link, "SELECT value FROM $table
3454 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3457 if (db_num_rows($result) == 1) {
3458 return db_fetch_result($result, 0, "value");
3463 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3469 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3470 $update_pcat = true) {
3472 if (!is_numeric($feed_id)) return;
3474 if (!$is_cat && $feed_id > 0) {
3475 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3476 WHERE id = '$feed_id'");
3477 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3480 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3482 /* When updating a label, all we need to do is recalculate feed counters
3483 * because labels are not cached */
3486 ccache_update_all($link, $owner_uid);
3491 $table = "ttrss_counters_cache";
3493 $table = "ttrss_cat_counters_cache";
3496 if ($is_cat && $feed_id >= 0) {
3497 if ($feed_id != 0) {
3498 $cat_qpart = "cat_id = '$feed_id'";
3500 $cat_qpart = "cat_id IS NULL";
3503 /* Recalculate counters for child feeds */
3505 $result = db_query($link, "SELECT id FROM ttrss_feeds
3506 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3508 while ($line = db_fetch_assoc($result)) {
3509 ccache_update($link, $line["id"], $owner_uid, false, false);
3512 $result = db_query($link, "SELECT SUM(value) AS sv
3513 FROM ttrss_counters_cache, ttrss_feeds
3514 WHERE id = feed_id AND $cat_qpart AND
3515 ttrss_feeds.owner_uid = '$owner_uid'");
3517 $unread = (int) db_fetch_result($result, 0, "sv");
3520 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3523 db_query($link, "BEGIN");
3525 $result = db_query($link, "SELECT feed_id FROM $table
3526 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3528 if (db_num_rows($result) == 1) {
3529 db_query($link, "UPDATE $table SET
3530 value = '$unread', updated = NOW() WHERE
3531 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3534 db_query($link, "INSERT INTO $table
3535 (feed_id, value, owner_uid, updated)
3537 ($feed_id, $unread, $owner_uid, NOW())");
3540 db_query($link, "COMMIT");
3542 if ($feed_id > 0 && $prev_unread != $unread) {
3546 /* Update parent category */
3550 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3551 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3553 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3555 ccache_update($link, $cat_id, $owner_uid, true);
3559 } else if ($feed_id < 0) {
3560 ccache_update_all($link, $owner_uid);
3566 /* function ccache_cleanup($link, $owner_uid) {
3568 if (DB_TYPE == "pgsql") {
3569 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3570 (SELECT count(*) FROM ttrss_counters_cache AS c2
3571 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3572 AND owner_uid = '$owner_uid'");
3574 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3575 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3576 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3577 AND owner_uid = '$owner_uid'");
3579 db_query($link, "DELETE c1 FROM
3580 ttrss_counters_cache AS c1,
3581 ttrss_counters_cache AS c2
3583 c1.owner_uid = '$owner_uid' AND
3584 c1.owner_uid = c2.owner_uid AND
3585 c1.feed_id = c2.feed_id");
3587 db_query($link, "DELETE c1 FROM
3588 ttrss_cat_counters_cache AS c1,
3589 ttrss_cat_counters_cache AS c2
3591 c1.owner_uid = '$owner_uid' AND
3592 c1.owner_uid = c2.owner_uid AND
3593 c1.feed_id = c2.feed_id");
3598 function label_find_id($link, $label, $owner_uid) {
3599 $result = db_query($link,
3600 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3601 AND owner_uid = '$owner_uid' LIMIT 1");
3603 if (db_num_rows($result) == 1) {
3604 return db_fetch_result($result, 0, "id");
3610 function get_article_labels($link, $id, $owner_uid = false) {
3613 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3615 $result = db_query($link, "SELECT label_cache FROM
3616 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3619 if (db_num_rows($result) > 0) {
3620 $label_cache = db_fetch_result($result, 0, "label_cache");
3623 $label_cache = json_decode($label_cache, true);
3625 if ($label_cache["no-labels"] == 1)
3628 return $label_cache;
3632 $result = db_query($link,
3633 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3634 FROM ttrss_labels2, ttrss_user_labels2
3636 AND article_id = '$id'
3637 AND owner_uid = ". $owner_uid . "
3640 while ($line = db_fetch_assoc($result)) {
3641 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3643 array_push($rv, $rk);
3647 label_update_cache($link, $owner_uid, $id, $rv);
3649 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3655 function label_find_caption($link, $label, $owner_uid) {
3656 $result = db_query($link,
3657 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3658 AND owner_uid = '$owner_uid' LIMIT 1");
3660 if (db_num_rows($result) == 1) {
3661 return db_fetch_result($result, 0, "caption");
3667 function get_all_labels($link, $owner_uid) {
3670 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3672 while ($line = db_fetch_assoc($result)) {
3673 array_push($rv, $line);
3679 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3682 label_clear_cache($link, $id);
3685 $labels = get_article_labels($link, $id);
3687 $labels = db_escape_string(json_encode($labels));
3689 db_query($link, "UPDATE ttrss_user_entries SET
3690 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3694 function label_clear_cache($link, $id) {
3696 db_query($link, "UPDATE ttrss_user_entries SET
3697 label_cache = '' WHERE ref_id = '$id'");
3701 function label_remove_article($link, $id, $label, $owner_uid) {
3703 $label_id = label_find_id($link, $label, $owner_uid);
3705 if (!$label_id) return;
3707 $result = db_query($link,
3708 "DELETE FROM ttrss_user_labels2
3710 label_id = '$label_id' AND
3711 article_id = '$id'");
3713 label_clear_cache($link, $id);
3716 function label_add_article($link, $id, $label, $owner_uid) {
3718 $label_id = label_find_id($link, $label, $owner_uid);
3720 if (!$label_id) return;
3722 $result = db_query($link,
3724 article_id FROM ttrss_labels2, ttrss_user_labels2
3727 label_id = '$label_id' AND
3728 article_id = '$id' AND owner_uid = '$owner_uid'
3731 if (db_num_rows($result) == 0) {
3732 db_query($link, "INSERT INTO ttrss_user_labels2
3733 (label_id, article_id) VALUES ('$label_id', '$id')");
3736 label_clear_cache($link, $id);
3740 function label_remove($link, $id, $owner_uid) {
3741 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3743 db_query($link, "BEGIN");
3745 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3748 $caption = db_fetch_result($result, 0, "caption");
3750 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3751 AND owner_uid = " . $owner_uid);
3753 if (db_affected_rows($link, $result) != 0 && $caption) {
3755 /* Remove access key for the label */
3757 $ext_id = -11 - $id;
3759 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3760 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3762 /* Disable filters that reference label being removed */
3764 db_query($link, "UPDATE ttrss_filters SET
3765 enabled = false WHERE action_param = '$caption'
3767 AND owner_uid = " . $owner_uid);
3769 /* Remove cached data */
3771 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3772 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3776 db_query($link, "COMMIT");
3779 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3781 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3783 db_query($link, "BEGIN");
3787 $result = db_query($link, "SELECT id FROM ttrss_labels2
3788 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3790 if (db_num_rows($result) == 0) {
3791 $result = db_query($link,
3792 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3793 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3795 $result = db_affected_rows($link, $result) != 0;
3798 db_query($link, "COMMIT");
3803 function format_tags_string($tags, $id) {
3806 $tags_nolinks_str = "";
3812 $formatted_tags = array();
3814 foreach ($tags as $tag) {
3816 $tag_escaped = str_replace("'", "\\'", $tag);
3818 if (mb_strlen($tag) > 30) {
3819 $tag = truncate_string($tag, 30);
3822 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3824 array_push($formatted_tags, $tag_str);
3826 $tmp_tags_str = implode(", ", $formatted_tags);
3828 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
3833 $tags_str = implode(", ", $formatted_tags);
3835 if ($num_tags < count($tags)) {
3836 $tags_str .= ", …";
3839 if ($num_tags == 0) {
3840 $tags_str = __("no tags");
3847 function format_article_labels($labels, $id) {
3851 foreach ($labels as $l) {
3852 $labels_str .= sprintf("<span class='hlLabelRef'
3853 style='color : %s; background-color : %s'>%s</span>",
3854 $l[2], $l[3], $l[1]);
3861 function format_article_note($id, $note) {
3863 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3864 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3865 __('(edit note)')."</div>$note</div>";
3870 function toggle_collapse_cat($link, $cat_id, $mode) {
3872 $mode = bool_to_sql_bool($mode);
3874 db_query($link, "UPDATE ttrss_feed_categories SET
3875 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3882 $pref_name = '_COLLAPSED_SPECIAL';
3885 $pref_name = '_COLLAPSED_LABELS';
3888 $pref_name = '_COLLAPSED_UNCAT';
3894 set_pref($link, $pref_name, 'true');
3896 set_pref($link, $pref_name, 'false');
3902 function remove_feed($link, $id, $owner_uid) {
3906 /* save starred articles in Archived feed */
3908 db_query($link, "BEGIN");
3910 /* prepare feed if necessary */
3912 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
3915 if (db_num_rows($result) == 0) {
3916 db_query($link, "INSERT INTO ttrss_archived_feeds
3917 (id, owner_uid, title, feed_url, site_url)
3918 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
3922 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
3923 orig_feed_id = '$id' WHERE feed_id = '$id' AND
3924 marked = true AND owner_uid = $owner_uid");
3926 /* Remove access key for the feed */
3928 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3929 feed_id = '$id' AND owner_uid = $owner_uid");
3931 /* remove the feed */
3933 db_query($link, "DELETE FROM ttrss_feeds
3934 WHERE id = '$id' AND owner_uid = $owner_uid");
3936 db_query($link, "COMMIT");
3938 if (file_exists(ICONS_DIR
. "/$id.ico")) {
3939 unlink(ICONS_DIR
. "/$id.ico");
3942 ccache_remove($link, $id, $owner_uid);
3945 label_remove($link, -11-$id, $owner_uid);
3946 ccache_remove($link, -11-$id, $owner_uid);
3950 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3951 if ($parent_cat_id) {
3952 $parent_qpart = "parent_cat = '$parent_cat_id'";
3953 $parent_insert = "'$parent_cat_id'";
3955 $parent_qpart = "parent_cat IS NULL";
3956 $parent_insert = "NULL";
3959 $result = db_query($link,
3960 "SELECT id FROM ttrss_feed_categories
3961 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3963 if (db_num_rows($result) == 0) {
3966 return db_fetch_result($result, 0, "id");
3970 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3972 if (!$feed_cat) return false;
3974 db_query($link, "BEGIN");
3976 if ($parent_cat_id) {
3977 $parent_qpart = "parent_cat = '$parent_cat_id'";
3978 $parent_insert = "'$parent_cat_id'";
3980 $parent_qpart = "parent_cat IS NULL";
3981 $parent_insert = "NULL";
3984 $result = db_query($link,
3985 "SELECT id FROM ttrss_feed_categories
3986 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3988 if (db_num_rows($result) == 0) {
3990 $result = db_query($link,
3991 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3992 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3994 db_query($link, "COMMIT");
4002 function remove_feed_category($link, $id, $owner_uid) {
4004 db_query($link, "DELETE FROM ttrss_feed_categories
4005 WHERE id = '$id' AND owner_uid = $owner_uid");
4007 ccache_remove($link, $id, $owner_uid, true);
4010 function archive_article($link, $id, $owner_uid) {
4011 db_query($link, "BEGIN");
4013 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4014 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4016 if (db_num_rows($result) != 0) {
4018 /* prepare the archived table */
4020 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4023 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4024 WHERE id = '$feed_id'");
4026 if (db_num_rows($result) == 0) {
4027 db_query($link, "INSERT INTO ttrss_archived_feeds
4028 (id, owner_uid, title, feed_url, site_url)
4029 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4030 WHERE id = '$feed_id'");
4033 db_query($link, "UPDATE ttrss_user_entries
4034 SET orig_feed_id = feed_id, feed_id = NULL
4035 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4039 db_query($link, "COMMIT");
4042 function getArticleFeed($link, $id) {
4043 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4044 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4046 if (db_num_rows($result) != 0) {
4047 return db_fetch_result($result, 0, "feed_id");
4054 * Fixes incomplete URLs by prepending "http://".
4055 * Also replaces feed:// with http://, and
4056 * prepends a trailing slash if the url is a domain name only.
4058 * @param string $url Possibly incomplete URL
4060 * @return string Fixed URL.
4062 function fix_url($url) {
4063 if (strpos($url, '://') === false) {
4064 $url = 'http://' . $url;
4065 } else if (substr($url, 0, 5) == 'feed:') {
4066 $url = 'http:' . substr($url, 5);
4069 //prepend slash if the URL has no slash in it
4070 // "http://www.example" -> "http://www.example/"
4071 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4075 if ($url != "http:///")
4081 function validate_feed_url($url) {
4082 $parts = parse_url($url);
4084 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4088 function get_article_enclosures($link, $id) {
4090 $query = "SELECT * FROM ttrss_enclosures
4091 WHERE post_id = '$id' AND content_url != ''";
4095 $result = db_query($link, $query);
4097 if (db_num_rows($result) > 0) {
4098 while ($line = db_fetch_assoc($result)) {
4099 array_push($rv, $line);
4106 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4112 if ($cat_id == -4 ||
$cat_id == -2) {
4113 $counters = getLabelCounters($link, true);
4115 foreach (array_values($counters) as $cv) {
4117 $unread = $cv["counter"];
4119 if ($unread ||
!$unread_only) {
4123 "title" => $cv["description"],
4124 "unread" => $cv["counter"],
4128 array_push($feeds, $row);
4135 if ($cat_id == -4 ||
$cat_id == -1) {
4136 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4137 $unread = getFeedUnread($link, $i);
4139 if ($unread ||
!$unread_only) {
4140 $title = getFeedTitle($link, $i);
4145 "unread" => $unread,
4148 array_push($feeds, $row);
4156 if ($include_nested && $cat_id) {
4157 $result = db_query($link, "SELECT
4158 id, title FROM ttrss_feed_categories
4159 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4160 " ORDER BY id, title");
4162 while ($line = db_fetch_assoc($result)) {
4163 $unread = getFeedUnread($link, $line["id"], true) +
4164 getCategoryChildrenUnread($link, $line["id"]);
4166 if ($unread ||
!$unread_only) {
4168 "id" => $line["id"],
4169 "title" => $line["title"],
4170 "unread" => $unread,
4173 array_push($feeds, $row);
4181 $limit_qpart = "LIMIT $limit OFFSET $offset";
4186 if ($cat_id == -4 ||
$cat_id == -3) {
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 owner_uid = " . $_SESSION["uid"] .
4191 " ORDER BY cat_id, title " . $limit_qpart);
4195 $cat_qpart = "cat_id = '$cat_id'";
4197 $cat_qpart = "cat_id IS NULL";
4199 $result = db_query($link, "SELECT
4200 id, feed_url, cat_id, title, order_id, ".
4201 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4202 FROM ttrss_feeds WHERE
4203 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4204 " ORDER BY cat_id, title " . $limit_qpart);
4207 while ($line = db_fetch_assoc($result)) {
4209 $unread = getFeedUnread($link, $line["id"]);
4211 $has_icon = feed_has_icon($line['id']);
4213 if ($unread ||
!$unread_only) {
4216 "feed_url" => $line["feed_url"],
4217 "title" => $line["title"],
4218 "id" => (int)$line["id"],
4219 "unread" => (int)$unread,
4220 "has_icon" => $has_icon,
4221 "cat_id" => (int)$line["cat_id"],
4222 "last_updated" => strtotime($line["last_updated"]),
4223 "order_id" => (int) $line["order_id"],
4226 array_push($feeds, $row);
4233 function api_get_headlines($link, $feed_id, $limit, $offset,
4234 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4235 $include_attachments, $since_id,
4236 $search = "", $search_mode = "", $match_on = "",
4237 $include_nested = false, $sanitize_content = true) {
4239 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4240 $view_mode, $is_cat, $search, $search_mode, $match_on,
4241 $order, $offset, 0, false, $since_id, $include_nested);
4243 $result = $qfh_ret[0];
4244 $feed_title = $qfh_ret[1];
4246 $headlines = array();
4248 while ($line = db_fetch_assoc($result)) {
4249 $is_updated = ($line["last_read"] == "" &&
4250 ($line["unread"] != "t" && $line["unread"] != "1"));
4252 $tags = explode(",", $line["tag_cache"]);
4253 $labels = json_decode($line["label_cache"], true);
4255 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4256 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4258 $headline_row = array(
4259 "id" => (int)$line["id"],
4260 "unread" => sql_bool_to_bool($line["unread"]),
4261 "marked" => sql_bool_to_bool($line["marked"]),
4262 "published" => sql_bool_to_bool($line["published"]),
4263 "updated" => strtotime($line["updated"]),
4264 "is_updated" => $is_updated,
4265 "title" => $line["title"],
4266 "link" => $line["link"],
4267 "feed_id" => $line["feed_id"],
4271 if ($include_attachments)
4272 $headline_row['attachments'] = get_article_enclosures($link,
4275 if ($show_excerpt) {
4276 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4277 $headline_row["excerpt"] = $excerpt;
4280 if ($show_content) {
4282 if ($line["cached_content"] != "") {
4283 $line["content_preview"] =& $line["cached_content"];
4286 if ($sanitize_content) {
4287 $headline_row["content"] = sanitize($link,
4288 $line["content_preview"], false, false, $line["site_url"]);
4290 $headline_row["content"] = $line["content_preview"];
4294 // unify label output to ease parsing
4295 if ($labels["no-labels"] == 1) $labels = array();
4297 $headline_row["labels"] = $labels;
4299 $headline_row["feed_title"] = $line["feed_title"];
4301 $headline_row["comments_count"] = (int)$line["num_comments"];
4302 $headline_row["comments_link"] = $line["comments"];
4304 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4306 array_push($headlines, $headline_row);
4312 function generate_error_feed($link, $error) {
4315 $reply['headlines']['id'] = -6;
4316 $reply['headlines']['is_cat'] = false;
4318 $reply['headlines']['toolbar'] = '';
4319 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4321 $reply['headlines-info'] = array("count" => 0,
4322 "vgroup_last_feed" => '',
4324 "disable_cache" => true);
4330 function generate_dashboard_feed($link) {
4333 $reply['headlines']['id'] = -5;
4334 $reply['headlines']['is_cat'] = false;
4336 $reply['headlines']['toolbar'] = '';
4337 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4339 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4341 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4342 WHERE owner_uid = " . $_SESSION['uid']);
4344 $last_updated = db_fetch_result($result, 0, "last_updated");
4345 $last_updated = make_local_datetime($link, $last_updated, false);
4347 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4349 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4350 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4352 $num_errors = db_fetch_result($result, 0, "num_errors");
4354 if ($num_errors > 0) {
4355 $reply['headlines']['content'] .= "<br/>";
4356 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4357 __('Some feeds have update errors (click for details)')."</a>";
4359 $reply['headlines']['content'] .= "</span></p>";
4361 $reply['headlines-info'] = array("count" => 0,
4362 "vgroup_last_feed" => '',
4364 "disable_cache" => true);
4369 function save_email_address($link, $email) {
4370 // FIXME: implement persistent storage of emails
4372 if (!$_SESSION['stored_emails'])
4373 $_SESSION['stored_emails'] = array();
4375 if (!in_array($email, $_SESSION['stored_emails']))
4376 array_push($_SESSION['stored_emails'], $email);
4379 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4380 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4382 $sql_is_cat = bool_to_sql_bool($is_cat);
4384 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4385 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4386 AND owner_uid = " . $owner_uid);
4388 if (db_num_rows($result) == 1) {
4389 $key = db_escape_string(sha1(uniqid(rand(), true)));
4391 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4392 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4393 AND owner_uid = " . $owner_uid);
4398 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4402 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4404 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4406 $sql_is_cat = bool_to_sql_bool($is_cat);
4408 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4409 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4410 AND owner_uid = " . $owner_uid);
4412 if (db_num_rows($result) == 1) {
4413 return db_fetch_result($result, 0, "access_key");
4415 $key = db_escape_string(sha1(uniqid(rand(), true)));
4417 $result = db_query($link, "INSERT INTO ttrss_access_keys
4418 (access_key, feed_id, is_cat, owner_uid)
4419 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4426 function get_feeds_from_html($url, $content)
4428 $url = fix_url($url);
4429 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4431 libxml_use_internal_errors(true);
4433 $doc = new DOMDocument();
4434 $doc->loadHTML($content);
4435 $xpath = new DOMXPath($doc);
4436 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4437 $feedUrls = array();
4438 foreach ($entries as $entry) {
4439 if ($entry->hasAttribute('href')) {
4440 $title = $entry->getAttribute('title');
4442 $title = $entry->getAttribute('type');
4444 $feedUrl = rewrite_relative_url(
4445 $baseUrl, $entry->getAttribute('href')
4447 $feedUrls[$feedUrl] = $title;
4453 function is_html($content) {
4454 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4457 function url_is_html($url, $login = false, $pass = false) {
4458 return is_html(fetch_file_contents($url, false, $login, $pass));
4461 function print_label_select($link, $name, $value, $attributes = "") {
4463 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4464 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4466 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4467 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4469 while ($line = db_fetch_assoc($result)) {
4471 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4473 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4474 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4478 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4485 function format_article_enclosures($link, $id, $always_display_enclosures,
4488 $result = get_article_enclosures($link, $id);
4491 if (count($result) > 0) {
4493 $entries_html = array();
4496 foreach ($result as $line) {
4498 $url = $line["content_url"];
4499 $ctype = $line["content_type"];
4501 if (!$ctype) $ctype = __("unknown type");
4503 $filename = substr($url, strrpos($url, "/")+
1);
4505 # $player = format_inline_player($link, $url, $ctype);
4507 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4508 # $filename . " (" . $ctype . ")" . "</a>";
4510 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4511 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4513 array_push($entries_html, $entry);
4517 $entry["type"] = $ctype;
4518 $entry["filename"] = $filename;
4519 $entry["url"] = $url;
4521 array_push($entries, $entry);
4524 if (!get_pref($link, "STRIP_IMAGES")) {
4525 if ($always_display_enclosures ||
4526 !preg_match("/<img/i", $article_content)) {
4528 foreach ($entries as $entry) {
4530 if (preg_match("/image/", $entry["type"]) ||
4531 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4534 alt=\"".htmlspecialchars($entry["filename"])."\"
4535 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4542 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4543 "<span>" . __('Attachments')."</span>";
4544 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4546 foreach ($entries_html as $entry) { $rv .= $entry; };
4548 $rv .= "</div></div>";
4554 function getLastArticleId($link) {
4555 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4556 WHERE owner_uid = " . $_SESSION["uid"]);
4558 if (db_num_rows($result) == 1) {
4559 return db_fetch_result($result, 0, "id");
4565 function build_url($parts) {
4566 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4570 * Converts a (possibly) relative URL to a absolute one.
4572 * @param string $url Base URL (i.e. from where the document is)
4573 * @param string $rel_url Possibly relative URL in the document
4575 * @return string Absolute URL
4577 function rewrite_relative_url($url, $rel_url) {
4578 if (strpos($rel_url, "magnet:") === 0) {
4580 } else if (strpos($rel_url, "://") !== false) {
4582 } else if (strpos($rel_url, "//") === 0) {
4583 # protocol-relative URL (rare but they exist)
4585 } else if (strpos($rel_url, "/") === 0)
4587 $parts = parse_url($url);
4588 $parts['path'] = $rel_url;
4590 return build_url($parts);
4593 $parts = parse_url($url);
4594 if (!isset($parts['path'])) {
4595 $parts['path'] = '/';
4597 $dir = $parts['path'];
4598 if (substr($dir, -1) !== '/') {
4599 $dir = dirname($parts['path']);
4600 $dir !== '/' && $dir .= '/';
4602 $parts['path'] = $dir . $rel_url;
4604 return build_url($parts);
4608 function sphinx_search($query, $offset = 0, $limit = 30) {
4609 require_once 'lib/sphinxapi.php';
4611 $sphinxClient = new SphinxClient();
4613 $sphinxClient->SetServer('localhost', 9312);
4614 $sphinxClient->SetConnectTimeout(1);
4616 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4617 'feed_title' => 20));
4619 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4620 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4621 $sphinxClient->SetLimits($offset, $limit, 1000);
4622 $sphinxClient->SetArrayResult(false);
4623 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4625 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4629 if (is_array($result['matches'])) {
4630 foreach (array_keys($result['matches']) as $int_id) {
4631 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4632 array_push($ids, $ref_id);
4639 function cleanup_tags($link, $days = 14, $limit = 1000) {
4641 if (DB_TYPE
== "pgsql") {
4642 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4643 } else if (DB_TYPE
== "mysql") {
4644 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4649 while ($limit > 0) {
4652 $query = "SELECT ttrss_tags.id AS id
4653 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4654 WHERE post_int_id = int_id AND $interval_query AND
4655 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4657 $result = db_query($link, $query);
4661 while ($line = db_fetch_assoc($result)) {
4662 array_push($ids, $line['id']);
4665 if (count($ids) > 0) {
4666 $ids = join(",", $ids);
4669 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4670 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4675 $limit -= $limit_part;
4680 return $tags_deleted;
4683 function print_user_stylesheet($link) {
4684 $value = get_pref($link, 'USER_STYLESHEET');
4687 print "<style type=\"text/css\">";
4688 print str_replace("<br/>", "\n", $value);
4694 /* function rewrite_urls($line) {
4699 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4700 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4705 function rewrite_urls($html) {
4706 libxml_use_internal_errors(true);
4708 $charset_hack = '<head>
4709 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4712 $doc = new DOMDocument();
4713 $doc->loadHTML($charset_hack . $html);
4714 $xpath = new DOMXPath($doc);
4716 $entries = $xpath->query('//*/text()');
4718 foreach ($entries as $entry) {
4719 if (strstr($entry->wholeText
, "://") !== false) {
4720 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4721 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4723 if ($text != $entry->wholeText
) {
4724 $cdoc = new DOMDocument();
4725 $cdoc->loadHTML($charset_hack . $text);
4728 foreach ($cdoc->childNodes
as $cnode) {
4729 $cnode = $doc->importNode($cnode, true);
4732 $entry->parentNode
->insertBefore($cnode);
4736 $entry->parentNode
->removeChild($entry);
4742 $node = $doc->getElementsByTagName('body')->item(0);
4744 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4746 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4751 function filter_to_sql($link, $filter, $owner_uid) {
4754 if (DB_TYPE
== "pgsql")
4757 $reg_qpart = "REGEXP";
4759 foreach ($filter["rules"] AS $rule) {
4760 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4761 $rule['reg_exp']) !== FALSE;
4763 if ($regexp_valid) {
4765 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4767 switch ($rule["type"]) {
4769 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4770 $rule['reg_exp'] . "')";
4773 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4774 $rule['reg_exp'] . "')";
4777 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4778 $rule['reg_exp'] . "') OR LOWER(" .
4779 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4782 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4783 $rule['reg_exp'] . "')";
4786 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4787 $rule['reg_exp'] . "')";
4790 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4791 $rule['reg_exp'] . "')";
4795 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4796 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4799 if (isset($rule["cat_id"])) {
4801 if ($rule["cat_id"] > 0) {
4802 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4803 array_push($children, $rule["cat_id"]);
4805 $children = join(",", $children);
4807 $cat_qpart = "cat_id IN ($children)";
4809 $cat_qpart = "cat_id IS NULL";
4812 $qpart .= " AND $cat_qpart";
4815 array_push($query, "($qpart)");
4820 if (count($query) > 0) {
4821 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
4827 if (!function_exists('gzdecode')) {
4828 function gzdecode($string) { // no support for 2nd argument
4829 return file_get_contents('compress.zlib://data:who/cares;base64,'.
4830 base64_encode($string));
4834 function get_random_bytes($length) {
4835 if (function_exists('openssl_random_pseudo_bytes')) {
4836 return openssl_random_pseudo_bytes($length);
4840 for ($i = 0; $i < $length; $i++
)
4841 $output .= chr(mt_rand(0, 255));
4847 function read_stdin() {
4848 $fp = fopen("php://stdin", "r");
4851 $line = trim(fgets($fp));
4859 function tmpdirname($path, $prefix) {
4860 // Use PHP's tmpfile function to create a temporary
4861 // directory name. Delete the file and keep the name.
4862 $tempname = tempnam($path,$prefix);
4866 if (!unlink($tempname))
4872 function getFeedCategory($link, $feed) {
4873 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
4874 WHERE id = '$feed'");
4876 if (db_num_rows($result) > 0) {
4877 return db_fetch_result($result, 0, "cat_id");
4884 function create_published_article($link, $title, $url, $content, $labels_str,
4887 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
4888 $content_hash = sha1($content);
4890 if ($labels_str != "") {
4891 $labels = explode(",", $labels_str);
4898 if (!$title) $title = $url;
4899 if (!$title && !$url) return false;
4901 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
4903 db_query($link, "BEGIN");
4905 // only check for our user data here, others might have shared this with different content etc
4906 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
4907 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
4909 if (db_num_rows($result) != 0) {
4910 $ref_id = db_fetch_result($result, 0, "id");
4912 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
4913 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
4915 if (db_num_rows($result) != 0) {
4916 $int_id = db_fetch_result($result, 0, "int_id");
4918 db_query($link, "UPDATE ttrss_entries SET
4919 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
4921 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
4922 int_id = '$int_id' AND owner_uid = '$owner_uid'");
4925 db_query($link, "INSERT INTO ttrss_user_entries
4926 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4928 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4931 if (count($labels) != 0) {
4932 foreach ($labels as $label) {
4933 label_add_article($link, $ref_id, trim($label), $owner_uid);
4940 $result = db_query($link, "INSERT INTO ttrss_entries
4941 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
4943 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
4945 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
4947 if (db_num_rows($result) != 0) {
4948 $ref_id = db_fetch_result($result, 0, "id");
4950 db_query($link, "INSERT INTO ttrss_user_entries
4951 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4953 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4955 if (count($labels) != 0) {
4956 foreach ($labels as $label) {
4957 label_add_article($link, $ref_id, trim($label), $owner_uid);
4965 db_query($link, "COMMIT");
4970 function implements_interface($class, $interface) {
4971 return in_array($interface, class_implements($class));