2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 99);
5 $fetch_last_error = false;
8 function __autoload($class) {
9 $class_file = str_replace("_", "/", strtolower(basename($class)));
11 $file = dirname(__FILE__
)."/../classes/$class_file.php";
13 if (file_exists($file)) {
19 mb_internal_encoding("UTF-8");
20 date_default_timezone_set('UTC');
21 if (defined('E_DEPRECATED')) {
22 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
24 error_reporting(E_ALL
& ~E_NOTICE
);
27 require_once 'config.php';
29 if (DB_TYPE
== "pgsql") {
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
32 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
35 define('THEME_VERSION_REQUIRED', 1.1);
38 * Return available translations names.
41 * @return array A array of available translations.
43 function get_translations() {
45 "auto" => "Detect automatically",
50 "fr_FR" => "Français",
51 "hu_HU" => "Magyar (Hungarian)",
52 "it_IT" => "Italiano",
53 "ja_JP" => "日本語 (Japanese)",
54 "nb_NO" => "Norwegian bokmål",
57 "pt_BR" => "Portuguese/Brazil",
58 "zh_CN" => "Simplified Chinese");
63 require_once "lib/accept-to-gettext.php";
64 require_once "lib/gettext/gettext.inc";
66 function startup_gettext() {
68 # Get locale from Accept-Language header
69 $lang = al2gt(array_keys(get_translations()), "text/html");
71 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
72 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
75 /* In login action of mobile version */
76 if ($_POST["language"] && defined('MOBILE_VERSION')) {
77 $lang = $_POST["language"];
79 $lang = $_SESSION["language"];
83 if (defined('LC_MESSAGES')) {
84 _setlocale(LC_MESSAGES
, $lang);
85 } else if (defined('LC_ALL')) {
86 _setlocale(LC_ALL
, $lang);
89 if (defined('MOBILE_VERSION')) {
90 _bindtextdomain("messages", "../locale");
92 _bindtextdomain("messages", "locale");
95 _textdomain("messages");
96 _bind_textdomain_codeset("messages", "UTF-8");
102 require_once 'db-prefs.php';
103 require_once 'version.php';
105 ini_set('user_agent', SELF_USER_AGENT
);
107 require_once 'lib/pubsubhubbub/publisher.php';
108 require_once 'lib/htmLawed.php';
111 $utc_tz = new DateTimeZone('UTC');
112 $schema_version = false;
115 * Print a timestamped debug message.
117 * @param string $msg The debug message.
120 function _debug($msg) {
121 if (defined('QUIET') && QUIET
) {
124 $ts = strftime("%H:%M:%S", time());
125 if (function_exists('posix_getpid')) {
126 $ts = "$ts/" . posix_getpid();
128 print "[$ts] $msg\n";
132 * Purge a feed old posts.
134 * @param mixed $link A database connection.
135 * @param mixed $feed_id The id of the purged feed.
136 * @param mixed $purge_interval Olderness of purged posts.
137 * @param boolean $debug Set to True to enable the debug. False by default.
141 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
143 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
147 $result = db_query($link,
148 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
152 if (db_num_rows($result) == 1) {
153 $owner_uid = db_fetch_result($result, 0, "owner_uid");
156 if ($purge_interval == -1 ||
!$purge_interval) {
158 ccache_update($link, $feed_id, $owner_uid);
163 if (!$owner_uid) return;
165 if (FORCE_ARTICLE_PURGE
== 0) {
166 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
169 $purge_unread = true;
170 $purge_interval = FORCE_ARTICLE_PURGE
;
173 if (!$purge_unread) $query_limit = " unread = false AND ";
175 if (DB_TYPE
== "pgsql") {
176 $pg_version = get_pgsql_version($link);
178 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
180 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
181 ttrss_entries.id = ref_id AND
183 feed_id = '$feed_id' AND
185 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
189 $result = db_query($link, "DELETE FROM ttrss_user_entries
191 WHERE ttrss_entries.id = ref_id AND
193 feed_id = '$feed_id' AND
195 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
198 $rows = pg_affected_rows($result);
202 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
203 marked = false AND feed_id = '$feed_id' AND
204 (SELECT date_updated FROM ttrss_entries WHERE
205 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
207 $result = db_query($link, "DELETE FROM ttrss_user_entries
208 USING ttrss_user_entries, ttrss_entries
209 WHERE ttrss_entries.id = ref_id AND
211 feed_id = '$feed_id' AND
213 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
215 $rows = mysql_affected_rows($link);
219 ccache_update($link, $feed_id, $owner_uid);
222 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
224 } // function purge_feed
226 function feed_purge_interval($link, $feed_id) {
228 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
229 WHERE id = '$feed_id'");
231 if (db_num_rows($result) == 1) {
232 $purge_interval = db_fetch_result($result, 0, "purge_interval");
233 $owner_uid = db_fetch_result($result, 0, "owner_uid");
235 if ($purge_interval == 0) $purge_interval = get_pref($link,
236 'PURGE_OLD_DAYS', $owner_uid);
238 return $purge_interval;
245 function purge_orphans($link, $do_output = false) {
247 // purge orphaned posts in main content table
248 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
249 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
252 $rows = db_affected_rows($link, $result);
253 _debug("Purged $rows orphaned posts.");
257 function get_feed_update_interval($link, $feed_id) {
258 $result = db_query($link, "SELECT owner_uid, update_interval FROM
259 ttrss_feeds WHERE id = '$feed_id'");
261 if (db_num_rows($result) == 1) {
262 $update_interval = db_fetch_result($result, 0, "update_interval");
263 $owner_uid = db_fetch_result($result, 0, "owner_uid");
265 if ($update_interval != 0) {
266 return $update_interval;
268 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
276 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
277 $login = urlencode($login);
278 $pass = urlencode($pass);
280 global $fetch_last_error;
282 if (function_exists('curl_init') && !ini_get("open_basedir")) {
283 $ch = curl_init($url);
285 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
286 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
287 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
288 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
289 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
290 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
291 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
292 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
293 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
294 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
297 curl_setopt($ch, CURLOPT_POST
, true);
298 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
302 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
304 $contents = @curl_exec
($ch);
306 if ($contents === false) {
307 $fetch_last_error = curl_error($ch);
312 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
313 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
316 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
322 if ($login && $pass ){
323 $url_parts = array();
325 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
327 if ($url_parts[1] && $url_parts[2]) {
328 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
332 $data = @file_get_contents
($url);
334 if (!$data && function_exists('error_get_last')) {
335 $error = error_get_last();
336 $fetch_last_error = $error["message"];
344 * Try to determine the favicon URL for a feed.
345 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
346 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
348 * @param string $url A feed or page URL
350 * @return mixed The favicon URL, or false if none was found.
352 function get_favicon_url($url) {
354 $favicon_url = false;
356 if ($html = @fetch_file_contents
($url)) {
358 libxml_use_internal_errors(true);
360 $doc = new DOMDocument();
361 $doc->loadHTML($html);
362 $xpath = new DOMXPath($doc);
364 $base = $xpath->query('/html/head/base');
365 foreach ($base as $b) {
366 $url = $b->getAttribute("href");
370 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
371 if (count($entries) > 0) {
372 foreach ($entries as $entry) {
373 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
380 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
383 } // function get_favicon_url
385 function check_feed_favicon($site_url, $feed, $link) {
386 # print "FAVICON [$site_url]: $favicon_url\n";
388 $icon_file = ICONS_DIR
. "/$feed.ico";
390 if (!file_exists($icon_file)) {
391 $favicon_url = get_favicon_url($site_url);
394 // Limiting to "image" type misses those served with text/plain
395 $contents = fetch_file_contents($favicon_url); // , "image");
398 // Crude image type matching.
399 // Patterns gleaned from the file(1) source code.
400 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
401 // 0 string \000\000\001\000 MS Windows icon resource
402 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
404 elseif (preg_match('/^GIF8/', $contents)) {
405 // 0 string GIF8 GIF image data
406 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
408 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
409 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
410 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
412 elseif (preg_match('/^\xff\xd8/', $contents)) {
413 // 0 beshort 0xffd8 JPEG image data
414 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
423 $fp = @fopen
($icon_file, "w");
426 fwrite($fp, $contents);
428 chmod($icon_file, 0644);
435 function print_select($id, $default, $values, $attributes = "") {
436 print "<select name=\"$id\" id=\"$id\" $attributes>";
437 foreach ($values as $v) {
439 $sel = "selected=\"1\"";
443 print "<option value=\"$v\" $sel>$v</option>";
448 function print_select_hash($id, $default, $values, $attributes = "") {
449 print "<select name=\"$id\" id='$id' $attributes>";
450 foreach (array_keys($values) as $v) {
452 $sel = 'selected="selected"';
456 print "<option $sel value=\"$v\">".$values[$v]."</option>";
462 function getmicrotime() {
463 list($usec, $sec) = explode(" ",microtime());
464 return ((float)$usec +
(float)$sec);
467 function print_radio($id, $default, $true_is, $values, $attributes = "") {
468 foreach ($values as $v) {
475 if ($v == $true_is) {
476 $sel .= " value=\"1\"";
478 $sel .= " value=\"0\"";
481 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
482 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
487 function initialize_user_prefs($link, $uid, $profile = false) {
489 $uid = db_escape_string($uid);
493 $profile_qpart = "AND profile IS NULL";
495 $profile_qpart = "AND profile = '$profile'";
498 if (get_schema_version($link) < 63) $profile_qpart = "";
500 db_query($link, "BEGIN");
502 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
504 $u_result = db_query($link, "SELECT pref_name
505 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
507 $active_prefs = array();
509 while ($line = db_fetch_assoc($u_result)) {
510 array_push($active_prefs, $line["pref_name"]);
513 while ($line = db_fetch_assoc($result)) {
514 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
515 // print "adding " . $line["pref_name"] . "<br>";
517 if (get_schema_version($link) < 63) {
518 db_query($link, "INSERT INTO ttrss_user_prefs
519 (owner_uid,pref_name,value) VALUES
520 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
523 db_query($link, "INSERT INTO ttrss_user_prefs
524 (owner_uid,pref_name,value, profile) VALUES
525 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
531 db_query($link, "COMMIT");
535 function get_ssl_certificate_id() {
536 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
537 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
538 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
539 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
540 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
545 function authenticate_user($link, $login, $password, $check_only = false) {
547 if (!SINGLE_USER_MODE
) {
550 $modules = explode(",", AUTH_MODULES
);
552 foreach ($modules as $module) {
553 $module_class = "auth_$module";
554 if (class_exists($module_class)) {
555 $authenticator = new $module_class($link);
557 $user_id = (int) $authenticator->authenticate($login, $password);
560 $_SESSION["auth_module"] = $module;
565 print T_sprintf("Fatal: authentication module %s not found.", $module);
570 if ($user_id && !$check_only) {
571 $_SESSION["uid"] = $user_id;
573 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
574 WHERE id = '$user_id'");
576 $_SESSION["name"] = db_fetch_result($result, 0, "login");
577 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
578 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
580 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
583 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
584 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
586 $_SESSION["last_version_check"] = time();
588 initialize_user_prefs($link, $_SESSION["uid"]);
597 $_SESSION["uid"] = 1;
598 $_SESSION["name"] = "admin";
599 $_SESSION["access_level"] = 10;
601 $_SESSION["hide_hello"] = true;
602 $_SESSION["hide_logout"] = true;
604 $_SESSION["auth_module"] = false;
606 if (!$_SESSION["csrf_token"]) {
607 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
610 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
612 initialize_user_prefs($link, $_SESSION["uid"]);
618 function make_password($length = 8) {
621 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
625 while ($i < $length) {
626 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
628 if (!strstr($password, $char)) {
636 // this is called after user is created to initialize default feeds, labels
639 // user preferences are checked on every login, not here
641 function initialize_user($link, $uid) {
643 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
644 values ('$uid', 'Tiny Tiny RSS: New Releases',
645 'http://tt-rss.org/releases.rss')");
647 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
648 values ('$uid', 'Tiny Tiny RSS: Forum',
649 'http://tt-rss.org/forum/rss.php')");
652 function logout_user() {
654 if (isset($_COOKIE[session_name()])) {
655 setcookie(session_name(), '', time()-42000, '/');
659 function validate_csrf($csrf_token) {
660 return $csrf_token == $_SESSION['csrf_token'];
663 function validate_session($link) {
664 if (SINGLE_USER_MODE
) return true;
666 $check_ip = $_SESSION['ip_address'];
668 switch (SESSION_CHECK_ADDRESS
) {
673 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
676 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
677 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
681 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
682 $_SESSION["login_error_msg"] =
683 __("Session failed to validate (incorrect IP)");
687 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
690 if ($_SESSION["uid"]) {
692 $result = db_query($link,
693 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
695 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
697 if ($pwd_hash != $_SESSION["pwd_hash"]) {
702 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
704 //print_r($_SESSION);
706 if (time() > $_SESSION["cookie_lifetime"]) {
714 function login_sequence($link, $login_form = 0) {
715 if (SINGLE_USER_MODE
) {
716 return authenticate_user($link, "admin", null);
718 if (!$_SESSION["uid"] ||
!validate_session($link)) {
720 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
721 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
723 authenticate_user($link, null, null, true);
726 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
729 /* bump login timestamp */
730 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
734 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
735 setcookie("ttrss_lang", $_SESSION["language"],
736 time() + SESSION_COOKIE_LIFETIME
);
741 function truncate_string($str, $max_len, $suffix = '…') {
742 if (mb_strlen($str, "utf-8") > $max_len - 3) {
743 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
749 function theme_image($link, $filename) {
751 $theme_path = get_user_theme_path($link);
753 if ($theme_path && is_file($theme_path.$filename)) {
754 return $theme_path.$filename;
763 function get_user_theme($link) {
765 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
766 $theme_name = get_pref($link, "_THEME_ID");
767 if (is_dir("themes/$theme_name")) {
778 function get_user_theme_path($link) {
781 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
782 $theme_name = get_pref($link, "_THEME_ID");
784 if ($theme_name && is_dir("themes/$theme_name")) {
785 $theme_path = "themes/$theme_name/";
794 if (is_file("$theme_path/theme.ini")) {
795 $ini = parse_ini_file("$theme_path/theme.ini", true);
796 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
804 function get_user_theme_options($link) {
805 $t = get_user_theme_path($link);
808 if (is_file("$t/theme.ini")) {
809 $ini = parse_ini_file("$t/theme.ini", true);
810 if ($ini['theme']['version']) {
811 return $ini['theme']['options'];
818 function print_theme_includes($link) {
820 $t = get_user_theme_path($link);
824 print "<link rel=\"stylesheet\" type=\"text/css\"
825 href=\"$t/theme.css?$time \">";
826 if (file_exists("$t/theme.js")) {
827 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
833 function get_all_themes() {
834 $themes = glob("themes/*");
840 foreach ($themes as $t) {
841 if (is_file("$t/theme.ini")) {
842 $ini = parse_ini_file("$t/theme.ini", true);
843 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
844 !$ini['theme']['disabled']) {
847 $entry["base"] = basename($t);
848 $entry["name"] = $ini['theme']['name'];
849 $entry["version"] = $ini['theme']['version'];
850 $entry["author"] = $ini['theme']['author'];
851 $entry["options"] = $ini['theme']['options'];
852 array_push($rv, $entry);
860 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
863 $source_tz = new DateTimeZone($source_tz);
864 } catch (Exception
$e) {
865 $source_tz = new DateTimeZone('UTC');
869 $dest_tz = new DateTimeZone($dest_tz);
870 } catch (Exception
$e) {
871 $dest_tz = new DateTimeZone('UTC');
874 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
875 return $dt->format('U') +
$dest_tz->getOffset($dt);
878 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
879 $no_smart_dt = false) {
881 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
882 if (!$timestamp) $timestamp = '1970-01-01 0:00';
887 # We store date in UTC internally
888 $dt = new DateTime($timestamp, $utc_tz);
890 if ($tz_offset == -1) {
892 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
895 $user_tz = new DateTimeZone($user_tz_string);
896 } catch (Exception
$e) {
900 $tz_offset = $user_tz->getOffset($dt);
903 $user_timestamp = $dt->format('U') +
$tz_offset;
906 return smart_date_time($link, $user_timestamp,
907 $tz_offset, $owner_uid);
910 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
912 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
914 return date($format, $user_timestamp);
918 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
919 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
921 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
922 return date("G:i", $timestamp);
923 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
924 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
925 return date($format, $timestamp);
927 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
928 return date($format, $timestamp);
932 function sql_bool_to_bool($s) {
933 if ($s == "t" ||
$s == "1" ||
$s == "true") {
940 function bool_to_sql_bool($s) {
948 // Session caching removed due to causing wrong redirects to upgrade
949 // script when get_schema_version() is called on an obsolete session
950 // created on a previous schema version.
951 function get_schema_version($link, $nocache = false) {
952 global $schema_version;
954 if (!$schema_version) {
955 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
956 $version = db_fetch_result($result, 0, "schema_version");
957 $schema_version = $version;
960 return $schema_version;
964 function sanity_check($link) {
965 require_once 'errors.php';
968 $schema_version = get_schema_version($link, true);
970 if ($schema_version != SCHEMA_VERSION
) {
974 if (DB_TYPE
== "mysql") {
975 $result = db_query($link, "SELECT true", false);
976 if (db_num_rows($result) != 1) {
981 if (db_escape_string("testTEST") != "testTEST") {
985 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
988 function file_is_locked($filename) {
989 if (function_exists('flock')) {
990 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
992 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1003 return true; // consider the file always locked and skip the test
1006 function make_lockfile($filename) {
1007 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1009 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1010 if (function_exists('posix_getpid')) {
1011 fwrite($fp, posix_getpid() . "\n");
1019 function make_stampfile($filename) {
1020 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1022 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1023 fwrite($fp, time() . "\n");
1024 flock($fp, LOCK_UN
);
1032 function sql_random_function() {
1033 if (DB_TYPE
== "mysql") {
1040 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1042 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1044 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1046 $ref_check_qpart = ($max_id &&
1047 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1049 if (is_numeric($feed)) {
1055 $children = getChildCategories($link, $feed, $owner_uid);
1056 array_push($children, $feed);
1058 $children = join(",", $children);
1060 $cat_qpart = "cat_id IN ($children)";
1062 $cat_qpart = "cat_id IS NULL";
1065 db_query($link, "UPDATE ttrss_user_entries
1066 SET unread = false,last_read = NOW()
1067 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1068 AND $ref_check_qpart
1069 AND owner_uid = $owner_uid");
1071 } else if ($feed == -2) {
1073 db_query($link, "UPDATE ttrss_user_entries
1074 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1075 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1076 AND $ref_check_qpart
1077 AND unread = true AND owner_uid = $owner_uid");
1080 } else if ($feed > 0) {
1082 db_query($link, "UPDATE ttrss_user_entries
1083 SET unread = false,last_read = NOW()
1084 WHERE feed_id = '$feed'
1085 AND $ref_check_qpart
1086 AND owner_uid = $owner_uid");
1088 } else if ($feed < 0 && $feed > -10) { // special, like starred
1091 db_query($link, "UPDATE ttrss_user_entries
1092 SET unread = false,last_read = NOW()
1094 AND $ref_check_qpart
1095 AND owner_uid = $owner_uid");
1099 db_query($link, "UPDATE ttrss_user_entries
1100 SET unread = false,last_read = NOW()
1101 WHERE published = true
1102 AND $ref_check_qpart
1103 AND owner_uid = $owner_uid");
1108 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1110 if (DB_TYPE
== "pgsql") {
1111 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1113 $match_part = "updated > DATE_SUB(NOW(),
1114 INTERVAL $intl HOUR) ";
1117 $result = db_query($link, "SELECT id FROM ttrss_entries,
1118 ttrss_user_entries WHERE $match_part AND
1120 ttrss_user_entries.ref_id = ttrss_entries.id AND
1121 owner_uid = $owner_uid");
1123 $affected_ids = array();
1125 while ($line = db_fetch_assoc($result)) {
1126 array_push($affected_ids, $line["id"]);
1129 catchupArticlesById($link, $affected_ids, 0);
1133 db_query($link, "UPDATE ttrss_user_entries
1134 SET unread = false,last_read = NOW()
1135 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1138 } else if ($feed < -10) { // label
1140 $label_id = -$feed - 11;
1142 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1143 SET unread = false, last_read = NOW()
1144 WHERE label_id = '$label_id' AND unread = true
1145 AND $ref_check_qpart
1146 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1150 ccache_update($link, $feed, $owner_uid, $cat_view);
1153 db_query($link, "BEGIN");
1155 $tag_name = db_escape_string($feed);
1157 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1158 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1160 while ($line = db_fetch_assoc($result)) {
1161 db_query($link, "UPDATE ttrss_user_entries SET
1162 unread = false, last_read = NOW()
1163 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1165 db_query($link, "COMMIT");
1169 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1171 if (!$omode) $omode = "flc";
1173 $data = getGlobalCounters($link);
1175 $data = array_merge($data, getVirtCounters($link));
1177 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1178 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1179 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1180 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1185 function getCategoryTitle($link, $cat_id) {
1187 if ($cat_id == -1) {
1188 return __("Special");
1189 } else if ($cat_id == -2) {
1190 return __("Labels");
1193 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1196 if (db_num_rows($result) == 1) {
1197 return db_fetch_result($result, 0, "title");
1199 return __("Uncategorized");
1205 function getCategoryCounters($link) {
1208 /* Labels category */
1210 $cv = array("id" => -2, "kind" => "cat",
1211 "counter" => getCategoryUnread($link, -2));
1213 array_push($ret_arr, $cv);
1215 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1216 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1217 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1218 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1219 WHERE ttrss_cat_counters_cache.feed_id = id AND
1220 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1221 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1223 while ($line = db_fetch_assoc($result)) {
1224 $line["cat_id"] = (int) $line["cat_id"];
1226 if ($line["num_children"] > 0) {
1227 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1232 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1233 "counter" => $line["unread"] +
$child_counter);
1235 array_push($ret_arr, $cv);
1238 /* Special case: NULL category doesn't actually exist in the DB */
1240 $cv = array("id" => 0, "kind" => "cat",
1241 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1243 array_push($ret_arr, $cv);
1248 // only accepts real cats (>= 0)
1249 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1250 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1252 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1253 AND owner_uid = $owner_uid");
1257 while ($line = db_fetch_assoc($result)) {
1258 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1259 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1265 function getCategoryUnread($link, $cat, $owner_uid = false) {
1267 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1272 $cat_query = "cat_id = '$cat'";
1274 $cat_query = "cat_id IS NULL";
1277 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1278 AND owner_uid = " . $owner_uid);
1280 $cat_feeds = array();
1281 while ($line = db_fetch_assoc($result)) {
1282 array_push($cat_feeds, "feed_id = " . $line["id"]);
1285 if (count($cat_feeds) == 0) return 0;
1287 $match_part = implode(" OR ", $cat_feeds);
1289 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1290 FROM ttrss_user_entries
1291 WHERE unread = true AND ($match_part)
1292 AND owner_uid = " . $owner_uid);
1296 # this needs to be rewritten
1297 while ($line = db_fetch_assoc($result)) {
1298 $unread +
= $line["unread"];
1302 } else if ($cat == -1) {
1303 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1304 } else if ($cat == -2) {
1306 $result = db_query($link, "
1307 SELECT COUNT(unread) AS unread FROM
1308 ttrss_user_entries, ttrss_user_labels2
1309 WHERE article_id = ref_id AND unread = true
1310 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1312 $unread = db_fetch_result($result, 0, "unread");
1319 function getFeedUnread($link, $feed, $is_cat = false) {
1320 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1323 function getLabelUnread($link, $label_id, $owner_uid = false) {
1324 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1326 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1327 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1329 if (db_num_rows($result) != 0) {
1330 return db_fetch_result($result, 0, "unread");
1336 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1337 $owner_uid = false) {
1339 $n_feed = (int) $feed;
1340 $need_entries = false;
1342 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1345 $unread_qpart = "unread = true";
1347 $unread_qpart = "true";
1351 return getCategoryUnread($link, $n_feed, $owner_uid);
1352 } else if ($n_feed == -6) {
1354 } else if ($feed != "0" && $n_feed == 0) {
1356 $feed = db_escape_string($feed);
1358 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1359 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1360 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1361 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1362 return db_fetch_result($result, 0, "count");
1364 } else if ($n_feed == -1) {
1365 $match_part = "marked = true";
1366 } else if ($n_feed == -2) {
1367 $match_part = "published = true";
1368 } else if ($n_feed == -3) {
1369 $match_part = "unread = true AND score >= 0";
1371 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1373 if (DB_TYPE
== "pgsql") {
1374 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1376 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1379 $need_entries = true;
1381 } else if ($n_feed == -4) {
1382 $match_part = "true";
1383 } else if ($n_feed >= 0) {
1386 $match_part = "feed_id = '$n_feed'";
1388 $match_part = "feed_id IS NULL";
1391 } else if ($feed < -10) {
1393 $label_id = -$feed - 11;
1395 return getLabelUnread($link, $label_id, $owner_uid);
1401 if ($need_entries) {
1402 $from_qpart = "ttrss_user_entries,ttrss_entries";
1403 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1405 $from_qpart = "ttrss_user_entries";
1408 $query = "SELECT count(int_id) AS unread
1409 FROM $from_qpart WHERE
1410 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1412 //echo "[$feed/$query]\n";
1414 $result = db_query($link, $query);
1418 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1419 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1420 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1421 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1424 $unread = db_fetch_result($result, 0, "unread");
1429 function getGlobalUnread($link, $user_id = false) {
1432 $user_id = $_SESSION["uid"];
1435 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1436 WHERE owner_uid = '$user_id' AND feed_id > 0");
1438 $c_id = db_fetch_result($result, 0, "c_id");
1443 function getGlobalCounters($link, $global_unread = -1) {
1446 if ($global_unread == -1) {
1447 $global_unread = getGlobalUnread($link);
1450 $cv = array("id" => "global-unread",
1451 "counter" => (int) $global_unread);
1453 array_push($ret_arr, $cv);
1455 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1456 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1458 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1460 $cv = array("id" => "subscribed-feeds",
1461 "counter" => (int) $subscribed_feeds);
1463 array_push($ret_arr, $cv);
1468 function getTagCounters($link) {
1472 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1473 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1474 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1475 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1476 ORDER BY count DESC LIMIT 55");
1480 while ($line = db_fetch_assoc($result)) {
1481 $tags[$line["tag_name"]] +
= $line["count"];
1484 foreach (array_keys($tags) as $tag) {
1485 $unread = $tags[$tag];
1486 $tag = htmlspecialchars($tag);
1488 $cv = array("id" => $tag,
1490 "counter" => $unread);
1492 array_push($ret_arr, $cv);
1498 function getVirtCounters($link) {
1502 for ($i = 0; $i >= -4; $i--) {
1504 $count = getFeedUnread($link, $i);
1506 $cv = array("id" => $i,
1507 "counter" => (int) $count);
1509 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1510 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1512 array_push($ret_arr, $cv);
1518 function getLabelCounters($link, $descriptions = false) {
1522 $owner_uid = $_SESSION["uid"];
1524 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1525 WHERE owner_uid = '$owner_uid'");
1527 while ($line = db_fetch_assoc($result)) {
1529 $id = -$line["id"] - 11;
1531 $label_name = $line["caption"];
1532 $count = getFeedUnread($link, $id);
1534 $cv = array("id" => $id,
1535 "counter" => (int) $count);
1538 $cv["description"] = $label_name;
1540 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1541 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1543 array_push($ret_arr, $cv);
1549 function getFeedCounters($link, $active_feed = false) {
1553 $query = "SELECT ttrss_feeds.id,
1555 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1556 last_error, value AS count
1557 FROM ttrss_feeds, ttrss_counters_cache
1558 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1559 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1560 AND ttrss_counters_cache.feed_id = id";
1562 $result = db_query($link, $query);
1563 $fctrs_modified = false;
1565 while ($line = db_fetch_assoc($result)) {
1568 $count = $line["count"];
1569 $last_error = htmlspecialchars($line["last_error"]);
1571 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1573 $has_img = feed_has_icon($id);
1575 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1578 $cv = array("id" => $id,
1579 "updated" => $last_updated,
1580 "counter" => (int) $count,
1581 "has_img" => (int) $has_img);
1584 $cv["error"] = $last_error;
1586 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1587 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1589 if ($active_feed && $id == $active_feed)
1590 $cv["title"] = truncate_string($line["title"], 30);
1592 array_push($ret_arr, $cv);
1599 function get_pgsql_version($link) {
1600 $result = db_query($link, "SELECT version() AS version");
1601 $version = explode(" ", db_fetch_result($result, 0, "version"));
1606 * @return array (code => Status code, message => error message if available)
1608 * 0 - OK, Feed already exists
1609 * 1 - OK, Feed added
1611 * 3 - URL content is HTML, no feeds available
1612 * 4 - URL content is HTML which contains multiple feeds.
1613 * Here you should call extractfeedurls in rpc-backend
1614 * to get all possible feeds.
1615 * 5 - Couldn't download the URL content.
1617 function subscribe_to_feed($link, $url, $cat_id = 0,
1618 $auth_login = '', $auth_pass = '', $need_auth = false) {
1620 global $fetch_last_error;
1622 require_once "include/rssfuncs.php";
1624 $url = fix_url($url);
1626 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1628 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1631 return array("code" => 5, "message" => $fetch_last_error);
1634 if (is_html($contents)) {
1635 $feedUrls = get_feeds_from_html($url, $contents);
1637 if (count($feedUrls) == 0) {
1638 return array("code" => 3);
1639 } else if (count($feedUrls) > 1) {
1640 return array("code" => 4, "feeds" => $feedUrls);
1642 //use feed url as new URL
1643 $url = key($feedUrls);
1646 if ($cat_id == "0" ||
!$cat_id) {
1647 $cat_qpart = "NULL";
1649 $cat_qpart = "'$cat_id'";
1652 $result = db_query($link,
1653 "SELECT id FROM ttrss_feeds
1654 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1656 if (db_num_rows($result) == 0) {
1657 $result = db_query($link,
1658 "INSERT INTO ttrss_feeds
1659 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1660 VALUES ('".$_SESSION["uid"]."', '$url',
1661 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1663 $result = db_query($link,
1664 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1665 AND owner_uid = " . $_SESSION["uid"]);
1667 $feed_id = db_fetch_result($result, 0, "id");
1670 update_rss_feed($link, $feed_id, true);
1673 return array("code" => 1);
1675 return array("code" => 0);
1679 function print_feed_select($link, $id, $default_id = "",
1680 $attributes = "", $include_all_feeds = true,
1681 $root_id = false, $nest_level = 0) {
1684 print "<select id=\"$id\" name=\"$id\" $attributes>";
1685 if ($include_all_feeds) {
1686 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1687 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1691 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1694 $parent_qpart = "parent_cat = '$root_id'";
1696 $parent_qpart = "parent_cat IS NULL";
1698 $result = db_query($link, "SELECT id,title,
1699 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1700 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1701 FROM ttrss_feed_categories
1702 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1704 while ($line = db_fetch_assoc($result)) {
1706 for ($i = 0; $i < $nest_level; $i++
)
1707 $line["title"] = " - " . $line["title"];
1709 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1711 printf("<option $is_selected value='CAT:%d'>%s</option>",
1712 $line["id"], htmlspecialchars($line["title"]));
1714 if ($line["num_children"] > 0)
1715 print_feed_select($link, $id, $default_id, $attributes,
1716 $include_all_feeds, $line["id"], $nest_level+
1);
1718 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1719 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1721 while ($fline = db_fetch_assoc($feed_result)) {
1722 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1724 $fline["title"] = " + " . $fline["title"];
1726 for ($i = 0; $i < $nest_level; $i++
)
1727 $fline["title"] = " - " . $fline["title"];
1729 printf("<option $is_selected value='%d'>%s</option>",
1730 $fline["id"], htmlspecialchars($fline["title"]));
1735 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1737 printf("<option $is_selected value='CAT:0'>%s</option>",
1738 __("Uncategorized"));
1740 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1741 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1743 while ($fline = db_fetch_assoc($feed_result)) {
1744 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1746 $fline["title"] = " + " . $fline["title"];
1748 for ($i = 0; $i < $nest_level; $i++
)
1749 $fline["title"] = " - " . $fline["title"];
1751 printf("<option $is_selected value='%d'>%s</option>",
1752 $fline["id"], htmlspecialchars($fline["title"]));
1757 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1758 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1760 while ($line = db_fetch_assoc($result)) {
1762 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1764 printf("<option $is_selected value='%d'>%s</option>",
1765 $line["id"], htmlspecialchars($line["title"]));
1774 function print_feed_cat_select($link, $id, $default_id,
1775 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1778 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1782 $parent_qpart = "parent_cat = '$root_id'";
1784 $parent_qpart = "parent_cat IS NULL";
1786 $result = db_query($link, "SELECT id,title,
1787 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1788 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1789 FROM ttrss_feed_categories
1790 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1792 while ($line = db_fetch_assoc($result)) {
1793 if ($line["id"] == $default_id) {
1794 $is_selected = "selected=\"1\"";
1799 for ($i = 0; $i < $nest_level; $i++
)
1800 $line["title"] = " - " . $line["title"];
1803 printf("<option $is_selected value='%d'>%s</option>",
1804 $line["id"], htmlspecialchars($line["title"]));
1806 if ($line["num_children"] > 0)
1807 print_feed_cat_select($link, $id, $default_id, $attributes,
1808 $include_all_cats, $line["id"], $nest_level+
1);
1812 if ($include_all_cats) {
1813 if (db_num_rows($result) > 0) {
1814 print "<option disabled=\"1\">--------</option>";
1817 if ($default_id == 0) {
1818 $is_selected = "selected=\"1\"";
1823 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1829 function checkbox_to_sql_bool($val) {
1830 return ($val == "on") ?
"true" : "false";
1833 function getFeedCatTitle($link, $id) {
1835 return __("Special");
1836 } else if ($id < -10) {
1837 return __("Labels");
1838 } else if ($id > 0) {
1839 $result = db_query($link, "SELECT ttrss_feed_categories.title
1840 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1841 cat_id = ttrss_feed_categories.id");
1842 if (db_num_rows($result) == 1) {
1843 return db_fetch_result($result, 0, "title");
1845 return __("Uncategorized");
1848 return "getFeedCatTitle($id) failed";
1853 function getFeedIcon($id) {
1856 return "images/archive.png";
1859 return "images/mark_set.png";
1862 return "images/pub_set.png";
1865 return "images/fresh.png";
1868 return "images/tag.png";
1871 return "images/recently_read.png";
1875 return "images/label.png";
1877 if (file_exists(ICONS_DIR
. "/$id.ico"))
1878 return ICONS_URL
. "/$id.ico";
1884 function getFeedTitle($link, $id, $cat = false) {
1886 return getCategoryTitle($link, $id);
1887 } else if ($id == -1) {
1888 return __("Starred articles");
1889 } else if ($id == -2) {
1890 return __("Published articles");
1891 } else if ($id == -3) {
1892 return __("Fresh articles");
1893 } else if ($id == -4) {
1894 return __("All articles");
1895 } else if ($id === 0 ||
$id === "0") {
1896 return __("Archived articles");
1897 } else if ($id == -6) {
1898 return __("Recently read");
1899 } else if ($id < -10) {
1900 $label_id = -$id - 11;
1901 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1902 if (db_num_rows($result) == 1) {
1903 return db_fetch_result($result, 0, "caption");
1905 return "Unknown label ($label_id)";
1908 } else if (is_numeric($id) && $id > 0) {
1909 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1910 if (db_num_rows($result) == 1) {
1911 return db_fetch_result($result, 0, "title");
1913 return "Unknown feed ($id)";
1920 function make_init_params($link) {
1923 $params["theme"] = get_user_theme($link);
1924 $params["theme_options"] = get_user_theme_options($link);
1926 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1927 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1928 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
1929 $params["sign_info"] = theme_image($link, "images/sign_info.png");
1931 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1932 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1933 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1934 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1936 $params[strtolower($param)] = (int) get_pref($link, $param);
1939 $params["icons_url"] = ICONS_URL
;
1940 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1941 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1942 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1943 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1944 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1946 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1947 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1949 $max_feed_id = db_fetch_result($result, 0, "mid");
1950 $num_feeds = db_fetch_result($result, 0, "nf");
1952 $params["max_feed_id"] = (int) $max_feed_id;
1953 $params["num_feeds"] = (int) $num_feeds;
1955 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1957 $params["csrf_token"] = $_SESSION["csrf_token"];
1962 function make_runtime_info($link) {
1965 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1966 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1968 $max_feed_id = db_fetch_result($result, 0, "mid");
1969 $num_feeds = db_fetch_result($result, 0, "nf");
1971 $data["max_feed_id"] = (int) $max_feed_id;
1972 $data["num_feeds"] = (int) $num_feeds;
1974 $data['last_article_id'] = getLastArticleId($link);
1975 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1977 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1979 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1981 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1983 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1986 $stamp_delta = time() - $stamp;
1988 if ($stamp_delta > 1800) {
1992 $_SESSION["daemon_stamp_check"] = time();
1995 $data['daemon_stamp_ok'] = $stamp_check;
1997 $stamp_fmt = date("Y.m.d, G:i", $stamp);
1999 $data['daemon_stamp'] = $stamp_fmt;
2004 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2005 $new_version_details = @check_for_update
($link);
2007 $data['new_version_available'] = (int) ($new_version_details != false);
2009 $_SESSION["last_version_check"] = time();
2010 $_SESSION["version_data"] = $new_version_details;
2016 function search_to_sql($link, $search, $match_on) {
2018 $search_query_part = "";
2020 $keywords = explode(" ", $search);
2021 $query_keywords = array();
2023 foreach ($keywords as $k) {
2024 if (strpos($k, "-") === 0) {
2031 $commandpair = explode(":", mb_strtolower($k), 2);
2033 if ($commandpair[0] == "note" && $commandpair[1]) {
2035 if ($commandpair[1] == "true")
2036 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2038 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2040 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2042 if ($commandpair[1] == "true")
2043 array_push($query_keywords, "($not (marked = true))");
2045 array_push($query_keywords, "($not (marked = false))");
2047 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2049 if ($commandpair[1] == "true")
2050 array_push($query_keywords, "($not (published = true))");
2052 array_push($query_keywords, "($not (published = false))");
2054 } else if (strpos($k, "@") === 0) {
2056 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2057 $orig_ts = strtotime(substr($k, 1));
2058 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2060 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2062 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2063 } else if ($match_on == "both") {
2064 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2065 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2066 } else if ($match_on == "title") {
2067 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2068 } else if ($match_on == "content") {
2069 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2073 $search_query_part = implode("AND", $query_keywords);
2075 return $search_query_part;
2078 function getParentCategories($link, $cat, $owner_uid) {
2081 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2082 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2084 while ($line = db_fetch_assoc($result)) {
2085 array_push($rv, $line["parent_cat"]);
2086 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2092 function getChildCategories($link, $cat, $owner_uid) {
2095 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2096 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2098 while ($line = db_fetch_assoc($result)) {
2099 array_push($rv, $line["id"]);
2100 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2106 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) {
2108 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2110 $ext_tables_part = "";
2114 if (SPHINX_ENABLED
) {
2115 $ids = join(",", @sphinx_search
($search, 0, 500));
2118 $search_query_part = "ref_id IN ($ids) AND ";
2120 $search_query_part = "ref_id = -1 AND ";
2123 $search_query_part = search_to_sql($link, $search, $match_on);
2124 $search_query_part .= " AND ";
2128 $search_query_part = "";
2133 if (DB_TYPE
== "pgsql") {
2134 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2136 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2139 $override_order = "updated DESC";
2141 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2143 // Try to check if SQL regexp implementation chokes on a valid regexp
2144 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2145 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2146 WHERE $filter_query_part LIMIT 1", false);
2148 $test = db_fetch_result($result, 0, "true");
2151 $filter_query_part = "false AND";
2153 $filter_query_part .= " AND";
2157 $filter_query_part = "";
2161 $since_id_part = "ttrss_entries.id > $since_id AND ";
2163 $since_id_part = "";
2166 $view_query_part = "";
2168 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2170 $view_query_part = " ";
2171 } else if ($feed != -1) {
2172 $unread = getFeedUnread($link, $feed, $cat_view);
2174 if ($cat_view && $feed > 0 && $include_children)
2175 $unread +
= getCategoryChildrenUnread($link, $feed);
2178 $view_query_part = " unread = true AND ";
2183 if ($view_mode == "marked") {
2184 $view_query_part = " marked = true AND ";
2187 if ($view_mode == "published") {
2188 $view_query_part = " published = true AND ";
2191 if ($view_mode == "unread") {
2192 $view_query_part = " unread = true AND ";
2195 if ($view_mode == "updated") {
2196 $view_query_part = " (last_read is null and unread = false) AND ";
2200 $limit_query_part = "LIMIT " . $limit;
2203 $allow_archived = false;
2205 $vfeed_query_part = "";
2207 // override query strategy and enable feed display when searching globally
2208 if ($search && $search_mode == "all_feeds") {
2209 $query_strategy_part = "true";
2210 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2212 } else if (!is_numeric($feed)) {
2213 $query_strategy_part = "true";
2214 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2215 id = feed_id) as feed_title,";
2216 } else if ($search && $search_mode == "this_cat") {
2217 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2220 if ($include_children) {
2221 $subcats = getChildCategories($link, $feed, $owner_uid);
2222 array_push($subcats, $feed);
2223 $cats_qpart = join(",", $subcats);
2225 $cats_qpart = $feed;
2228 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2231 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2234 } else if ($feed > 0) {
2239 if ($include_children) {
2241 $subcats = getChildCategories($link, $feed, $owner_uid);
2243 array_push($subcats, $feed);
2244 $query_strategy_part = "cat_id IN (".
2245 implode(",", $subcats).")";
2248 $query_strategy_part = "cat_id = '$feed'";
2252 $query_strategy_part = "cat_id IS NULL";
2255 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2258 $query_strategy_part = "feed_id = '$feed'";
2260 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2261 $query_strategy_part = "feed_id IS NULL";
2262 $allow_archived = true;
2263 } else if ($feed == 0 && $cat_view) { // uncategorized
2264 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2265 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2266 } else if ($feed == -1) { // starred virtual feed
2267 $query_strategy_part = "marked = true";
2268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2269 $allow_archived = true;
2271 } else if ($feed == -2) { // published virtual feed OR labels category
2274 $query_strategy_part = "published = true";
2275 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2276 $allow_archived = true;
2278 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2280 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2282 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2284 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2285 ttrss_user_labels2.article_id = ref_id";
2288 } else if ($feed == -6) { // recently read
2289 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2290 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2291 $allow_archived = true;
2293 if (!$override_order) $override_order = "last_read DESC";
2294 } else if ($feed == -3) { // fresh virtual feed
2295 $query_strategy_part = "unread = true AND score >= 0";
2297 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2299 if (DB_TYPE
== "pgsql") {
2300 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2302 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2305 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2306 } else if ($feed == -4) { // all articles virtual feed
2307 $query_strategy_part = "true";
2308 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2309 } else if ($feed <= -10) { // labels
2310 $label_id = -$feed - 11;
2312 $query_strategy_part = "label_id = '$label_id' AND
2313 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2314 ttrss_user_labels2.article_id = ref_id";
2316 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2317 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2318 $allow_archived = true;
2321 $query_strategy_part = "true";
2324 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2325 $date_sort_field = "updated";
2327 $date_sort_field = "date_entered";
2330 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2331 $order_by = "$date_sort_field";
2333 $order_by = "$date_sort_field DESC";
2336 if ($view_mode != "noscores") {
2337 $order_by = "score DESC, $order_by";
2340 if ($override_order) {
2341 $order_by = $override_order;
2347 $feed_title = T_sprintf("Search results: %s", $search);
2350 $feed_title = getCategoryTitle($link, $feed);
2352 if (is_numeric($feed) && $feed > 0) {
2353 $result = db_query($link, "SELECT title,site_url,last_error
2354 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2356 $feed_title = db_fetch_result($result, 0, "title");
2357 $feed_site_url = db_fetch_result($result, 0, "site_url");
2358 $last_error = db_fetch_result($result, 0, "last_error");
2360 $feed_title = getFeedTitle($link, $feed);
2365 $content_query_part = "content as content_preview, cached_content, ";
2367 if (is_numeric($feed)) {
2370 $feed_kind = "Feeds";
2372 $feed_kind = "Labels";
2375 if ($limit_query_part) {
2376 $offset_query_part = "OFFSET $offset";
2379 // proper override_order applied above
2380 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2381 if (!$override_order) {
2382 $order_by = "ttrss_feeds.title, $order_by";
2384 $order_by = "ttrss_feeds.title, $override_order";
2388 if (!$allow_archived) {
2389 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2390 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2393 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2394 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2397 $query = "SELECT DISTINCT
2400 ttrss_entries.id,ttrss_entries.title,
2404 always_display_enclosures,
2410 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2411 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2414 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2420 ttrss_user_entries.ref_id = ttrss_entries.id AND
2421 ttrss_user_entries.owner_uid = '$owner_uid' AND
2426 $query_strategy_part ORDER BY $order_by
2427 $limit_query_part $offset_query_part";
2429 if ($_REQUEST["debug"]) print $query;
2431 $result = db_query($link, $query);
2436 $select_qpart = "SELECT DISTINCT " .
2440 "ttrss_entries.id as id," .
2453 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2456 $content_query_part .
2457 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2460 $feed_kind = "Tags";
2461 $all_tags = explode(",", $feed);
2462 if ($search_mode == 'any') {
2463 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2464 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2465 $where_qpart = " WHERE " .
2466 "ref_id = ttrss_entries.id AND " .
2467 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2468 "post_int_id = int_id AND $tag_sql AND " .
2470 $search_query_part .
2471 $query_strategy_part . " ORDER BY $order_by " .
2476 $sub_selects = array();
2477 $sub_ands = array();
2478 foreach ($all_tags as $term) {
2479 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");
2486 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2491 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2492 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2493 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2494 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2496 // error_log("TAG SQL: " . $tag_sql);
2497 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2499 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2500 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2503 return array($result, $feed_title, $feed_site_url, $last_error);
2507 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2508 if (!$owner) $owner = $_SESSION["uid"];
2510 $res = trim($str); if (!$res) return '';
2512 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
2513 $res = htmLawed($res, $config);
2515 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2516 $res = preg_replace('/<img[^>]+>/is', '', $res);
2519 if (strpos($res, "href=") === false)
2520 $res = rewrite_urls($res);
2522 $charset_hack = '<head>
2523 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2526 $res = trim($res); if (!$res) return '';
2528 libxml_use_internal_errors(true);
2530 $doc = new DOMDocument();
2531 $doc->loadHTML($charset_hack . $res);
2532 $xpath = new DOMXPath($doc);
2534 $entries = $xpath->query('(//a[@href]|//img[@src])');
2537 foreach ($entries as $entry) {
2541 if ($entry->hasAttribute('href'))
2542 $entry->setAttribute('href',
2543 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2545 if ($entry->hasAttribute('src'))
2546 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2547 $entry->setAttribute('src',
2548 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2551 if (strtolower($entry->nodeName
) == "a") {
2552 $entry->setAttribute("target", "_blank");
2555 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2556 $br = $doc->createElement("br");
2558 if ($entry->parentNode
->nextSibling
) {
2559 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2566 $node = $doc->getElementsByTagName('body')->item(0);
2568 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2571 function check_for_update($link) {
2572 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2573 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2575 $version_data = @fetch_file_contents
($version_url);
2577 if ($version_data) {
2578 $version_data = json_decode($version_data, true);
2579 if ($version_data && $version_data['version']) {
2581 if (version_compare(VERSION
, $version_data['version']) == -1) {
2582 return $version_data;
2590 function markArticlesById($link, $ids, $cmode) {
2594 foreach ($ids as $id) {
2595 array_push($tmp_ids, "ref_id = '$id'");
2598 $ids_qpart = join(" OR ", $tmp_ids);
2601 db_query($link, "UPDATE ttrss_user_entries SET
2602 marked = false,last_read = NOW()
2603 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2604 } else if ($cmode == 1) {
2605 db_query($link, "UPDATE ttrss_user_entries SET
2607 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2609 db_query($link, "UPDATE ttrss_user_entries SET
2610 marked = NOT marked,last_read = NOW()
2611 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2615 function publishArticlesById($link, $ids, $cmode) {
2619 foreach ($ids as $id) {
2620 array_push($tmp_ids, "ref_id = '$id'");
2623 $ids_qpart = join(" OR ", $tmp_ids);
2626 db_query($link, "UPDATE ttrss_user_entries SET
2627 published = false,last_read = NOW()
2628 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2629 } else if ($cmode == 1) {
2630 db_query($link, "UPDATE ttrss_user_entries SET
2631 published = true,last_read = NOW()
2632 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2634 db_query($link, "UPDATE ttrss_user_entries SET
2635 published = NOT published,last_read = NOW()
2636 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2639 if (PUBSUBHUBBUB_HUB
) {
2640 $rss_link = get_self_url_prefix() .
2641 "/public.php?op=rss&id=-2&key=" .
2642 get_feed_access_key($link, -2, false);
2644 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2646 $pubsub_result = $p->publish_update($rss_link);
2650 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2652 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2653 if (count($ids) == 0) return;
2657 foreach ($ids as $id) {
2658 array_push($tmp_ids, "ref_id = '$id'");
2661 $ids_qpart = join(" OR ", $tmp_ids);
2664 db_query($link, "UPDATE ttrss_user_entries SET
2665 unread = false,last_read = NOW()
2666 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2667 } else if ($cmode == 1) {
2668 db_query($link, "UPDATE ttrss_user_entries SET
2670 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2672 db_query($link, "UPDATE ttrss_user_entries SET
2673 unread = NOT unread,last_read = NOW()
2674 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2679 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2680 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2682 while ($line = db_fetch_assoc($result)) {
2683 ccache_update($link, $line["feed_id"], $owner_uid);
2687 function catchupArticleById($link, $id, $cmode) {
2690 db_query($link, "UPDATE ttrss_user_entries SET
2691 unread = false,last_read = NOW()
2692 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2693 } else if ($cmode == 1) {
2694 db_query($link, "UPDATE ttrss_user_entries SET
2696 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2698 db_query($link, "UPDATE ttrss_user_entries SET
2699 unread = NOT unread,last_read = NOW()
2700 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2703 $feed_id = getArticleFeed($link, $id);
2704 ccache_update($link, $feed_id, $_SESSION["uid"]);
2707 function make_guid_from_title($title) {
2708 return preg_replace("/[ \"\',.:;]/", "-",
2709 mb_strtolower(strip_tags($title), 'utf-8'));
2712 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2714 $a_id = db_escape_string($id);
2716 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2718 $query = "SELECT DISTINCT tag_name,
2719 owner_uid as owner FROM
2720 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2721 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2723 $obj_id = md5("TAGS:$owner_uid:$id");
2726 /* check cache first */
2728 if ($tag_cache === false) {
2729 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2730 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2732 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2736 $tags = explode(",", $tag_cache);
2739 /* do it the hard way */
2741 $tmp_result = db_query($link, $query);
2743 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2744 array_push($tags, $tmp_line["tag_name"]);
2747 /* update the cache */
2749 $tags_str = db_escape_string(join(",", $tags));
2751 db_query($link, "UPDATE ttrss_user_entries
2752 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2753 AND owner_uid = $owner_uid");
2759 function trim_array($array) {
2761 array_walk($tmp, 'trim');
2765 function tag_is_valid($tag) {
2766 if ($tag == '') return false;
2767 if (preg_match("/^[0-9]*$/", $tag)) return false;
2768 if (mb_strlen($tag) > 250) return false;
2770 if (function_exists('iconv')) {
2771 $tag = iconv("utf-8", "utf-8", $tag);
2774 if (!$tag) return false;
2779 function render_login_form($link, $form_id = 0) {
2782 require_once "login_form.php";
2785 require_once "mobile/login_form.php";
2791 // from http://developer.apple.com/internet/safari/faq.html
2792 function no_cache_incantation() {
2793 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2794 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2795 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2796 header("Cache-Control: post-check=0, pre-check=0", false);
2797 header("Pragma: no-cache"); // HTTP/1.0
2800 function format_warning($msg, $id = "") {
2802 return "<div class=\"warning\" id=\"$id\">
2803 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
2806 function format_notice($msg, $id = "") {
2808 return "<div class=\"notice\" id=\"$id\">
2809 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
2812 function format_error($msg, $id = "") {
2814 return "<div class=\"error\" id=\"$id\">
2815 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
2818 function print_notice($msg) {
2819 return print format_notice($msg);
2822 function print_warning($msg) {
2823 return print format_warning($msg);
2826 function print_error($msg) {
2827 return print format_error($msg);
2831 function T_sprintf() {
2832 $args = func_get_args();
2833 return vsprintf(__(array_shift($args)), $args);
2836 function format_inline_player($link, $url, $ctype) {
2840 if (strpos($ctype, "audio/") === 0) {
2842 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2843 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2844 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2846 $id = 'AUDIO-' . uniqid();
2848 $entry .= "<audio id=\"$id\"\">
2849 <source src=\"$url\"></source>
2852 $entry .= "<span onclick=\"player(this)\"
2853 title=\"".__("Click to play")."\" status=\"0\"
2854 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2858 $entry .= "<object type=\"application/x-shockwave-flash\"
2859 data=\"lib/button/musicplayer.swf?song_url=$url\"
2860 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2861 <param name=\"movie\"
2862 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2867 $filename = substr($url, strrpos($url, "/")+
1);
2869 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2870 $filename . " (" . $ctype . ")" . "</a>";
2875 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2876 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2882 /* we can figure out feed_id from article id anyway, why do we
2883 * pass feed_id here? let's ignore the argument :( */
2885 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2886 WHERE ref_id = '$id'");
2888 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2890 $rv['feed_id'] = $feed_id;
2892 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2894 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2895 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2897 if (db_num_rows($result) == 1) {
2898 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2899 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2900 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2902 $rtl_content = false;
2903 $always_display_enclosures = false;
2904 $cache_content = false;
2908 $rtl_tag = "dir=\"RTL\"";
2915 if ($mark_as_read) {
2916 $result = db_query($link, "UPDATE ttrss_user_entries
2917 SET unread = false,last_read = NOW()
2918 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2920 ccache_update($link, $feed_id, $owner_uid);
2923 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2924 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
2925 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
2926 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2933 FROM ttrss_entries,ttrss_user_entries
2934 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
2938 $line = db_fetch_assoc($result);
2940 if ($line["icon_url"]) {
2941 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
2943 $feed_icon = " ";
2946 $feed_site_url = $line['site_url'];
2948 $num_comments = $line["num_comments"];
2949 $entry_comments = "";
2951 if ($num_comments > 0) {
2952 if ($line["comments"]) {
2953 $comments_url = htmlspecialchars($line["comments"]);
2955 $comments_url = htmlspecialchars($line["link"]);
2957 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
2959 if ($line["comments"] && $line["link"] != $line["comments"]) {
2960 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
2965 header("Content-Type: text/html");
2966 $rv['content'] .= "<html><head>
2967 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
2968 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2969 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2973 $title_escaped = htmlspecialchars($line['title']);
2975 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
2976 truncate_string(strip_tags($line['title']), 15) . "</div>";
2978 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2979 strip_tags($line['title']) . "</div>";
2981 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
2983 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
2984 class=\"postHeader\" id=\"POSTHDR-$id\">";
2986 $entry_author = $line["author"];
2988 if ($entry_author) {
2989 $entry_author = __(" - ") . $entry_author;
2992 $parsed_updated = make_local_datetime($link, $line["updated"], true,
2995 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
2997 if ($line["link"]) {
2998 $rv['content'] .= "<div class='postTitle'><a target='_blank'
2999 title=\"".htmlspecialchars($line['title'])."\"
3001 htmlspecialchars($line["link"]) . "\">" .
3003 "<span class='author'>$entry_author</span></a></div>";
3005 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3008 $tag_cache = $line["tag_cache"];
3011 $tags = get_article_tags($link, $id, $owner_uid);
3013 $tags = explode(",", $tag_cache);
3015 $tags_str = format_tags_string($tags, $id);
3016 $tags_str_full = join(", ", $tags);
3018 if (!$tags_str_full) $tags_str_full = __("no tags");
3020 if (!$entry_comments) $entry_comments = " "; # placeholder
3022 $rv['content'] .= "<div class='postTags' style='float : right'>
3023 <img src='".theme_image($link, 'images/tag.png')."'
3024 class='tagsPic' alt='Tags' title='Tags'> ";
3027 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3028 <a title=\"".__('Edit tags for this article')."\"
3029 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3031 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3032 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3033 position=\"below\">$tags_str_full</div>";
3035 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3036 class='tagsPic' style=\"cursor : pointer\"
3037 onclick=\"postOpenInNewTab(event, $id)\"
3038 alt='Zoom' title='".__('Open article in new tab')."'>";
3042 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
3043 $rv['content'] .= $p->hook_article_button($line);
3046 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3047 class='tagsPic' style=\"cursor : pointer\"
3048 onclick=\"closeArticlePanel($id)\"
3049 title='".__('Close article')."'>";
3052 $tags_str = strip_tags($tags_str);
3053 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3055 $rv['content'] .= "</div>";
3056 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3058 if ($line["orig_feed_id"]) {
3060 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3061 WHERE id = ".$line["orig_feed_id"]);
3063 if (db_num_rows($tmp_result) != 0) {
3065 $rv['content'] .= "<div clear='both'>";
3066 $rv['content'] .= __("Originally from:");
3068 $rv['content'] .= " ";
3070 $tmp_line = db_fetch_assoc($tmp_result);
3072 $rv['content'] .= "<a target='_blank'
3073 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3074 $tmp_line['title'] . "</a>";
3076 $rv['content'] .= " ";
3078 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3079 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3081 $rv['content'] .= "</div>";
3085 $rv['content'] .= "</div>";
3087 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3088 if ($line['note']) {
3089 $rv['content'] .= format_article_note($id, $line['note']);
3091 $rv['content'] .= "</div>";
3093 $rv['content'] .= "<div class=\"postIcon\">" .
3094 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3095 href=\"".htmlspecialchars($feed_site_url)."\">".
3096 $feed_icon . "</a></div>";
3098 $rv['content'] .= "<div class=\"postContent\">";
3102 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3104 $ngram_result = db_query($link, "SELECT id,title FROM
3105 ttrss_entries,ttrss_user_entries
3106 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3107 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3108 AND title != '$title_escaped'
3109 AND owner_uid = $owner_uid");
3111 if (db_num_rows($ngram_result) > 0) {
3112 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3113 "<span>" . __('Related')."</span>";
3114 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3116 while ($nline = db_fetch_assoc($ngram_result)) {
3117 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3118 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3121 $rv['content'] .= "</div></div><br/";
3125 if ($cache_content && $line["cached_content"] != "") {
3126 $line["content"] =& $line["cached_content"];
3129 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3132 $rv['content'] .= $article_content;
3134 $rv['content'] .= format_article_enclosures($link, $id,
3135 $always_display_enclosures, $article_content);
3137 $rv['content'] .= "</div>";
3139 $rv['content'] .= "</div>";
3145 <div style=\"text-align : center\">
3146 <button onclick=\"return window.close()\">".
3147 __("Close this window")."</button></div>";
3148 $rv['content'] .= "</body></html>";
3155 function print_checkpoint($n, $s) {
3156 $ts = getmicrotime();
3157 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3161 function sanitize_tag($tag) {
3164 $tag = mb_strtolower($tag, 'utf-8');
3166 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3168 // $tag = str_replace('"', "", $tag);
3169 // $tag = str_replace("+", " ", $tag);
3170 $tag = str_replace("technorati tag: ", "", $tag);
3175 function get_self_url_prefix() {
3176 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3177 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3179 return SELF_URL_PATH
;
3183 function opml_publish_url($link){
3185 $url_path = get_self_url_prefix();
3186 $url_path .= "/opml.php?op=publish&key=" .
3187 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3193 * Purge a feed contents, marked articles excepted.
3195 * @param mixed $link The database connection.
3196 * @param integer $id The id of the feed to purge.
3199 function clear_feed_articles($link, $id) {
3202 $result = db_query($link, "DELETE FROM ttrss_user_entries
3203 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3205 $result = db_query($link, "DELETE FROM ttrss_user_entries
3206 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3209 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3210 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3212 ccache_update($link, $id, $_SESSION['uid']);
3213 } // function clear_feed_articles
3216 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3218 * @return string The Mozilla Firefox feed adding URL.
3220 function add_feed_url() {
3221 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3223 $url_path = get_self_url_prefix() .
3224 "/public.php?op=subscribe&feed_url=%s";
3226 } // function add_feed_url
3228 function encrypt_password($pass, $salt = '', $mode2 = false) {
3229 if ($salt && $mode2) {
3230 return "MODE2:" . hash('sha256', $salt . $pass);
3232 return "SHA1X:" . sha1("$salt:$pass");
3234 return "SHA1:" . sha1($pass);
3236 } // function encrypt_password
3238 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3241 $cat_id = (int)getFeedCategory($link, $feed_id);
3243 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3244 owner_uid = $owner_uid AND enabled = true");
3246 $check_cats = join(",", array_merge(
3247 getParentCategories($link, $cat_id, $owner_uid),
3250 while ($line = db_fetch_assoc($result)) {
3251 $filter_id = $line["id"];
3253 $result2 = db_query($link, "SELECT
3254 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3255 FROM ttrss_filters2_rules AS r,
3256 ttrss_filter_types AS t
3258 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3259 (feed_id IS NULL OR feed_id = '$feed_id') AND
3260 filter_type = t.id AND filter_id = '$filter_id'");
3265 while ($rule_line = db_fetch_assoc($result2)) {
3266 # print_r($rule_line);
3269 $rule["reg_exp"] = $rule_line["reg_exp"];
3270 $rule["type"] = $rule_line["type_name"];
3272 array_push($rules, $rule);
3275 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3276 FROM ttrss_filters2_actions AS a,
3277 ttrss_filter_actions AS t
3279 action_id = t.id AND filter_id = '$filter_id'");
3281 while ($action_line = db_fetch_assoc($result2)) {
3282 # print_r($action_line);
3285 $action["type"] = $action_line["type_name"];
3286 $action["param"] = $action_line["action_param"];
3288 array_push($actions, $action);
3293 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3294 $filter["rules"] = $rules;
3295 $filter["actions"] = $actions;
3297 if (count($rules) > 0 && count($actions) > 0) {
3298 array_push($filters, $filter);
3305 function get_score_pic($score) {
3307 return "score_high.png";
3308 } else if ($score > 0) {
3309 return "score_half_high.png";
3310 } else if ($score < -100) {
3311 return "score_low.png";
3312 } else if ($score < 0) {
3313 return "score_half_low.png";
3315 return "score_neutral.png";
3319 function feed_has_icon($id) {
3320 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3323 function init_connection($link) {
3326 if (DB_TYPE
== "pgsql") {
3327 pg_query($link, "set client_encoding = 'UTF-8'");
3328 pg_set_client_encoding("UNICODE");
3329 pg_query($link, "set datestyle = 'ISO, european'");
3330 pg_query($link, "set TIME ZONE 0");
3332 db_query($link, "SET time_zone = '+0:0'");
3334 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3335 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3341 $pluginhost = new PluginHost($link);
3342 $pluginhost->load(PLUGINS
);
3346 print "Unable to connect to database:" . db_last_error();
3351 /* function ccache_zero($link, $feed_id, $owner_uid) {
3352 db_query($link, "UPDATE ttrss_counters_cache SET
3353 value = 0, updated = NOW() WHERE
3354 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3357 function ccache_zero_all($link, $owner_uid) {
3358 db_query($link, "UPDATE ttrss_counters_cache SET
3359 value = 0 WHERE owner_uid = '$owner_uid'");
3361 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3362 value = 0 WHERE owner_uid = '$owner_uid'");
3365 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3368 $table = "ttrss_counters_cache";
3370 $table = "ttrss_cat_counters_cache";
3373 db_query($link, "DELETE FROM $table WHERE
3374 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3378 function ccache_update_all($link, $owner_uid) {
3380 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3382 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3383 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3385 while ($line = db_fetch_assoc($result)) {
3386 ccache_update($link, $line["feed_id"], $owner_uid, true);
3389 /* We have to manually include category 0 */
3391 ccache_update($link, 0, $owner_uid, true);
3394 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3395 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3397 while ($line = db_fetch_assoc($result)) {
3398 print ccache_update($link, $line["feed_id"], $owner_uid);
3405 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3406 $no_update = false) {
3408 if (!is_numeric($feed_id)) return;
3411 $table = "ttrss_counters_cache";
3413 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3414 WHERE id = '$feed_id'");
3415 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3418 $table = "ttrss_cat_counters_cache";
3421 if (DB_TYPE
== "pgsql") {
3422 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3423 } else if (DB_TYPE
== "mysql") {
3424 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3427 $result = db_query($link, "SELECT value FROM $table
3428 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3431 if (db_num_rows($result) == 1) {
3432 return db_fetch_result($result, 0, "value");
3437 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3443 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3444 $update_pcat = true) {
3446 if (!is_numeric($feed_id)) return;
3448 if (!$is_cat && $feed_id > 0) {
3449 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3450 WHERE id = '$feed_id'");
3451 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3454 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3456 /* When updating a label, all we need to do is recalculate feed counters
3457 * because labels are not cached */
3460 ccache_update_all($link, $owner_uid);
3465 $table = "ttrss_counters_cache";
3467 $table = "ttrss_cat_counters_cache";
3470 if ($is_cat && $feed_id >= 0) {
3471 if ($feed_id != 0) {
3472 $cat_qpart = "cat_id = '$feed_id'";
3474 $cat_qpart = "cat_id IS NULL";
3477 /* Recalculate counters for child feeds */
3479 $result = db_query($link, "SELECT id FROM ttrss_feeds
3480 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3482 while ($line = db_fetch_assoc($result)) {
3483 ccache_update($link, $line["id"], $owner_uid, false, false);
3486 $result = db_query($link, "SELECT SUM(value) AS sv
3487 FROM ttrss_counters_cache, ttrss_feeds
3488 WHERE id = feed_id AND $cat_qpart AND
3489 ttrss_feeds.owner_uid = '$owner_uid'");
3491 $unread = (int) db_fetch_result($result, 0, "sv");
3494 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3497 db_query($link, "BEGIN");
3499 $result = db_query($link, "SELECT feed_id FROM $table
3500 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3502 if (db_num_rows($result) == 1) {
3503 db_query($link, "UPDATE $table SET
3504 value = '$unread', updated = NOW() WHERE
3505 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3508 db_query($link, "INSERT INTO $table
3509 (feed_id, value, owner_uid, updated)
3511 ($feed_id, $unread, $owner_uid, NOW())");
3514 db_query($link, "COMMIT");
3516 if ($feed_id > 0 && $prev_unread != $unread) {
3520 /* Update parent category */
3524 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3525 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3527 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3529 ccache_update($link, $cat_id, $owner_uid, true);
3533 } else if ($feed_id < 0) {
3534 ccache_update_all($link, $owner_uid);
3540 /* function ccache_cleanup($link, $owner_uid) {
3542 if (DB_TYPE == "pgsql") {
3543 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3544 (SELECT count(*) FROM ttrss_counters_cache AS c2
3545 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3546 AND owner_uid = '$owner_uid'");
3548 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3549 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3550 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3551 AND owner_uid = '$owner_uid'");
3553 db_query($link, "DELETE c1 FROM
3554 ttrss_counters_cache AS c1,
3555 ttrss_counters_cache AS c2
3557 c1.owner_uid = '$owner_uid' AND
3558 c1.owner_uid = c2.owner_uid AND
3559 c1.feed_id = c2.feed_id");
3561 db_query($link, "DELETE c1 FROM
3562 ttrss_cat_counters_cache AS c1,
3563 ttrss_cat_counters_cache AS c2
3565 c1.owner_uid = '$owner_uid' AND
3566 c1.owner_uid = c2.owner_uid AND
3567 c1.feed_id = c2.feed_id");
3572 function label_find_id($link, $label, $owner_uid) {
3573 $result = db_query($link,
3574 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3575 AND owner_uid = '$owner_uid' LIMIT 1");
3577 if (db_num_rows($result) == 1) {
3578 return db_fetch_result($result, 0, "id");
3584 function get_article_labels($link, $id, $owner_uid = false) {
3587 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3589 $result = db_query($link, "SELECT label_cache FROM
3590 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3593 if (db_num_rows($result) > 0) {
3594 $label_cache = db_fetch_result($result, 0, "label_cache");
3597 $label_cache = json_decode($label_cache, true);
3599 if ($label_cache["no-labels"] == 1)
3602 return $label_cache;
3606 $result = db_query($link,
3607 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3608 FROM ttrss_labels2, ttrss_user_labels2
3610 AND article_id = '$id'
3611 AND owner_uid = ". $owner_uid . "
3614 while ($line = db_fetch_assoc($result)) {
3615 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3617 array_push($rv, $rk);
3621 label_update_cache($link, $owner_uid, $id, $rv);
3623 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3629 function label_find_caption($link, $label, $owner_uid) {
3630 $result = db_query($link,
3631 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3632 AND owner_uid = '$owner_uid' LIMIT 1");
3634 if (db_num_rows($result) == 1) {
3635 return db_fetch_result($result, 0, "caption");
3641 function get_all_labels($link, $owner_uid) {
3644 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3646 while ($line = db_fetch_assoc($result)) {
3647 array_push($rv, $line);
3653 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3656 label_clear_cache($link, $id);
3659 $labels = get_article_labels($link, $id);
3661 $labels = db_escape_string(json_encode($labels));
3663 db_query($link, "UPDATE ttrss_user_entries SET
3664 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3668 function label_clear_cache($link, $id) {
3670 db_query($link, "UPDATE ttrss_user_entries SET
3671 label_cache = '' WHERE ref_id = '$id'");
3675 function label_remove_article($link, $id, $label, $owner_uid) {
3677 $label_id = label_find_id($link, $label, $owner_uid);
3679 if (!$label_id) return;
3681 $result = db_query($link,
3682 "DELETE FROM ttrss_user_labels2
3684 label_id = '$label_id' AND
3685 article_id = '$id'");
3687 label_clear_cache($link, $id);
3690 function label_add_article($link, $id, $label, $owner_uid) {
3692 $label_id = label_find_id($link, $label, $owner_uid);
3694 if (!$label_id) return;
3696 $result = db_query($link,
3698 article_id FROM ttrss_labels2, ttrss_user_labels2
3701 label_id = '$label_id' AND
3702 article_id = '$id' AND owner_uid = '$owner_uid'
3705 if (db_num_rows($result) == 0) {
3706 db_query($link, "INSERT INTO ttrss_user_labels2
3707 (label_id, article_id) VALUES ('$label_id', '$id')");
3710 label_clear_cache($link, $id);
3714 function label_remove($link, $id, $owner_uid) {
3715 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3717 db_query($link, "BEGIN");
3719 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3722 $caption = db_fetch_result($result, 0, "caption");
3724 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3725 AND owner_uid = " . $owner_uid);
3727 if (db_affected_rows($link, $result) != 0 && $caption) {
3729 /* Remove access key for the label */
3731 $ext_id = -11 - $id;
3733 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3734 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3736 /* Disable filters that reference label being removed */
3738 db_query($link, "UPDATE ttrss_filters SET
3739 enabled = false WHERE action_param = '$caption'
3741 AND owner_uid = " . $owner_uid);
3743 /* Remove cached data */
3745 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3746 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3750 db_query($link, "COMMIT");
3753 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3755 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3757 db_query($link, "BEGIN");
3761 $result = db_query($link, "SELECT id FROM ttrss_labels2
3762 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3764 if (db_num_rows($result) == 0) {
3765 $result = db_query($link,
3766 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3767 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3769 $result = db_affected_rows($link, $result) != 0;
3772 db_query($link, "COMMIT");
3777 function format_tags_string($tags, $id) {
3780 $tags_nolinks_str = "";
3786 $formatted_tags = array();
3788 foreach ($tags as $tag) {
3790 $tag_escaped = str_replace("'", "\\'", $tag);
3792 if (mb_strlen($tag) > 30) {
3793 $tag = truncate_string($tag, 30);
3796 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3798 array_push($formatted_tags, $tag_str);
3800 $tmp_tags_str = implode(", ", $formatted_tags);
3802 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
3807 $tags_str = implode(", ", $formatted_tags);
3809 if ($num_tags < count($tags)) {
3810 $tags_str .= ", …";
3813 if ($num_tags == 0) {
3814 $tags_str = __("no tags");
3821 function format_article_labels($labels, $id) {
3825 foreach ($labels as $l) {
3826 $labels_str .= sprintf("<span class='hlLabelRef'
3827 style='color : %s; background-color : %s'>%s</span>",
3828 $l[2], $l[3], $l[1]);
3835 function format_article_note($id, $note) {
3837 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3838 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3839 __('(edit note)')."</div>$note</div>";
3844 function toggle_collapse_cat($link, $cat_id, $mode) {
3846 $mode = bool_to_sql_bool($mode);
3848 db_query($link, "UPDATE ttrss_feed_categories SET
3849 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3856 $pref_name = '_COLLAPSED_SPECIAL';
3859 $pref_name = '_COLLAPSED_LABELS';
3862 $pref_name = '_COLLAPSED_UNCAT';
3868 set_pref($link, $pref_name, 'true');
3870 set_pref($link, $pref_name, 'false');
3876 function remove_feed($link, $id, $owner_uid) {
3880 /* save starred articles in Archived feed */
3882 db_query($link, "BEGIN");
3884 /* prepare feed if necessary */
3886 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
3889 if (db_num_rows($result) == 0) {
3890 db_query($link, "INSERT INTO ttrss_archived_feeds
3891 (id, owner_uid, title, feed_url, site_url)
3892 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
3896 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
3897 orig_feed_id = '$id' WHERE feed_id = '$id' AND
3898 marked = true AND owner_uid = $owner_uid");
3900 /* Remove access key for the feed */
3902 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3903 feed_id = '$id' AND owner_uid = $owner_uid");
3905 /* remove the feed */
3907 db_query($link, "DELETE FROM ttrss_feeds
3908 WHERE id = '$id' AND owner_uid = $owner_uid");
3910 db_query($link, "COMMIT");
3912 if (file_exists(ICONS_DIR
. "/$id.ico")) {
3913 unlink(ICONS_DIR
. "/$id.ico");
3916 ccache_remove($link, $id, $owner_uid);
3919 label_remove($link, -11-$id, $owner_uid);
3920 ccache_remove($link, -11-$id, $owner_uid);
3924 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3925 if ($parent_cat_id) {
3926 $parent_qpart = "parent_cat = '$parent_cat_id'";
3927 $parent_insert = "'$parent_cat_id'";
3929 $parent_qpart = "parent_cat IS NULL";
3930 $parent_insert = "NULL";
3933 $result = db_query($link,
3934 "SELECT id FROM ttrss_feed_categories
3935 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3937 if (db_num_rows($result) == 0) {
3940 return db_fetch_result($result, 0, "id");
3944 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3946 if (!$feed_cat) return false;
3948 db_query($link, "BEGIN");
3950 if ($parent_cat_id) {
3951 $parent_qpart = "parent_cat = '$parent_cat_id'";
3952 $parent_insert = "'$parent_cat_id'";
3954 $parent_qpart = "parent_cat IS NULL";
3955 $parent_insert = "NULL";
3958 $result = db_query($link,
3959 "SELECT id FROM ttrss_feed_categories
3960 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3962 if (db_num_rows($result) == 0) {
3964 $result = db_query($link,
3965 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3966 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3968 db_query($link, "COMMIT");
3976 function remove_feed_category($link, $id, $owner_uid) {
3978 db_query($link, "DELETE FROM ttrss_feed_categories
3979 WHERE id = '$id' AND owner_uid = $owner_uid");
3981 ccache_remove($link, $id, $owner_uid, true);
3984 function archive_article($link, $id, $owner_uid) {
3985 db_query($link, "BEGIN");
3987 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3988 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3990 if (db_num_rows($result) != 0) {
3992 /* prepare the archived table */
3994 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3997 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
3998 WHERE id = '$feed_id'");
4000 if (db_num_rows($result) == 0) {
4001 db_query($link, "INSERT INTO ttrss_archived_feeds
4002 (id, owner_uid, title, feed_url, site_url)
4003 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4004 WHERE id = '$feed_id'");
4007 db_query($link, "UPDATE ttrss_user_entries
4008 SET orig_feed_id = feed_id, feed_id = NULL
4009 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4013 db_query($link, "COMMIT");
4016 function getArticleFeed($link, $id) {
4017 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4018 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4020 if (db_num_rows($result) != 0) {
4021 return db_fetch_result($result, 0, "feed_id");
4028 * Fixes incomplete URLs by prepending "http://".
4029 * Also replaces feed:// with http://, and
4030 * prepends a trailing slash if the url is a domain name only.
4032 * @param string $url Possibly incomplete URL
4034 * @return string Fixed URL.
4036 function fix_url($url) {
4037 if (strpos($url, '://') === false) {
4038 $url = 'http://' . $url;
4039 } else if (substr($url, 0, 5) == 'feed:') {
4040 $url = 'http:' . substr($url, 5);
4043 //prepend slash if the URL has no slash in it
4044 // "http://www.example" -> "http://www.example/"
4045 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4049 if ($url != "http:///")
4055 function validate_feed_url($url) {
4056 $parts = parse_url($url);
4058 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4062 function get_article_enclosures($link, $id) {
4064 $query = "SELECT * FROM ttrss_enclosures
4065 WHERE post_id = '$id' AND content_url != ''";
4069 $result = db_query($link, $query);
4071 if (db_num_rows($result) > 0) {
4072 while ($line = db_fetch_assoc($result)) {
4073 array_push($rv, $line);
4080 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4086 if ($cat_id == -4 ||
$cat_id == -2) {
4087 $counters = getLabelCounters($link, true);
4089 foreach (array_values($counters) as $cv) {
4091 $unread = $cv["counter"];
4093 if ($unread ||
!$unread_only) {
4097 "title" => $cv["description"],
4098 "unread" => $cv["counter"],
4102 array_push($feeds, $row);
4109 if ($cat_id == -4 ||
$cat_id == -1) {
4110 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4111 $unread = getFeedUnread($link, $i);
4113 if ($unread ||
!$unread_only) {
4114 $title = getFeedTitle($link, $i);
4119 "unread" => $unread,
4122 array_push($feeds, $row);
4130 if ($include_nested && $cat_id) {
4131 $result = db_query($link, "SELECT
4132 id, title FROM ttrss_feed_categories
4133 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4134 " ORDER BY id, title");
4136 while ($line = db_fetch_assoc($result)) {
4137 $unread = getFeedUnread($link, $line["id"], true) +
4138 getCategoryChildrenUnread($link, $line["id"]);
4140 if ($unread ||
!$unread_only) {
4142 "id" => $line["id"],
4143 "title" => $line["title"],
4144 "unread" => $unread,
4147 array_push($feeds, $row);
4155 $limit_qpart = "LIMIT $limit OFFSET $offset";
4160 if ($cat_id == -4 ||
$cat_id == -3) {
4161 $result = db_query($link, "SELECT
4162 id, feed_url, cat_id, title, order_id, ".
4163 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4164 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4165 " ORDER BY cat_id, title " . $limit_qpart);
4169 $cat_qpart = "cat_id = '$cat_id'";
4171 $cat_qpart = "cat_id IS NULL";
4173 $result = db_query($link, "SELECT
4174 id, feed_url, cat_id, title, order_id, ".
4175 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4176 FROM ttrss_feeds WHERE
4177 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4178 " ORDER BY cat_id, title " . $limit_qpart);
4181 while ($line = db_fetch_assoc($result)) {
4183 $unread = getFeedUnread($link, $line["id"]);
4185 $has_icon = feed_has_icon($line['id']);
4187 if ($unread ||
!$unread_only) {
4190 "feed_url" => $line["feed_url"],
4191 "title" => $line["title"],
4192 "id" => (int)$line["id"],
4193 "unread" => (int)$unread,
4194 "has_icon" => $has_icon,
4195 "cat_id" => (int)$line["cat_id"],
4196 "last_updated" => strtotime($line["last_updated"]),
4197 "order_id" => (int) $line["order_id"],
4200 array_push($feeds, $row);
4207 function api_get_headlines($link, $feed_id, $limit, $offset,
4208 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4209 $include_attachments, $since_id,
4210 $search = "", $search_mode = "", $match_on = "",
4211 $include_nested = false, $sanitize_content = true) {
4213 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4214 $view_mode, $is_cat, $search, $search_mode, $match_on,
4215 $order, $offset, 0, false, $since_id, $include_nested);
4217 $result = $qfh_ret[0];
4218 $feed_title = $qfh_ret[1];
4220 $headlines = array();
4222 while ($line = db_fetch_assoc($result)) {
4223 $is_updated = ($line["last_read"] == "" &&
4224 ($line["unread"] != "t" && $line["unread"] != "1"));
4226 $tags = explode(",", $line["tag_cache"]);
4227 $labels = json_decode($line["label_cache"], true);
4229 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4230 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4232 $headline_row = array(
4233 "id" => (int)$line["id"],
4234 "unread" => sql_bool_to_bool($line["unread"]),
4235 "marked" => sql_bool_to_bool($line["marked"]),
4236 "published" => sql_bool_to_bool($line["published"]),
4237 "updated" => strtotime($line["updated"]),
4238 "is_updated" => $is_updated,
4239 "title" => $line["title"],
4240 "link" => $line["link"],
4241 "feed_id" => $line["feed_id"],
4245 if ($include_attachments)
4246 $headline_row['attachments'] = get_article_enclosures($link,
4249 if ($show_excerpt) {
4250 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4251 $headline_row["excerpt"] = $excerpt;
4254 if ($show_content) {
4256 if ($line["cached_content"] != "") {
4257 $line["content_preview"] =& $line["cached_content"];
4260 if ($sanitize_content) {
4261 $headline_row["content"] = sanitize($link,
4262 $line["content_preview"], false, false, $line["site_url"]);
4264 $headline_row["content"] = $line["content_preview"];
4268 // unify label output to ease parsing
4269 if ($labels["no-labels"] == 1) $labels = array();
4271 $headline_row["labels"] = $labels;
4273 $headline_row["feed_title"] = $line["feed_title"];
4275 $headline_row["comments_count"] = (int)$line["num_comments"];
4276 $headline_row["comments_link"] = $line["comments"];
4278 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4280 array_push($headlines, $headline_row);
4286 function generate_error_feed($link, $error) {
4289 $reply['headlines']['id'] = -6;
4290 $reply['headlines']['is_cat'] = false;
4292 $reply['headlines']['toolbar'] = '';
4293 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4295 $reply['headlines-info'] = array("count" => 0,
4296 "vgroup_last_feed" => '',
4298 "disable_cache" => true);
4304 function generate_dashboard_feed($link) {
4307 $reply['headlines']['id'] = -5;
4308 $reply['headlines']['is_cat'] = false;
4310 $reply['headlines']['toolbar'] = '';
4311 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4313 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4315 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4316 WHERE owner_uid = " . $_SESSION['uid']);
4318 $last_updated = db_fetch_result($result, 0, "last_updated");
4319 $last_updated = make_local_datetime($link, $last_updated, false);
4321 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4323 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4324 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4326 $num_errors = db_fetch_result($result, 0, "num_errors");
4328 if ($num_errors > 0) {
4329 $reply['headlines']['content'] .= "<br/>";
4330 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4331 __('Some feeds have update errors (click for details)')."</a>";
4333 $reply['headlines']['content'] .= "</span></p>";
4335 $reply['headlines-info'] = array("count" => 0,
4336 "vgroup_last_feed" => '',
4338 "disable_cache" => true);
4343 function save_email_address($link, $email) {
4344 // FIXME: implement persistent storage of emails
4346 if (!$_SESSION['stored_emails'])
4347 $_SESSION['stored_emails'] = array();
4349 if (!in_array($email, $_SESSION['stored_emails']))
4350 array_push($_SESSION['stored_emails'], $email);
4353 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4354 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4356 $sql_is_cat = bool_to_sql_bool($is_cat);
4358 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4359 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4360 AND owner_uid = " . $owner_uid);
4362 if (db_num_rows($result) == 1) {
4363 $key = db_escape_string(sha1(uniqid(rand(), true)));
4365 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4366 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4367 AND owner_uid = " . $owner_uid);
4372 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4376 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4378 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4380 $sql_is_cat = bool_to_sql_bool($is_cat);
4382 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4383 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4384 AND owner_uid = " . $owner_uid);
4386 if (db_num_rows($result) == 1) {
4387 return db_fetch_result($result, 0, "access_key");
4389 $key = db_escape_string(sha1(uniqid(rand(), true)));
4391 $result = db_query($link, "INSERT INTO ttrss_access_keys
4392 (access_key, feed_id, is_cat, owner_uid)
4393 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4400 function get_feeds_from_html($url, $content)
4402 $url = fix_url($url);
4403 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4405 libxml_use_internal_errors(true);
4407 $doc = new DOMDocument();
4408 $doc->loadHTML($content);
4409 $xpath = new DOMXPath($doc);
4410 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4411 $feedUrls = array();
4412 foreach ($entries as $entry) {
4413 if ($entry->hasAttribute('href')) {
4414 $title = $entry->getAttribute('title');
4416 $title = $entry->getAttribute('type');
4418 $feedUrl = rewrite_relative_url(
4419 $baseUrl, $entry->getAttribute('href')
4421 $feedUrls[$feedUrl] = $title;
4427 function is_html($content) {
4428 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4431 function url_is_html($url, $login = false, $pass = false) {
4432 return is_html(fetch_file_contents($url, false, $login, $pass));
4435 function print_label_select($link, $name, $value, $attributes = "") {
4437 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4438 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4440 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4441 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4443 while ($line = db_fetch_assoc($result)) {
4445 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4447 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4448 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4452 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4459 function format_article_enclosures($link, $id, $always_display_enclosures,
4462 $result = get_article_enclosures($link, $id);
4465 if (count($result) > 0) {
4467 $entries_html = array();
4470 foreach ($result as $line) {
4472 $url = $line["content_url"];
4473 $ctype = $line["content_type"];
4475 if (!$ctype) $ctype = __("unknown type");
4477 $filename = substr($url, strrpos($url, "/")+
1);
4479 # $player = format_inline_player($link, $url, $ctype);
4481 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4482 # $filename . " (" . $ctype . ")" . "</a>";
4484 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4485 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4487 array_push($entries_html, $entry);
4491 $entry["type"] = $ctype;
4492 $entry["filename"] = $filename;
4493 $entry["url"] = $url;
4495 array_push($entries, $entry);
4498 if (!get_pref($link, "STRIP_IMAGES")) {
4499 if ($always_display_enclosures ||
4500 !preg_match("/<img/i", $article_content)) {
4502 foreach ($entries as $entry) {
4504 if (preg_match("/image/", $entry["type"]) ||
4505 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4508 alt=\"".htmlspecialchars($entry["filename"])."\"
4509 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4516 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4517 "<span>" . __('Attachments')."</span>";
4518 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4520 foreach ($entries_html as $entry) { $rv .= $entry; };
4522 $rv .= "</div></div>";
4528 function getLastArticleId($link) {
4529 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4530 WHERE owner_uid = " . $_SESSION["uid"]);
4532 if (db_num_rows($result) == 1) {
4533 return db_fetch_result($result, 0, "id");
4539 function build_url($parts) {
4540 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4544 * Converts a (possibly) relative URL to a absolute one.
4546 * @param string $url Base URL (i.e. from where the document is)
4547 * @param string $rel_url Possibly relative URL in the document
4549 * @return string Absolute URL
4551 function rewrite_relative_url($url, $rel_url) {
4552 if (strpos($rel_url, "magnet:") === 0) {
4554 } else if (strpos($rel_url, "://") !== false) {
4556 } else if (strpos($rel_url, "//") === 0) {
4557 # protocol-relative URL (rare but they exist)
4559 } else if (strpos($rel_url, "/") === 0)
4561 $parts = parse_url($url);
4562 $parts['path'] = $rel_url;
4564 return build_url($parts);
4567 $parts = parse_url($url);
4568 if (!isset($parts['path'])) {
4569 $parts['path'] = '/';
4571 $dir = $parts['path'];
4572 if (substr($dir, -1) !== '/') {
4573 $dir = dirname($parts['path']);
4574 $dir !== '/' && $dir .= '/';
4576 $parts['path'] = $dir . $rel_url;
4578 return build_url($parts);
4582 function sphinx_search($query, $offset = 0, $limit = 30) {
4583 require_once 'lib/sphinxapi.php';
4585 $sphinxClient = new SphinxClient();
4587 $sphinxClient->SetServer('localhost', 9312);
4588 $sphinxClient->SetConnectTimeout(1);
4590 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4591 'feed_title' => 20));
4593 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4594 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4595 $sphinxClient->SetLimits($offset, $limit, 1000);
4596 $sphinxClient->SetArrayResult(false);
4597 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4599 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4603 if (is_array($result['matches'])) {
4604 foreach (array_keys($result['matches']) as $int_id) {
4605 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4606 array_push($ids, $ref_id);
4613 function cleanup_tags($link, $days = 14, $limit = 1000) {
4615 if (DB_TYPE
== "pgsql") {
4616 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4617 } else if (DB_TYPE
== "mysql") {
4618 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4623 while ($limit > 0) {
4626 $query = "SELECT ttrss_tags.id AS id
4627 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4628 WHERE post_int_id = int_id AND $interval_query AND
4629 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4631 $result = db_query($link, $query);
4635 while ($line = db_fetch_assoc($result)) {
4636 array_push($ids, $line['id']);
4639 if (count($ids) > 0) {
4640 $ids = join(",", $ids);
4643 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4644 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4649 $limit -= $limit_part;
4654 return $tags_deleted;
4657 function print_user_stylesheet($link) {
4658 $value = get_pref($link, 'USER_STYLESHEET');
4661 print "<style type=\"text/css\">";
4662 print str_replace("<br/>", "\n", $value);
4668 /* function rewrite_urls($line) {
4673 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4674 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
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));