2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 98);
5 $fetch_last_error = false;
7 function __autoload($class) {
8 $class_file = str_replace("_", "/", strtolower(basename($class)));
10 $file = dirname(__FILE__
)."/../classes/$class_file.php";
12 if (file_exists($file)) {
17 mb_internal_encoding("UTF-8");
18 date_default_timezone_set('UTC');
19 if (defined('E_DEPRECATED')) {
20 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
22 error_reporting(E_ALL
& ~E_NOTICE
);
25 require_once 'config.php';
27 if (DB_TYPE
== "pgsql") {
28 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
33 define('THEME_VERSION_REQUIRED', 1.1);
36 * Return available translations names.
39 * @return array A array of available translations.
41 function get_translations() {
43 "auto" => "Detect automatically",
48 "fr_FR" => "Français",
49 "hu_HU" => "Magyar (Hungarian)",
50 "it_IT" => "Italiano",
51 "ja_JP" => "日本語 (Japanese)",
52 "nb_NO" => "Norwegian bokmål",
55 "pt_BR" => "Portuguese/Brazil",
56 "zh_CN" => "Simplified Chinese");
61 require_once "lib/accept-to-gettext.php";
62 require_once "lib/gettext/gettext.inc";
64 function startup_gettext() {
66 # Get locale from Accept-Language header
67 $lang = al2gt(array_keys(get_translations()), "text/html");
69 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
70 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
73 /* In login action of mobile version */
74 if ($_POST["language"] && defined('MOBILE_VERSION')) {
75 $lang = $_POST["language"];
77 $lang = $_SESSION["language"];
81 if (defined('LC_MESSAGES')) {
82 _setlocale(LC_MESSAGES
, $lang);
83 } else if (defined('LC_ALL')) {
84 _setlocale(LC_ALL
, $lang);
87 if (defined('MOBILE_VERSION')) {
88 _bindtextdomain("messages", "../locale");
90 _bindtextdomain("messages", "locale");
93 _textdomain("messages");
94 _bind_textdomain_codeset("messages", "UTF-8");
100 require_once 'db-prefs.php';
101 require_once 'version.php';
103 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
105 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
106 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
108 ini_set('user_agent', SELF_USER_AGENT
);
110 require_once 'lib/pubsubhubbub/publisher.php';
111 require_once 'lib/htmLawed.php';
114 $utc_tz = new DateTimeZone('UTC');
115 $schema_version = false;
118 * Print a timestamped debug message.
120 * @param string $msg The debug message.
123 function _debug($msg) {
124 if (defined('QUIET') && QUIET
) {
127 $ts = strftime("%H:%M:%S", time());
128 if (function_exists('posix_getpid')) {
129 $ts = "$ts/" . posix_getpid();
131 print "[$ts] $msg\n";
135 * Purge a feed old posts.
137 * @param mixed $link A database connection.
138 * @param mixed $feed_id The id of the purged feed.
139 * @param mixed $purge_interval Olderness of purged posts.
140 * @param boolean $debug Set to True to enable the debug. False by default.
144 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
146 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
150 $result = db_query($link,
151 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
155 if (db_num_rows($result) == 1) {
156 $owner_uid = db_fetch_result($result, 0, "owner_uid");
159 if ($purge_interval == -1 ||
!$purge_interval) {
161 ccache_update($link, $feed_id, $owner_uid);
166 if (!$owner_uid) return;
168 if (FORCE_ARTICLE_PURGE
== 0) {
169 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
172 $purge_unread = true;
173 $purge_interval = FORCE_ARTICLE_PURGE
;
176 if (!$purge_unread) $query_limit = " unread = false AND ";
178 if (DB_TYPE
== "pgsql") {
179 $pg_version = get_pgsql_version($link);
181 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
183 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
184 ttrss_entries.id = ref_id AND
186 feed_id = '$feed_id' AND
188 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
194 WHERE ttrss_entries.id = ref_id AND
196 feed_id = '$feed_id' AND
198 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
201 $rows = pg_affected_rows($result);
205 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
206 marked = false AND feed_id = '$feed_id' AND
207 (SELECT date_updated FROM ttrss_entries WHERE
208 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
210 $result = db_query($link, "DELETE FROM ttrss_user_entries
211 USING ttrss_user_entries, ttrss_entries
212 WHERE ttrss_entries.id = ref_id AND
214 feed_id = '$feed_id' AND
216 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
218 $rows = mysql_affected_rows($link);
222 ccache_update($link, $feed_id, $owner_uid);
225 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
227 } // function purge_feed
229 function feed_purge_interval($link, $feed_id) {
231 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
232 WHERE id = '$feed_id'");
234 if (db_num_rows($result) == 1) {
235 $purge_interval = db_fetch_result($result, 0, "purge_interval");
236 $owner_uid = db_fetch_result($result, 0, "owner_uid");
238 if ($purge_interval == 0) $purge_interval = get_pref($link,
239 'PURGE_OLD_DAYS', $owner_uid);
241 return $purge_interval;
248 function purge_orphans($link, $do_output = false) {
250 // purge orphaned posts in main content table
251 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
252 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
255 $rows = db_affected_rows($link, $result);
256 _debug("Purged $rows orphaned posts.");
260 function get_feed_update_interval($link, $feed_id) {
261 $result = db_query($link, "SELECT owner_uid, update_interval FROM
262 ttrss_feeds WHERE id = '$feed_id'");
264 if (db_num_rows($result) == 1) {
265 $update_interval = db_fetch_result($result, 0, "update_interval");
266 $owner_uid = db_fetch_result($result, 0, "owner_uid");
268 if ($update_interval != 0) {
269 return $update_interval;
271 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
279 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
280 $login = urlencode($login);
281 $pass = urlencode($pass);
283 global $fetch_last_error;
285 if (function_exists('curl_init') && !ini_get("open_basedir")) {
286 $ch = curl_init($url);
288 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
289 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
290 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
291 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
292 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
293 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
295 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
296 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
297 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
300 curl_setopt($ch, CURLOPT_POST
, true);
301 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
305 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
307 $contents = @curl_exec
($ch);
309 if ($contents === false) {
310 $fetch_last_error = curl_error($ch);
315 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
316 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
319 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
325 if ($login && $pass ){
326 $url_parts = array();
328 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
330 if ($url_parts[1] && $url_parts[2]) {
331 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
335 $data = @file_get_contents
($url);
337 if (!$data && function_exists('error_get_last')) {
338 $error = error_get_last();
339 $fetch_last_error = $error["message"];
347 * Try to determine the favicon URL for a feed.
348 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
349 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
351 * @param string $url A feed or page URL
353 * @return mixed The favicon URL, or false if none was found.
355 function get_favicon_url($url) {
357 $favicon_url = false;
359 if ($html = @fetch_file_contents
($url)) {
361 libxml_use_internal_errors(true);
363 $doc = new DOMDocument();
364 $doc->loadHTML($html);
365 $xpath = new DOMXPath($doc);
367 $base = $xpath->query('/html/head/base');
368 foreach ($base as $b) {
369 $url = $b->getAttribute("href");
373 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
374 if (count($entries) > 0) {
375 foreach ($entries as $entry) {
376 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
383 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
386 } // function get_favicon_url
388 function check_feed_favicon($site_url, $feed, $link) {
389 # print "FAVICON [$site_url]: $favicon_url\n";
391 $icon_file = ICONS_DIR
. "/$feed.ico";
393 if (!file_exists($icon_file)) {
394 $favicon_url = get_favicon_url($site_url);
397 // Limiting to "image" type misses those served with text/plain
398 $contents = fetch_file_contents($favicon_url); // , "image");
401 // Crude image type matching.
402 // Patterns gleaned from the file(1) source code.
403 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
404 // 0 string \000\000\001\000 MS Windows icon resource
405 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
407 elseif (preg_match('/^GIF8/', $contents)) {
408 // 0 string GIF8 GIF image data
409 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
411 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
412 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
413 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
415 elseif (preg_match('/^\xff\xd8/', $contents)) {
416 // 0 beshort 0xffd8 JPEG image data
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
420 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
426 $fp = @fopen
($icon_file, "w");
429 fwrite($fp, $contents);
431 chmod($icon_file, 0644);
438 function print_select($id, $default, $values, $attributes = "") {
439 print "<select name=\"$id\" id=\"$id\" $attributes>";
440 foreach ($values as $v) {
442 $sel = "selected=\"1\"";
446 print "<option value=\"$v\" $sel>$v</option>";
451 function print_select_hash($id, $default, $values, $attributes = "") {
452 print "<select name=\"$id\" id='$id' $attributes>";
453 foreach (array_keys($values) as $v) {
455 $sel = 'selected="selected"';
459 print "<option $sel value=\"$v\">".$values[$v]."</option>";
465 function getmicrotime() {
466 list($usec, $sec) = explode(" ",microtime());
467 return ((float)$usec +
(float)$sec);
470 function print_radio($id, $default, $true_is, $values, $attributes = "") {
471 foreach ($values as $v) {
478 if ($v == $true_is) {
479 $sel .= " value=\"1\"";
481 $sel .= " value=\"0\"";
484 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
485 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
490 function initialize_user_prefs($link, $uid, $profile = false) {
492 $uid = db_escape_string($uid);
496 $profile_qpart = "AND profile IS NULL";
498 $profile_qpart = "AND profile = '$profile'";
501 if (get_schema_version($link) < 63) $profile_qpart = "";
503 db_query($link, "BEGIN");
505 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
507 $u_result = db_query($link, "SELECT pref_name
508 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
510 $active_prefs = array();
512 while ($line = db_fetch_assoc($u_result)) {
513 array_push($active_prefs, $line["pref_name"]);
516 while ($line = db_fetch_assoc($result)) {
517 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
518 // print "adding " . $line["pref_name"] . "<br>";
520 if (get_schema_version($link) < 63) {
521 db_query($link, "INSERT INTO ttrss_user_prefs
522 (owner_uid,pref_name,value) VALUES
523 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
526 db_query($link, "INSERT INTO ttrss_user_prefs
527 (owner_uid,pref_name,value, profile) VALUES
528 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
534 db_query($link, "COMMIT");
538 function get_ssl_certificate_id() {
539 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
540 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
541 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
542 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
543 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
548 function authenticate_user($link, $login, $password, $check_only = false) {
550 if (!SINGLE_USER_MODE
) {
553 $modules = explode(",", AUTH_MODULES
);
555 foreach ($modules as $module) {
556 $module_class = "auth_$module";
557 if (class_exists($module_class)) {
558 $authenticator = new $module_class($link);
560 $user_id = (int) $authenticator->authenticate($login, $password);
563 $_SESSION["auth_module"] = $module;
568 print T_sprintf("Fatal: authentication module %s not found.", $module);
573 if ($user_id && !$check_only) {
574 $_SESSION["uid"] = $user_id;
576 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
577 WHERE id = '$user_id'");
579 $_SESSION["name"] = db_fetch_result($result, 0, "login");
580 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
581 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
583 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
586 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
587 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
589 $_SESSION["last_version_check"] = time();
591 initialize_user_prefs($link, $_SESSION["uid"]);
600 $_SESSION["uid"] = 1;
601 $_SESSION["name"] = "admin";
602 $_SESSION["access_level"] = 10;
604 $_SESSION["hide_hello"] = true;
605 $_SESSION["hide_logout"] = true;
607 $_SESSION["auth_module"] = false;
609 if (!$_SESSION["csrf_token"]) {
610 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
613 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
615 initialize_user_prefs($link, $_SESSION["uid"]);
621 function make_password($length = 8) {
624 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
628 while ($i < $length) {
629 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
631 if (!strstr($password, $char)) {
639 // this is called after user is created to initialize default feeds, labels
642 // user preferences are checked on every login, not here
644 function initialize_user($link, $uid) {
646 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
647 values ('$uid', 'Tiny Tiny RSS: New Releases',
648 'http://tt-rss.org/releases.rss')");
650 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
651 values ('$uid', 'Tiny Tiny RSS: Forum',
652 'http://tt-rss.org/forum/rss.php')");
655 function logout_user() {
657 if (isset($_COOKIE[session_name()])) {
658 setcookie(session_name(), '', time()-42000, '/');
662 function validate_csrf($csrf_token) {
663 return $csrf_token == $_SESSION['csrf_token'];
666 function validate_session($link) {
667 if (SINGLE_USER_MODE
) return true;
669 $check_ip = $_SESSION['ip_address'];
671 switch (SESSION_CHECK_ADDRESS
) {
676 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
679 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
680 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
684 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
685 $_SESSION["login_error_msg"] =
686 __("Session failed to validate (incorrect IP)");
690 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
693 if ($_SESSION["uid"]) {
695 $result = db_query($link,
696 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
698 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
700 if ($pwd_hash != $_SESSION["pwd_hash"]) {
705 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
707 //print_r($_SESSION);
709 if (time() > $_SESSION["cookie_lifetime"]) {
717 function login_sequence($link, $login_form = 0) {
718 if (SINGLE_USER_MODE
) {
719 return authenticate_user($link, "admin", null);
721 if (!$_SESSION["uid"] ||
!validate_session($link)) {
723 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
724 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
726 authenticate_user($link, null, null, true);
729 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
732 /* bump login timestamp */
733 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
737 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
738 setcookie("ttrss_lang", $_SESSION["language"],
739 time() + SESSION_COOKIE_LIFETIME
);
744 function truncate_string($str, $max_len, $suffix = '…') {
745 if (mb_strlen($str, "utf-8") > $max_len - 3) {
746 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
752 function theme_image($link, $filename) {
754 $theme_path = get_user_theme_path($link);
756 if ($theme_path && is_file($theme_path.$filename)) {
757 return $theme_path.$filename;
766 function get_user_theme($link) {
768 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
769 $theme_name = get_pref($link, "_THEME_ID");
770 if (is_dir("themes/$theme_name")) {
781 function get_user_theme_path($link) {
784 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
785 $theme_name = get_pref($link, "_THEME_ID");
787 if ($theme_name && is_dir("themes/$theme_name")) {
788 $theme_path = "themes/$theme_name/";
797 if (is_file("$theme_path/theme.ini")) {
798 $ini = parse_ini_file("$theme_path/theme.ini", true);
799 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
807 function get_user_theme_options($link) {
808 $t = get_user_theme_path($link);
811 if (is_file("$t/theme.ini")) {
812 $ini = parse_ini_file("$t/theme.ini", true);
813 if ($ini['theme']['version']) {
814 return $ini['theme']['options'];
821 function print_theme_includes($link) {
823 $t = get_user_theme_path($link);
827 print "<link rel=\"stylesheet\" type=\"text/css\"
828 href=\"$t/theme.css?$time \">";
829 if (file_exists("$t/theme.js")) {
830 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
836 function get_all_themes() {
837 $themes = glob("themes/*");
843 foreach ($themes as $t) {
844 if (is_file("$t/theme.ini")) {
845 $ini = parse_ini_file("$t/theme.ini", true);
846 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
847 !$ini['theme']['disabled']) {
850 $entry["base"] = basename($t);
851 $entry["name"] = $ini['theme']['name'];
852 $entry["version"] = $ini['theme']['version'];
853 $entry["author"] = $ini['theme']['author'];
854 $entry["options"] = $ini['theme']['options'];
855 array_push($rv, $entry);
863 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
866 $source_tz = new DateTimeZone($source_tz);
867 } catch (Exception
$e) {
868 $source_tz = new DateTimeZone('UTC');
872 $dest_tz = new DateTimeZone($dest_tz);
873 } catch (Exception
$e) {
874 $dest_tz = new DateTimeZone('UTC');
877 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
878 return $dt->format('U') +
$dest_tz->getOffset($dt);
881 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
882 $no_smart_dt = false) {
884 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
885 if (!$timestamp) $timestamp = '1970-01-01 0:00';
890 # We store date in UTC internally
891 $dt = new DateTime($timestamp, $utc_tz);
893 if ($tz_offset == -1) {
895 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
898 $user_tz = new DateTimeZone($user_tz_string);
899 } catch (Exception
$e) {
903 $tz_offset = $user_tz->getOffset($dt);
906 $user_timestamp = $dt->format('U') +
$tz_offset;
909 return smart_date_time($link, $user_timestamp,
910 $tz_offset, $owner_uid);
913 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
915 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
917 return date($format, $user_timestamp);
921 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
922 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
924 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
925 return date("G:i", $timestamp);
926 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
927 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
928 return date($format, $timestamp);
930 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
931 return date($format, $timestamp);
935 function sql_bool_to_bool($s) {
936 if ($s == "t" ||
$s == "1" ||
$s == "true") {
943 function bool_to_sql_bool($s) {
951 // Session caching removed due to causing wrong redirects to upgrade
952 // script when get_schema_version() is called on an obsolete session
953 // created on a previous schema version.
954 function get_schema_version($link, $nocache = false) {
955 global $schema_version;
957 if (!$schema_version) {
958 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
959 $version = db_fetch_result($result, 0, "schema_version");
960 $schema_version = $version;
963 return $schema_version;
967 function sanity_check($link) {
968 require_once 'errors.php';
971 $schema_version = get_schema_version($link, true);
973 if ($schema_version != SCHEMA_VERSION
) {
977 if (DB_TYPE
== "mysql") {
978 $result = db_query($link, "SELECT true", false);
979 if (db_num_rows($result) != 1) {
984 if (db_escape_string("testTEST") != "testTEST") {
988 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
991 function file_is_locked($filename) {
992 if (function_exists('flock')) {
993 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
995 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1006 return true; // consider the file always locked and skip the test
1009 function make_lockfile($filename) {
1010 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1012 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1013 if (function_exists('posix_getpid')) {
1014 fwrite($fp, posix_getpid() . "\n");
1022 function make_stampfile($filename) {
1023 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1025 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1026 fwrite($fp, time() . "\n");
1027 flock($fp, LOCK_UN
);
1035 function sql_random_function() {
1036 if (DB_TYPE
== "mysql") {
1043 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1045 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1047 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1049 $ref_check_qpart = ($max_id &&
1050 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1052 if (is_numeric($feed)) {
1058 $children = getChildCategories($link, $feed, $owner_uid);
1059 array_push($children, $feed);
1061 $children = join(",", $children);
1063 $cat_qpart = "cat_id IN ($children)";
1065 $cat_qpart = "cat_id IS NULL";
1068 db_query($link, "UPDATE ttrss_user_entries
1069 SET unread = false,last_read = NOW()
1070 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1071 AND $ref_check_qpart
1072 AND owner_uid = $owner_uid");
1074 } else if ($feed == -2) {
1076 db_query($link, "UPDATE ttrss_user_entries
1077 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1078 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1079 AND $ref_check_qpart
1080 AND unread = true AND owner_uid = $owner_uid");
1083 } else if ($feed > 0) {
1085 db_query($link, "UPDATE ttrss_user_entries
1086 SET unread = false,last_read = NOW()
1087 WHERE feed_id = '$feed'
1088 AND $ref_check_qpart
1089 AND owner_uid = $owner_uid");
1091 } else if ($feed < 0 && $feed > -10) { // special, like starred
1094 db_query($link, "UPDATE ttrss_user_entries
1095 SET unread = false,last_read = NOW()
1097 AND $ref_check_qpart
1098 AND owner_uid = $owner_uid");
1102 db_query($link, "UPDATE ttrss_user_entries
1103 SET unread = false,last_read = NOW()
1104 WHERE published = true
1105 AND $ref_check_qpart
1106 AND owner_uid = $owner_uid");
1111 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1113 if (DB_TYPE
== "pgsql") {
1114 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1116 $match_part = "updated > DATE_SUB(NOW(),
1117 INTERVAL $intl HOUR) ";
1120 $result = db_query($link, "SELECT id FROM ttrss_entries,
1121 ttrss_user_entries WHERE $match_part AND
1123 ttrss_user_entries.ref_id = ttrss_entries.id AND
1124 owner_uid = $owner_uid");
1126 $affected_ids = array();
1128 while ($line = db_fetch_assoc($result)) {
1129 array_push($affected_ids, $line["id"]);
1132 catchupArticlesById($link, $affected_ids, 0);
1136 db_query($link, "UPDATE ttrss_user_entries
1137 SET unread = false,last_read = NOW()
1138 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1141 } else if ($feed < -10) { // label
1143 $label_id = -$feed - 11;
1145 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1146 SET unread = false, last_read = NOW()
1147 WHERE label_id = '$label_id' AND unread = true
1148 AND $ref_check_qpart
1149 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1153 ccache_update($link, $feed, $owner_uid, $cat_view);
1156 db_query($link, "BEGIN");
1158 $tag_name = db_escape_string($feed);
1160 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1161 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1163 while ($line = db_fetch_assoc($result)) {
1164 db_query($link, "UPDATE ttrss_user_entries SET
1165 unread = false, last_read = NOW()
1166 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1168 db_query($link, "COMMIT");
1172 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1174 if (!$omode) $omode = "flc";
1176 $data = getGlobalCounters($link);
1178 $data = array_merge($data, getVirtCounters($link));
1180 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1181 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1182 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1183 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1188 function getCategoryTitle($link, $cat_id) {
1190 if ($cat_id == -1) {
1191 return __("Special");
1192 } else if ($cat_id == -2) {
1193 return __("Labels");
1196 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1199 if (db_num_rows($result) == 1) {
1200 return db_fetch_result($result, 0, "title");
1202 return __("Uncategorized");
1208 function getCategoryCounters($link) {
1211 /* Labels category */
1213 $cv = array("id" => -2, "kind" => "cat",
1214 "counter" => getCategoryUnread($link, -2));
1216 array_push($ret_arr, $cv);
1218 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1219 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1220 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1221 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1222 WHERE ttrss_cat_counters_cache.feed_id = id AND
1223 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1224 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1226 while ($line = db_fetch_assoc($result)) {
1227 $line["cat_id"] = (int) $line["cat_id"];
1229 if ($line["num_children"] > 0) {
1230 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1235 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1236 "counter" => $line["unread"] +
$child_counter);
1238 array_push($ret_arr, $cv);
1241 /* Special case: NULL category doesn't actually exist in the DB */
1243 $cv = array("id" => 0, "kind" => "cat",
1244 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1246 array_push($ret_arr, $cv);
1251 // only accepts real cats (>= 0)
1252 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1253 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1255 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1256 AND owner_uid = $owner_uid");
1260 while ($line = db_fetch_assoc($result)) {
1261 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1262 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1268 function getCategoryUnread($link, $cat, $owner_uid = false) {
1270 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1275 $cat_query = "cat_id = '$cat'";
1277 $cat_query = "cat_id IS NULL";
1280 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1281 AND owner_uid = " . $owner_uid);
1283 $cat_feeds = array();
1284 while ($line = db_fetch_assoc($result)) {
1285 array_push($cat_feeds, "feed_id = " . $line["id"]);
1288 if (count($cat_feeds) == 0) return 0;
1290 $match_part = implode(" OR ", $cat_feeds);
1292 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1293 FROM ttrss_user_entries
1294 WHERE unread = true AND ($match_part)
1295 AND owner_uid = " . $owner_uid);
1299 # this needs to be rewritten
1300 while ($line = db_fetch_assoc($result)) {
1301 $unread +
= $line["unread"];
1305 } else if ($cat == -1) {
1306 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1307 } else if ($cat == -2) {
1309 $result = db_query($link, "
1310 SELECT COUNT(unread) AS unread FROM
1311 ttrss_user_entries, ttrss_user_labels2
1312 WHERE article_id = ref_id AND unread = true
1313 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1315 $unread = db_fetch_result($result, 0, "unread");
1322 function getFeedUnread($link, $feed, $is_cat = false) {
1323 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1326 function getLabelUnread($link, $label_id, $owner_uid = false) {
1327 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1329 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1330 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1332 if (db_num_rows($result) != 0) {
1333 return db_fetch_result($result, 0, "unread");
1339 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1340 $owner_uid = false) {
1342 $n_feed = (int) $feed;
1343 $need_entries = false;
1345 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1348 $unread_qpart = "unread = true";
1350 $unread_qpart = "true";
1354 return getCategoryUnread($link, $n_feed, $owner_uid);
1355 } else if ($n_feed == -6) {
1357 } else if ($feed != "0" && $n_feed == 0) {
1359 $feed = db_escape_string($feed);
1361 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1362 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1363 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1364 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1365 return db_fetch_result($result, 0, "count");
1367 } else if ($n_feed == -1) {
1368 $match_part = "marked = true";
1369 } else if ($n_feed == -2) {
1370 $match_part = "published = true";
1371 } else if ($n_feed == -3) {
1372 $match_part = "unread = true AND score >= 0";
1374 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1376 if (DB_TYPE
== "pgsql") {
1377 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1379 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1382 $need_entries = true;
1384 } else if ($n_feed == -4) {
1385 $match_part = "true";
1386 } else if ($n_feed >= 0) {
1389 $match_part = "feed_id = '$n_feed'";
1391 $match_part = "feed_id IS NULL";
1394 } else if ($feed < -10) {
1396 $label_id = -$feed - 11;
1398 return getLabelUnread($link, $label_id, $owner_uid);
1404 if ($need_entries) {
1405 $from_qpart = "ttrss_user_entries,ttrss_entries";
1406 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1408 $from_qpart = "ttrss_user_entries";
1411 $query = "SELECT count(int_id) AS unread
1412 FROM $from_qpart WHERE
1413 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1415 //echo "[$feed/$query]\n";
1417 $result = db_query($link, $query);
1421 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1422 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1423 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1424 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1427 $unread = db_fetch_result($result, 0, "unread");
1432 function getGlobalUnread($link, $user_id = false) {
1435 $user_id = $_SESSION["uid"];
1438 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1439 WHERE owner_uid = '$user_id' AND feed_id > 0");
1441 $c_id = db_fetch_result($result, 0, "c_id");
1446 function getGlobalCounters($link, $global_unread = -1) {
1449 if ($global_unread == -1) {
1450 $global_unread = getGlobalUnread($link);
1453 $cv = array("id" => "global-unread",
1454 "counter" => (int) $global_unread);
1456 array_push($ret_arr, $cv);
1458 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1459 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1461 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1463 $cv = array("id" => "subscribed-feeds",
1464 "counter" => (int) $subscribed_feeds);
1466 array_push($ret_arr, $cv);
1471 function getTagCounters($link) {
1475 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1476 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1477 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1478 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1479 ORDER BY count DESC LIMIT 55");
1483 while ($line = db_fetch_assoc($result)) {
1484 $tags[$line["tag_name"]] +
= $line["count"];
1487 foreach (array_keys($tags) as $tag) {
1488 $unread = $tags[$tag];
1489 $tag = htmlspecialchars($tag);
1491 $cv = array("id" => $tag,
1493 "counter" => $unread);
1495 array_push($ret_arr, $cv);
1501 function getVirtCounters($link) {
1505 for ($i = 0; $i >= -4; $i--) {
1507 $count = getFeedUnread($link, $i);
1509 $cv = array("id" => $i,
1510 "counter" => (int) $count);
1512 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1513 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1515 array_push($ret_arr, $cv);
1521 function getLabelCounters($link, $descriptions = false) {
1525 $owner_uid = $_SESSION["uid"];
1527 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1528 WHERE owner_uid = '$owner_uid'");
1530 while ($line = db_fetch_assoc($result)) {
1532 $id = -$line["id"] - 11;
1534 $label_name = $line["caption"];
1535 $count = getFeedUnread($link, $id);
1537 $cv = array("id" => $id,
1538 "counter" => (int) $count);
1541 $cv["description"] = $label_name;
1543 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1544 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1546 array_push($ret_arr, $cv);
1552 function getFeedCounters($link, $active_feed = false) {
1556 $query = "SELECT ttrss_feeds.id,
1558 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1559 last_error, value AS count
1560 FROM ttrss_feeds, ttrss_counters_cache
1561 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1562 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1563 AND ttrss_counters_cache.feed_id = id";
1565 $result = db_query($link, $query);
1566 $fctrs_modified = false;
1568 while ($line = db_fetch_assoc($result)) {
1571 $count = $line["count"];
1572 $last_error = htmlspecialchars($line["last_error"]);
1574 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1576 $has_img = feed_has_icon($id);
1578 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1581 $cv = array("id" => $id,
1582 "updated" => $last_updated,
1583 "counter" => (int) $count,
1584 "has_img" => (int) $has_img);
1587 $cv["error"] = $last_error;
1589 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1590 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1592 if ($active_feed && $id == $active_feed)
1593 $cv["title"] = truncate_string($line["title"], 30);
1595 array_push($ret_arr, $cv);
1602 function get_pgsql_version($link) {
1603 $result = db_query($link, "SELECT version() AS version");
1604 $version = explode(" ", db_fetch_result($result, 0, "version"));
1609 * @return array (code => Status code, message => error message if available)
1611 * 0 - OK, Feed already exists
1612 * 1 - OK, Feed added
1614 * 3 - URL content is HTML, no feeds available
1615 * 4 - URL content is HTML which contains multiple feeds.
1616 * Here you should call extractfeedurls in rpc-backend
1617 * to get all possible feeds.
1618 * 5 - Couldn't download the URL content.
1620 function subscribe_to_feed($link, $url, $cat_id = 0,
1621 $auth_login = '', $auth_pass = '', $need_auth = false) {
1623 global $fetch_last_error;
1625 require_once "include/rssfuncs.php";
1627 $url = fix_url($url);
1629 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1633 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1636 return array("code" => 5, "message" => $fetch_last_error);
1639 if (is_html($contents)) {
1640 $feedUrls = get_feeds_from_html($url, $contents);
1642 if (count($feedUrls) == 0) {
1643 return array("code" => 3);
1644 } else if (count($feedUrls) > 1) {
1645 return array("code" => 4, "feeds" => $feedUrls);
1647 //use feed url as new URL
1648 $url = key($feedUrls);
1651 if ($cat_id == "0" ||
!$cat_id) {
1652 $cat_qpart = "NULL";
1654 $cat_qpart = "'$cat_id'";
1657 $result = db_query($link,
1658 "SELECT id FROM ttrss_feeds
1659 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1661 if (db_num_rows($result) == 0) {
1662 $result = db_query($link,
1663 "INSERT INTO ttrss_feeds
1664 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1665 VALUES ('".$_SESSION["uid"]."', '$url',
1666 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1668 $result = db_query($link,
1669 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1670 AND owner_uid = " . $_SESSION["uid"]);
1672 $feed_id = db_fetch_result($result, 0, "id");
1675 update_rss_feed($link, $feed_id, true);
1678 return array("code" => 1);
1680 return array("code" => 0);
1684 function print_feed_select($link, $id, $default_id = "",
1685 $attributes = "", $include_all_feeds = true,
1686 $root_id = false, $nest_level = 0) {
1689 print "<select id=\"$id\" name=\"$id\" $attributes>";
1690 if ($include_all_feeds) {
1691 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1692 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1696 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1699 $parent_qpart = "parent_cat = '$root_id'";
1701 $parent_qpart = "parent_cat IS NULL";
1703 $result = db_query($link, "SELECT id,title,
1704 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1705 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1706 FROM ttrss_feed_categories
1707 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1709 while ($line = db_fetch_assoc($result)) {
1711 for ($i = 0; $i < $nest_level; $i++
)
1712 $line["title"] = " - " . $line["title"];
1714 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1716 printf("<option $is_selected value='CAT:%d'>%s</option>",
1717 $line["id"], htmlspecialchars($line["title"]));
1719 if ($line["num_children"] > 0)
1720 print_feed_select($link, $id, $default_id, $attributes,
1721 $include_all_feeds, $line["id"], $nest_level+
1);
1723 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1724 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1726 while ($fline = db_fetch_assoc($feed_result)) {
1727 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1729 $fline["title"] = " + " . $fline["title"];
1731 for ($i = 0; $i < $nest_level; $i++
)
1732 $fline["title"] = " - " . $fline["title"];
1734 printf("<option $is_selected value='%d'>%s</option>",
1735 $fline["id"], htmlspecialchars($fline["title"]));
1740 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1742 printf("<option $is_selected value='CAT:0'>%s</option>",
1743 __("Uncategorized"));
1745 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1746 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1748 while ($fline = db_fetch_assoc($feed_result)) {
1749 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1751 $fline["title"] = " + " . $fline["title"];
1753 for ($i = 0; $i < $nest_level; $i++
)
1754 $fline["title"] = " - " . $fline["title"];
1756 printf("<option $is_selected value='%d'>%s</option>",
1757 $fline["id"], htmlspecialchars($fline["title"]));
1762 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1763 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1765 while ($line = db_fetch_assoc($result)) {
1767 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1769 printf("<option $is_selected value='%d'>%s</option>",
1770 $line["id"], htmlspecialchars($line["title"]));
1779 function print_feed_cat_select($link, $id, $default_id,
1780 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1783 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1787 $parent_qpart = "parent_cat = '$root_id'";
1789 $parent_qpart = "parent_cat IS NULL";
1791 $result = db_query($link, "SELECT id,title,
1792 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1793 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1794 FROM ttrss_feed_categories
1795 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1797 while ($line = db_fetch_assoc($result)) {
1798 if ($line["id"] == $default_id) {
1799 $is_selected = "selected=\"1\"";
1804 for ($i = 0; $i < $nest_level; $i++
)
1805 $line["title"] = " - " . $line["title"];
1808 printf("<option $is_selected value='%d'>%s</option>",
1809 $line["id"], htmlspecialchars($line["title"]));
1811 if ($line["num_children"] > 0)
1812 print_feed_cat_select($link, $id, $default_id, $attributes,
1813 $include_all_cats, $line["id"], $nest_level+
1);
1817 if ($include_all_cats) {
1818 if (db_num_rows($result) > 0) {
1819 print "<option disabled=\"1\">--------</option>";
1822 if ($default_id == 0) {
1823 $is_selected = "selected=\"1\"";
1828 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1834 function checkbox_to_sql_bool($val) {
1835 return ($val == "on") ?
"true" : "false";
1838 function getFeedCatTitle($link, $id) {
1840 return __("Special");
1841 } else if ($id < -10) {
1842 return __("Labels");
1843 } else if ($id > 0) {
1844 $result = db_query($link, "SELECT ttrss_feed_categories.title
1845 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1846 cat_id = ttrss_feed_categories.id");
1847 if (db_num_rows($result) == 1) {
1848 return db_fetch_result($result, 0, "title");
1850 return __("Uncategorized");
1853 return "getFeedCatTitle($id) failed";
1858 function getFeedIcon($id) {
1861 return "images/archive.png";
1864 return "images/mark_set.png";
1867 return "images/pub_set.png";
1870 return "images/fresh.png";
1873 return "images/tag.png";
1876 return "images/recently_read.png";
1880 return "images/label.png";
1882 if (file_exists(ICONS_DIR
. "/$id.ico"))
1883 return ICONS_URL
. "/$id.ico";
1889 function getFeedTitle($link, $id, $cat = false) {
1891 return getCategoryTitle($link, $id);
1892 } else if ($id == -1) {
1893 return __("Starred articles");
1894 } else if ($id == -2) {
1895 return __("Published articles");
1896 } else if ($id == -3) {
1897 return __("Fresh articles");
1898 } else if ($id == -4) {
1899 return __("All articles");
1900 } else if ($id === 0 ||
$id === "0") {
1901 return __("Archived articles");
1902 } else if ($id == -6) {
1903 return __("Recently read");
1904 } else if ($id < -10) {
1905 $label_id = -$id - 11;
1906 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1907 if (db_num_rows($result) == 1) {
1908 return db_fetch_result($result, 0, "caption");
1910 return "Unknown label ($label_id)";
1913 } else if (is_numeric($id) && $id > 0) {
1914 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1915 if (db_num_rows($result) == 1) {
1916 return db_fetch_result($result, 0, "title");
1918 return "Unknown feed ($id)";
1925 function make_init_params($link) {
1928 $params["theme"] = get_user_theme($link);
1929 $params["theme_options"] = get_user_theme_options($link);
1931 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1932 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1933 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
1934 $params["sign_info"] = theme_image($link, "images/sign_info.png");
1936 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1937 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1938 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1939 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1941 $params[strtolower($param)] = (int) get_pref($link, $param);
1944 $params["icons_url"] = ICONS_URL
;
1945 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1946 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1947 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1948 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1949 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1951 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1952 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1954 $max_feed_id = db_fetch_result($result, 0, "mid");
1955 $num_feeds = db_fetch_result($result, 0, "nf");
1957 $params["max_feed_id"] = (int) $max_feed_id;
1958 $params["num_feeds"] = (int) $num_feeds;
1960 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1962 $params["csrf_token"] = $_SESSION["csrf_token"];
1967 function make_runtime_info($link) {
1970 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1971 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1973 $max_feed_id = db_fetch_result($result, 0, "mid");
1974 $num_feeds = db_fetch_result($result, 0, "nf");
1976 $data["max_feed_id"] = (int) $max_feed_id;
1977 $data["num_feeds"] = (int) $num_feeds;
1979 $data['last_article_id'] = getLastArticleId($link);
1980 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1982 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1984 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1986 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1988 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1991 $stamp_delta = time() - $stamp;
1993 if ($stamp_delta > 1800) {
1997 $_SESSION["daemon_stamp_check"] = time();
2000 $data['daemon_stamp_ok'] = $stamp_check;
2002 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2004 $data['daemon_stamp'] = $stamp_fmt;
2009 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2010 $new_version_details = @check_for_update
($link);
2012 $data['new_version_available'] = (int) ($new_version_details != false);
2014 $_SESSION["last_version_check"] = time();
2015 $_SESSION["version_data"] = $new_version_details;
2021 function search_to_sql($link, $search, $match_on) {
2023 $search_query_part = "";
2025 $keywords = explode(" ", $search);
2026 $query_keywords = array();
2028 foreach ($keywords as $k) {
2029 if (strpos($k, "-") === 0) {
2036 $commandpair = explode(":", mb_strtolower($k), 2);
2038 if ($commandpair[0] == "note" && $commandpair[1]) {
2040 if ($commandpair[1] == "true")
2041 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2043 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2045 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2047 if ($commandpair[1] == "true")
2048 array_push($query_keywords, "($not (marked = true))");
2050 array_push($query_keywords, "($not (marked = false))");
2052 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2054 if ($commandpair[1] == "true")
2055 array_push($query_keywords, "($not (published = true))");
2057 array_push($query_keywords, "($not (published = false))");
2059 } else if (strpos($k, "@") === 0) {
2061 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2062 $orig_ts = strtotime(substr($k, 1));
2063 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2065 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2067 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2068 } else if ($match_on == "both") {
2069 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2070 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2071 } else if ($match_on == "title") {
2072 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2073 } else if ($match_on == "content") {
2074 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2078 $search_query_part = implode("AND", $query_keywords);
2080 return $search_query_part;
2083 function getParentCategories($link, $cat, $owner_uid) {
2086 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2087 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2089 while ($line = db_fetch_assoc($result)) {
2090 array_push($rv, $line["parent_cat"]);
2091 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2097 function getChildCategories($link, $cat, $owner_uid) {
2100 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2101 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2103 while ($line = db_fetch_assoc($result)) {
2104 array_push($rv, $line["id"]);
2105 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2111 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) {
2113 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2115 $ext_tables_part = "";
2119 if (SPHINX_ENABLED
) {
2120 $ids = join(",", @sphinx_search
($search, 0, 500));
2123 $search_query_part = "ref_id IN ($ids) AND ";
2125 $search_query_part = "ref_id = -1 AND ";
2128 $search_query_part = search_to_sql($link, $search, $match_on);
2129 $search_query_part .= " AND ";
2133 $search_query_part = "";
2138 if (DB_TYPE
== "pgsql") {
2139 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2141 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2144 $override_order = "updated DESC";
2146 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2148 // Try to check if SQL regexp implementation chokes on a valid regexp
2149 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2150 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2151 WHERE $filter_query_part LIMIT 1", false);
2153 $test = db_fetch_result($result, 0, "true");
2156 $filter_query_part = "false AND";
2158 $filter_query_part .= " AND";
2162 $filter_query_part = "";
2166 $since_id_part = "ttrss_entries.id > $since_id AND ";
2168 $since_id_part = "";
2171 $view_query_part = "";
2173 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2175 $view_query_part = " ";
2176 } else if ($feed != -1) {
2177 $unread = getFeedUnread($link, $feed, $cat_view);
2179 if ($cat_view && $feed > 0 && $include_children)
2180 $unread +
= getCategoryChildrenUnread($link, $feed);
2183 $view_query_part = " unread = true AND ";
2188 if ($view_mode == "marked") {
2189 $view_query_part = " marked = true AND ";
2192 if ($view_mode == "published") {
2193 $view_query_part = " published = true AND ";
2196 if ($view_mode == "unread") {
2197 $view_query_part = " unread = true AND ";
2200 if ($view_mode == "updated") {
2201 $view_query_part = " (last_read is null and unread = false) AND ";
2205 $limit_query_part = "LIMIT " . $limit;
2208 $allow_archived = false;
2210 $vfeed_query_part = "";
2212 // override query strategy and enable feed display when searching globally
2213 if ($search && $search_mode == "all_feeds") {
2214 $query_strategy_part = "true";
2215 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2217 } else if (!is_numeric($feed)) {
2218 $query_strategy_part = "true";
2219 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2220 id = feed_id) as feed_title,";
2221 } else if ($search && $search_mode == "this_cat") {
2222 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2225 if ($include_children) {
2226 $subcats = getChildCategories($link, $feed, $owner_uid);
2227 array_push($subcats, $feed);
2228 $cats_qpart = join(",", $subcats);
2230 $cats_qpart = $feed;
2233 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2236 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2239 } else if ($feed > 0) {
2244 if ($include_children) {
2246 $subcats = getChildCategories($link, $feed, $owner_uid);
2248 array_push($subcats, $feed);
2249 $query_strategy_part = "cat_id IN (".
2250 implode(",", $subcats).")";
2253 $query_strategy_part = "cat_id = '$feed'";
2257 $query_strategy_part = "cat_id IS NULL";
2260 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2263 $query_strategy_part = "feed_id = '$feed'";
2265 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2266 $query_strategy_part = "feed_id IS NULL";
2267 $allow_archived = true;
2268 } else if ($feed == 0 && $cat_view) { // uncategorized
2269 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2270 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2271 } else if ($feed == -1) { // starred virtual feed
2272 $query_strategy_part = "marked = true";
2273 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2274 $allow_archived = true;
2276 } else if ($feed == -2) { // published virtual feed OR labels category
2279 $query_strategy_part = "published = true";
2280 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2281 $allow_archived = true;
2283 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2285 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2287 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2289 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2290 ttrss_user_labels2.article_id = ref_id";
2293 } else if ($feed == -6) { // recently read
2294 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2295 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2296 $allow_archived = true;
2298 if (!$override_order) $override_order = "last_read DESC";
2299 } else if ($feed == -3) { // fresh virtual feed
2300 $query_strategy_part = "unread = true AND score >= 0";
2302 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2304 if (DB_TYPE
== "pgsql") {
2305 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2307 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2310 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2311 } else if ($feed == -4) { // all articles virtual feed
2312 $query_strategy_part = "true";
2313 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2314 } else if ($feed <= -10) { // labels
2315 $label_id = -$feed - 11;
2317 $query_strategy_part = "label_id = '$label_id' AND
2318 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2319 ttrss_user_labels2.article_id = ref_id";
2321 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2322 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2323 $allow_archived = true;
2326 $query_strategy_part = "true";
2329 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2330 $date_sort_field = "updated";
2332 $date_sort_field = "date_entered";
2335 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2336 $order_by = "$date_sort_field";
2338 $order_by = "$date_sort_field DESC";
2341 if ($view_mode != "noscores") {
2342 $order_by = "score DESC, $order_by";
2345 if ($override_order) {
2346 $order_by = $override_order;
2352 $feed_title = T_sprintf("Search results: %s", $search);
2355 $feed_title = getCategoryTitle($link, $feed);
2357 if (is_numeric($feed) && $feed > 0) {
2358 $result = db_query($link, "SELECT title,site_url,last_error
2359 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2361 $feed_title = db_fetch_result($result, 0, "title");
2362 $feed_site_url = db_fetch_result($result, 0, "site_url");
2363 $last_error = db_fetch_result($result, 0, "last_error");
2365 $feed_title = getFeedTitle($link, $feed);
2370 $content_query_part = "content as content_preview,";
2372 if (is_numeric($feed)) {
2375 $feed_kind = "Feeds";
2377 $feed_kind = "Labels";
2380 if ($limit_query_part) {
2381 $offset_query_part = "OFFSET $offset";
2384 // proper override_order applied above
2385 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2386 if (!$override_order) {
2387 $order_by = "ttrss_feeds.title, $order_by";
2389 $order_by = "ttrss_feeds.title, $override_order";
2393 if (!$allow_archived) {
2394 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2395 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2398 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2399 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2402 $query = "SELECT DISTINCT
2405 ttrss_entries.id,ttrss_entries.title,
2409 always_display_enclosures,
2415 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2416 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2419 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2425 ttrss_user_entries.ref_id = ttrss_entries.id AND
2426 ttrss_user_entries.owner_uid = '$owner_uid' AND
2431 $query_strategy_part ORDER BY $order_by
2432 $limit_query_part $offset_query_part";
2434 if ($_REQUEST["debug"]) print $query;
2436 $result = db_query($link, $query);
2441 $select_qpart = "SELECT DISTINCT " .
2445 "ttrss_entries.id as id," .
2458 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2461 $content_query_part .
2462 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2465 $feed_kind = "Tags";
2466 $all_tags = explode(",", $feed);
2467 if ($search_mode == 'any') {
2468 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2469 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2470 $where_qpart = " WHERE " .
2471 "ref_id = ttrss_entries.id AND " .
2472 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2473 "post_int_id = int_id AND $tag_sql AND " .
2475 $search_query_part .
2476 $query_strategy_part . " ORDER BY $order_by " .
2481 $sub_selects = array();
2482 $sub_ands = array();
2483 foreach ($all_tags as $term) {
2484 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");
2491 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2496 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2497 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2498 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2499 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2501 // error_log("TAG SQL: " . $tag_sql);
2502 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2504 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2505 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2508 return array($result, $feed_title, $feed_site_url, $last_error);
2512 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2513 if (!$owner) $owner = $_SESSION["uid"];
2515 $res = trim($str); if (!$res) return '';
2517 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
2518 $res = htmLawed($res, $config);
2520 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2521 $res = preg_replace('/<img[^>]+>/is', '', $res);
2524 if (strpos($res, "href=") === false)
2525 $res = rewrite_urls($res);
2527 $charset_hack = '<head>
2528 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2531 $res = trim($res); if (!$res) return '';
2533 libxml_use_internal_errors(true);
2535 $doc = new DOMDocument();
2536 $doc->loadHTML($charset_hack . $res);
2537 $xpath = new DOMXPath($doc);
2539 $entries = $xpath->query('(//a[@href]|//img[@src])');
2542 foreach ($entries as $entry) {
2546 if ($entry->hasAttribute('href'))
2547 $entry->setAttribute('href',
2548 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2550 if ($entry->hasAttribute('src'))
2551 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2552 $entry->setAttribute('src',
2553 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2556 if (strtolower($entry->nodeName
) == "a") {
2557 $entry->setAttribute("target", "_blank");
2560 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2561 $br = $doc->createElement("br");
2563 if ($entry->parentNode
->nextSibling
) {
2564 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2571 $node = $doc->getElementsByTagName('body')->item(0);
2573 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2577 * Send by mail a digest of last articles.
2579 * @param mixed $link The database connection.
2580 * @param integer $limit The maximum number of articles by digest.
2581 * @return boolean Return false if digests are not enabled.
2583 function send_headlines_digests($link, $debug = false) {
2585 require_once 'lib/phpmailer/class.phpmailer.php';
2587 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2588 $limit = 1000; // maximum amount of headlines to include
2590 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2592 if (DB_TYPE
== "pgsql") {
2593 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2594 } else if (DB_TYPE
== "mysql") {
2595 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2598 $result = db_query($link, "SELECT id,email FROM ttrss_users
2599 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2601 while ($line = db_fetch_assoc($result)) {
2603 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2604 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2606 // try to send digests within 2 hours of preferred time
2607 if ($preferred_ts && time() >= $preferred_ts &&
2608 time() - $preferred_ts <= 7200) {
2610 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2612 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2616 // reset tz_offset global to prevent tz cache clash between users
2619 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2620 $digest = $tuple[0];
2621 $headlines_count = $tuple[1];
2622 $affected_ids = $tuple[2];
2623 $digest_text = $tuple[3];
2625 if ($headlines_count > 0) {
2627 $mail = new PHPMailer();
2629 $mail->PluginDir
= "lib/phpmailer/";
2630 $mail->SetLanguage("en", "lib/phpmailer/language/");
2632 $mail->CharSet
= "UTF-8";
2634 $mail->From
= SMTP_FROM_ADDRESS
;
2635 $mail->FromName
= SMTP_FROM_NAME
;
2636 $mail->AddAddress($line["email"], $line["login"]);
2639 $mail->Host
= SMTP_HOST
;
2640 $mail->Mailer
= "smtp";
2641 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2642 $mail->Username
= SMTP_LOGIN
;
2643 $mail->Password
= SMTP_PASSWORD
;
2646 $mail->IsHTML(true);
2647 $mail->Subject
= DIGEST_SUBJECT
;
2648 $mail->Body
= $digest;
2649 $mail->AltBody
= $digest_text;
2651 $rc = $mail->Send();
2653 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2655 if ($debug) print "RC=$rc\n";
2657 if ($rc && $do_catchup) {
2658 if ($debug) print "Marking affected articles as read...\n";
2659 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2662 if ($debug) print "No headlines\n";
2665 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2666 WHERE id = " . $line["id"]);
2672 if ($debug) _debug("All done.");
2676 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2678 require_once "lib/MiniTemplator.class.php";
2680 $tpl = new MiniTemplator
;
2681 $tpl_t = new MiniTemplator
;
2683 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2684 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2686 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2687 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2689 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2690 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2692 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2693 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2695 $affected_ids = array();
2697 if (DB_TYPE
== "pgsql") {
2698 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2699 } else if (DB_TYPE
== "mysql") {
2700 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2703 $result = db_query($link, "SELECT ttrss_entries.title,
2704 ttrss_feeds.title AS feed_title,
2705 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2707 ttrss_user_entries.ref_id,
2711 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2713 ttrss_user_entries,ttrss_entries,ttrss_feeds
2715 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2717 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2718 AND include_in_digest = true
2720 AND ttrss_user_entries.owner_uid = $user_id
2723 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2726 $cur_feed_title = "";
2728 $headlines_count = db_num_rows($result);
2730 $headlines = array();
2732 while ($line = db_fetch_assoc($result)) {
2733 array_push($headlines, $line);
2736 for ($i = 0; $i < sizeof($headlines); $i++
) {
2738 $line = $headlines[$i];
2740 array_push($affected_ids, $line["ref_id"]);
2742 $updated = make_local_datetime($link, $line['last_updated'], false,
2745 /* if ($line["score"] != 0) {
2746 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2748 $line["title"] .= " (".$line['score'].")";
2751 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2752 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2755 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2756 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2757 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2758 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2759 $tpl->setVariable('ARTICLE_EXCERPT',
2760 truncate_string(strip_tags($line["content"]), 300));
2761 // $tpl->setVariable('ARTICLE_CONTENT',
2762 // strip_tags($article_content));
2764 $tpl->addBlock('article');
2766 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2767 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2768 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2769 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2770 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2771 // truncate_string(strip_tags($line["excerpt"]), 100));
2773 $tpl_t->addBlock('article');
2775 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2776 $tpl->addBlock('feed');
2777 $tpl_t->addBlock('feed');
2782 $tpl->addBlock('digest');
2783 $tpl->generateOutputToString($tmp);
2785 $tpl_t->addBlock('digest');
2786 $tpl_t->generateOutputToString($tmp_t);
2788 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2791 function check_for_update($link) {
2792 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2793 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2795 $version_data = @fetch_file_contents
($version_url);
2797 if ($version_data) {
2798 $version_data = json_decode($version_data, true);
2799 if ($version_data && $version_data['version']) {
2801 if (version_compare(VERSION
, $version_data['version']) == -1) {
2802 return $version_data;
2810 function markArticlesById($link, $ids, $cmode) {
2814 foreach ($ids as $id) {
2815 array_push($tmp_ids, "ref_id = '$id'");
2818 $ids_qpart = join(" OR ", $tmp_ids);
2821 db_query($link, "UPDATE ttrss_user_entries SET
2822 marked = false,last_read = NOW()
2823 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2824 } else if ($cmode == 1) {
2825 db_query($link, "UPDATE ttrss_user_entries SET
2827 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2829 db_query($link, "UPDATE ttrss_user_entries SET
2830 marked = NOT marked,last_read = NOW()
2831 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2835 function publishArticlesById($link, $ids, $cmode) {
2839 foreach ($ids as $id) {
2840 array_push($tmp_ids, "ref_id = '$id'");
2843 $ids_qpart = join(" OR ", $tmp_ids);
2846 db_query($link, "UPDATE ttrss_user_entries SET
2847 published = false,last_read = NOW()
2848 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2849 } else if ($cmode == 1) {
2850 db_query($link, "UPDATE ttrss_user_entries SET
2851 published = true,last_read = NOW()
2852 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2854 db_query($link, "UPDATE ttrss_user_entries SET
2855 published = NOT published,last_read = NOW()
2856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2859 if (PUBSUBHUBBUB_HUB
) {
2860 $rss_link = get_self_url_prefix() .
2861 "/public.php?op=rss&id=-2&key=" .
2862 get_feed_access_key($link, -2, false);
2864 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2866 $pubsub_result = $p->publish_update($rss_link);
2870 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2872 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2873 if (count($ids) == 0) return;
2877 foreach ($ids as $id) {
2878 array_push($tmp_ids, "ref_id = '$id'");
2881 $ids_qpart = join(" OR ", $tmp_ids);
2884 db_query($link, "UPDATE ttrss_user_entries SET
2885 unread = false,last_read = NOW()
2886 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2887 } else if ($cmode == 1) {
2888 db_query($link, "UPDATE ttrss_user_entries SET
2890 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2892 db_query($link, "UPDATE ttrss_user_entries SET
2893 unread = NOT unread,last_read = NOW()
2894 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2899 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2900 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2902 while ($line = db_fetch_assoc($result)) {
2903 ccache_update($link, $line["feed_id"], $owner_uid);
2907 function catchupArticleById($link, $id, $cmode) {
2910 db_query($link, "UPDATE ttrss_user_entries SET
2911 unread = false,last_read = NOW()
2912 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2913 } else if ($cmode == 1) {
2914 db_query($link, "UPDATE ttrss_user_entries SET
2916 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2918 db_query($link, "UPDATE ttrss_user_entries SET
2919 unread = NOT unread,last_read = NOW()
2920 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2923 $feed_id = getArticleFeed($link, $id);
2924 ccache_update($link, $feed_id, $_SESSION["uid"]);
2927 function make_guid_from_title($title) {
2928 return preg_replace("/[ \"\',.:;]/", "-",
2929 mb_strtolower(strip_tags($title), 'utf-8'));
2932 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2934 $a_id = db_escape_string($id);
2936 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2938 $query = "SELECT DISTINCT tag_name,
2939 owner_uid as owner FROM
2940 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2941 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2943 $obj_id = md5("TAGS:$owner_uid:$id");
2946 /* check cache first */
2948 if ($tag_cache === false) {
2949 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2950 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2952 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2956 $tags = explode(",", $tag_cache);
2959 /* do it the hard way */
2961 $tmp_result = db_query($link, $query);
2963 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2964 array_push($tags, $tmp_line["tag_name"]);
2967 /* update the cache */
2969 $tags_str = db_escape_string(join(",", $tags));
2971 db_query($link, "UPDATE ttrss_user_entries
2972 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2973 AND owner_uid = $owner_uid");
2979 function trim_array($array) {
2981 array_walk($tmp, 'trim');
2985 function tag_is_valid($tag) {
2986 if ($tag == '') return false;
2987 if (preg_match("/^[0-9]*$/", $tag)) return false;
2988 if (mb_strlen($tag) > 250) return false;
2990 if (function_exists('iconv')) {
2991 $tag = iconv("utf-8", "utf-8", $tag);
2994 if (!$tag) return false;
2999 function render_login_form($link, $form_id = 0) {
3002 require_once "login_form.php";
3005 require_once "mobile/login_form.php";
3011 // from http://developer.apple.com/internet/safari/faq.html
3012 function no_cache_incantation() {
3013 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3014 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3015 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3016 header("Cache-Control: post-check=0, pre-check=0", false);
3017 header("Pragma: no-cache"); // HTTP/1.0
3020 function format_warning($msg, $id = "") {
3022 return "<div class=\"warning\" id=\"$id\">
3023 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3026 function format_notice($msg, $id = "") {
3028 return "<div class=\"notice\" id=\"$id\">
3029 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3032 function format_error($msg, $id = "") {
3034 return "<div class=\"error\" id=\"$id\">
3035 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3038 function print_notice($msg) {
3039 return print format_notice($msg);
3042 function print_warning($msg) {
3043 return print format_warning($msg);
3046 function print_error($msg) {
3047 return print format_error($msg);
3051 function T_sprintf() {
3052 $args = func_get_args();
3053 return vsprintf(__(array_shift($args)), $args);
3056 function format_inline_player($link, $url, $ctype) {
3060 if (strpos($ctype, "audio/") === 0) {
3062 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3063 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3064 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3066 $id = 'AUDIO-' . uniqid();
3068 $entry .= "<audio id=\"$id\"\">
3069 <source src=\"$url\"></source>
3072 $entry .= "<span onclick=\"player(this)\"
3073 title=\"".__("Click to play")."\" status=\"0\"
3074 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3078 $entry .= "<object type=\"application/x-shockwave-flash\"
3079 data=\"lib/button/musicplayer.swf?song_url=$url\"
3080 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3081 <param name=\"movie\"
3082 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3087 $filename = substr($url, strrpos($url, "/")+
1);
3089 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3090 $filename . " (" . $ctype . ")" . "</a>";
3095 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3096 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3102 /* we can figure out feed_id from article id anyway, why do we
3103 * pass feed_id here? let's ignore the argument :( */
3105 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3106 WHERE ref_id = '$id'");
3108 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3110 $rv['feed_id'] = $feed_id;
3112 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3114 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3115 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3117 if (db_num_rows($result) == 1) {
3118 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3119 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3121 $rtl_content = false;
3122 $always_display_enclosures = false;
3126 $rtl_tag = "dir=\"RTL\"";
3133 if ($mark_as_read) {
3134 $result = db_query($link, "UPDATE ttrss_user_entries
3135 SET unread = false,last_read = NOW()
3136 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3138 ccache_update($link, $feed_id, $owner_uid);
3141 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3142 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3143 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3144 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3150 FROM ttrss_entries,ttrss_user_entries
3151 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3155 $line = db_fetch_assoc($result);
3157 if ($line["icon_url"]) {
3158 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3160 $feed_icon = " ";
3163 $feed_site_url = $line['site_url'];
3165 $num_comments = $line["num_comments"];
3166 $entry_comments = "";
3168 if ($num_comments > 0) {
3169 if ($line["comments"]) {
3170 $comments_url = htmlspecialchars($line["comments"]);
3172 $comments_url = htmlspecialchars($line["link"]);
3174 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3176 if ($line["comments"] && $line["link"] != $line["comments"]) {
3177 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
3182 header("Content-Type: text/html");
3183 $rv['content'] .= "<html><head>
3184 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3185 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3186 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3190 $title_escaped = htmlspecialchars($line['title']);
3192 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3193 truncate_string(strip_tags($line['title']), 15) . "</div>";
3195 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3196 strip_tags($line['title']) . "</div>";
3198 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3200 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3201 class=\"postHeader\" id=\"POSTHDR-$id\">";
3203 $entry_author = $line["author"];
3205 if ($entry_author) {
3206 $entry_author = __(" - ") . $entry_author;
3209 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3212 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3214 if ($line["link"]) {
3215 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3216 title=\"".htmlspecialchars($line['title'])."\"
3218 htmlspecialchars($line["link"]) . "\">" .
3220 "<span class='author'>$entry_author</span></a></div>";
3222 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3225 $tag_cache = $line["tag_cache"];
3228 $tags = get_article_tags($link, $id, $owner_uid);
3230 $tags = explode(",", $tag_cache);
3232 $tags_str = format_tags_string($tags, $id);
3233 $tags_str_full = join(", ", $tags);
3235 if (!$tags_str_full) $tags_str_full = __("no tags");
3237 if (!$entry_comments) $entry_comments = " "; # placeholder
3239 $rv['content'] .= "<div class='postTags' style='float : right'>
3240 <img src='".theme_image($link, 'images/tag.png')."'
3241 class='tagsPic' alt='Tags' title='Tags'> ";
3244 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3245 <a title=\"".__('Edit tags for this article')."\"
3246 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3248 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3249 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3250 position=\"below\">$tags_str_full</div>";
3252 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3253 class='tagsPic' style=\"cursor : pointer\"
3254 onclick=\"postOpenInNewTab(event, $id)\"
3255 alt='Zoom' title='".__('Open article in new tab')."'>";
3257 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3259 foreach ($button_plugins as $p) {
3260 $pclass = "button_" . trim($p);
3262 if (class_exists($pclass)) {
3263 $plugin = new $pclass($link);
3264 $rv['content'] .= $plugin->render($id, $line);
3268 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3269 class='tagsPic' style=\"cursor : pointer\"
3270 onclick=\"closeArticlePanel($id)\"
3271 title='".__('Close article')."'>";
3274 $tags_str = strip_tags($tags_str);
3275 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3277 $rv['content'] .= "</div>";
3278 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3280 if ($line["orig_feed_id"]) {
3282 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3283 WHERE id = ".$line["orig_feed_id"]);
3285 if (db_num_rows($tmp_result) != 0) {
3287 $rv['content'] .= "<div clear='both'>";
3288 $rv['content'] .= __("Originally from:");
3290 $rv['content'] .= " ";
3292 $tmp_line = db_fetch_assoc($tmp_result);
3294 $rv['content'] .= "<a target='_blank'
3295 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3296 $tmp_line['title'] . "</a>";
3298 $rv['content'] .= " ";
3300 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3301 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3303 $rv['content'] .= "</div>";
3307 $rv['content'] .= "</div>";
3309 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3310 if ($line['note']) {
3311 $rv['content'] .= format_article_note($id, $line['note']);
3313 $rv['content'] .= "</div>";
3315 $rv['content'] .= "<div class=\"postIcon\">" .
3316 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3317 href=\"".htmlspecialchars($feed_site_url)."\">".
3318 $feed_icon . "</a></div>";
3320 $rv['content'] .= "<div class=\"postContent\">";
3324 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3326 $ngram_result = db_query($link, "SELECT id,title FROM
3327 ttrss_entries,ttrss_user_entries
3328 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3329 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3330 AND title != '$title_escaped'
3331 AND owner_uid = $owner_uid");
3333 if (db_num_rows($ngram_result) > 0) {
3334 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3335 "<span>" . __('Related')."</span>";
3336 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3338 while ($nline = db_fetch_assoc($ngram_result)) {
3339 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3340 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3343 $rv['content'] .= "</div></div><br/";
3347 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3350 $rv['content'] .= $article_content;
3352 $rv['content'] .= format_article_enclosures($link, $id,
3353 $always_display_enclosures, $article_content);
3355 $rv['content'] .= "</div>";
3357 $rv['content'] .= "</div>";
3363 <div style=\"text-align : center\">
3364 <button onclick=\"return window.close()\">".
3365 __("Close this window")."</button></div>";
3366 $rv['content'] .= "</body></html>";
3373 function print_checkpoint($n, $s) {
3374 $ts = getmicrotime();
3375 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3379 function sanitize_tag($tag) {
3382 $tag = mb_strtolower($tag, 'utf-8');
3384 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3386 // $tag = str_replace('"', "", $tag);
3387 // $tag = str_replace("+", " ", $tag);
3388 $tag = str_replace("technorati tag: ", "", $tag);
3393 function get_self_url_prefix() {
3394 return SELF_URL_PATH
;
3397 function opml_publish_url($link){
3399 $url_path = get_self_url_prefix();
3400 $url_path .= "/opml.php?op=publish&key=" .
3401 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3407 * Purge a feed contents, marked articles excepted.
3409 * @param mixed $link The database connection.
3410 * @param integer $id The id of the feed to purge.
3413 function clear_feed_articles($link, $id) {
3416 $result = db_query($link, "DELETE FROM ttrss_user_entries
3417 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3419 $result = db_query($link, "DELETE FROM ttrss_user_entries
3420 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3423 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3424 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3426 ccache_update($link, $id, $_SESSION['uid']);
3427 } // function clear_feed_articles
3430 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3432 * @return string The Mozilla Firefox feed adding URL.
3434 function add_feed_url() {
3435 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3437 $url_path = get_self_url_prefix() .
3438 "/public.php?op=subscribe&feed_url=%s";
3440 } // function add_feed_url
3442 function encrypt_password($pass, $salt = '', $mode2 = false) {
3443 if ($salt && $mode2) {
3444 return "MODE2:" . hash('sha256', $salt . $pass);
3446 return "SHA1X:" . sha1("$salt:$pass");
3448 return "SHA1:" . sha1($pass);
3450 } // function encrypt_password
3452 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3455 $cat_id = (int)getFeedCategory($link, $feed_id);
3457 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3458 owner_uid = $owner_uid AND enabled = true");
3460 $check_cats = join(",", array_merge(
3461 getParentCategories($link, $cat_id, $owner_uid),
3464 while ($line = db_fetch_assoc($result)) {
3465 $filter_id = $line["id"];
3467 $result2 = db_query($link, "SELECT
3468 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3469 FROM ttrss_filters2_rules AS r,
3470 ttrss_filter_types AS t
3472 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3473 (feed_id IS NULL OR feed_id = '$feed_id') AND
3474 filter_type = t.id AND filter_id = '$filter_id'");
3479 while ($rule_line = db_fetch_assoc($result2)) {
3480 # print_r($rule_line);
3483 $rule["reg_exp"] = $rule_line["reg_exp"];
3484 $rule["type"] = $rule_line["type_name"];
3486 array_push($rules, $rule);
3489 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3490 FROM ttrss_filters2_actions AS a,
3491 ttrss_filter_actions AS t
3493 action_id = t.id AND filter_id = '$filter_id'");
3495 while ($action_line = db_fetch_assoc($result2)) {
3496 # print_r($action_line);
3499 $action["type"] = $action_line["type_name"];
3500 $action["param"] = $action_line["action_param"];
3502 array_push($actions, $action);
3507 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3508 $filter["rules"] = $rules;
3509 $filter["actions"] = $actions;
3511 if (count($rules) > 0 && count($actions) > 0) {
3512 array_push($filters, $filter);
3519 function get_score_pic($score) {
3521 return "score_high.png";
3522 } else if ($score > 0) {
3523 return "score_half_high.png";
3524 } else if ($score < -100) {
3525 return "score_low.png";
3526 } else if ($score < 0) {
3527 return "score_half_low.png";
3529 return "score_neutral.png";
3533 function feed_has_icon($id) {
3534 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3537 function init_connection($link) {
3540 if (DB_TYPE
== "pgsql") {
3541 pg_query($link, "set client_encoding = 'UTF-8'");
3542 pg_set_client_encoding("UNICODE");
3543 pg_query($link, "set datestyle = 'ISO, european'");
3544 pg_query($link, "set TIME ZONE 0");
3546 db_query($link, "SET time_zone = '+0:0'");
3548 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3549 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3554 print "Unable to connect to database:" . db_last_error();
3559 /* function ccache_zero($link, $feed_id, $owner_uid) {
3560 db_query($link, "UPDATE ttrss_counters_cache SET
3561 value = 0, updated = NOW() WHERE
3562 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3565 function ccache_zero_all($link, $owner_uid) {
3566 db_query($link, "UPDATE ttrss_counters_cache SET
3567 value = 0 WHERE owner_uid = '$owner_uid'");
3569 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3570 value = 0 WHERE owner_uid = '$owner_uid'");
3573 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3576 $table = "ttrss_counters_cache";
3578 $table = "ttrss_cat_counters_cache";
3581 db_query($link, "DELETE FROM $table WHERE
3582 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3586 function ccache_update_all($link, $owner_uid) {
3588 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3590 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3591 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3593 while ($line = db_fetch_assoc($result)) {
3594 ccache_update($link, $line["feed_id"], $owner_uid, true);
3597 /* We have to manually include category 0 */
3599 ccache_update($link, 0, $owner_uid, true);
3602 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3603 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3605 while ($line = db_fetch_assoc($result)) {
3606 print ccache_update($link, $line["feed_id"], $owner_uid);
3613 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3614 $no_update = false) {
3616 if (!is_numeric($feed_id)) return;
3619 $table = "ttrss_counters_cache";
3621 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3622 WHERE id = '$feed_id'");
3623 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3626 $table = "ttrss_cat_counters_cache";
3629 if (DB_TYPE
== "pgsql") {
3630 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3631 } else if (DB_TYPE
== "mysql") {
3632 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3635 $result = db_query($link, "SELECT value FROM $table
3636 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3639 if (db_num_rows($result) == 1) {
3640 return db_fetch_result($result, 0, "value");
3645 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3651 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3652 $update_pcat = true) {
3654 if (!is_numeric($feed_id)) return;
3656 if (!$is_cat && $feed_id > 0) {
3657 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3658 WHERE id = '$feed_id'");
3659 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3662 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3664 /* When updating a label, all we need to do is recalculate feed counters
3665 * because labels are not cached */
3668 ccache_update_all($link, $owner_uid);
3673 $table = "ttrss_counters_cache";
3675 $table = "ttrss_cat_counters_cache";
3678 if ($is_cat && $feed_id >= 0) {
3679 if ($feed_id != 0) {
3680 $cat_qpart = "cat_id = '$feed_id'";
3682 $cat_qpart = "cat_id IS NULL";
3685 /* Recalculate counters for child feeds */
3687 $result = db_query($link, "SELECT id FROM ttrss_feeds
3688 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3690 while ($line = db_fetch_assoc($result)) {
3691 ccache_update($link, $line["id"], $owner_uid, false, false);
3694 $result = db_query($link, "SELECT SUM(value) AS sv
3695 FROM ttrss_counters_cache, ttrss_feeds
3696 WHERE id = feed_id AND $cat_qpart AND
3697 ttrss_feeds.owner_uid = '$owner_uid'");
3699 $unread = (int) db_fetch_result($result, 0, "sv");
3702 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3705 db_query($link, "BEGIN");
3707 $result = db_query($link, "SELECT feed_id FROM $table
3708 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3710 if (db_num_rows($result) == 1) {
3711 db_query($link, "UPDATE $table SET
3712 value = '$unread', updated = NOW() WHERE
3713 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3716 db_query($link, "INSERT INTO $table
3717 (feed_id, value, owner_uid, updated)
3719 ($feed_id, $unread, $owner_uid, NOW())");
3722 db_query($link, "COMMIT");
3724 if ($feed_id > 0 && $prev_unread != $unread) {
3728 /* Update parent category */
3732 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3733 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3735 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3737 ccache_update($link, $cat_id, $owner_uid, true);
3741 } else if ($feed_id < 0) {
3742 ccache_update_all($link, $owner_uid);
3748 /* function ccache_cleanup($link, $owner_uid) {
3750 if (DB_TYPE == "pgsql") {
3751 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3752 (SELECT count(*) FROM ttrss_counters_cache AS c2
3753 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3754 AND owner_uid = '$owner_uid'");
3756 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3757 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3758 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3759 AND owner_uid = '$owner_uid'");
3761 db_query($link, "DELETE c1 FROM
3762 ttrss_counters_cache AS c1,
3763 ttrss_counters_cache AS c2
3765 c1.owner_uid = '$owner_uid' AND
3766 c1.owner_uid = c2.owner_uid AND
3767 c1.feed_id = c2.feed_id");
3769 db_query($link, "DELETE c1 FROM
3770 ttrss_cat_counters_cache AS c1,
3771 ttrss_cat_counters_cache AS c2
3773 c1.owner_uid = '$owner_uid' AND
3774 c1.owner_uid = c2.owner_uid AND
3775 c1.feed_id = c2.feed_id");
3780 function label_find_id($link, $label, $owner_uid) {
3781 $result = db_query($link,
3782 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3783 AND owner_uid = '$owner_uid' LIMIT 1");
3785 if (db_num_rows($result) == 1) {
3786 return db_fetch_result($result, 0, "id");
3792 function get_article_labels($link, $id, $owner_uid = false) {
3795 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3797 $result = db_query($link, "SELECT label_cache FROM
3798 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3801 if (db_num_rows($result) > 0) {
3802 $label_cache = db_fetch_result($result, 0, "label_cache");
3805 $label_cache = json_decode($label_cache, true);
3807 if ($label_cache["no-labels"] == 1)
3810 return $label_cache;
3814 $result = db_query($link,
3815 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3816 FROM ttrss_labels2, ttrss_user_labels2
3818 AND article_id = '$id'
3819 AND owner_uid = ". $owner_uid . "
3822 while ($line = db_fetch_assoc($result)) {
3823 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3825 array_push($rv, $rk);
3829 label_update_cache($link, $owner_uid, $id, $rv);
3831 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3837 function label_find_caption($link, $label, $owner_uid) {
3838 $result = db_query($link,
3839 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3840 AND owner_uid = '$owner_uid' LIMIT 1");
3842 if (db_num_rows($result) == 1) {
3843 return db_fetch_result($result, 0, "caption");
3849 function get_all_labels($link, $owner_uid) {
3852 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3854 while ($line = db_fetch_assoc($result)) {
3855 array_push($rv, $line);
3861 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3864 label_clear_cache($link, $id);
3867 $labels = get_article_labels($link, $id);
3869 $labels = db_escape_string(json_encode($labels));
3871 db_query($link, "UPDATE ttrss_user_entries SET
3872 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3876 function label_clear_cache($link, $id) {
3878 db_query($link, "UPDATE ttrss_user_entries SET
3879 label_cache = '' WHERE ref_id = '$id'");
3883 function label_remove_article($link, $id, $label, $owner_uid) {
3885 $label_id = label_find_id($link, $label, $owner_uid);
3887 if (!$label_id) return;
3889 $result = db_query($link,
3890 "DELETE FROM ttrss_user_labels2
3892 label_id = '$label_id' AND
3893 article_id = '$id'");
3895 label_clear_cache($link, $id);
3898 function label_add_article($link, $id, $label, $owner_uid) {
3900 $label_id = label_find_id($link, $label, $owner_uid);
3902 if (!$label_id) return;
3904 $result = db_query($link,
3906 article_id FROM ttrss_labels2, ttrss_user_labels2
3909 label_id = '$label_id' AND
3910 article_id = '$id' AND owner_uid = '$owner_uid'
3913 if (db_num_rows($result) == 0) {
3914 db_query($link, "INSERT INTO ttrss_user_labels2
3915 (label_id, article_id) VALUES ('$label_id', '$id')");
3918 label_clear_cache($link, $id);
3922 function label_remove($link, $id, $owner_uid) {
3923 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3925 db_query($link, "BEGIN");
3927 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3930 $caption = db_fetch_result($result, 0, "caption");
3932 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3933 AND owner_uid = " . $owner_uid);
3935 if (db_affected_rows($link, $result) != 0 && $caption) {
3937 /* Remove access key for the label */
3939 $ext_id = -11 - $id;
3941 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3942 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3944 /* Disable filters that reference label being removed */
3946 db_query($link, "UPDATE ttrss_filters SET
3947 enabled = false WHERE action_param = '$caption'
3949 AND owner_uid = " . $owner_uid);
3951 /* Remove cached data */
3953 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3954 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3958 db_query($link, "COMMIT");
3961 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3963 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3965 db_query($link, "BEGIN");
3969 $result = db_query($link, "SELECT id FROM ttrss_labels2
3970 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3972 if (db_num_rows($result) == 0) {
3973 $result = db_query($link,
3974 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3975 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3977 $result = db_affected_rows($link, $result) != 0;
3980 db_query($link, "COMMIT");
3985 function format_tags_string($tags, $id) {
3988 $tags_nolinks_str = "";
3994 $formatted_tags = array();
3996 foreach ($tags as $tag) {
3998 $tag_escaped = str_replace("'", "\\'", $tag);
4000 if (mb_strlen($tag) > 30) {
4001 $tag = truncate_string($tag, 30);
4004 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4006 array_push($formatted_tags, $tag_str);
4008 $tmp_tags_str = implode(", ", $formatted_tags);
4010 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4015 $tags_str = implode(", ", $formatted_tags);
4017 if ($num_tags < count($tags)) {
4018 $tags_str .= ", …";
4021 if ($num_tags == 0) {
4022 $tags_str = __("no tags");
4029 function format_article_labels($labels, $id) {
4033 foreach ($labels as $l) {
4034 $labels_str .= sprintf("<span class='hlLabelRef'
4035 style='color : %s; background-color : %s'>%s</span>",
4036 $l[2], $l[3], $l[1]);
4043 function format_article_note($id, $note) {
4045 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4046 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4047 __('(edit note)')."</div>$note</div>";
4052 function toggle_collapse_cat($link, $cat_id, $mode) {
4054 $mode = bool_to_sql_bool($mode);
4056 db_query($link, "UPDATE ttrss_feed_categories SET
4057 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4064 $pref_name = '_COLLAPSED_SPECIAL';
4067 $pref_name = '_COLLAPSED_LABELS';
4070 $pref_name = '_COLLAPSED_UNCAT';
4076 set_pref($link, $pref_name, 'true');
4078 set_pref($link, $pref_name, 'false');
4084 function remove_feed($link, $id, $owner_uid) {
4088 /* save starred articles in Archived feed */
4090 db_query($link, "BEGIN");
4092 /* prepare feed if necessary */
4094 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4097 if (db_num_rows($result) == 0) {
4098 db_query($link, "INSERT INTO ttrss_archived_feeds
4099 (id, owner_uid, title, feed_url, site_url)
4100 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4104 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4105 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4106 marked = true AND owner_uid = $owner_uid");
4108 /* Remove access key for the feed */
4110 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4111 feed_id = '$id' AND owner_uid = $owner_uid");
4113 /* remove the feed */
4115 db_query($link, "DELETE FROM ttrss_feeds
4116 WHERE id = '$id' AND owner_uid = $owner_uid");
4118 db_query($link, "COMMIT");
4120 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4121 unlink(ICONS_DIR
. "/$id.ico");
4124 ccache_remove($link, $id, $owner_uid);
4127 label_remove($link, -11-$id, $owner_uid);
4128 ccache_remove($link, -11-$id, $owner_uid);
4132 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
4133 if ($parent_cat_id) {
4134 $parent_qpart = "parent_cat = '$parent_cat_id'";
4135 $parent_insert = "'$parent_cat_id'";
4137 $parent_qpart = "parent_cat IS NULL";
4138 $parent_insert = "NULL";
4141 $result = db_query($link,
4142 "SELECT id FROM ttrss_feed_categories
4143 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4145 if (db_num_rows($result) == 0) {
4148 return db_fetch_result($result, 0, "id");
4152 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
4154 if (!$feed_cat) return false;
4156 db_query($link, "BEGIN");
4158 if ($parent_cat_id) {
4159 $parent_qpart = "parent_cat = '$parent_cat_id'";
4160 $parent_insert = "'$parent_cat_id'";
4162 $parent_qpart = "parent_cat IS NULL";
4163 $parent_insert = "NULL";
4166 $result = db_query($link,
4167 "SELECT id FROM ttrss_feed_categories
4168 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4170 if (db_num_rows($result) == 0) {
4172 $result = db_query($link,
4173 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4174 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
4176 db_query($link, "COMMIT");
4184 function remove_feed_category($link, $id, $owner_uid) {
4186 db_query($link, "DELETE FROM ttrss_feed_categories
4187 WHERE id = '$id' AND owner_uid = $owner_uid");
4189 ccache_remove($link, $id, $owner_uid, true);
4192 function archive_article($link, $id, $owner_uid) {
4193 db_query($link, "BEGIN");
4195 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4196 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4198 if (db_num_rows($result) != 0) {
4200 /* prepare the archived table */
4202 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4205 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4206 WHERE id = '$feed_id'");
4208 if (db_num_rows($result) == 0) {
4209 db_query($link, "INSERT INTO ttrss_archived_feeds
4210 (id, owner_uid, title, feed_url, site_url)
4211 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4212 WHERE id = '$feed_id'");
4215 db_query($link, "UPDATE ttrss_user_entries
4216 SET orig_feed_id = feed_id, feed_id = NULL
4217 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4221 db_query($link, "COMMIT");
4224 function getArticleFeed($link, $id) {
4225 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4226 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4228 if (db_num_rows($result) != 0) {
4229 return db_fetch_result($result, 0, "feed_id");
4236 * Fixes incomplete URLs by prepending "http://".
4237 * Also replaces feed:// with http://, and
4238 * prepends a trailing slash if the url is a domain name only.
4240 * @param string $url Possibly incomplete URL
4242 * @return string Fixed URL.
4244 function fix_url($url) {
4245 if (strpos($url, '://') === false) {
4246 $url = 'http://' . $url;
4247 } else if (substr($url, 0, 5) == 'feed:') {
4248 $url = 'http:' . substr($url, 5);
4251 //prepend slash if the URL has no slash in it
4252 // "http://www.example" -> "http://www.example/"
4253 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4257 if ($url != "http:///")
4263 function validate_feed_url($url) {
4264 $parts = parse_url($url);
4266 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4270 function get_article_enclosures($link, $id) {
4272 $query = "SELECT * FROM ttrss_enclosures
4273 WHERE post_id = '$id' AND content_url != ''";
4277 $result = db_query($link, $query);
4279 if (db_num_rows($result) > 0) {
4280 while ($line = db_fetch_assoc($result)) {
4281 array_push($rv, $line);
4288 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4294 if ($cat_id == -4 ||
$cat_id == -2) {
4295 $counters = getLabelCounters($link, true);
4297 foreach (array_values($counters) as $cv) {
4299 $unread = $cv["counter"];
4301 if ($unread ||
!$unread_only) {
4305 "title" => $cv["description"],
4306 "unread" => $cv["counter"],
4310 array_push($feeds, $row);
4317 if ($cat_id == -4 ||
$cat_id == -1) {
4318 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4319 $unread = getFeedUnread($link, $i);
4321 if ($unread ||
!$unread_only) {
4322 $title = getFeedTitle($link, $i);
4327 "unread" => $unread,
4330 array_push($feeds, $row);
4338 if ($include_nested && $cat_id) {
4339 $result = db_query($link, "SELECT
4340 id, title FROM ttrss_feed_categories
4341 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4342 " ORDER BY id, title");
4344 while ($line = db_fetch_assoc($result)) {
4345 $unread = getFeedUnread($link, $line["id"], true) +
4346 getCategoryChildrenUnread($link, $line["id"]);
4348 if ($unread ||
!$unread_only) {
4350 "id" => $line["id"],
4351 "title" => $line["title"],
4352 "unread" => $unread,
4355 array_push($feeds, $row);
4363 $limit_qpart = "LIMIT $limit OFFSET $offset";
4368 if ($cat_id == -4 ||
$cat_id == -3) {
4369 $result = db_query($link, "SELECT
4370 id, feed_url, cat_id, title, order_id, ".
4371 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4372 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4373 " ORDER BY cat_id, title " . $limit_qpart);
4377 $cat_qpart = "cat_id = '$cat_id'";
4379 $cat_qpart = "cat_id IS NULL";
4381 $result = db_query($link, "SELECT
4382 id, feed_url, cat_id, title, order_id, ".
4383 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4384 FROM ttrss_feeds WHERE
4385 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4386 " ORDER BY cat_id, title " . $limit_qpart);
4389 while ($line = db_fetch_assoc($result)) {
4391 $unread = getFeedUnread($link, $line["id"]);
4393 $has_icon = feed_has_icon($line['id']);
4395 if ($unread ||
!$unread_only) {
4398 "feed_url" => $line["feed_url"],
4399 "title" => $line["title"],
4400 "id" => (int)$line["id"],
4401 "unread" => (int)$unread,
4402 "has_icon" => $has_icon,
4403 "cat_id" => (int)$line["cat_id"],
4404 "last_updated" => strtotime($line["last_updated"]),
4405 "order_id" => (int) $line["order_id"],
4408 array_push($feeds, $row);
4415 function api_get_headlines($link, $feed_id, $limit, $offset,
4416 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4417 $include_attachments, $since_id,
4418 $search = "", $search_mode = "", $match_on = "",
4419 $include_nested = false, $sanitize_content = true) {
4421 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4422 $view_mode, $is_cat, $search, $search_mode, $match_on,
4423 $order, $offset, 0, false, $since_id, $include_nested);
4425 $result = $qfh_ret[0];
4426 $feed_title = $qfh_ret[1];
4428 $headlines = array();
4430 while ($line = db_fetch_assoc($result)) {
4431 $is_updated = ($line["last_read"] == "" &&
4432 ($line["unread"] != "t" && $line["unread"] != "1"));
4434 $tags = explode(",", $line["tag_cache"]);
4435 $labels = json_decode($line["label_cache"], true);
4437 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4438 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4440 $headline_row = array(
4441 "id" => (int)$line["id"],
4442 "unread" => sql_bool_to_bool($line["unread"]),
4443 "marked" => sql_bool_to_bool($line["marked"]),
4444 "published" => sql_bool_to_bool($line["published"]),
4445 "updated" => strtotime($line["updated"]),
4446 "is_updated" => $is_updated,
4447 "title" => $line["title"],
4448 "link" => $line["link"],
4449 "feed_id" => $line["feed_id"],
4453 if ($include_attachments)
4454 $headline_row['attachments'] = get_article_enclosures($link,
4457 if ($show_excerpt) {
4458 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4459 $headline_row["excerpt"] = $excerpt;
4462 if ($show_content) {
4463 if ($sanitize_content) {
4464 $headline_row["content"] = sanitize($link,
4465 $line["content_preview"], false, false, $line["site_url"]);
4467 $headline_row["content"] = $line["content_preview"];
4471 // unify label output to ease parsing
4472 if ($labels["no-labels"] == 1) $labels = array();
4474 $headline_row["labels"] = $labels;
4476 $headline_row["feed_title"] = $line["feed_title"];
4478 $headline_row["comments_count"] = (int)$line["num_comments"];
4479 $headline_row["comments_link"] = $line["comments"];
4481 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4483 array_push($headlines, $headline_row);
4489 function generate_error_feed($link, $error) {
4492 $reply['headlines']['id'] = -6;
4493 $reply['headlines']['is_cat'] = false;
4495 $reply['headlines']['toolbar'] = '';
4496 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4498 $reply['headlines-info'] = array("count" => 0,
4499 "vgroup_last_feed" => '',
4501 "disable_cache" => true);
4507 function generate_dashboard_feed($link) {
4510 $reply['headlines']['id'] = -5;
4511 $reply['headlines']['is_cat'] = false;
4513 $reply['headlines']['toolbar'] = '';
4514 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4516 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4518 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4519 WHERE owner_uid = " . $_SESSION['uid']);
4521 $last_updated = db_fetch_result($result, 0, "last_updated");
4522 $last_updated = make_local_datetime($link, $last_updated, false);
4524 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4526 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4527 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4529 $num_errors = db_fetch_result($result, 0, "num_errors");
4531 if ($num_errors > 0) {
4532 $reply['headlines']['content'] .= "<br/>";
4533 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4534 __('Some feeds have update errors (click for details)')."</a>";
4536 $reply['headlines']['content'] .= "</span></p>";
4538 $reply['headlines-info'] = array("count" => 0,
4539 "vgroup_last_feed" => '',
4541 "disable_cache" => true);
4546 function save_email_address($link, $email) {
4547 // FIXME: implement persistent storage of emails
4549 if (!$_SESSION['stored_emails'])
4550 $_SESSION['stored_emails'] = array();
4552 if (!in_array($email, $_SESSION['stored_emails']))
4553 array_push($_SESSION['stored_emails'], $email);
4556 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4557 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4559 $sql_is_cat = bool_to_sql_bool($is_cat);
4561 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4562 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4563 AND owner_uid = " . $owner_uid);
4565 if (db_num_rows($result) == 1) {
4566 $key = db_escape_string(sha1(uniqid(rand(), true)));
4568 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4569 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4570 AND owner_uid = " . $owner_uid);
4575 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4579 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4581 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4583 $sql_is_cat = bool_to_sql_bool($is_cat);
4585 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4586 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4587 AND owner_uid = " . $owner_uid);
4589 if (db_num_rows($result) == 1) {
4590 return db_fetch_result($result, 0, "access_key");
4592 $key = db_escape_string(sha1(uniqid(rand(), true)));
4594 $result = db_query($link, "INSERT INTO ttrss_access_keys
4595 (access_key, feed_id, is_cat, owner_uid)
4596 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4603 function get_feeds_from_html($url, $content)
4605 $url = fix_url($url);
4606 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4608 libxml_use_internal_errors(true);
4610 $doc = new DOMDocument();
4611 $doc->loadHTML($content);
4612 $xpath = new DOMXPath($doc);
4613 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4614 $feedUrls = array();
4615 foreach ($entries as $entry) {
4616 if ($entry->hasAttribute('href')) {
4617 $title = $entry->getAttribute('title');
4619 $title = $entry->getAttribute('type');
4621 $feedUrl = rewrite_relative_url(
4622 $baseUrl, $entry->getAttribute('href')
4624 $feedUrls[$feedUrl] = $title;
4630 function is_html($content) {
4631 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4634 function url_is_html($url, $login = false, $pass = false) {
4635 return is_html(fetch_file_contents($url, false, $login, $pass));
4638 function print_label_select($link, $name, $value, $attributes = "") {
4640 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4641 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4643 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4644 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4646 while ($line = db_fetch_assoc($result)) {
4648 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4650 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4651 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4655 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4662 function format_article_enclosures($link, $id, $always_display_enclosures,
4665 $result = get_article_enclosures($link, $id);
4668 if (count($result) > 0) {
4670 $entries_html = array();
4673 foreach ($result as $line) {
4675 $url = $line["content_url"];
4676 $ctype = $line["content_type"];
4678 if (!$ctype) $ctype = __("unknown type");
4680 $filename = substr($url, strrpos($url, "/")+
1);
4682 # $player = format_inline_player($link, $url, $ctype);
4684 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4685 # $filename . " (" . $ctype . ")" . "</a>";
4687 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4688 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4690 array_push($entries_html, $entry);
4694 $entry["type"] = $ctype;
4695 $entry["filename"] = $filename;
4696 $entry["url"] = $url;
4698 array_push($entries, $entry);
4701 if (!get_pref($link, "STRIP_IMAGES")) {
4702 if ($always_display_enclosures ||
4703 !preg_match("/<img/i", $article_content)) {
4705 foreach ($entries as $entry) {
4707 if (preg_match("/image/", $entry["type"]) ||
4708 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4711 alt=\"".htmlspecialchars($entry["filename"])."\"
4712 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4719 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4720 "<span>" . __('Attachments')."</span>";
4721 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4723 foreach ($entries_html as $entry) { $rv .= $entry; };
4725 $rv .= "</div></div>";
4731 function getLastArticleId($link) {
4732 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4733 WHERE owner_uid = " . $_SESSION["uid"]);
4735 if (db_num_rows($result) == 1) {
4736 return db_fetch_result($result, 0, "id");
4742 function build_url($parts) {
4743 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4747 * Converts a (possibly) relative URL to a absolute one.
4749 * @param string $url Base URL (i.e. from where the document is)
4750 * @param string $rel_url Possibly relative URL in the document
4752 * @return string Absolute URL
4754 function rewrite_relative_url($url, $rel_url) {
4755 if (strpos($rel_url, "magnet:") === 0) {
4757 } else if (strpos($rel_url, "://") !== false) {
4759 } else if (strpos($rel_url, "//") === 0) {
4760 # protocol-relative URL (rare but they exist)
4762 } else if (strpos($rel_url, "/") === 0)
4764 $parts = parse_url($url);
4765 $parts['path'] = $rel_url;
4767 return build_url($parts);
4770 $parts = parse_url($url);
4771 if (!isset($parts['path'])) {
4772 $parts['path'] = '/';
4774 $dir = $parts['path'];
4775 if (substr($dir, -1) !== '/') {
4776 $dir = dirname($parts['path']);
4777 $dir !== '/' && $dir .= '/';
4779 $parts['path'] = $dir . $rel_url;
4781 return build_url($parts);
4785 function sphinx_search($query, $offset = 0, $limit = 30) {
4786 require_once 'lib/sphinxapi.php';
4788 $sphinxClient = new SphinxClient();
4790 $sphinxClient->SetServer('localhost', 9312);
4791 $sphinxClient->SetConnectTimeout(1);
4793 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4794 'feed_title' => 20));
4796 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4797 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4798 $sphinxClient->SetLimits($offset, $limit, 1000);
4799 $sphinxClient->SetArrayResult(false);
4800 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4802 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4806 if (is_array($result['matches'])) {
4807 foreach (array_keys($result['matches']) as $int_id) {
4808 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4809 array_push($ids, $ref_id);
4816 function cleanup_tags($link, $days = 14, $limit = 1000) {
4818 if (DB_TYPE
== "pgsql") {
4819 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4820 } else if (DB_TYPE
== "mysql") {
4821 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4826 while ($limit > 0) {
4829 $query = "SELECT ttrss_tags.id AS id
4830 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4831 WHERE post_int_id = int_id AND $interval_query AND
4832 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4834 $result = db_query($link, $query);
4838 while ($line = db_fetch_assoc($result)) {
4839 array_push($ids, $line['id']);
4842 if (count($ids) > 0) {
4843 $ids = join(",", $ids);
4846 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4847 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4852 $limit -= $limit_part;
4857 return $tags_deleted;
4860 function print_user_stylesheet($link) {
4861 $value = get_pref($link, 'USER_STYLESHEET');
4864 print "<style type=\"text/css\">";
4865 print str_replace("<br/>", "\n", $value);
4871 /* function rewrite_urls($line) {
4876 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4877 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4882 function rewrite_urls($html) {
4883 libxml_use_internal_errors(true);
4885 $charset_hack = '<head>
4886 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4889 $doc = new DOMDocument();
4890 $doc->loadHTML($charset_hack . $html);
4891 $xpath = new DOMXPath($doc);
4893 $entries = $xpath->query('//*/text()');
4895 foreach ($entries as $entry) {
4896 if (strstr($entry->wholeText
, "://") !== false) {
4897 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4898 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4900 if ($text != $entry->wholeText
) {
4901 $cdoc = new DOMDocument();
4902 $cdoc->loadHTML($charset_hack . $text);
4905 foreach ($cdoc->childNodes
as $cnode) {
4906 $cnode = $doc->importNode($cnode, true);
4909 $entry->parentNode
->insertBefore($cnode);
4913 $entry->parentNode
->removeChild($entry);
4919 $node = $doc->getElementsByTagName('body')->item(0);
4921 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4923 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4928 function filter_to_sql($link, $filter, $owner_uid) {
4931 if (DB_TYPE
== "pgsql")
4934 $reg_qpart = "REGEXP";
4936 foreach ($filter["rules"] AS $rule) {
4937 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4938 $rule['reg_exp']) !== FALSE;
4940 if ($regexp_valid) {
4942 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4944 switch ($rule["type"]) {
4946 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4947 $rule['reg_exp'] . "')";
4950 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4951 $rule['reg_exp'] . "')";
4954 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4955 $rule['reg_exp'] . "') OR LOWER(" .
4956 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4959 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4960 $rule['reg_exp'] . "')";
4963 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4964 $rule['reg_exp'] . "')";
4967 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4968 $rule['reg_exp'] . "')";
4972 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4973 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4976 if (isset($rule["cat_id"])) {
4978 if ($rule["cat_id"] > 0) {
4979 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4980 array_push($children, $rule["cat_id"]);
4982 $children = join(",", $children);
4984 $cat_qpart = "cat_id IN ($children)";
4986 $cat_qpart = "cat_id IS NULL";
4989 $qpart .= " AND $cat_qpart";
4992 array_push($query, "($qpart)");
4997 if (count($query) > 0) {
4998 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
5005 // -1 - never connected
5006 // 0 - no data received
5007 // 1 - data received successfully
5008 // 2 - did not receive valid data
5009 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5011 function get_linked_feeds($link, $instance_id = false) {
5013 $instance_qpart = "id = '$instance_id' AND ";
5015 $instance_qpart = "";
5017 if (DB_TYPE
== "pgsql") {
5018 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5020 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5023 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5024 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5026 while ($line = db_fetch_assoc($result)) {
5029 _debug("Updating: " . $line['access_url'] . " ($id)");
5031 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5032 $post_query = 'key=' . $line['access_key'];
5034 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5036 // try doing it the old way
5038 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5039 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5043 $feeds = json_decode($feeds, true);
5046 if ($feeds['error']) {
5047 $status = $feeds['error']['code'] +
10;
5050 if ($status == 16) {
5051 db_query($link, "DELETE FROM ttrss_linked_feeds
5052 WHERE instance_id = '$id'");
5057 if (count($feeds['feeds']) > 0) {
5059 db_query($link, "DELETE FROM ttrss_linked_feeds
5060 WHERE instance_id = '$id'");
5062 foreach ($feeds['feeds'] as $feed) {
5063 $feed_url = db_escape_string($feed['feed_url']);
5064 $title = db_escape_string($feed['title']);
5065 $subscribers = db_escape_string($feed['subscribers']);
5066 $site_url = db_escape_string($feed['site_url']);
5068 db_query($link, "INSERT INTO ttrss_linked_feeds
5069 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5071 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5074 // received 0 feeds, this might indicate that
5075 // the instance on the other hand is rebuilding feedbrowser cache
5076 // we will try again later
5078 // TODO: maybe perform expiration based on updated here?
5081 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5091 _debug("Status: $status");
5093 db_query($link, "UPDATE ttrss_linked_instances SET
5094 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5099 function make_feed_browser($link, $search, $limit, $mode = 1) {
5101 $owner_uid = $_SESSION["uid"];
5105 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5106 UPPER(title) LIKE UPPER('%$search%'))";
5112 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5113 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5114 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5115 AND owner_uid = '$owner_uid') $search_qpart
5116 ORDER BY subscribers DESC LIMIT $limit"); */
5118 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5119 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5120 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5122 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5123 WHERE tf.feed_url = qqq.feed_url
5124 AND owner_uid = '$owner_uid') $search_qpart
5125 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5127 } else if ($mode == 2) {
5128 $result = db_query($link, "SELECT *,
5129 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5130 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5132 ttrss_archived_feeds
5134 (SELECT COUNT(*) FROM ttrss_feeds
5135 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5136 owner_uid = '$owner_uid') = 0 AND
5137 owner_uid = '$owner_uid' $search_qpart
5138 ORDER BY id DESC LIMIT $limit");
5143 while ($line = db_fetch_assoc($result)) {
5147 $feed_url = htmlspecialchars($line["feed_url"]);
5148 $site_url = htmlspecialchars($line["site_url"]);
5149 $subscribers = $line["subscribers"];
5151 $check_box = "<input onclick='toggleSelectListRow2(this)'
5152 dojoType=\"dijit.form.CheckBox\"
5153 type=\"checkbox\" \">";
5155 $class = ($feedctr %
2) ?
"even" : "odd";
5157 $site_url = "<a target=\"_blank\"
5159 <span class=\"fb_feedTitle\">".
5160 htmlspecialchars($line["title"])."</span></a>";
5162 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5163 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5164 style='vertical-align : middle'></a>";
5166 $rv .= "<li>$check_box $feed_url $site_url".
5167 " <span class='subscribers'>($subscribers)</span></li>";
5169 } else if ($mode == 2) {
5170 $feed_url = htmlspecialchars($line["feed_url"]);
5171 $site_url = htmlspecialchars($line["site_url"]);
5172 $title = htmlspecialchars($line["title"]);
5174 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5175 type=\"checkbox\">";
5177 $class = ($feedctr %
2) ?
"even" : "odd";
5179 if ($line['articles_archived'] > 0) {
5180 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5181 $archived = " <span class='subscribers'>($archived)</span>";
5186 $site_url = "<a target=\"_blank\"
5188 <span class=\"fb_feedTitle\">".
5189 htmlspecialchars($line["title"])."</span></a>";
5191 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5192 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5193 style='vertical-align : middle'></a>";
5196 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5197 "$check_box $feed_url $site_url $archived</li>";
5203 if ($feedctr == 0) {
5204 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5210 if (!function_exists('gzdecode')) {
5211 function gzdecode($string) { // no support for 2nd argument
5212 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5213 base64_encode($string));
5217 function perform_data_import($link, $filename, $owner_uid) {
5221 $num_feeds_created = 0;
5223 $doc = @DOMDocument
::load($filename);
5226 $contents = file_get_contents($filename);
5229 $data = @gzuncompress
($contents);
5233 $data = @gzdecode
($contents);
5237 $doc = DOMDocument
::loadXML($data);
5242 $xpath = new DOMXpath($doc);
5244 $container = $doc->firstChild
;
5246 if ($container && $container->hasAttribute('schema-version')) {
5247 $schema_version = $container->getAttribute('schema-version');
5249 if ($schema_version != SCHEMA_VERSION
) {
5250 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5255 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5259 $articles = $xpath->query("//article");
5261 foreach ($articles as $article_node) {
5262 if ($article_node->childNodes
) {
5268 foreach ($article_node->childNodes
as $child) {
5269 if ($child->nodeName
!= 'label_cache')
5270 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5272 $article[$child->nodeName
] = $child->nodeValue
;
5275 //print_r($article);
5277 if ($article['guid']) {
5281 //db_query($link, "BEGIN");
5283 //print 'GUID:' . $article['guid'] . "\n";
5285 $result = db_query($link, "SELECT id FROM ttrss_entries
5286 WHERE guid = '".$article['guid']."'");
5288 if (db_num_rows($result) == 0) {
5290 $result = db_query($link,
5291 "INSERT INTO ttrss_entries
5305 ('".$article['title']."',
5306 '".$article['guid']."',
5307 '".$article['link']."',
5308 '".$article['updated']."',
5309 '".$article['content']."',
5310 '".sha1($article['content'])."',
5318 $result = db_query($link, "SELECT id FROM ttrss_entries
5319 WHERE guid = '".$article['guid']."'");
5321 if (db_num_rows($result) != 0) {
5322 $ref_id = db_fetch_result($result, 0, "id");
5326 $ref_id = db_fetch_result($result, 0, "id");
5329 //print "Got ref ID: $ref_id\n";
5333 $feed_url = $article['feed_url'];
5334 $feed_title = $article['feed_title'];
5338 if ($feed_url && $feed_title) {
5339 $result = db_query($link, "SELECT id FROM ttrss_feeds
5340 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5342 if (db_num_rows($result) != 0) {
5343 $feed = db_fetch_result($result, 0, "id");
5345 // try autocreating feed in Uncategorized...
5347 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5348 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5350 $result = db_query($link, "SELECT id FROM ttrss_feeds
5351 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5353 if (db_num_rows($result) != 0) {
5354 ++
$num_feeds_created;
5356 $feed = db_fetch_result($result, 0, "id");
5361 if ($feed != 'NULL')
5362 $feed_qpart = "feed_id = $feed";
5364 $feed_qpart = "feed_id IS NULL";
5366 //print "$ref_id / $feed / " . $article['title'] . "\n";
5368 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5369 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5371 if (db_num_rows($result) == 0) {
5373 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5374 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5375 $score = (int) $article['score'];
5377 $tag_cache = $article['tag_cache'];
5378 $label_cache = db_escape_string($article['label_cache']);
5379 $note = $article['note'];
5381 //print "Importing " . $article['title'] . "<br/>";
5385 $result = db_query($link,
5386 "INSERT INTO ttrss_user_entries
5387 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5388 published, score, tag_cache, label_cache, uuid, note)
5389 VALUES ($ref_id, $owner_uid, $feed, false,
5390 NULL, $marked, $published, $score, '$tag_cache',
5391 '$label_cache', '', '$note')");
5393 $label_cache = json_decode($label_cache, true);
5395 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5396 foreach ($label_cache as $label) {
5398 label_create($link, $label[1],
5399 $label[2], $label[3], $owner_uid);
5401 label_add_article($link, $ref_id, $label[1], $owner_uid);
5406 //db_query($link, "COMMIT");
5414 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5415 $num_processed, $num_imported, $num_feeds_created) .
5420 print "<p>" . __("Could not load XML document.") . "</p>";
5425 function get_random_bytes($length) {
5426 if (function_exists('openssl_random_pseudo_bytes')) {
5427 return openssl_random_pseudo_bytes($length);
5431 for ($i = 0; $i < $length; $i++
)
5432 $output .= chr(mt_rand(0, 255));
5438 function read_stdin() {
5439 $fp = fopen("php://stdin", "r");
5442 $line = trim(fgets($fp));
5450 function tmpdirname($path, $prefix) {
5451 // Use PHP's tmpfile function to create a temporary
5452 // directory name. Delete the file and keep the name.
5453 $tempname = tempnam($path,$prefix);
5457 if (!unlink($tempname))
5463 function getFeedCategory($link, $feed) {
5464 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5465 WHERE id = '$feed'");
5467 if (db_num_rows($result) > 0) {
5468 return db_fetch_result($result, 0, "cat_id");
5475 function create_published_article($link, $title, $url, $content, $labels_str,
5478 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
5479 $content_hash = sha1($content);
5481 if ($labels_str != "") {
5482 $labels = explode(",", $labels_str);
5489 if (!$title) $title = $url;
5490 if (!$title && !$url) return false;
5492 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
5494 db_query($link, "BEGIN");
5496 // only check for our user data here, others might have shared this with different content etc
5497 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
5498 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
5500 if (db_num_rows($result) != 0) {
5501 $ref_id = db_fetch_result($result, 0, "id");
5503 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
5504 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
5506 if (db_num_rows($result) != 0) {
5507 $int_id = db_fetch_result($result, 0, "int_id");
5509 db_query($link, "UPDATE ttrss_entries SET
5510 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
5512 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
5513 int_id = '$int_id' AND owner_uid = '$owner_uid'");
5516 db_query($link, "INSERT INTO ttrss_user_entries
5517 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5519 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5522 if (count($labels) != 0) {
5523 foreach ($labels as $label) {
5524 label_add_article($link, $ref_id, trim($label), $owner_uid);
5531 $result = db_query($link, "INSERT INTO ttrss_entries
5532 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
5534 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
5536 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
5538 if (db_num_rows($result) != 0) {
5539 $ref_id = db_fetch_result($result, 0, "id");
5541 db_query($link, "INSERT INTO ttrss_user_entries
5542 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5544 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5546 if (count($labels) != 0) {
5547 foreach ($labels as $label) {
5548 label_add_article($link, $ref_id, trim($label), $owner_uid);
5556 db_query($link, "COMMIT");