2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 101);
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
) {
552 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER
) as $plugin) {
554 $user_id = (int) $plugin->authenticate($login, $password);
557 $_SESSION["auth_module"] = strtolower(get_class($plugin));
562 if ($user_id && !$check_only) {
563 $_SESSION["uid"] = $user_id;
565 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
566 WHERE id = '$user_id'");
568 $_SESSION["name"] = db_fetch_result($result, 0, "login");
569 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
570 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
572 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
575 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
576 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
578 $_SESSION["last_version_check"] = time();
580 initialize_user_prefs($link, $_SESSION["uid"]);
589 $_SESSION["uid"] = 1;
590 $_SESSION["name"] = "admin";
591 $_SESSION["access_level"] = 10;
593 $_SESSION["hide_hello"] = true;
594 $_SESSION["hide_logout"] = true;
596 $_SESSION["auth_module"] = false;
598 if (!$_SESSION["csrf_token"]) {
599 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
602 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
604 initialize_user_prefs($link, $_SESSION["uid"]);
610 function make_password($length = 8) {
613 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
617 while ($i < $length) {
618 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
620 if (!strstr($password, $char)) {
628 // this is called after user is created to initialize default feeds, labels
631 // user preferences are checked on every login, not here
633 function initialize_user($link, $uid) {
635 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
636 values ('$uid', 'Tiny Tiny RSS: New Releases',
637 'http://tt-rss.org/releases.rss')");
639 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
640 values ('$uid', 'Tiny Tiny RSS: Forum',
641 'http://tt-rss.org/forum/rss.php')");
644 function logout_user() {
646 if (isset($_COOKIE[session_name()])) {
647 setcookie(session_name(), '', time()-42000, '/');
651 function validate_csrf($csrf_token) {
652 return $csrf_token == $_SESSION['csrf_token'];
655 function validate_session($link) {
656 if (SINGLE_USER_MODE
) return true;
658 $check_ip = $_SESSION['ip_address'];
660 switch (SESSION_CHECK_ADDRESS
) {
665 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
668 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
669 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
673 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
674 $_SESSION["login_error_msg"] =
675 __("Session failed to validate (incorrect IP)");
679 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
682 if ($_SESSION["uid"]) {
684 $result = db_query($link,
685 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
687 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
689 if ($pwd_hash != $_SESSION["pwd_hash"]) {
694 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
696 //print_r($_SESSION);
698 if (time() > $_SESSION["cookie_lifetime"]) {
706 function load_user_plugins($link, $owner_uid) {
708 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
711 $pluginhost->load($plugins, $pluginhost::KIND_USER
, $owner_uid);
713 if (get_schema_version($link) > 100) {
714 $pluginhost->load_data();
719 function login_sequence($link, $login_form = 0) {
720 if (SINGLE_USER_MODE
) {
721 authenticate_user($link, "admin", null);
722 load_user_plugins($link, $_SESSION["uid"]);
724 if (!$_SESSION["uid"] ||
!validate_session($link)) {
726 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
727 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
729 authenticate_user($link, null, null, true);
732 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
735 /* bump login timestamp */
736 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
740 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
741 setcookie("ttrss_lang", $_SESSION["language"],
742 time() + SESSION_COOKIE_LIFETIME
);
745 if ($_SESSION["uid"]) {
746 load_user_plugins($link, $_SESSION["uid"]);
751 function truncate_string($str, $max_len, $suffix = '…') {
752 if (mb_strlen($str, "utf-8") > $max_len - 3) {
753 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
759 function theme_image($link, $filename) {
761 $theme_path = get_user_theme_path($link);
763 if ($theme_path && is_file($theme_path.$filename)) {
764 return $theme_path.$filename;
773 function get_user_theme($link) {
775 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
776 $theme_name = get_pref($link, "_THEME_ID");
777 if (is_dir("themes/$theme_name")) {
788 function get_user_theme_path($link) {
791 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
792 $theme_name = get_pref($link, "_THEME_ID");
794 if ($theme_name && is_dir("themes/$theme_name")) {
795 $theme_path = "themes/$theme_name/";
804 if (is_file("$theme_path/theme.ini")) {
805 $ini = parse_ini_file("$theme_path/theme.ini", true);
806 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
814 function get_user_theme_options($link) {
815 $t = get_user_theme_path($link);
818 if (is_file("$t/theme.ini")) {
819 $ini = parse_ini_file("$t/theme.ini", true);
820 if ($ini['theme']['version']) {
821 return $ini['theme']['options'];
828 function print_theme_includes($link) {
830 $t = get_user_theme_path($link);
834 print "<link rel=\"stylesheet\" type=\"text/css\"
835 href=\"$t/theme.css?$time \">";
836 if (file_exists("$t/theme.js")) {
837 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
843 function get_all_themes() {
844 $themes = glob("themes/*");
850 foreach ($themes as $t) {
851 if (is_file("$t/theme.ini")) {
852 $ini = parse_ini_file("$t/theme.ini", true);
853 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
854 !$ini['theme']['disabled']) {
857 $entry["base"] = basename($t);
858 $entry["name"] = $ini['theme']['name'];
859 $entry["version"] = $ini['theme']['version'];
860 $entry["author"] = $ini['theme']['author'];
861 $entry["options"] = $ini['theme']['options'];
862 array_push($rv, $entry);
870 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
873 $source_tz = new DateTimeZone($source_tz);
874 } catch (Exception
$e) {
875 $source_tz = new DateTimeZone('UTC');
879 $dest_tz = new DateTimeZone($dest_tz);
880 } catch (Exception
$e) {
881 $dest_tz = new DateTimeZone('UTC');
884 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
885 return $dt->format('U') +
$dest_tz->getOffset($dt);
888 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
889 $no_smart_dt = false) {
891 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
892 if (!$timestamp) $timestamp = '1970-01-01 0:00';
897 # We store date in UTC internally
898 $dt = new DateTime($timestamp, $utc_tz);
900 if ($tz_offset == -1) {
902 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
905 $user_tz = new DateTimeZone($user_tz_string);
906 } catch (Exception
$e) {
910 $tz_offset = $user_tz->getOffset($dt);
913 $user_timestamp = $dt->format('U') +
$tz_offset;
916 return smart_date_time($link, $user_timestamp,
917 $tz_offset, $owner_uid);
920 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
922 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
924 return date($format, $user_timestamp);
928 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
929 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
931 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
932 return date("G:i", $timestamp);
933 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
934 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
935 return date($format, $timestamp);
937 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
938 return date($format, $timestamp);
942 function sql_bool_to_bool($s) {
943 if ($s == "t" ||
$s == "1" ||
$s == "true") {
950 function bool_to_sql_bool($s) {
958 // Session caching removed due to causing wrong redirects to upgrade
959 // script when get_schema_version() is called on an obsolete session
960 // created on a previous schema version.
961 function get_schema_version($link, $nocache = false) {
962 global $schema_version;
964 if (!$schema_version) {
965 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
966 $version = db_fetch_result($result, 0, "schema_version");
967 $schema_version = $version;
970 return $schema_version;
974 function sanity_check($link) {
975 require_once 'errors.php';
978 $schema_version = get_schema_version($link, true);
980 if ($schema_version != SCHEMA_VERSION
) {
984 if (DB_TYPE
== "mysql") {
985 $result = db_query($link, "SELECT true", false);
986 if (db_num_rows($result) != 1) {
991 if (db_escape_string("testTEST") != "testTEST") {
995 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
998 function file_is_locked($filename) {
999 if (function_exists('flock')) {
1000 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1002 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1003 flock($fp, LOCK_UN
);
1013 return true; // consider the file always locked and skip the test
1016 function make_lockfile($filename) {
1017 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1019 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1020 if (function_exists('posix_getpid')) {
1021 fwrite($fp, posix_getpid() . "\n");
1029 function make_stampfile($filename) {
1030 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1032 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1033 fwrite($fp, time() . "\n");
1034 flock($fp, LOCK_UN
);
1042 function sql_random_function() {
1043 if (DB_TYPE
== "mysql") {
1050 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1052 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1054 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1056 $ref_check_qpart = ($max_id &&
1057 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1059 if (is_numeric($feed)) {
1065 $children = getChildCategories($link, $feed, $owner_uid);
1066 array_push($children, $feed);
1068 $children = join(",", $children);
1070 $cat_qpart = "cat_id IN ($children)";
1072 $cat_qpart = "cat_id IS NULL";
1075 db_query($link, "UPDATE ttrss_user_entries
1076 SET unread = false,last_read = NOW()
1077 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1078 AND $ref_check_qpart
1079 AND owner_uid = $owner_uid");
1081 } else if ($feed == -2) {
1083 db_query($link, "UPDATE ttrss_user_entries
1084 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1085 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1086 AND $ref_check_qpart
1087 AND unread = true AND owner_uid = $owner_uid");
1090 } else if ($feed > 0) {
1092 db_query($link, "UPDATE ttrss_user_entries
1093 SET unread = false,last_read = NOW()
1094 WHERE feed_id = '$feed'
1095 AND $ref_check_qpart
1096 AND owner_uid = $owner_uid");
1098 } else if ($feed < 0 && $feed > -10) { // special, like starred
1101 db_query($link, "UPDATE ttrss_user_entries
1102 SET unread = false,last_read = NOW()
1104 AND $ref_check_qpart
1105 AND owner_uid = $owner_uid");
1109 db_query($link, "UPDATE ttrss_user_entries
1110 SET unread = false,last_read = NOW()
1111 WHERE published = true
1112 AND $ref_check_qpart
1113 AND owner_uid = $owner_uid");
1118 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1120 if (DB_TYPE
== "pgsql") {
1121 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1123 $match_part = "updated > DATE_SUB(NOW(),
1124 INTERVAL $intl HOUR) ";
1127 $result = db_query($link, "SELECT id FROM ttrss_entries,
1128 ttrss_user_entries WHERE $match_part AND
1130 ttrss_user_entries.ref_id = ttrss_entries.id AND
1131 owner_uid = $owner_uid");
1133 $affected_ids = array();
1135 while ($line = db_fetch_assoc($result)) {
1136 array_push($affected_ids, $line["id"]);
1139 catchupArticlesById($link, $affected_ids, 0);
1143 db_query($link, "UPDATE ttrss_user_entries
1144 SET unread = false,last_read = NOW()
1145 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1148 } else if ($feed < -10) { // label
1150 $label_id = -$feed - 11;
1152 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1153 SET unread = false, last_read = NOW()
1154 WHERE label_id = '$label_id' AND unread = true
1155 AND $ref_check_qpart
1156 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1160 ccache_update($link, $feed, $owner_uid, $cat_view);
1163 db_query($link, "BEGIN");
1165 $tag_name = db_escape_string($feed);
1167 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1168 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1170 while ($line = db_fetch_assoc($result)) {
1171 db_query($link, "UPDATE ttrss_user_entries SET
1172 unread = false, last_read = NOW()
1173 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1175 db_query($link, "COMMIT");
1179 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1181 if (!$omode) $omode = "flc";
1183 $data = getGlobalCounters($link);
1185 $data = array_merge($data, getVirtCounters($link));
1187 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1188 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1189 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1190 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1195 function getCategoryTitle($link, $cat_id) {
1197 if ($cat_id == -1) {
1198 return __("Special");
1199 } else if ($cat_id == -2) {
1200 return __("Labels");
1203 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1206 if (db_num_rows($result) == 1) {
1207 return db_fetch_result($result, 0, "title");
1209 return __("Uncategorized");
1215 function getCategoryCounters($link) {
1218 /* Labels category */
1220 $cv = array("id" => -2, "kind" => "cat",
1221 "counter" => getCategoryUnread($link, -2));
1223 array_push($ret_arr, $cv);
1225 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1226 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1227 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1228 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1229 WHERE ttrss_cat_counters_cache.feed_id = id AND
1230 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1231 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1233 while ($line = db_fetch_assoc($result)) {
1234 $line["cat_id"] = (int) $line["cat_id"];
1236 if ($line["num_children"] > 0) {
1237 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1242 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1243 "counter" => $line["unread"] +
$child_counter);
1245 array_push($ret_arr, $cv);
1248 /* Special case: NULL category doesn't actually exist in the DB */
1250 $cv = array("id" => 0, "kind" => "cat",
1251 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1253 array_push($ret_arr, $cv);
1258 // only accepts real cats (>= 0)
1259 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1260 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1262 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1263 AND owner_uid = $owner_uid");
1267 while ($line = db_fetch_assoc($result)) {
1268 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1269 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1275 function getCategoryUnread($link, $cat, $owner_uid = false) {
1277 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1282 $cat_query = "cat_id = '$cat'";
1284 $cat_query = "cat_id IS NULL";
1287 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1288 AND owner_uid = " . $owner_uid);
1290 $cat_feeds = array();
1291 while ($line = db_fetch_assoc($result)) {
1292 array_push($cat_feeds, "feed_id = " . $line["id"]);
1295 if (count($cat_feeds) == 0) return 0;
1297 $match_part = implode(" OR ", $cat_feeds);
1299 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1300 FROM ttrss_user_entries
1301 WHERE unread = true AND ($match_part)
1302 AND owner_uid = " . $owner_uid);
1306 # this needs to be rewritten
1307 while ($line = db_fetch_assoc($result)) {
1308 $unread +
= $line["unread"];
1312 } else if ($cat == -1) {
1313 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1314 } else if ($cat == -2) {
1316 $result = db_query($link, "
1317 SELECT COUNT(unread) AS unread FROM
1318 ttrss_user_entries, ttrss_user_labels2
1319 WHERE article_id = ref_id AND unread = true
1320 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1322 $unread = db_fetch_result($result, 0, "unread");
1329 function getFeedUnread($link, $feed, $is_cat = false) {
1330 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1333 function getLabelUnread($link, $label_id, $owner_uid = false) {
1334 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1336 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1337 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1339 if (db_num_rows($result) != 0) {
1340 return db_fetch_result($result, 0, "unread");
1346 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1347 $owner_uid = false) {
1349 $n_feed = (int) $feed;
1350 $need_entries = false;
1352 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1355 $unread_qpart = "unread = true";
1357 $unread_qpart = "true";
1361 return getCategoryUnread($link, $n_feed, $owner_uid);
1362 } else if ($n_feed == -6) {
1364 } else if ($feed != "0" && $n_feed == 0) {
1366 $feed = db_escape_string($feed);
1368 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1369 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1370 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1371 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1372 return db_fetch_result($result, 0, "count");
1374 } else if ($n_feed == -1) {
1375 $match_part = "marked = true";
1376 } else if ($n_feed == -2) {
1377 $match_part = "published = true";
1378 } else if ($n_feed == -3) {
1379 $match_part = "unread = true AND score >= 0";
1381 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1383 if (DB_TYPE
== "pgsql") {
1384 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1386 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1389 $need_entries = true;
1391 } else if ($n_feed == -4) {
1392 $match_part = "true";
1393 } else if ($n_feed >= 0) {
1396 $match_part = "feed_id = '$n_feed'";
1398 $match_part = "feed_id IS NULL";
1401 } else if ($feed < -10) {
1403 $label_id = -$feed - 11;
1405 return getLabelUnread($link, $label_id, $owner_uid);
1411 if ($need_entries) {
1412 $from_qpart = "ttrss_user_entries,ttrss_entries";
1413 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1415 $from_qpart = "ttrss_user_entries";
1418 $query = "SELECT count(int_id) AS unread
1419 FROM $from_qpart WHERE
1420 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1422 //echo "[$feed/$query]\n";
1424 $result = db_query($link, $query);
1428 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1429 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1430 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1431 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1434 $unread = db_fetch_result($result, 0, "unread");
1439 function getGlobalUnread($link, $user_id = false) {
1442 $user_id = $_SESSION["uid"];
1445 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1446 WHERE owner_uid = '$user_id' AND feed_id > 0");
1448 $c_id = db_fetch_result($result, 0, "c_id");
1453 function getGlobalCounters($link, $global_unread = -1) {
1456 if ($global_unread == -1) {
1457 $global_unread = getGlobalUnread($link);
1460 $cv = array("id" => "global-unread",
1461 "counter" => (int) $global_unread);
1463 array_push($ret_arr, $cv);
1465 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1466 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1468 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1470 $cv = array("id" => "subscribed-feeds",
1471 "counter" => (int) $subscribed_feeds);
1473 array_push($ret_arr, $cv);
1478 function getTagCounters($link) {
1482 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1483 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1484 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1485 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1486 ORDER BY count DESC LIMIT 55");
1490 while ($line = db_fetch_assoc($result)) {
1491 $tags[$line["tag_name"]] +
= $line["count"];
1494 foreach (array_keys($tags) as $tag) {
1495 $unread = $tags[$tag];
1496 $tag = htmlspecialchars($tag);
1498 $cv = array("id" => $tag,
1500 "counter" => $unread);
1502 array_push($ret_arr, $cv);
1508 function getVirtCounters($link) {
1512 for ($i = 0; $i >= -4; $i--) {
1514 $count = getFeedUnread($link, $i);
1516 $cv = array("id" => $i,
1517 "counter" => (int) $count);
1519 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1520 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1522 array_push($ret_arr, $cv);
1528 function getLabelCounters($link, $descriptions = false) {
1532 $owner_uid = $_SESSION["uid"];
1534 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1535 WHERE owner_uid = '$owner_uid'");
1537 while ($line = db_fetch_assoc($result)) {
1539 $id = -$line["id"] - 11;
1541 $label_name = $line["caption"];
1542 $count = getFeedUnread($link, $id);
1544 $cv = array("id" => $id,
1545 "counter" => (int) $count);
1548 $cv["description"] = $label_name;
1550 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1551 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1553 array_push($ret_arr, $cv);
1559 function getFeedCounters($link, $active_feed = false) {
1563 $query = "SELECT ttrss_feeds.id,
1565 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1566 last_error, value AS count
1567 FROM ttrss_feeds, ttrss_counters_cache
1568 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1569 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1570 AND ttrss_counters_cache.feed_id = id";
1572 $result = db_query($link, $query);
1573 $fctrs_modified = false;
1575 while ($line = db_fetch_assoc($result)) {
1578 $count = $line["count"];
1579 $last_error = htmlspecialchars($line["last_error"]);
1581 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1583 $has_img = feed_has_icon($id);
1585 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1588 $cv = array("id" => $id,
1589 "updated" => $last_updated,
1590 "counter" => (int) $count,
1591 "has_img" => (int) $has_img);
1594 $cv["error"] = $last_error;
1596 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1597 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1599 if ($active_feed && $id == $active_feed)
1600 $cv["title"] = truncate_string($line["title"], 30);
1602 array_push($ret_arr, $cv);
1609 function get_pgsql_version($link) {
1610 $result = db_query($link, "SELECT version() AS version");
1611 $version = explode(" ", db_fetch_result($result, 0, "version"));
1616 * @return array (code => Status code, message => error message if available)
1618 * 0 - OK, Feed already exists
1619 * 1 - OK, Feed added
1621 * 3 - URL content is HTML, no feeds available
1622 * 4 - URL content is HTML which contains multiple feeds.
1623 * Here you should call extractfeedurls in rpc-backend
1624 * to get all possible feeds.
1625 * 5 - Couldn't download the URL content.
1627 function subscribe_to_feed($link, $url, $cat_id = 0,
1628 $auth_login = '', $auth_pass = '', $need_auth = false) {
1630 global $fetch_last_error;
1632 require_once "include/rssfuncs.php";
1634 $url = fix_url($url);
1636 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1638 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1641 return array("code" => 5, "message" => $fetch_last_error);
1644 if (is_html($contents)) {
1645 $feedUrls = get_feeds_from_html($url, $contents);
1647 if (count($feedUrls) == 0) {
1648 return array("code" => 3);
1649 } else if (count($feedUrls) > 1) {
1650 return array("code" => 4, "feeds" => $feedUrls);
1652 //use feed url as new URL
1653 $url = key($feedUrls);
1656 if ($cat_id == "0" ||
!$cat_id) {
1657 $cat_qpart = "NULL";
1659 $cat_qpart = "'$cat_id'";
1662 $result = db_query($link,
1663 "SELECT id FROM ttrss_feeds
1664 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1666 if (db_num_rows($result) == 0) {
1667 $result = db_query($link,
1668 "INSERT INTO ttrss_feeds
1669 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1670 VALUES ('".$_SESSION["uid"]."', '$url',
1671 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1673 $result = db_query($link,
1674 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1675 AND owner_uid = " . $_SESSION["uid"]);
1677 $feed_id = db_fetch_result($result, 0, "id");
1680 update_rss_feed($link, $feed_id, true);
1683 return array("code" => 1);
1685 return array("code" => 0);
1689 function print_feed_select($link, $id, $default_id = "",
1690 $attributes = "", $include_all_feeds = true,
1691 $root_id = false, $nest_level = 0) {
1694 print "<select id=\"$id\" name=\"$id\" $attributes>";
1695 if ($include_all_feeds) {
1696 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1697 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1701 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1704 $parent_qpart = "parent_cat = '$root_id'";
1706 $parent_qpart = "parent_cat IS NULL";
1708 $result = db_query($link, "SELECT id,title,
1709 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1710 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1711 FROM ttrss_feed_categories
1712 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1714 while ($line = db_fetch_assoc($result)) {
1716 for ($i = 0; $i < $nest_level; $i++
)
1717 $line["title"] = " - " . $line["title"];
1719 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1721 printf("<option $is_selected value='CAT:%d'>%s</option>",
1722 $line["id"], htmlspecialchars($line["title"]));
1724 if ($line["num_children"] > 0)
1725 print_feed_select($link, $id, $default_id, $attributes,
1726 $include_all_feeds, $line["id"], $nest_level+
1);
1728 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1729 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1731 while ($fline = db_fetch_assoc($feed_result)) {
1732 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1734 $fline["title"] = " + " . $fline["title"];
1736 for ($i = 0; $i < $nest_level; $i++
)
1737 $fline["title"] = " - " . $fline["title"];
1739 printf("<option $is_selected value='%d'>%s</option>",
1740 $fline["id"], htmlspecialchars($fline["title"]));
1745 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1747 printf("<option $is_selected value='CAT:0'>%s</option>",
1748 __("Uncategorized"));
1750 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1751 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1753 while ($fline = db_fetch_assoc($feed_result)) {
1754 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1756 $fline["title"] = " + " . $fline["title"];
1758 for ($i = 0; $i < $nest_level; $i++
)
1759 $fline["title"] = " - " . $fline["title"];
1761 printf("<option $is_selected value='%d'>%s</option>",
1762 $fline["id"], htmlspecialchars($fline["title"]));
1767 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1768 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1770 while ($line = db_fetch_assoc($result)) {
1772 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1774 printf("<option $is_selected value='%d'>%s</option>",
1775 $line["id"], htmlspecialchars($line["title"]));
1784 function print_feed_cat_select($link, $id, $default_id,
1785 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1788 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1792 $parent_qpart = "parent_cat = '$root_id'";
1794 $parent_qpart = "parent_cat IS NULL";
1796 $result = db_query($link, "SELECT id,title,
1797 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1798 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1799 FROM ttrss_feed_categories
1800 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1802 while ($line = db_fetch_assoc($result)) {
1803 if ($line["id"] == $default_id) {
1804 $is_selected = "selected=\"1\"";
1809 for ($i = 0; $i < $nest_level; $i++
)
1810 $line["title"] = " - " . $line["title"];
1813 printf("<option $is_selected value='%d'>%s</option>",
1814 $line["id"], htmlspecialchars($line["title"]));
1816 if ($line["num_children"] > 0)
1817 print_feed_cat_select($link, $id, $default_id, $attributes,
1818 $include_all_cats, $line["id"], $nest_level+
1);
1822 if ($include_all_cats) {
1823 if (db_num_rows($result) > 0) {
1824 print "<option disabled=\"1\">--------</option>";
1827 if ($default_id == 0) {
1828 $is_selected = "selected=\"1\"";
1833 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1839 function checkbox_to_sql_bool($val) {
1840 return ($val == "on") ?
"true" : "false";
1843 function getFeedCatTitle($link, $id) {
1845 return __("Special");
1846 } else if ($id < -10) {
1847 return __("Labels");
1848 } else if ($id > 0) {
1849 $result = db_query($link, "SELECT ttrss_feed_categories.title
1850 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1851 cat_id = ttrss_feed_categories.id");
1852 if (db_num_rows($result) == 1) {
1853 return db_fetch_result($result, 0, "title");
1855 return __("Uncategorized");
1858 return "getFeedCatTitle($id) failed";
1863 function getFeedIcon($id) {
1866 return "images/archive.png";
1869 return "images/mark_set.svg";
1872 return "images/pub_set.svg";
1875 return "images/fresh.png";
1878 return "images/tag.png";
1881 return "images/recently_read.png";
1885 return "images/label.png";
1887 if (file_exists(ICONS_DIR
. "/$id.ico"))
1888 return ICONS_URL
. "/$id.ico";
1894 function getFeedTitle($link, $id, $cat = false) {
1896 return getCategoryTitle($link, $id);
1897 } else if ($id == -1) {
1898 return __("Starred articles");
1899 } else if ($id == -2) {
1900 return __("Published articles");
1901 } else if ($id == -3) {
1902 return __("Fresh articles");
1903 } else if ($id == -4) {
1904 return __("All articles");
1905 } else if ($id === 0 ||
$id === "0") {
1906 return __("Archived articles");
1907 } else if ($id == -6) {
1908 return __("Recently read");
1909 } else if ($id < -10) {
1910 $label_id = -$id - 11;
1911 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1912 if (db_num_rows($result) == 1) {
1913 return db_fetch_result($result, 0, "caption");
1915 return "Unknown label ($label_id)";
1918 } else if (is_numeric($id) && $id > 0) {
1919 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1920 if (db_num_rows($result) == 1) {
1921 return db_fetch_result($result, 0, "title");
1923 return "Unknown feed ($id)";
1930 function make_init_params($link) {
1933 $params["theme"] = get_user_theme($link);
1934 $params["theme_options"] = get_user_theme_options($link);
1936 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1937 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1938 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1939 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
1941 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1942 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1943 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1944 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1946 $params[strtolower($param)] = (int) get_pref($link, $param);
1949 $params["icons_url"] = ICONS_URL
;
1950 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1951 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1952 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1953 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1954 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1956 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1957 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1959 $max_feed_id = db_fetch_result($result, 0, "mid");
1960 $num_feeds = db_fetch_result($result, 0, "nf");
1962 $params["max_feed_id"] = (int) $max_feed_id;
1963 $params["num_feeds"] = (int) $num_feeds;
1965 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1967 $params["csrf_token"] = $_SESSION["csrf_token"];
1972 function make_runtime_info($link) {
1975 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1976 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1978 $max_feed_id = db_fetch_result($result, 0, "mid");
1979 $num_feeds = db_fetch_result($result, 0, "nf");
1981 $data["max_feed_id"] = (int) $max_feed_id;
1982 $data["num_feeds"] = (int) $num_feeds;
1984 $data['last_article_id'] = getLastArticleId($link);
1985 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1987 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1989 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1991 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1993 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1996 $stamp_delta = time() - $stamp;
1998 if ($stamp_delta > 1800) {
2002 $_SESSION["daemon_stamp_check"] = time();
2005 $data['daemon_stamp_ok'] = $stamp_check;
2007 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2009 $data['daemon_stamp'] = $stamp_fmt;
2014 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2015 $new_version_details = @check_for_update
($link);
2017 $data['new_version_available'] = (int) ($new_version_details != false);
2019 $_SESSION["last_version_check"] = time();
2020 $_SESSION["version_data"] = $new_version_details;
2026 function search_to_sql($link, $search, $match_on) {
2028 $search_query_part = "";
2030 $keywords = explode(" ", $search);
2031 $query_keywords = array();
2033 foreach ($keywords as $k) {
2034 if (strpos($k, "-") === 0) {
2041 $commandpair = explode(":", mb_strtolower($k), 2);
2043 if ($commandpair[0] == "note" && $commandpair[1]) {
2045 if ($commandpair[1] == "true")
2046 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2048 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2050 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2052 if ($commandpair[1] == "true")
2053 array_push($query_keywords, "($not (marked = true))");
2055 array_push($query_keywords, "($not (marked = false))");
2057 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2059 if ($commandpair[1] == "true")
2060 array_push($query_keywords, "($not (published = true))");
2062 array_push($query_keywords, "($not (published = false))");
2064 } else if (strpos($k, "@") === 0) {
2066 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2067 $orig_ts = strtotime(substr($k, 1));
2068 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2070 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2072 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2073 } else if ($match_on == "both") {
2074 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2075 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2076 } else if ($match_on == "title") {
2077 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2078 } else if ($match_on == "content") {
2079 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2083 $search_query_part = implode("AND", $query_keywords);
2085 return $search_query_part;
2088 function getParentCategories($link, $cat, $owner_uid) {
2091 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2092 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2094 while ($line = db_fetch_assoc($result)) {
2095 array_push($rv, $line["parent_cat"]);
2096 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2102 function getChildCategories($link, $cat, $owner_uid) {
2105 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2106 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2108 while ($line = db_fetch_assoc($result)) {
2109 array_push($rv, $line["id"]);
2110 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2116 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) {
2118 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2120 $ext_tables_part = "";
2124 if (SPHINX_ENABLED
) {
2125 $ids = join(",", @sphinx_search
($search, 0, 500));
2128 $search_query_part = "ref_id IN ($ids) AND ";
2130 $search_query_part = "ref_id = -1 AND ";
2133 $search_query_part = search_to_sql($link, $search, $match_on);
2134 $search_query_part .= " AND ";
2138 $search_query_part = "";
2143 if (DB_TYPE
== "pgsql") {
2144 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2146 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2149 $override_order = "updated DESC";
2151 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2153 // Try to check if SQL regexp implementation chokes on a valid regexp
2154 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2155 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2156 WHERE $filter_query_part LIMIT 1", false);
2158 $test = db_fetch_result($result, 0, "true");
2161 $filter_query_part = "false AND";
2163 $filter_query_part .= " AND";
2167 $filter_query_part = "";
2171 $since_id_part = "ttrss_entries.id > $since_id AND ";
2173 $since_id_part = "";
2176 $view_query_part = "";
2178 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2180 $view_query_part = " ";
2181 } else if ($feed != -1) {
2182 $unread = getFeedUnread($link, $feed, $cat_view);
2184 if ($cat_view && $feed > 0 && $include_children)
2185 $unread +
= getCategoryChildrenUnread($link, $feed);
2188 $view_query_part = " unread = true AND ";
2193 if ($view_mode == "marked") {
2194 $view_query_part = " marked = true AND ";
2197 if ($view_mode == "published") {
2198 $view_query_part = " published = true AND ";
2201 if ($view_mode == "unread") {
2202 $view_query_part = " unread = true AND ";
2205 if ($view_mode == "updated") {
2206 $view_query_part = " (last_read is null and unread = false) AND ";
2210 $limit_query_part = "LIMIT " . $limit;
2213 $allow_archived = false;
2215 $vfeed_query_part = "";
2217 // override query strategy and enable feed display when searching globally
2218 if ($search && $search_mode == "all_feeds") {
2219 $query_strategy_part = "true";
2220 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2222 } else if (!is_numeric($feed)) {
2223 $query_strategy_part = "true";
2224 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2225 id = feed_id) as feed_title,";
2226 } else if ($search && $search_mode == "this_cat") {
2227 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2230 if ($include_children) {
2231 $subcats = getChildCategories($link, $feed, $owner_uid);
2232 array_push($subcats, $feed);
2233 $cats_qpart = join(",", $subcats);
2235 $cats_qpart = $feed;
2238 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2241 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2244 } else if ($feed > 0) {
2249 if ($include_children) {
2251 $subcats = getChildCategories($link, $feed, $owner_uid);
2253 array_push($subcats, $feed);
2254 $query_strategy_part = "cat_id IN (".
2255 implode(",", $subcats).")";
2258 $query_strategy_part = "cat_id = '$feed'";
2262 $query_strategy_part = "cat_id IS NULL";
2265 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2268 $query_strategy_part = "feed_id = '$feed'";
2270 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2271 $query_strategy_part = "feed_id IS NULL";
2272 $allow_archived = true;
2273 } else if ($feed == 0 && $cat_view) { // uncategorized
2274 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2275 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2276 } else if ($feed == -1) { // starred virtual feed
2277 $query_strategy_part = "marked = true";
2278 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2279 $allow_archived = true;
2281 } else if ($feed == -2) { // published virtual feed OR labels category
2284 $query_strategy_part = "published = true";
2285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2286 $allow_archived = true;
2288 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2290 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2292 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2294 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2295 ttrss_user_labels2.article_id = ref_id";
2298 } else if ($feed == -6) { // recently read
2299 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2300 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2301 $allow_archived = true;
2303 if (!$override_order) $override_order = "last_read DESC";
2304 } else if ($feed == -3) { // fresh virtual feed
2305 $query_strategy_part = "unread = true AND score >= 0";
2307 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2309 if (DB_TYPE
== "pgsql") {
2310 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2312 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2315 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2316 } else if ($feed == -4) { // all articles virtual feed
2317 $query_strategy_part = "true";
2318 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2319 } else if ($feed <= -10) { // labels
2320 $label_id = -$feed - 11;
2322 $query_strategy_part = "label_id = '$label_id' AND
2323 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2324 ttrss_user_labels2.article_id = ref_id";
2326 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2327 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2328 $allow_archived = true;
2331 $query_strategy_part = "true";
2334 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2335 $date_sort_field = "updated";
2337 $date_sort_field = "date_entered";
2340 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2341 $order_by = "$date_sort_field";
2343 $order_by = "$date_sort_field DESC";
2346 if ($view_mode != "noscores") {
2347 $order_by = "score DESC, $order_by";
2350 if ($override_order) {
2351 $order_by = $override_order;
2357 $feed_title = T_sprintf("Search results: %s", $search);
2360 $feed_title = getCategoryTitle($link, $feed);
2362 if (is_numeric($feed) && $feed > 0) {
2363 $result = db_query($link, "SELECT title,site_url,last_error
2364 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2366 $feed_title = db_fetch_result($result, 0, "title");
2367 $feed_site_url = db_fetch_result($result, 0, "site_url");
2368 $last_error = db_fetch_result($result, 0, "last_error");
2370 $feed_title = getFeedTitle($link, $feed);
2375 $content_query_part = "content as content_preview, cached_content, ";
2377 if (is_numeric($feed)) {
2380 $feed_kind = "Feeds";
2382 $feed_kind = "Labels";
2385 if ($limit_query_part) {
2386 $offset_query_part = "OFFSET $offset";
2389 // proper override_order applied above
2390 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2391 if (!$override_order) {
2392 $order_by = "ttrss_feeds.title, $order_by";
2394 $order_by = "ttrss_feeds.title, $override_order";
2398 if (!$allow_archived) {
2399 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2400 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2403 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2404 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2407 $query = "SELECT DISTINCT
2410 ttrss_entries.id,ttrss_entries.title,
2414 always_display_enclosures,
2420 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2421 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2424 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2430 ttrss_user_entries.ref_id = ttrss_entries.id AND
2431 ttrss_user_entries.owner_uid = '$owner_uid' AND
2436 $query_strategy_part ORDER BY $order_by
2437 $limit_query_part $offset_query_part";
2439 if ($_REQUEST["debug"]) print $query;
2441 $result = db_query($link, $query);
2446 $select_qpart = "SELECT DISTINCT " .
2450 "ttrss_entries.id as id," .
2463 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2466 $content_query_part .
2467 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2470 $feed_kind = "Tags";
2471 $all_tags = explode(",", $feed);
2472 if ($search_mode == 'any') {
2473 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2474 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2475 $where_qpart = " WHERE " .
2476 "ref_id = ttrss_entries.id AND " .
2477 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2478 "post_int_id = int_id AND $tag_sql AND " .
2480 $search_query_part .
2481 $query_strategy_part . " ORDER BY $order_by " .
2486 $sub_selects = array();
2487 $sub_ands = array();
2488 foreach ($all_tags as $term) {
2489 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");
2496 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2501 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2502 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2503 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2504 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2506 // error_log("TAG SQL: " . $tag_sql);
2507 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2509 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2510 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2513 return array($result, $feed_title, $feed_site_url, $last_error);
2517 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2518 if (!$owner) $owner = $_SESSION["uid"];
2520 $res = trim($str); if (!$res) return '';
2522 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
2523 $res = htmLawed($res, $config);
2525 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2526 $res = preg_replace('/<img[^>]+>/is', '', $res);
2529 if (strpos($res, "href=") === false)
2530 $res = rewrite_urls($res);
2532 $charset_hack = '<head>
2533 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2536 $res = trim($res); if (!$res) return '';
2538 libxml_use_internal_errors(true);
2540 $doc = new DOMDocument();
2541 $doc->loadHTML($charset_hack . $res);
2542 $xpath = new DOMXPath($doc);
2544 $entries = $xpath->query('(//a[@href]|//img[@src])');
2547 foreach ($entries as $entry) {
2551 if ($entry->hasAttribute('href'))
2552 $entry->setAttribute('href',
2553 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2555 if ($entry->hasAttribute('src'))
2556 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2557 $entry->setAttribute('src',
2558 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2561 if (strtolower($entry->nodeName
) == "a") {
2562 $entry->setAttribute("target", "_blank");
2565 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2566 $br = $doc->createElement("br");
2568 if ($entry->parentNode
->nextSibling
) {
2569 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2576 $node = $doc->getElementsByTagName('body')->item(0);
2578 // http://tt-rss.org/redmine/issues/357
2579 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2582 function check_for_update($link) {
2583 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2584 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2586 $version_data = @fetch_file_contents
($version_url);
2588 if ($version_data) {
2589 $version_data = json_decode($version_data, true);
2590 if ($version_data && $version_data['version']) {
2592 if (version_compare(VERSION
, $version_data['version']) == -1) {
2593 return $version_data;
2601 function markArticlesById($link, $ids, $cmode) {
2605 foreach ($ids as $id) {
2606 array_push($tmp_ids, "ref_id = '$id'");
2609 $ids_qpart = join(" OR ", $tmp_ids);
2612 db_query($link, "UPDATE ttrss_user_entries SET
2613 marked = false,last_read = NOW()
2614 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2615 } else if ($cmode == 1) {
2616 db_query($link, "UPDATE ttrss_user_entries SET
2618 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2620 db_query($link, "UPDATE ttrss_user_entries SET
2621 marked = NOT marked,last_read = NOW()
2622 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2626 function publishArticlesById($link, $ids, $cmode) {
2630 foreach ($ids as $id) {
2631 array_push($tmp_ids, "ref_id = '$id'");
2634 $ids_qpart = join(" OR ", $tmp_ids);
2637 db_query($link, "UPDATE ttrss_user_entries SET
2638 published = false,last_read = NOW()
2639 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2640 } else if ($cmode == 1) {
2641 db_query($link, "UPDATE ttrss_user_entries SET
2642 published = true,last_read = NOW()
2643 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2645 db_query($link, "UPDATE ttrss_user_entries SET
2646 published = NOT published,last_read = NOW()
2647 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2650 if (PUBSUBHUBBUB_HUB
) {
2651 $rss_link = get_self_url_prefix() .
2652 "/public.php?op=rss&id=-2&key=" .
2653 get_feed_access_key($link, -2, false);
2655 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2657 $pubsub_result = $p->publish_update($rss_link);
2661 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2663 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2664 if (count($ids) == 0) return;
2668 foreach ($ids as $id) {
2669 array_push($tmp_ids, "ref_id = '$id'");
2672 $ids_qpart = join(" OR ", $tmp_ids);
2675 db_query($link, "UPDATE ttrss_user_entries SET
2676 unread = false,last_read = NOW()
2677 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2678 } else if ($cmode == 1) {
2679 db_query($link, "UPDATE ttrss_user_entries SET
2681 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2683 db_query($link, "UPDATE ttrss_user_entries SET
2684 unread = NOT unread,last_read = NOW()
2685 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2690 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2691 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2693 while ($line = db_fetch_assoc($result)) {
2694 ccache_update($link, $line["feed_id"], $owner_uid);
2698 function catchupArticleById($link, $id, $cmode) {
2701 db_query($link, "UPDATE ttrss_user_entries SET
2702 unread = false,last_read = NOW()
2703 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2704 } else if ($cmode == 1) {
2705 db_query($link, "UPDATE ttrss_user_entries SET
2707 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2709 db_query($link, "UPDATE ttrss_user_entries SET
2710 unread = NOT unread,last_read = NOW()
2711 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2714 $feed_id = getArticleFeed($link, $id);
2715 ccache_update($link, $feed_id, $_SESSION["uid"]);
2718 function make_guid_from_title($title) {
2719 return preg_replace("/[ \"\',.:;]/", "-",
2720 mb_strtolower(strip_tags($title), 'utf-8'));
2723 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2725 $a_id = db_escape_string($id);
2727 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2729 $query = "SELECT DISTINCT tag_name,
2730 owner_uid as owner FROM
2731 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2732 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2734 $obj_id = md5("TAGS:$owner_uid:$id");
2737 /* check cache first */
2739 if ($tag_cache === false) {
2740 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2741 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2743 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2747 $tags = explode(",", $tag_cache);
2750 /* do it the hard way */
2752 $tmp_result = db_query($link, $query);
2754 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2755 array_push($tags, $tmp_line["tag_name"]);
2758 /* update the cache */
2760 $tags_str = db_escape_string(join(",", $tags));
2762 db_query($link, "UPDATE ttrss_user_entries
2763 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2764 AND owner_uid = $owner_uid");
2770 function trim_array($array) {
2772 array_walk($tmp, 'trim');
2776 function tag_is_valid($tag) {
2777 if ($tag == '') return false;
2778 if (preg_match("/^[0-9]*$/", $tag)) return false;
2779 if (mb_strlen($tag) > 250) return false;
2781 if (function_exists('iconv')) {
2782 $tag = iconv("utf-8", "utf-8", $tag);
2785 if (!$tag) return false;
2790 function render_login_form($link, $form_id = 0) {
2793 require_once "login_form.php";
2796 require_once "mobile/login_form.php";
2802 // from http://developer.apple.com/internet/safari/faq.html
2803 function no_cache_incantation() {
2804 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2805 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2806 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2807 header("Cache-Control: post-check=0, pre-check=0", false);
2808 header("Pragma: no-cache"); // HTTP/1.0
2811 function format_warning($msg, $id = "") {
2813 return "<div class=\"warning\" id=\"$id\">
2814 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2817 function format_notice($msg, $id = "") {
2819 return "<div class=\"notice\" id=\"$id\">
2820 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
2823 function format_error($msg, $id = "") {
2825 return "<div class=\"error\" id=\"$id\">
2826 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2829 function print_notice($msg) {
2830 return print format_notice($msg);
2833 function print_warning($msg) {
2834 return print format_warning($msg);
2837 function print_error($msg) {
2838 return print format_error($msg);
2842 function T_sprintf() {
2843 $args = func_get_args();
2844 return vsprintf(__(array_shift($args)), $args);
2847 function format_inline_player($link, $url, $ctype) {
2851 if (strpos($ctype, "audio/") === 0) {
2853 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2854 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2855 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2857 $id = 'AUDIO-' . uniqid();
2859 $entry .= "<audio id=\"$id\"\">
2860 <source src=\"$url\"></source>
2863 $entry .= "<span onclick=\"player(this)\"
2864 title=\"".__("Click to play")."\" status=\"0\"
2865 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2869 $entry .= "<object type=\"application/x-shockwave-flash\"
2870 data=\"lib/button/musicplayer.swf?song_url=$url\"
2871 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2872 <param name=\"movie\"
2873 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2878 $filename = substr($url, strrpos($url, "/")+
1);
2880 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2881 $filename . " (" . $ctype . ")" . "</a>";
2886 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2887 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2893 /* we can figure out feed_id from article id anyway, why do we
2894 * pass feed_id here? let's ignore the argument :( */
2896 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2897 WHERE ref_id = '$id'");
2899 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2901 $rv['feed_id'] = $feed_id;
2903 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2905 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2906 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2908 if (db_num_rows($result) == 1) {
2909 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2910 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2911 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2913 $rtl_content = false;
2914 $always_display_enclosures = false;
2915 $cache_content = false;
2919 $rtl_tag = "dir=\"RTL\"";
2926 if ($mark_as_read) {
2927 $result = db_query($link, "UPDATE ttrss_user_entries
2928 SET unread = false,last_read = NOW()
2929 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2931 ccache_update($link, $feed_id, $owner_uid);
2934 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2935 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
2936 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
2937 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2944 FROM ttrss_entries,ttrss_user_entries
2945 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
2949 $line = db_fetch_assoc($result);
2951 if ($line["icon_url"]) {
2952 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
2954 $feed_icon = " ";
2957 $feed_site_url = $line['site_url'];
2959 $num_comments = $line["num_comments"];
2960 $entry_comments = "";
2962 if ($num_comments > 0) {
2963 if ($line["comments"]) {
2964 $comments_url = htmlspecialchars($line["comments"]);
2966 $comments_url = htmlspecialchars($line["link"]);
2968 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
2970 if ($line["comments"] && $line["link"] != $line["comments"]) {
2971 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
2976 header("Content-Type: text/html");
2977 $rv['content'] .= "<html><head>
2978 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
2979 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2980 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2984 $title_escaped = htmlspecialchars($line['title']);
2986 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
2987 truncate_string(strip_tags($line['title']), 15) . "</div>";
2989 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2990 strip_tags($line['title']) . "</div>";
2992 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
2994 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
2995 class=\"postHeader\" id=\"POSTHDR-$id\">";
2997 $entry_author = $line["author"];
2999 if ($entry_author) {
3000 $entry_author = __(" - ") . $entry_author;
3003 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3006 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3008 if ($line["link"]) {
3009 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3010 title=\"".htmlspecialchars($line['title'])."\"
3012 htmlspecialchars($line["link"]) . "\">" .
3014 "<span class='author'>$entry_author</span></a></div>";
3016 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3019 $tag_cache = $line["tag_cache"];
3022 $tags = get_article_tags($link, $id, $owner_uid);
3024 $tags = explode(",", $tag_cache);
3026 $tags_str = format_tags_string($tags, $id);
3027 $tags_str_full = join(", ", $tags);
3029 if (!$tags_str_full) $tags_str_full = __("no tags");
3031 if (!$entry_comments) $entry_comments = " "; # placeholder
3033 $rv['content'] .= "<div class='postTags' style='float : right'>
3034 <img src='".theme_image($link, 'images/tag.png')."'
3035 class='tagsPic' alt='Tags' title='Tags'> ";
3038 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3039 <a title=\"".__('Edit tags for this article')."\"
3040 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3042 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3043 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3044 position=\"below\">$tags_str_full</div>";
3046 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3047 class='tagsPic' style=\"cursor : pointer\"
3048 onclick=\"postOpenInNewTab(event, $id)\"
3049 alt='Zoom' title='".__('Open article in new tab')."'>";
3053 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
3054 $rv['content'] .= $p->hook_article_button($line);
3057 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3058 class='tagsPic' style=\"cursor : pointer\"
3059 onclick=\"closeArticlePanel($id)\"
3060 title='".__('Close article')."'>";
3063 $tags_str = strip_tags($tags_str);
3064 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3066 $rv['content'] .= "</div>";
3067 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3069 if ($line["orig_feed_id"]) {
3071 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3072 WHERE id = ".$line["orig_feed_id"]);
3074 if (db_num_rows($tmp_result) != 0) {
3076 $rv['content'] .= "<div clear='both'>";
3077 $rv['content'] .= __("Originally from:");
3079 $rv['content'] .= " ";
3081 $tmp_line = db_fetch_assoc($tmp_result);
3083 $rv['content'] .= "<a target='_blank'
3084 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3085 $tmp_line['title'] . "</a>";
3087 $rv['content'] .= " ";
3089 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3090 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
3092 $rv['content'] .= "</div>";
3096 $rv['content'] .= "</div>";
3098 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3099 if ($line['note']) {
3100 $rv['content'] .= format_article_note($id, $line['note']);
3102 $rv['content'] .= "</div>";
3104 $rv['content'] .= "<div class=\"postIcon\">" .
3105 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3106 href=\"".htmlspecialchars($feed_site_url)."\">".
3107 $feed_icon . "</a></div>";
3109 $rv['content'] .= "<div class=\"postContent\">";
3113 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3115 $ngram_result = db_query($link, "SELECT id,title FROM
3116 ttrss_entries,ttrss_user_entries
3117 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3118 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3119 AND title != '$title_escaped'
3120 AND owner_uid = $owner_uid");
3122 if (db_num_rows($ngram_result) > 0) {
3123 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3124 "<span>" . __('Related')."</span>";
3125 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3127 while ($nline = db_fetch_assoc($ngram_result)) {
3128 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3129 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3132 $rv['content'] .= "</div></div><br/";
3136 if ($cache_content && $line["cached_content"] != "") {
3137 $line["content"] =& $line["cached_content"];
3140 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3143 $rv['content'] .= $article_content;
3145 $rv['content'] .= format_article_enclosures($link, $id,
3146 $always_display_enclosures, $article_content);
3148 $rv['content'] .= "</div>";
3150 $rv['content'] .= "</div>";
3156 <div style=\"text-align : center\">
3157 <button onclick=\"return window.close()\">".
3158 __("Close this window")."</button></div>";
3159 $rv['content'] .= "</body></html>";
3166 function print_checkpoint($n, $s) {
3167 $ts = getmicrotime();
3168 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3172 function sanitize_tag($tag) {
3175 $tag = mb_strtolower($tag, 'utf-8');
3177 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3179 // $tag = str_replace('"', "", $tag);
3180 // $tag = str_replace("+", " ", $tag);
3181 $tag = str_replace("technorati tag: ", "", $tag);
3186 function get_self_url_prefix() {
3187 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3188 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3190 return SELF_URL_PATH
;
3194 function opml_publish_url($link){
3196 $url_path = get_self_url_prefix();
3197 $url_path .= "/opml.php?op=publish&key=" .
3198 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3204 * Purge a feed contents, marked articles excepted.
3206 * @param mixed $link The database connection.
3207 * @param integer $id The id of the feed to purge.
3210 function clear_feed_articles($link, $id) {
3213 $result = db_query($link, "DELETE FROM ttrss_user_entries
3214 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3216 $result = db_query($link, "DELETE FROM ttrss_user_entries
3217 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3220 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3221 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3223 ccache_update($link, $id, $_SESSION['uid']);
3224 } // function clear_feed_articles
3227 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3229 * @return string The Mozilla Firefox feed adding URL.
3231 function add_feed_url() {
3232 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3234 $url_path = get_self_url_prefix() .
3235 "/public.php?op=subscribe&feed_url=%s";
3237 } // function add_feed_url
3239 function encrypt_password($pass, $salt = '', $mode2 = false) {
3240 if ($salt && $mode2) {
3241 return "MODE2:" . hash('sha256', $salt . $pass);
3243 return "SHA1X:" . sha1("$salt:$pass");
3245 return "SHA1:" . sha1($pass);
3247 } // function encrypt_password
3249 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3252 $cat_id = (int)getFeedCategory($link, $feed_id);
3254 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3255 owner_uid = $owner_uid AND enabled = true");
3257 $check_cats = join(",", array_merge(
3258 getParentCategories($link, $cat_id, $owner_uid),
3261 while ($line = db_fetch_assoc($result)) {
3262 $filter_id = $line["id"];
3264 $result2 = db_query($link, "SELECT
3265 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3266 FROM ttrss_filters2_rules AS r,
3267 ttrss_filter_types AS t
3269 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3270 (feed_id IS NULL OR feed_id = '$feed_id') AND
3271 filter_type = t.id AND filter_id = '$filter_id'");
3276 while ($rule_line = db_fetch_assoc($result2)) {
3277 # print_r($rule_line);
3280 $rule["reg_exp"] = $rule_line["reg_exp"];
3281 $rule["type"] = $rule_line["type_name"];
3283 array_push($rules, $rule);
3286 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3287 FROM ttrss_filters2_actions AS a,
3288 ttrss_filter_actions AS t
3290 action_id = t.id AND filter_id = '$filter_id'");
3292 while ($action_line = db_fetch_assoc($result2)) {
3293 # print_r($action_line);
3296 $action["type"] = $action_line["type_name"];
3297 $action["param"] = $action_line["action_param"];
3299 array_push($actions, $action);
3304 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3305 $filter["rules"] = $rules;
3306 $filter["actions"] = $actions;
3308 if (count($rules) > 0 && count($actions) > 0) {
3309 array_push($filters, $filter);
3316 function get_score_pic($score) {
3318 return "score_high.png";
3319 } else if ($score > 0) {
3320 return "score_half_high.png";
3321 } else if ($score < -100) {
3322 return "score_low.png";
3323 } else if ($score < 0) {
3324 return "score_half_low.png";
3326 return "score_neutral.png";
3330 function feed_has_icon($id) {
3331 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3334 function init_connection($link) {
3337 if (DB_TYPE
== "pgsql") {
3338 pg_query($link, "set client_encoding = 'UTF-8'");
3339 pg_set_client_encoding("UNICODE");
3340 pg_query($link, "set datestyle = 'ISO, european'");
3341 pg_query($link, "set TIME ZONE 0");
3343 db_query($link, "SET time_zone = '+0:0'");
3345 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3346 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3352 $pluginhost = new PluginHost($link);
3353 $pluginhost->load(PLUGINS
, $pluginhost::KIND_ALL
);
3357 print "Unable to connect to database:" . db_last_error();
3362 /* function ccache_zero($link, $feed_id, $owner_uid) {
3363 db_query($link, "UPDATE ttrss_counters_cache SET
3364 value = 0, updated = NOW() WHERE
3365 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3368 function ccache_zero_all($link, $owner_uid) {
3369 db_query($link, "UPDATE ttrss_counters_cache SET
3370 value = 0 WHERE owner_uid = '$owner_uid'");
3372 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3373 value = 0 WHERE owner_uid = '$owner_uid'");
3376 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3379 $table = "ttrss_counters_cache";
3381 $table = "ttrss_cat_counters_cache";
3384 db_query($link, "DELETE FROM $table WHERE
3385 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3389 function ccache_update_all($link, $owner_uid) {
3391 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3393 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3394 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3396 while ($line = db_fetch_assoc($result)) {
3397 ccache_update($link, $line["feed_id"], $owner_uid, true);
3400 /* We have to manually include category 0 */
3402 ccache_update($link, 0, $owner_uid, true);
3405 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3406 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3408 while ($line = db_fetch_assoc($result)) {
3409 print ccache_update($link, $line["feed_id"], $owner_uid);
3416 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3417 $no_update = false) {
3419 if (!is_numeric($feed_id)) return;
3422 $table = "ttrss_counters_cache";
3424 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3425 WHERE id = '$feed_id'");
3426 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3429 $table = "ttrss_cat_counters_cache";
3432 if (DB_TYPE
== "pgsql") {
3433 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3434 } else if (DB_TYPE
== "mysql") {
3435 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3438 $result = db_query($link, "SELECT value FROM $table
3439 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3442 if (db_num_rows($result) == 1) {
3443 return db_fetch_result($result, 0, "value");
3448 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3454 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3455 $update_pcat = true) {
3457 if (!is_numeric($feed_id)) return;
3459 if (!$is_cat && $feed_id > 0) {
3460 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3461 WHERE id = '$feed_id'");
3462 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3465 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3467 /* When updating a label, all we need to do is recalculate feed counters
3468 * because labels are not cached */
3471 ccache_update_all($link, $owner_uid);
3476 $table = "ttrss_counters_cache";
3478 $table = "ttrss_cat_counters_cache";
3481 if ($is_cat && $feed_id >= 0) {
3482 if ($feed_id != 0) {
3483 $cat_qpart = "cat_id = '$feed_id'";
3485 $cat_qpart = "cat_id IS NULL";
3488 /* Recalculate counters for child feeds */
3490 $result = db_query($link, "SELECT id FROM ttrss_feeds
3491 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3493 while ($line = db_fetch_assoc($result)) {
3494 ccache_update($link, $line["id"], $owner_uid, false, false);
3497 $result = db_query($link, "SELECT SUM(value) AS sv
3498 FROM ttrss_counters_cache, ttrss_feeds
3499 WHERE id = feed_id AND $cat_qpart AND
3500 ttrss_feeds.owner_uid = '$owner_uid'");
3502 $unread = (int) db_fetch_result($result, 0, "sv");
3505 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3508 db_query($link, "BEGIN");
3510 $result = db_query($link, "SELECT feed_id FROM $table
3511 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3513 if (db_num_rows($result) == 1) {
3514 db_query($link, "UPDATE $table SET
3515 value = '$unread', updated = NOW() WHERE
3516 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3519 db_query($link, "INSERT INTO $table
3520 (feed_id, value, owner_uid, updated)
3522 ($feed_id, $unread, $owner_uid, NOW())");
3525 db_query($link, "COMMIT");
3527 if ($feed_id > 0 && $prev_unread != $unread) {
3531 /* Update parent category */
3535 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3536 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3538 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3540 ccache_update($link, $cat_id, $owner_uid, true);
3544 } else if ($feed_id < 0) {
3545 ccache_update_all($link, $owner_uid);
3551 /* function ccache_cleanup($link, $owner_uid) {
3553 if (DB_TYPE == "pgsql") {
3554 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3555 (SELECT count(*) FROM ttrss_counters_cache AS c2
3556 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3557 AND owner_uid = '$owner_uid'");
3559 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3560 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3561 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3562 AND owner_uid = '$owner_uid'");
3564 db_query($link, "DELETE c1 FROM
3565 ttrss_counters_cache AS c1,
3566 ttrss_counters_cache AS c2
3568 c1.owner_uid = '$owner_uid' AND
3569 c1.owner_uid = c2.owner_uid AND
3570 c1.feed_id = c2.feed_id");
3572 db_query($link, "DELETE c1 FROM
3573 ttrss_cat_counters_cache AS c1,
3574 ttrss_cat_counters_cache AS c2
3576 c1.owner_uid = '$owner_uid' AND
3577 c1.owner_uid = c2.owner_uid AND
3578 c1.feed_id = c2.feed_id");
3583 function label_find_id($link, $label, $owner_uid) {
3584 $result = db_query($link,
3585 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3586 AND owner_uid = '$owner_uid' LIMIT 1");
3588 if (db_num_rows($result) == 1) {
3589 return db_fetch_result($result, 0, "id");
3595 function get_article_labels($link, $id, $owner_uid = false) {
3598 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3600 $result = db_query($link, "SELECT label_cache FROM
3601 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3604 if (db_num_rows($result) > 0) {
3605 $label_cache = db_fetch_result($result, 0, "label_cache");
3608 $label_cache = json_decode($label_cache, true);
3610 if ($label_cache["no-labels"] == 1)
3613 return $label_cache;
3617 $result = db_query($link,
3618 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3619 FROM ttrss_labels2, ttrss_user_labels2
3621 AND article_id = '$id'
3622 AND owner_uid = ". $owner_uid . "
3625 while ($line = db_fetch_assoc($result)) {
3626 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3628 array_push($rv, $rk);
3632 label_update_cache($link, $owner_uid, $id, $rv);
3634 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3640 function label_find_caption($link, $label, $owner_uid) {
3641 $result = db_query($link,
3642 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3643 AND owner_uid = '$owner_uid' LIMIT 1");
3645 if (db_num_rows($result) == 1) {
3646 return db_fetch_result($result, 0, "caption");
3652 function get_all_labels($link, $owner_uid) {
3655 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3657 while ($line = db_fetch_assoc($result)) {
3658 array_push($rv, $line);
3664 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3667 label_clear_cache($link, $id);
3670 $labels = get_article_labels($link, $id);
3672 $labels = db_escape_string(json_encode($labels));
3674 db_query($link, "UPDATE ttrss_user_entries SET
3675 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3679 function label_clear_cache($link, $id) {
3681 db_query($link, "UPDATE ttrss_user_entries SET
3682 label_cache = '' WHERE ref_id = '$id'");
3686 function label_remove_article($link, $id, $label, $owner_uid) {
3688 $label_id = label_find_id($link, $label, $owner_uid);
3690 if (!$label_id) return;
3692 $result = db_query($link,
3693 "DELETE FROM ttrss_user_labels2
3695 label_id = '$label_id' AND
3696 article_id = '$id'");
3698 label_clear_cache($link, $id);
3701 function label_add_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,
3709 article_id FROM ttrss_labels2, ttrss_user_labels2
3712 label_id = '$label_id' AND
3713 article_id = '$id' AND owner_uid = '$owner_uid'
3716 if (db_num_rows($result) == 0) {
3717 db_query($link, "INSERT INTO ttrss_user_labels2
3718 (label_id, article_id) VALUES ('$label_id', '$id')");
3721 label_clear_cache($link, $id);
3725 function label_remove($link, $id, $owner_uid) {
3726 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3728 db_query($link, "BEGIN");
3730 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3733 $caption = db_fetch_result($result, 0, "caption");
3735 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3736 AND owner_uid = " . $owner_uid);
3738 if (db_affected_rows($link, $result) != 0 && $caption) {
3740 /* Remove access key for the label */
3742 $ext_id = -11 - $id;
3744 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3745 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3747 /* Disable filters that reference label being removed */
3749 db_query($link, "UPDATE ttrss_filters SET
3750 enabled = false WHERE action_param = '$caption'
3752 AND owner_uid = " . $owner_uid);
3754 /* Remove cached data */
3756 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3757 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3761 db_query($link, "COMMIT");
3764 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3766 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3768 db_query($link, "BEGIN");
3772 $result = db_query($link, "SELECT id FROM ttrss_labels2
3773 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3775 if (db_num_rows($result) == 0) {
3776 $result = db_query($link,
3777 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3778 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3780 $result = db_affected_rows($link, $result) != 0;
3783 db_query($link, "COMMIT");
3788 function format_tags_string($tags, $id) {
3791 $tags_nolinks_str = "";
3797 $formatted_tags = array();
3799 foreach ($tags as $tag) {
3801 $tag_escaped = str_replace("'", "\\'", $tag);
3803 if (mb_strlen($tag) > 30) {
3804 $tag = truncate_string($tag, 30);
3807 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3809 array_push($formatted_tags, $tag_str);
3811 $tmp_tags_str = implode(", ", $formatted_tags);
3813 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
3818 $tags_str = implode(", ", $formatted_tags);
3820 if ($num_tags < count($tags)) {
3821 $tags_str .= ", …";
3824 if ($num_tags == 0) {
3825 $tags_str = __("no tags");
3832 function format_article_labels($labels, $id) {
3836 foreach ($labels as $l) {
3837 $labels_str .= sprintf("<span class='hlLabelRef'
3838 style='color : %s; background-color : %s'>%s</span>",
3839 $l[2], $l[3], $l[1]);
3846 function format_article_note($id, $note) {
3848 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3849 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3850 __('(edit note)')."</div>$note</div>";
3855 function toggle_collapse_cat($link, $cat_id, $mode) {
3857 $mode = bool_to_sql_bool($mode);
3859 db_query($link, "UPDATE ttrss_feed_categories SET
3860 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3867 $pref_name = '_COLLAPSED_SPECIAL';
3870 $pref_name = '_COLLAPSED_LABELS';
3873 $pref_name = '_COLLAPSED_UNCAT';
3879 set_pref($link, $pref_name, 'true');
3881 set_pref($link, $pref_name, 'false');
3887 function remove_feed($link, $id, $owner_uid) {
3891 /* save starred articles in Archived feed */
3893 db_query($link, "BEGIN");
3895 /* prepare feed if necessary */
3897 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
3900 if (db_num_rows($result) == 0) {
3901 db_query($link, "INSERT INTO ttrss_archived_feeds
3902 (id, owner_uid, title, feed_url, site_url)
3903 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
3907 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
3908 orig_feed_id = '$id' WHERE feed_id = '$id' AND
3909 marked = true AND owner_uid = $owner_uid");
3911 /* Remove access key for the feed */
3913 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3914 feed_id = '$id' AND owner_uid = $owner_uid");
3916 /* remove the feed */
3918 db_query($link, "DELETE FROM ttrss_feeds
3919 WHERE id = '$id' AND owner_uid = $owner_uid");
3921 db_query($link, "COMMIT");
3923 if (file_exists(ICONS_DIR
. "/$id.ico")) {
3924 unlink(ICONS_DIR
. "/$id.ico");
3927 ccache_remove($link, $id, $owner_uid);
3930 label_remove($link, -11-$id, $owner_uid);
3931 ccache_remove($link, -11-$id, $owner_uid);
3935 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3936 if ($parent_cat_id) {
3937 $parent_qpart = "parent_cat = '$parent_cat_id'";
3938 $parent_insert = "'$parent_cat_id'";
3940 $parent_qpart = "parent_cat IS NULL";
3941 $parent_insert = "NULL";
3944 $result = db_query($link,
3945 "SELECT id FROM ttrss_feed_categories
3946 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3948 if (db_num_rows($result) == 0) {
3951 return db_fetch_result($result, 0, "id");
3955 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3957 if (!$feed_cat) return false;
3959 db_query($link, "BEGIN");
3961 if ($parent_cat_id) {
3962 $parent_qpart = "parent_cat = '$parent_cat_id'";
3963 $parent_insert = "'$parent_cat_id'";
3965 $parent_qpart = "parent_cat IS NULL";
3966 $parent_insert = "NULL";
3969 $result = db_query($link,
3970 "SELECT id FROM ttrss_feed_categories
3971 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3973 if (db_num_rows($result) == 0) {
3975 $result = db_query($link,
3976 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3977 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3979 db_query($link, "COMMIT");
3987 function remove_feed_category($link, $id, $owner_uid) {
3989 db_query($link, "DELETE FROM ttrss_feed_categories
3990 WHERE id = '$id' AND owner_uid = $owner_uid");
3992 ccache_remove($link, $id, $owner_uid, true);
3995 function archive_article($link, $id, $owner_uid) {
3996 db_query($link, "BEGIN");
3998 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3999 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4001 if (db_num_rows($result) != 0) {
4003 /* prepare the archived table */
4005 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4008 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4009 WHERE id = '$feed_id'");
4011 if (db_num_rows($result) == 0) {
4012 db_query($link, "INSERT INTO ttrss_archived_feeds
4013 (id, owner_uid, title, feed_url, site_url)
4014 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4015 WHERE id = '$feed_id'");
4018 db_query($link, "UPDATE ttrss_user_entries
4019 SET orig_feed_id = feed_id, feed_id = NULL
4020 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4024 db_query($link, "COMMIT");
4027 function getArticleFeed($link, $id) {
4028 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4029 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4031 if (db_num_rows($result) != 0) {
4032 return db_fetch_result($result, 0, "feed_id");
4039 * Fixes incomplete URLs by prepending "http://".
4040 * Also replaces feed:// with http://, and
4041 * prepends a trailing slash if the url is a domain name only.
4043 * @param string $url Possibly incomplete URL
4045 * @return string Fixed URL.
4047 function fix_url($url) {
4048 if (strpos($url, '://') === false) {
4049 $url = 'http://' . $url;
4050 } else if (substr($url, 0, 5) == 'feed:') {
4051 $url = 'http:' . substr($url, 5);
4054 //prepend slash if the URL has no slash in it
4055 // "http://www.example" -> "http://www.example/"
4056 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4060 if ($url != "http:///")
4066 function validate_feed_url($url) {
4067 $parts = parse_url($url);
4069 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4073 function get_article_enclosures($link, $id) {
4075 $query = "SELECT * FROM ttrss_enclosures
4076 WHERE post_id = '$id' AND content_url != ''";
4080 $result = db_query($link, $query);
4082 if (db_num_rows($result) > 0) {
4083 while ($line = db_fetch_assoc($result)) {
4084 array_push($rv, $line);
4091 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4097 if ($cat_id == -4 ||
$cat_id == -2) {
4098 $counters = getLabelCounters($link, true);
4100 foreach (array_values($counters) as $cv) {
4102 $unread = $cv["counter"];
4104 if ($unread ||
!$unread_only) {
4108 "title" => $cv["description"],
4109 "unread" => $cv["counter"],
4113 array_push($feeds, $row);
4120 if ($cat_id == -4 ||
$cat_id == -1) {
4121 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4122 $unread = getFeedUnread($link, $i);
4124 if ($unread ||
!$unread_only) {
4125 $title = getFeedTitle($link, $i);
4130 "unread" => $unread,
4133 array_push($feeds, $row);
4141 if ($include_nested && $cat_id) {
4142 $result = db_query($link, "SELECT
4143 id, title FROM ttrss_feed_categories
4144 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4145 " ORDER BY id, title");
4147 while ($line = db_fetch_assoc($result)) {
4148 $unread = getFeedUnread($link, $line["id"], true) +
4149 getCategoryChildrenUnread($link, $line["id"]);
4151 if ($unread ||
!$unread_only) {
4153 "id" => $line["id"],
4154 "title" => $line["title"],
4155 "unread" => $unread,
4158 array_push($feeds, $row);
4166 $limit_qpart = "LIMIT $limit OFFSET $offset";
4171 if ($cat_id == -4 ||
$cat_id == -3) {
4172 $result = db_query($link, "SELECT
4173 id, feed_url, cat_id, title, order_id, ".
4174 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4175 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4176 " ORDER BY cat_id, title " . $limit_qpart);
4180 $cat_qpart = "cat_id = '$cat_id'";
4182 $cat_qpart = "cat_id IS NULL";
4184 $result = db_query($link, "SELECT
4185 id, feed_url, cat_id, title, order_id, ".
4186 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4187 FROM ttrss_feeds WHERE
4188 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4189 " ORDER BY cat_id, title " . $limit_qpart);
4192 while ($line = db_fetch_assoc($result)) {
4194 $unread = getFeedUnread($link, $line["id"]);
4196 $has_icon = feed_has_icon($line['id']);
4198 if ($unread ||
!$unread_only) {
4201 "feed_url" => $line["feed_url"],
4202 "title" => $line["title"],
4203 "id" => (int)$line["id"],
4204 "unread" => (int)$unread,
4205 "has_icon" => $has_icon,
4206 "cat_id" => (int)$line["cat_id"],
4207 "last_updated" => strtotime($line["last_updated"]),
4208 "order_id" => (int) $line["order_id"],
4211 array_push($feeds, $row);
4218 function api_get_headlines($link, $feed_id, $limit, $offset,
4219 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4220 $include_attachments, $since_id,
4221 $search = "", $search_mode = "", $match_on = "",
4222 $include_nested = false, $sanitize_content = true) {
4224 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4225 $view_mode, $is_cat, $search, $search_mode, $match_on,
4226 $order, $offset, 0, false, $since_id, $include_nested);
4228 $result = $qfh_ret[0];
4229 $feed_title = $qfh_ret[1];
4231 $headlines = array();
4233 while ($line = db_fetch_assoc($result)) {
4234 $is_updated = ($line["last_read"] == "" &&
4235 ($line["unread"] != "t" && $line["unread"] != "1"));
4237 $tags = explode(",", $line["tag_cache"]);
4238 $labels = json_decode($line["label_cache"], true);
4240 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4241 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4243 $headline_row = array(
4244 "id" => (int)$line["id"],
4245 "unread" => sql_bool_to_bool($line["unread"]),
4246 "marked" => sql_bool_to_bool($line["marked"]),
4247 "published" => sql_bool_to_bool($line["published"]),
4248 "updated" => strtotime($line["updated"]),
4249 "is_updated" => $is_updated,
4250 "title" => $line["title"],
4251 "link" => $line["link"],
4252 "feed_id" => $line["feed_id"],
4256 if ($include_attachments)
4257 $headline_row['attachments'] = get_article_enclosures($link,
4260 if ($show_excerpt) {
4261 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4262 $headline_row["excerpt"] = $excerpt;
4265 if ($show_content) {
4267 if ($line["cached_content"] != "") {
4268 $line["content_preview"] =& $line["cached_content"];
4271 if ($sanitize_content) {
4272 $headline_row["content"] = sanitize($link,
4273 $line["content_preview"], false, false, $line["site_url"]);
4275 $headline_row["content"] = $line["content_preview"];
4279 // unify label output to ease parsing
4280 if ($labels["no-labels"] == 1) $labels = array();
4282 $headline_row["labels"] = $labels;
4284 $headline_row["feed_title"] = $line["feed_title"];
4286 $headline_row["comments_count"] = (int)$line["num_comments"];
4287 $headline_row["comments_link"] = $line["comments"];
4289 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4291 array_push($headlines, $headline_row);
4297 function generate_error_feed($link, $error) {
4300 $reply['headlines']['id'] = -6;
4301 $reply['headlines']['is_cat'] = false;
4303 $reply['headlines']['toolbar'] = '';
4304 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4306 $reply['headlines-info'] = array("count" => 0,
4307 "vgroup_last_feed" => '',
4309 "disable_cache" => true);
4315 function generate_dashboard_feed($link) {
4318 $reply['headlines']['id'] = -5;
4319 $reply['headlines']['is_cat'] = false;
4321 $reply['headlines']['toolbar'] = '';
4322 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4324 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4326 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4327 WHERE owner_uid = " . $_SESSION['uid']);
4329 $last_updated = db_fetch_result($result, 0, "last_updated");
4330 $last_updated = make_local_datetime($link, $last_updated, false);
4332 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4334 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4335 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4337 $num_errors = db_fetch_result($result, 0, "num_errors");
4339 if ($num_errors > 0) {
4340 $reply['headlines']['content'] .= "<br/>";
4341 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4342 __('Some feeds have update errors (click for details)')."</a>";
4344 $reply['headlines']['content'] .= "</span></p>";
4346 $reply['headlines-info'] = array("count" => 0,
4347 "vgroup_last_feed" => '',
4349 "disable_cache" => true);
4354 function save_email_address($link, $email) {
4355 // FIXME: implement persistent storage of emails
4357 if (!$_SESSION['stored_emails'])
4358 $_SESSION['stored_emails'] = array();
4360 if (!in_array($email, $_SESSION['stored_emails']))
4361 array_push($_SESSION['stored_emails'], $email);
4364 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4365 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4367 $sql_is_cat = bool_to_sql_bool($is_cat);
4369 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4370 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4371 AND owner_uid = " . $owner_uid);
4373 if (db_num_rows($result) == 1) {
4374 $key = db_escape_string(sha1(uniqid(rand(), true)));
4376 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4377 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4378 AND owner_uid = " . $owner_uid);
4383 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4387 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4389 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4391 $sql_is_cat = bool_to_sql_bool($is_cat);
4393 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4394 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4395 AND owner_uid = " . $owner_uid);
4397 if (db_num_rows($result) == 1) {
4398 return db_fetch_result($result, 0, "access_key");
4400 $key = db_escape_string(sha1(uniqid(rand(), true)));
4402 $result = db_query($link, "INSERT INTO ttrss_access_keys
4403 (access_key, feed_id, is_cat, owner_uid)
4404 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4411 function get_feeds_from_html($url, $content)
4413 $url = fix_url($url);
4414 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4416 libxml_use_internal_errors(true);
4418 $doc = new DOMDocument();
4419 $doc->loadHTML($content);
4420 $xpath = new DOMXPath($doc);
4421 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4422 $feedUrls = array();
4423 foreach ($entries as $entry) {
4424 if ($entry->hasAttribute('href')) {
4425 $title = $entry->getAttribute('title');
4427 $title = $entry->getAttribute('type');
4429 $feedUrl = rewrite_relative_url(
4430 $baseUrl, $entry->getAttribute('href')
4432 $feedUrls[$feedUrl] = $title;
4438 function is_html($content) {
4439 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4442 function url_is_html($url, $login = false, $pass = false) {
4443 return is_html(fetch_file_contents($url, false, $login, $pass));
4446 function print_label_select($link, $name, $value, $attributes = "") {
4448 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4449 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4451 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4452 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4454 while ($line = db_fetch_assoc($result)) {
4456 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4458 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4459 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4463 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4470 function format_article_enclosures($link, $id, $always_display_enclosures,
4473 $result = get_article_enclosures($link, $id);
4476 if (count($result) > 0) {
4478 $entries_html = array();
4481 foreach ($result as $line) {
4483 $url = $line["content_url"];
4484 $ctype = $line["content_type"];
4486 if (!$ctype) $ctype = __("unknown type");
4488 $filename = substr($url, strrpos($url, "/")+
1);
4490 # $player = format_inline_player($link, $url, $ctype);
4492 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4493 # $filename . " (" . $ctype . ")" . "</a>";
4495 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4496 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4498 array_push($entries_html, $entry);
4502 $entry["type"] = $ctype;
4503 $entry["filename"] = $filename;
4504 $entry["url"] = $url;
4506 array_push($entries, $entry);
4509 if (!get_pref($link, "STRIP_IMAGES")) {
4510 if ($always_display_enclosures ||
4511 !preg_match("/<img/i", $article_content)) {
4513 foreach ($entries as $entry) {
4515 if (preg_match("/image/", $entry["type"]) ||
4516 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4519 alt=\"".htmlspecialchars($entry["filename"])."\"
4520 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4527 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4528 "<span>" . __('Attachments')."</span>";
4529 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4531 foreach ($entries_html as $entry) { $rv .= $entry; };
4533 $rv .= "</div></div>";
4539 function getLastArticleId($link) {
4540 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4541 WHERE owner_uid = " . $_SESSION["uid"]);
4543 if (db_num_rows($result) == 1) {
4544 return db_fetch_result($result, 0, "id");
4550 function build_url($parts) {
4551 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4555 * Converts a (possibly) relative URL to a absolute one.
4557 * @param string $url Base URL (i.e. from where the document is)
4558 * @param string $rel_url Possibly relative URL in the document
4560 * @return string Absolute URL
4562 function rewrite_relative_url($url, $rel_url) {
4563 if (strpos($rel_url, "magnet:") === 0) {
4565 } else if (strpos($rel_url, "://") !== false) {
4567 } else if (strpos($rel_url, "//") === 0) {
4568 # protocol-relative URL (rare but they exist)
4570 } else if (strpos($rel_url, "/") === 0)
4572 $parts = parse_url($url);
4573 $parts['path'] = $rel_url;
4575 return build_url($parts);
4578 $parts = parse_url($url);
4579 if (!isset($parts['path'])) {
4580 $parts['path'] = '/';
4582 $dir = $parts['path'];
4583 if (substr($dir, -1) !== '/') {
4584 $dir = dirname($parts['path']);
4585 $dir !== '/' && $dir .= '/';
4587 $parts['path'] = $dir . $rel_url;
4589 return build_url($parts);
4593 function sphinx_search($query, $offset = 0, $limit = 30) {
4594 require_once 'lib/sphinxapi.php';
4596 $sphinxClient = new SphinxClient();
4598 $sphinxClient->SetServer('localhost', 9312);
4599 $sphinxClient->SetConnectTimeout(1);
4601 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4602 'feed_title' => 20));
4604 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4605 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4606 $sphinxClient->SetLimits($offset, $limit, 1000);
4607 $sphinxClient->SetArrayResult(false);
4608 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4610 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4614 if (is_array($result['matches'])) {
4615 foreach (array_keys($result['matches']) as $int_id) {
4616 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4617 array_push($ids, $ref_id);
4624 function cleanup_tags($link, $days = 14, $limit = 1000) {
4626 if (DB_TYPE
== "pgsql") {
4627 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4628 } else if (DB_TYPE
== "mysql") {
4629 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4634 while ($limit > 0) {
4637 $query = "SELECT ttrss_tags.id AS id
4638 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4639 WHERE post_int_id = int_id AND $interval_query AND
4640 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4642 $result = db_query($link, $query);
4646 while ($line = db_fetch_assoc($result)) {
4647 array_push($ids, $line['id']);
4650 if (count($ids) > 0) {
4651 $ids = join(",", $ids);
4654 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4655 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4660 $limit -= $limit_part;
4665 return $tags_deleted;
4668 function print_user_stylesheet($link) {
4669 $value = get_pref($link, 'USER_STYLESHEET');
4672 print "<style type=\"text/css\">";
4673 print str_replace("<br/>", "\n", $value);
4679 function rewrite_urls($html) {
4680 libxml_use_internal_errors(true);
4682 $charset_hack = '<head>
4683 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4686 $doc = new DOMDocument();
4687 $doc->loadHTML($charset_hack . $html);
4688 $xpath = new DOMXPath($doc);
4690 $entries = $xpath->query('//*/text()');
4692 foreach ($entries as $entry) {
4693 if (strstr($entry->wholeText
, "://") !== false) {
4694 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4695 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4697 if ($text != $entry->wholeText
) {
4698 $cdoc = new DOMDocument();
4699 $cdoc->loadHTML($charset_hack . $text);
4702 foreach ($cdoc->childNodes
as $cnode) {
4703 $cnode = $doc->importNode($cnode, true);
4706 $entry->parentNode
->insertBefore($cnode);
4710 $entry->parentNode
->removeChild($entry);
4716 $node = $doc->getElementsByTagName('body')->item(0);
4718 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4720 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4725 function filter_to_sql($link, $filter, $owner_uid) {
4728 if (DB_TYPE
== "pgsql")
4731 $reg_qpart = "REGEXP";
4733 foreach ($filter["rules"] AS $rule) {
4734 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4735 $rule['reg_exp']) !== FALSE;
4737 if ($regexp_valid) {
4739 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4741 switch ($rule["type"]) {
4743 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4744 $rule['reg_exp'] . "')";
4747 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4748 $rule['reg_exp'] . "')";
4751 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4752 $rule['reg_exp'] . "') OR LOWER(" .
4753 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4756 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4757 $rule['reg_exp'] . "')";
4760 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4761 $rule['reg_exp'] . "')";
4764 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4765 $rule['reg_exp'] . "')";
4769 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4770 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4773 if (isset($rule["cat_id"])) {
4775 if ($rule["cat_id"] > 0) {
4776 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4777 array_push($children, $rule["cat_id"]);
4779 $children = join(",", $children);
4781 $cat_qpart = "cat_id IN ($children)";
4783 $cat_qpart = "cat_id IS NULL";
4786 $qpart .= " AND $cat_qpart";
4789 array_push($query, "($qpart)");
4794 if (count($query) > 0) {
4795 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
4801 if (!function_exists('gzdecode')) {
4802 function gzdecode($string) { // no support for 2nd argument
4803 return file_get_contents('compress.zlib://data:who/cares;base64,'.
4804 base64_encode($string));
4808 function get_random_bytes($length) {
4809 if (function_exists('openssl_random_pseudo_bytes')) {
4810 return openssl_random_pseudo_bytes($length);
4814 for ($i = 0; $i < $length; $i++
)
4815 $output .= chr(mt_rand(0, 255));
4821 function read_stdin() {
4822 $fp = fopen("php://stdin", "r");
4825 $line = trim(fgets($fp));
4833 function tmpdirname($path, $prefix) {
4834 // Use PHP's tmpfile function to create a temporary
4835 // directory name. Delete the file and keep the name.
4836 $tempname = tempnam($path,$prefix);
4840 if (!unlink($tempname))
4846 function getFeedCategory($link, $feed) {
4847 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
4848 WHERE id = '$feed'");
4850 if (db_num_rows($result) > 0) {
4851 return db_fetch_result($result, 0, "cat_id");
4858 function create_published_article($link, $title, $url, $content, $labels_str,
4861 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
4862 $content_hash = sha1($content);
4864 if ($labels_str != "") {
4865 $labels = explode(",", $labels_str);
4872 if (!$title) $title = $url;
4873 if (!$title && !$url) return false;
4875 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
4877 db_query($link, "BEGIN");
4879 // only check for our user data here, others might have shared this with different content etc
4880 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
4881 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
4883 if (db_num_rows($result) != 0) {
4884 $ref_id = db_fetch_result($result, 0, "id");
4886 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
4887 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
4889 if (db_num_rows($result) != 0) {
4890 $int_id = db_fetch_result($result, 0, "int_id");
4892 db_query($link, "UPDATE ttrss_entries SET
4893 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
4895 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
4896 int_id = '$int_id' AND owner_uid = '$owner_uid'");
4899 db_query($link, "INSERT INTO ttrss_user_entries
4900 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4902 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4905 if (count($labels) != 0) {
4906 foreach ($labels as $label) {
4907 label_add_article($link, $ref_id, trim($label), $owner_uid);
4914 $result = db_query($link, "INSERT INTO ttrss_entries
4915 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
4917 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
4919 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
4921 if (db_num_rows($result) != 0) {
4922 $ref_id = db_fetch_result($result, 0, "id");
4924 db_query($link, "INSERT INTO ttrss_user_entries
4925 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
4927 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
4929 if (count($labels) != 0) {
4930 foreach ($labels as $label) {
4931 label_add_article($link, $ref_id, trim($label), $owner_uid);
4939 db_query($link, "COMMIT");
4944 function implements_interface($class, $interface) {
4945 return in_array($interface, class_implements($class));