2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 99);
5 $fetch_last_error = false;
7 function __autoload($class) {
8 $class_file = str_replace("_", "/", strtolower(basename($class)));
10 $file = dirname(__FILE__
)."/../plugins/$class_file.php";
12 if (file_exists($file)) {
17 $file = dirname(__FILE__
)."/../classes/$class_file.php";
19 if (file_exists($file)) {
25 mb_internal_encoding("UTF-8");
26 date_default_timezone_set('UTC');
27 if (defined('E_DEPRECATED')) {
28 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
30 error_reporting(E_ALL
& ~E_NOTICE
);
33 require_once 'config.php';
35 if (DB_TYPE
== "pgsql") {
36 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
38 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
41 define('THEME_VERSION_REQUIRED', 1.1);
44 * Return available translations names.
47 * @return array A array of available translations.
49 function get_translations() {
51 "auto" => "Detect automatically",
56 "fr_FR" => "Français",
57 "hu_HU" => "Magyar (Hungarian)",
58 "it_IT" => "Italiano",
59 "ja_JP" => "日本語 (Japanese)",
60 "nb_NO" => "Norwegian bokmål",
63 "pt_BR" => "Portuguese/Brazil",
64 "zh_CN" => "Simplified Chinese");
69 require_once "lib/accept-to-gettext.php";
70 require_once "lib/gettext/gettext.inc";
72 function startup_gettext() {
74 # Get locale from Accept-Language header
75 $lang = al2gt(array_keys(get_translations()), "text/html");
77 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
78 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
81 /* In login action of mobile version */
82 if ($_POST["language"] && defined('MOBILE_VERSION')) {
83 $lang = $_POST["language"];
85 $lang = $_SESSION["language"];
89 if (defined('LC_MESSAGES')) {
90 _setlocale(LC_MESSAGES
, $lang);
91 } else if (defined('LC_ALL')) {
92 _setlocale(LC_ALL
, $lang);
95 if (defined('MOBILE_VERSION')) {
96 _bindtextdomain("messages", "../locale");
98 _bindtextdomain("messages", "locale");
101 _textdomain("messages");
102 _bind_textdomain_codeset("messages", "UTF-8");
108 require_once 'db-prefs.php';
109 require_once 'version.php';
111 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
113 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
114 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
116 ini_set('user_agent', SELF_USER_AGENT
);
118 require_once 'lib/pubsubhubbub/publisher.php';
119 require_once 'lib/htmLawed.php';
122 $utc_tz = new DateTimeZone('UTC');
123 $schema_version = false;
126 * Print a timestamped debug message.
128 * @param string $msg The debug message.
131 function _debug($msg) {
132 if (defined('QUIET') && QUIET
) {
135 $ts = strftime("%H:%M:%S", time());
136 if (function_exists('posix_getpid')) {
137 $ts = "$ts/" . posix_getpid();
139 print "[$ts] $msg\n";
143 * Purge a feed old posts.
145 * @param mixed $link A database connection.
146 * @param mixed $feed_id The id of the purged feed.
147 * @param mixed $purge_interval Olderness of purged posts.
148 * @param boolean $debug Set to True to enable the debug. False by default.
152 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
154 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
158 $result = db_query($link,
159 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
163 if (db_num_rows($result) == 1) {
164 $owner_uid = db_fetch_result($result, 0, "owner_uid");
167 if ($purge_interval == -1 ||
!$purge_interval) {
169 ccache_update($link, $feed_id, $owner_uid);
174 if (!$owner_uid) return;
176 if (FORCE_ARTICLE_PURGE
== 0) {
177 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
180 $purge_unread = true;
181 $purge_interval = FORCE_ARTICLE_PURGE
;
184 if (!$purge_unread) $query_limit = " unread = false AND ";
186 if (DB_TYPE
== "pgsql") {
187 $pg_version = get_pgsql_version($link);
189 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
191 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
192 ttrss_entries.id = ref_id AND
194 feed_id = '$feed_id' AND
196 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
200 $result = db_query($link, "DELETE FROM ttrss_user_entries
202 WHERE ttrss_entries.id = ref_id AND
204 feed_id = '$feed_id' AND
206 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
209 $rows = pg_affected_rows($result);
213 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
214 marked = false AND feed_id = '$feed_id' AND
215 (SELECT date_updated FROM ttrss_entries WHERE
216 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
218 $result = db_query($link, "DELETE FROM ttrss_user_entries
219 USING ttrss_user_entries, ttrss_entries
220 WHERE ttrss_entries.id = ref_id AND
222 feed_id = '$feed_id' AND
224 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
226 $rows = mysql_affected_rows($link);
230 ccache_update($link, $feed_id, $owner_uid);
233 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
235 } // function purge_feed
237 function feed_purge_interval($link, $feed_id) {
239 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
240 WHERE id = '$feed_id'");
242 if (db_num_rows($result) == 1) {
243 $purge_interval = db_fetch_result($result, 0, "purge_interval");
244 $owner_uid = db_fetch_result($result, 0, "owner_uid");
246 if ($purge_interval == 0) $purge_interval = get_pref($link,
247 'PURGE_OLD_DAYS', $owner_uid);
249 return $purge_interval;
256 function purge_orphans($link, $do_output = false) {
258 // purge orphaned posts in main content table
259 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
260 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
263 $rows = db_affected_rows($link, $result);
264 _debug("Purged $rows orphaned posts.");
268 function get_feed_update_interval($link, $feed_id) {
269 $result = db_query($link, "SELECT owner_uid, update_interval FROM
270 ttrss_feeds WHERE id = '$feed_id'");
272 if (db_num_rows($result) == 1) {
273 $update_interval = db_fetch_result($result, 0, "update_interval");
274 $owner_uid = db_fetch_result($result, 0, "owner_uid");
276 if ($update_interval != 0) {
277 return $update_interval;
279 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
287 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
288 $login = urlencode($login);
289 $pass = urlencode($pass);
291 global $fetch_last_error;
293 if (function_exists('curl_init') && !ini_get("open_basedir")) {
294 $ch = curl_init($url);
296 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
297 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
298 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
299 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
300 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
301 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
302 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
303 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
304 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
305 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
308 curl_setopt($ch, CURLOPT_POST
, true);
309 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
313 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
315 $contents = @curl_exec
($ch);
317 if ($contents === false) {
318 $fetch_last_error = curl_error($ch);
323 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
324 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
327 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
333 if ($login && $pass ){
334 $url_parts = array();
336 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
338 if ($url_parts[1] && $url_parts[2]) {
339 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
343 $data = @file_get_contents
($url);
345 if (!$data && function_exists('error_get_last')) {
346 $error = error_get_last();
347 $fetch_last_error = $error["message"];
355 * Try to determine the favicon URL for a feed.
356 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
357 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
359 * @param string $url A feed or page URL
361 * @return mixed The favicon URL, or false if none was found.
363 function get_favicon_url($url) {
365 $favicon_url = false;
367 if ($html = @fetch_file_contents
($url)) {
369 libxml_use_internal_errors(true);
371 $doc = new DOMDocument();
372 $doc->loadHTML($html);
373 $xpath = new DOMXPath($doc);
375 $base = $xpath->query('/html/head/base');
376 foreach ($base as $b) {
377 $url = $b->getAttribute("href");
381 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
382 if (count($entries) > 0) {
383 foreach ($entries as $entry) {
384 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
391 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
394 } // function get_favicon_url
396 function check_feed_favicon($site_url, $feed, $link) {
397 # print "FAVICON [$site_url]: $favicon_url\n";
399 $icon_file = ICONS_DIR
. "/$feed.ico";
401 if (!file_exists($icon_file)) {
402 $favicon_url = get_favicon_url($site_url);
405 // Limiting to "image" type misses those served with text/plain
406 $contents = fetch_file_contents($favicon_url); // , "image");
409 // Crude image type matching.
410 // Patterns gleaned from the file(1) source code.
411 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
412 // 0 string \000\000\001\000 MS Windows icon resource
413 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
415 elseif (preg_match('/^GIF8/', $contents)) {
416 // 0 string GIF8 GIF image data
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
419 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
420 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
421 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
423 elseif (preg_match('/^\xff\xd8/', $contents)) {
424 // 0 beshort 0xffd8 JPEG image data
425 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
428 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
434 $fp = @fopen
($icon_file, "w");
437 fwrite($fp, $contents);
439 chmod($icon_file, 0644);
446 function print_select($id, $default, $values, $attributes = "") {
447 print "<select name=\"$id\" id=\"$id\" $attributes>";
448 foreach ($values as $v) {
450 $sel = "selected=\"1\"";
454 print "<option value=\"$v\" $sel>$v</option>";
459 function print_select_hash($id, $default, $values, $attributes = "") {
460 print "<select name=\"$id\" id='$id' $attributes>";
461 foreach (array_keys($values) as $v) {
463 $sel = 'selected="selected"';
467 print "<option $sel value=\"$v\">".$values[$v]."</option>";
473 function getmicrotime() {
474 list($usec, $sec) = explode(" ",microtime());
475 return ((float)$usec +
(float)$sec);
478 function print_radio($id, $default, $true_is, $values, $attributes = "") {
479 foreach ($values as $v) {
486 if ($v == $true_is) {
487 $sel .= " value=\"1\"";
489 $sel .= " value=\"0\"";
492 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
493 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
498 function initialize_user_prefs($link, $uid, $profile = false) {
500 $uid = db_escape_string($uid);
504 $profile_qpart = "AND profile IS NULL";
506 $profile_qpart = "AND profile = '$profile'";
509 if (get_schema_version($link) < 63) $profile_qpart = "";
511 db_query($link, "BEGIN");
513 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
515 $u_result = db_query($link, "SELECT pref_name
516 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
518 $active_prefs = array();
520 while ($line = db_fetch_assoc($u_result)) {
521 array_push($active_prefs, $line["pref_name"]);
524 while ($line = db_fetch_assoc($result)) {
525 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
526 // print "adding " . $line["pref_name"] . "<br>";
528 if (get_schema_version($link) < 63) {
529 db_query($link, "INSERT INTO ttrss_user_prefs
530 (owner_uid,pref_name,value) VALUES
531 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
534 db_query($link, "INSERT INTO ttrss_user_prefs
535 (owner_uid,pref_name,value, profile) VALUES
536 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
542 db_query($link, "COMMIT");
546 function get_ssl_certificate_id() {
547 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
548 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
549 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
550 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
551 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
556 function authenticate_user($link, $login, $password, $check_only = false) {
558 if (!SINGLE_USER_MODE
) {
561 $modules = explode(",", AUTH_MODULES
);
563 foreach ($modules as $module) {
564 $module_class = "auth_$module";
565 if (class_exists($module_class)) {
566 $authenticator = new $module_class($link);
568 $user_id = (int) $authenticator->authenticate($login, $password);
571 $_SESSION["auth_module"] = $module;
576 print T_sprintf("Fatal: authentication module %s not found.", $module);
581 if ($user_id && !$check_only) {
582 $_SESSION["uid"] = $user_id;
584 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
585 WHERE id = '$user_id'");
587 $_SESSION["name"] = db_fetch_result($result, 0, "login");
588 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
589 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
591 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
594 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
595 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
597 $_SESSION["last_version_check"] = time();
599 initialize_user_prefs($link, $_SESSION["uid"]);
608 $_SESSION["uid"] = 1;
609 $_SESSION["name"] = "admin";
610 $_SESSION["access_level"] = 10;
612 $_SESSION["hide_hello"] = true;
613 $_SESSION["hide_logout"] = true;
615 $_SESSION["auth_module"] = false;
617 if (!$_SESSION["csrf_token"]) {
618 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
621 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
623 initialize_user_prefs($link, $_SESSION["uid"]);
629 function make_password($length = 8) {
632 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
636 while ($i < $length) {
637 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
639 if (!strstr($password, $char)) {
647 // this is called after user is created to initialize default feeds, labels
650 // user preferences are checked on every login, not here
652 function initialize_user($link, $uid) {
654 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
655 values ('$uid', 'Tiny Tiny RSS: New Releases',
656 'http://tt-rss.org/releases.rss')");
658 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
659 values ('$uid', 'Tiny Tiny RSS: Forum',
660 'http://tt-rss.org/forum/rss.php')");
663 function logout_user() {
665 if (isset($_COOKIE[session_name()])) {
666 setcookie(session_name(), '', time()-42000, '/');
670 function validate_csrf($csrf_token) {
671 return $csrf_token == $_SESSION['csrf_token'];
674 function validate_session($link) {
675 if (SINGLE_USER_MODE
) return true;
677 $check_ip = $_SESSION['ip_address'];
679 switch (SESSION_CHECK_ADDRESS
) {
684 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
687 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
688 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
692 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
693 $_SESSION["login_error_msg"] =
694 __("Session failed to validate (incorrect IP)");
698 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
701 if ($_SESSION["uid"]) {
703 $result = db_query($link,
704 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
706 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
708 if ($pwd_hash != $_SESSION["pwd_hash"]) {
713 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
715 //print_r($_SESSION);
717 if (time() > $_SESSION["cookie_lifetime"]) {
725 function login_sequence($link, $login_form = 0) {
726 if (SINGLE_USER_MODE
) {
727 return authenticate_user($link, "admin", null);
729 if (!$_SESSION["uid"] ||
!validate_session($link)) {
731 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
732 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
734 authenticate_user($link, null, null, true);
737 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
740 /* bump login timestamp */
741 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
745 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
746 setcookie("ttrss_lang", $_SESSION["language"],
747 time() + SESSION_COOKIE_LIFETIME
);
752 function truncate_string($str, $max_len, $suffix = '…') {
753 if (mb_strlen($str, "utf-8") > $max_len - 3) {
754 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
760 function theme_image($link, $filename) {
762 $theme_path = get_user_theme_path($link);
764 if ($theme_path && is_file($theme_path.$filename)) {
765 return $theme_path.$filename;
774 function get_user_theme($link) {
776 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
777 $theme_name = get_pref($link, "_THEME_ID");
778 if (is_dir("themes/$theme_name")) {
789 function get_user_theme_path($link) {
792 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
793 $theme_name = get_pref($link, "_THEME_ID");
795 if ($theme_name && is_dir("themes/$theme_name")) {
796 $theme_path = "themes/$theme_name/";
805 if (is_file("$theme_path/theme.ini")) {
806 $ini = parse_ini_file("$theme_path/theme.ini", true);
807 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
815 function get_user_theme_options($link) {
816 $t = get_user_theme_path($link);
819 if (is_file("$t/theme.ini")) {
820 $ini = parse_ini_file("$t/theme.ini", true);
821 if ($ini['theme']['version']) {
822 return $ini['theme']['options'];
829 function print_theme_includes($link) {
831 $t = get_user_theme_path($link);
835 print "<link rel=\"stylesheet\" type=\"text/css\"
836 href=\"$t/theme.css?$time \">";
837 if (file_exists("$t/theme.js")) {
838 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
844 function get_all_themes() {
845 $themes = glob("themes/*");
851 foreach ($themes as $t) {
852 if (is_file("$t/theme.ini")) {
853 $ini = parse_ini_file("$t/theme.ini", true);
854 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
855 !$ini['theme']['disabled']) {
858 $entry["base"] = basename($t);
859 $entry["name"] = $ini['theme']['name'];
860 $entry["version"] = $ini['theme']['version'];
861 $entry["author"] = $ini['theme']['author'];
862 $entry["options"] = $ini['theme']['options'];
863 array_push($rv, $entry);
871 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
874 $source_tz = new DateTimeZone($source_tz);
875 } catch (Exception
$e) {
876 $source_tz = new DateTimeZone('UTC');
880 $dest_tz = new DateTimeZone($dest_tz);
881 } catch (Exception
$e) {
882 $dest_tz = new DateTimeZone('UTC');
885 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
886 return $dt->format('U') +
$dest_tz->getOffset($dt);
889 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
890 $no_smart_dt = false) {
892 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
893 if (!$timestamp) $timestamp = '1970-01-01 0:00';
898 # We store date in UTC internally
899 $dt = new DateTime($timestamp, $utc_tz);
901 if ($tz_offset == -1) {
903 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
906 $user_tz = new DateTimeZone($user_tz_string);
907 } catch (Exception
$e) {
911 $tz_offset = $user_tz->getOffset($dt);
914 $user_timestamp = $dt->format('U') +
$tz_offset;
917 return smart_date_time($link, $user_timestamp,
918 $tz_offset, $owner_uid);
921 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
923 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
925 return date($format, $user_timestamp);
929 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
930 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
932 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
933 return date("G:i", $timestamp);
934 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
935 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
936 return date($format, $timestamp);
938 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
939 return date($format, $timestamp);
943 function sql_bool_to_bool($s) {
944 if ($s == "t" ||
$s == "1" ||
$s == "true") {
951 function bool_to_sql_bool($s) {
959 // Session caching removed due to causing wrong redirects to upgrade
960 // script when get_schema_version() is called on an obsolete session
961 // created on a previous schema version.
962 function get_schema_version($link, $nocache = false) {
963 global $schema_version;
965 if (!$schema_version) {
966 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
967 $version = db_fetch_result($result, 0, "schema_version");
968 $schema_version = $version;
971 return $schema_version;
975 function sanity_check($link) {
976 require_once 'errors.php';
979 $schema_version = get_schema_version($link, true);
981 if ($schema_version != SCHEMA_VERSION
) {
985 if (DB_TYPE
== "mysql") {
986 $result = db_query($link, "SELECT true", false);
987 if (db_num_rows($result) != 1) {
992 if (db_escape_string("testTEST") != "testTEST") {
996 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
999 function file_is_locked($filename) {
1000 if (function_exists('flock')) {
1001 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1003 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1004 flock($fp, LOCK_UN
);
1014 return true; // consider the file always locked and skip the test
1017 function make_lockfile($filename) {
1018 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1020 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1021 if (function_exists('posix_getpid')) {
1022 fwrite($fp, posix_getpid() . "\n");
1030 function make_stampfile($filename) {
1031 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1033 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1034 fwrite($fp, time() . "\n");
1035 flock($fp, LOCK_UN
);
1043 function sql_random_function() {
1044 if (DB_TYPE
== "mysql") {
1051 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1053 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1055 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1057 $ref_check_qpart = ($max_id &&
1058 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1060 if (is_numeric($feed)) {
1066 $children = getChildCategories($link, $feed, $owner_uid);
1067 array_push($children, $feed);
1069 $children = join(",", $children);
1071 $cat_qpart = "cat_id IN ($children)";
1073 $cat_qpart = "cat_id IS NULL";
1076 db_query($link, "UPDATE ttrss_user_entries
1077 SET unread = false,last_read = NOW()
1078 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1079 AND $ref_check_qpart
1080 AND owner_uid = $owner_uid");
1082 } else if ($feed == -2) {
1084 db_query($link, "UPDATE ttrss_user_entries
1085 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1086 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1087 AND $ref_check_qpart
1088 AND unread = true AND owner_uid = $owner_uid");
1091 } else if ($feed > 0) {
1093 db_query($link, "UPDATE ttrss_user_entries
1094 SET unread = false,last_read = NOW()
1095 WHERE feed_id = '$feed'
1096 AND $ref_check_qpart
1097 AND owner_uid = $owner_uid");
1099 } else if ($feed < 0 && $feed > -10) { // special, like starred
1102 db_query($link, "UPDATE ttrss_user_entries
1103 SET unread = false,last_read = NOW()
1105 AND $ref_check_qpart
1106 AND owner_uid = $owner_uid");
1110 db_query($link, "UPDATE ttrss_user_entries
1111 SET unread = false,last_read = NOW()
1112 WHERE published = true
1113 AND $ref_check_qpart
1114 AND owner_uid = $owner_uid");
1119 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1121 if (DB_TYPE
== "pgsql") {
1122 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1124 $match_part = "updated > DATE_SUB(NOW(),
1125 INTERVAL $intl HOUR) ";
1128 $result = db_query($link, "SELECT id FROM ttrss_entries,
1129 ttrss_user_entries WHERE $match_part AND
1131 ttrss_user_entries.ref_id = ttrss_entries.id AND
1132 owner_uid = $owner_uid");
1134 $affected_ids = array();
1136 while ($line = db_fetch_assoc($result)) {
1137 array_push($affected_ids, $line["id"]);
1140 catchupArticlesById($link, $affected_ids, 0);
1144 db_query($link, "UPDATE ttrss_user_entries
1145 SET unread = false,last_read = NOW()
1146 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1149 } else if ($feed < -10) { // label
1151 $label_id = -$feed - 11;
1153 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1154 SET unread = false, last_read = NOW()
1155 WHERE label_id = '$label_id' AND unread = true
1156 AND $ref_check_qpart
1157 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1161 ccache_update($link, $feed, $owner_uid, $cat_view);
1164 db_query($link, "BEGIN");
1166 $tag_name = db_escape_string($feed);
1168 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1169 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1171 while ($line = db_fetch_assoc($result)) {
1172 db_query($link, "UPDATE ttrss_user_entries SET
1173 unread = false, last_read = NOW()
1174 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1176 db_query($link, "COMMIT");
1180 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1182 if (!$omode) $omode = "flc";
1184 $data = getGlobalCounters($link);
1186 $data = array_merge($data, getVirtCounters($link));
1188 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1189 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1190 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1191 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1196 function getCategoryTitle($link, $cat_id) {
1198 if ($cat_id == -1) {
1199 return __("Special");
1200 } else if ($cat_id == -2) {
1201 return __("Labels");
1204 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1207 if (db_num_rows($result) == 1) {
1208 return db_fetch_result($result, 0, "title");
1210 return __("Uncategorized");
1216 function getCategoryCounters($link) {
1219 /* Labels category */
1221 $cv = array("id" => -2, "kind" => "cat",
1222 "counter" => getCategoryUnread($link, -2));
1224 array_push($ret_arr, $cv);
1226 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1227 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1228 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1229 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1230 WHERE ttrss_cat_counters_cache.feed_id = id AND
1231 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1232 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1234 while ($line = db_fetch_assoc($result)) {
1235 $line["cat_id"] = (int) $line["cat_id"];
1237 if ($line["num_children"] > 0) {
1238 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1243 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1244 "counter" => $line["unread"] +
$child_counter);
1246 array_push($ret_arr, $cv);
1249 /* Special case: NULL category doesn't actually exist in the DB */
1251 $cv = array("id" => 0, "kind" => "cat",
1252 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1254 array_push($ret_arr, $cv);
1259 // only accepts real cats (>= 0)
1260 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1261 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1263 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1264 AND owner_uid = $owner_uid");
1268 while ($line = db_fetch_assoc($result)) {
1269 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1270 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1276 function getCategoryUnread($link, $cat, $owner_uid = false) {
1278 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1283 $cat_query = "cat_id = '$cat'";
1285 $cat_query = "cat_id IS NULL";
1288 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1289 AND owner_uid = " . $owner_uid);
1291 $cat_feeds = array();
1292 while ($line = db_fetch_assoc($result)) {
1293 array_push($cat_feeds, "feed_id = " . $line["id"]);
1296 if (count($cat_feeds) == 0) return 0;
1298 $match_part = implode(" OR ", $cat_feeds);
1300 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1301 FROM ttrss_user_entries
1302 WHERE unread = true AND ($match_part)
1303 AND owner_uid = " . $owner_uid);
1307 # this needs to be rewritten
1308 while ($line = db_fetch_assoc($result)) {
1309 $unread +
= $line["unread"];
1313 } else if ($cat == -1) {
1314 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1315 } else if ($cat == -2) {
1317 $result = db_query($link, "
1318 SELECT COUNT(unread) AS unread FROM
1319 ttrss_user_entries, ttrss_user_labels2
1320 WHERE article_id = ref_id AND unread = true
1321 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1323 $unread = db_fetch_result($result, 0, "unread");
1330 function getFeedUnread($link, $feed, $is_cat = false) {
1331 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1334 function getLabelUnread($link, $label_id, $owner_uid = false) {
1335 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1337 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1338 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1340 if (db_num_rows($result) != 0) {
1341 return db_fetch_result($result, 0, "unread");
1347 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1348 $owner_uid = false) {
1350 $n_feed = (int) $feed;
1351 $need_entries = false;
1353 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1356 $unread_qpart = "unread = true";
1358 $unread_qpart = "true";
1362 return getCategoryUnread($link, $n_feed, $owner_uid);
1363 } else if ($n_feed == -6) {
1365 } else if ($feed != "0" && $n_feed == 0) {
1367 $feed = db_escape_string($feed);
1369 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1370 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1371 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1372 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1373 return db_fetch_result($result, 0, "count");
1375 } else if ($n_feed == -1) {
1376 $match_part = "marked = true";
1377 } else if ($n_feed == -2) {
1378 $match_part = "published = true";
1379 } else if ($n_feed == -3) {
1380 $match_part = "unread = true AND score >= 0";
1382 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1384 if (DB_TYPE
== "pgsql") {
1385 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1387 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1390 $need_entries = true;
1392 } else if ($n_feed == -4) {
1393 $match_part = "true";
1394 } else if ($n_feed >= 0) {
1397 $match_part = "feed_id = '$n_feed'";
1399 $match_part = "feed_id IS NULL";
1402 } else if ($feed < -10) {
1404 $label_id = -$feed - 11;
1406 return getLabelUnread($link, $label_id, $owner_uid);
1412 if ($need_entries) {
1413 $from_qpart = "ttrss_user_entries,ttrss_entries";
1414 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1416 $from_qpart = "ttrss_user_entries";
1419 $query = "SELECT count(int_id) AS unread
1420 FROM $from_qpart WHERE
1421 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1423 //echo "[$feed/$query]\n";
1425 $result = db_query($link, $query);
1429 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1430 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1431 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1432 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1435 $unread = db_fetch_result($result, 0, "unread");
1440 function getGlobalUnread($link, $user_id = false) {
1443 $user_id = $_SESSION["uid"];
1446 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1447 WHERE owner_uid = '$user_id' AND feed_id > 0");
1449 $c_id = db_fetch_result($result, 0, "c_id");
1454 function getGlobalCounters($link, $global_unread = -1) {
1457 if ($global_unread == -1) {
1458 $global_unread = getGlobalUnread($link);
1461 $cv = array("id" => "global-unread",
1462 "counter" => (int) $global_unread);
1464 array_push($ret_arr, $cv);
1466 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1467 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1469 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1471 $cv = array("id" => "subscribed-feeds",
1472 "counter" => (int) $subscribed_feeds);
1474 array_push($ret_arr, $cv);
1479 function getTagCounters($link) {
1483 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1484 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1485 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1486 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1487 ORDER BY count DESC LIMIT 55");
1491 while ($line = db_fetch_assoc($result)) {
1492 $tags[$line["tag_name"]] +
= $line["count"];
1495 foreach (array_keys($tags) as $tag) {
1496 $unread = $tags[$tag];
1497 $tag = htmlspecialchars($tag);
1499 $cv = array("id" => $tag,
1501 "counter" => $unread);
1503 array_push($ret_arr, $cv);
1509 function getVirtCounters($link) {
1513 for ($i = 0; $i >= -4; $i--) {
1515 $count = getFeedUnread($link, $i);
1517 $cv = array("id" => $i,
1518 "counter" => (int) $count);
1520 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1521 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1523 array_push($ret_arr, $cv);
1529 function getLabelCounters($link, $descriptions = false) {
1533 $owner_uid = $_SESSION["uid"];
1535 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1536 WHERE owner_uid = '$owner_uid'");
1538 while ($line = db_fetch_assoc($result)) {
1540 $id = -$line["id"] - 11;
1542 $label_name = $line["caption"];
1543 $count = getFeedUnread($link, $id);
1545 $cv = array("id" => $id,
1546 "counter" => (int) $count);
1549 $cv["description"] = $label_name;
1551 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1552 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1554 array_push($ret_arr, $cv);
1560 function getFeedCounters($link, $active_feed = false) {
1564 $query = "SELECT ttrss_feeds.id,
1566 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1567 last_error, value AS count
1568 FROM ttrss_feeds, ttrss_counters_cache
1569 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1570 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1571 AND ttrss_counters_cache.feed_id = id";
1573 $result = db_query($link, $query);
1574 $fctrs_modified = false;
1576 while ($line = db_fetch_assoc($result)) {
1579 $count = $line["count"];
1580 $last_error = htmlspecialchars($line["last_error"]);
1582 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1584 $has_img = feed_has_icon($id);
1586 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1589 $cv = array("id" => $id,
1590 "updated" => $last_updated,
1591 "counter" => (int) $count,
1592 "has_img" => (int) $has_img);
1595 $cv["error"] = $last_error;
1597 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1598 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1600 if ($active_feed && $id == $active_feed)
1601 $cv["title"] = truncate_string($line["title"], 30);
1603 array_push($ret_arr, $cv);
1610 function get_pgsql_version($link) {
1611 $result = db_query($link, "SELECT version() AS version");
1612 $version = explode(" ", db_fetch_result($result, 0, "version"));
1617 * @return array (code => Status code, message => error message if available)
1619 * 0 - OK, Feed already exists
1620 * 1 - OK, Feed added
1622 * 3 - URL content is HTML, no feeds available
1623 * 4 - URL content is HTML which contains multiple feeds.
1624 * Here you should call extractfeedurls in rpc-backend
1625 * to get all possible feeds.
1626 * 5 - Couldn't download the URL content.
1628 function subscribe_to_feed($link, $url, $cat_id = 0,
1629 $auth_login = '', $auth_pass = '', $need_auth = false) {
1631 global $fetch_last_error;
1633 require_once "include/rssfuncs.php";
1635 $url = fix_url($url);
1637 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1641 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1644 return array("code" => 5, "message" => $fetch_last_error);
1647 if (is_html($contents)) {
1648 $feedUrls = get_feeds_from_html($url, $contents);
1650 if (count($feedUrls) == 0) {
1651 return array("code" => 3);
1652 } else if (count($feedUrls) > 1) {
1653 return array("code" => 4, "feeds" => $feedUrls);
1655 //use feed url as new URL
1656 $url = key($feedUrls);
1659 if ($cat_id == "0" ||
!$cat_id) {
1660 $cat_qpart = "NULL";
1662 $cat_qpart = "'$cat_id'";
1665 $result = db_query($link,
1666 "SELECT id FROM ttrss_feeds
1667 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1669 if (db_num_rows($result) == 0) {
1670 $result = db_query($link,
1671 "INSERT INTO ttrss_feeds
1672 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1673 VALUES ('".$_SESSION["uid"]."', '$url',
1674 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1676 $result = db_query($link,
1677 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1678 AND owner_uid = " . $_SESSION["uid"]);
1680 $feed_id = db_fetch_result($result, 0, "id");
1683 update_rss_feed($link, $feed_id, true);
1686 return array("code" => 1);
1688 return array("code" => 0);
1692 function print_feed_select($link, $id, $default_id = "",
1693 $attributes = "", $include_all_feeds = true,
1694 $root_id = false, $nest_level = 0) {
1697 print "<select id=\"$id\" name=\"$id\" $attributes>";
1698 if ($include_all_feeds) {
1699 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1700 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1704 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1707 $parent_qpart = "parent_cat = '$root_id'";
1709 $parent_qpart = "parent_cat IS NULL";
1711 $result = db_query($link, "SELECT id,title,
1712 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1713 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1714 FROM ttrss_feed_categories
1715 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1717 while ($line = db_fetch_assoc($result)) {
1719 for ($i = 0; $i < $nest_level; $i++
)
1720 $line["title"] = " - " . $line["title"];
1722 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1724 printf("<option $is_selected value='CAT:%d'>%s</option>",
1725 $line["id"], htmlspecialchars($line["title"]));
1727 if ($line["num_children"] > 0)
1728 print_feed_select($link, $id, $default_id, $attributes,
1729 $include_all_feeds, $line["id"], $nest_level+
1);
1731 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1732 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1734 while ($fline = db_fetch_assoc($feed_result)) {
1735 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1737 $fline["title"] = " + " . $fline["title"];
1739 for ($i = 0; $i < $nest_level; $i++
)
1740 $fline["title"] = " - " . $fline["title"];
1742 printf("<option $is_selected value='%d'>%s</option>",
1743 $fline["id"], htmlspecialchars($fline["title"]));
1748 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1750 printf("<option $is_selected value='CAT:0'>%s</option>",
1751 __("Uncategorized"));
1753 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1754 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1756 while ($fline = db_fetch_assoc($feed_result)) {
1757 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1759 $fline["title"] = " + " . $fline["title"];
1761 for ($i = 0; $i < $nest_level; $i++
)
1762 $fline["title"] = " - " . $fline["title"];
1764 printf("<option $is_selected value='%d'>%s</option>",
1765 $fline["id"], htmlspecialchars($fline["title"]));
1770 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1771 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1773 while ($line = db_fetch_assoc($result)) {
1775 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1777 printf("<option $is_selected value='%d'>%s</option>",
1778 $line["id"], htmlspecialchars($line["title"]));
1787 function print_feed_cat_select($link, $id, $default_id,
1788 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1791 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1795 $parent_qpart = "parent_cat = '$root_id'";
1797 $parent_qpart = "parent_cat IS NULL";
1799 $result = db_query($link, "SELECT id,title,
1800 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1801 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1802 FROM ttrss_feed_categories
1803 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1805 while ($line = db_fetch_assoc($result)) {
1806 if ($line["id"] == $default_id) {
1807 $is_selected = "selected=\"1\"";
1812 for ($i = 0; $i < $nest_level; $i++
)
1813 $line["title"] = " - " . $line["title"];
1816 printf("<option $is_selected value='%d'>%s</option>",
1817 $line["id"], htmlspecialchars($line["title"]));
1819 if ($line["num_children"] > 0)
1820 print_feed_cat_select($link, $id, $default_id, $attributes,
1821 $include_all_cats, $line["id"], $nest_level+
1);
1825 if ($include_all_cats) {
1826 if (db_num_rows($result) > 0) {
1827 print "<option disabled=\"1\">--------</option>";
1830 if ($default_id == 0) {
1831 $is_selected = "selected=\"1\"";
1836 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1842 function checkbox_to_sql_bool($val) {
1843 return ($val == "on") ?
"true" : "false";
1846 function getFeedCatTitle($link, $id) {
1848 return __("Special");
1849 } else if ($id < -10) {
1850 return __("Labels");
1851 } else if ($id > 0) {
1852 $result = db_query($link, "SELECT ttrss_feed_categories.title
1853 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1854 cat_id = ttrss_feed_categories.id");
1855 if (db_num_rows($result) == 1) {
1856 return db_fetch_result($result, 0, "title");
1858 return __("Uncategorized");
1861 return "getFeedCatTitle($id) failed";
1866 function getFeedIcon($id) {
1869 return "images/archive.png";
1872 return "images/mark_set.png";
1875 return "images/pub_set.png";
1878 return "images/fresh.png";
1881 return "images/tag.png";
1884 return "images/recently_read.png";
1888 return "images/label.png";
1890 if (file_exists(ICONS_DIR
. "/$id.ico"))
1891 return ICONS_URL
. "/$id.ico";
1897 function getFeedTitle($link, $id, $cat = false) {
1899 return getCategoryTitle($link, $id);
1900 } else if ($id == -1) {
1901 return __("Starred articles");
1902 } else if ($id == -2) {
1903 return __("Published articles");
1904 } else if ($id == -3) {
1905 return __("Fresh articles");
1906 } else if ($id == -4) {
1907 return __("All articles");
1908 } else if ($id === 0 ||
$id === "0") {
1909 return __("Archived articles");
1910 } else if ($id == -6) {
1911 return __("Recently read");
1912 } else if ($id < -10) {
1913 $label_id = -$id - 11;
1914 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1915 if (db_num_rows($result) == 1) {
1916 return db_fetch_result($result, 0, "caption");
1918 return "Unknown label ($label_id)";
1921 } else if (is_numeric($id) && $id > 0) {
1922 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1923 if (db_num_rows($result) == 1) {
1924 return db_fetch_result($result, 0, "title");
1926 return "Unknown feed ($id)";
1933 function make_init_params($link) {
1936 $params["theme"] = get_user_theme($link);
1937 $params["theme_options"] = get_user_theme_options($link);
1939 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1940 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1941 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
1942 $params["sign_info"] = theme_image($link, "images/sign_info.png");
1944 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1945 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1946 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1947 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1949 $params[strtolower($param)] = (int) get_pref($link, $param);
1952 $params["icons_url"] = ICONS_URL
;
1953 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1954 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1955 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1956 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1957 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1959 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1960 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1962 $max_feed_id = db_fetch_result($result, 0, "mid");
1963 $num_feeds = db_fetch_result($result, 0, "nf");
1965 $params["max_feed_id"] = (int) $max_feed_id;
1966 $params["num_feeds"] = (int) $num_feeds;
1968 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1970 $params["csrf_token"] = $_SESSION["csrf_token"];
1975 function make_runtime_info($link) {
1978 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1979 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1981 $max_feed_id = db_fetch_result($result, 0, "mid");
1982 $num_feeds = db_fetch_result($result, 0, "nf");
1984 $data["max_feed_id"] = (int) $max_feed_id;
1985 $data["num_feeds"] = (int) $num_feeds;
1987 $data['last_article_id'] = getLastArticleId($link);
1988 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1990 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1992 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1994 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1996 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1999 $stamp_delta = time() - $stamp;
2001 if ($stamp_delta > 1800) {
2005 $_SESSION["daemon_stamp_check"] = time();
2008 $data['daemon_stamp_ok'] = $stamp_check;
2010 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2012 $data['daemon_stamp'] = $stamp_fmt;
2017 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2018 $new_version_details = @check_for_update
($link);
2020 $data['new_version_available'] = (int) ($new_version_details != false);
2022 $_SESSION["last_version_check"] = time();
2023 $_SESSION["version_data"] = $new_version_details;
2029 function search_to_sql($link, $search, $match_on) {
2031 $search_query_part = "";
2033 $keywords = explode(" ", $search);
2034 $query_keywords = array();
2036 foreach ($keywords as $k) {
2037 if (strpos($k, "-") === 0) {
2044 $commandpair = explode(":", mb_strtolower($k), 2);
2046 if ($commandpair[0] == "note" && $commandpair[1]) {
2048 if ($commandpair[1] == "true")
2049 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2051 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2053 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2055 if ($commandpair[1] == "true")
2056 array_push($query_keywords, "($not (marked = true))");
2058 array_push($query_keywords, "($not (marked = false))");
2060 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2062 if ($commandpair[1] == "true")
2063 array_push($query_keywords, "($not (published = true))");
2065 array_push($query_keywords, "($not (published = false))");
2067 } else if (strpos($k, "@") === 0) {
2069 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2070 $orig_ts = strtotime(substr($k, 1));
2071 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2073 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2075 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2076 } else if ($match_on == "both") {
2077 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2078 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2079 } else if ($match_on == "title") {
2080 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2081 } else if ($match_on == "content") {
2082 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2086 $search_query_part = implode("AND", $query_keywords);
2088 return $search_query_part;
2091 function getParentCategories($link, $cat, $owner_uid) {
2094 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2095 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2097 while ($line = db_fetch_assoc($result)) {
2098 array_push($rv, $line["parent_cat"]);
2099 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2105 function getChildCategories($link, $cat, $owner_uid) {
2108 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2109 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2111 while ($line = db_fetch_assoc($result)) {
2112 array_push($rv, $line["id"]);
2113 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2119 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) {
2121 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2123 $ext_tables_part = "";
2127 if (SPHINX_ENABLED
) {
2128 $ids = join(",", @sphinx_search
($search, 0, 500));
2131 $search_query_part = "ref_id IN ($ids) AND ";
2133 $search_query_part = "ref_id = -1 AND ";
2136 $search_query_part = search_to_sql($link, $search, $match_on);
2137 $search_query_part .= " AND ";
2141 $search_query_part = "";
2146 if (DB_TYPE
== "pgsql") {
2147 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2149 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2152 $override_order = "updated DESC";
2154 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2156 // Try to check if SQL regexp implementation chokes on a valid regexp
2157 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2158 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2159 WHERE $filter_query_part LIMIT 1", false);
2161 $test = db_fetch_result($result, 0, "true");
2164 $filter_query_part = "false AND";
2166 $filter_query_part .= " AND";
2170 $filter_query_part = "";
2174 $since_id_part = "ttrss_entries.id > $since_id AND ";
2176 $since_id_part = "";
2179 $view_query_part = "";
2181 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2183 $view_query_part = " ";
2184 } else if ($feed != -1) {
2185 $unread = getFeedUnread($link, $feed, $cat_view);
2187 if ($cat_view && $feed > 0 && $include_children)
2188 $unread +
= getCategoryChildrenUnread($link, $feed);
2191 $view_query_part = " unread = true AND ";
2196 if ($view_mode == "marked") {
2197 $view_query_part = " marked = true AND ";
2200 if ($view_mode == "published") {
2201 $view_query_part = " published = true AND ";
2204 if ($view_mode == "unread") {
2205 $view_query_part = " unread = true AND ";
2208 if ($view_mode == "updated") {
2209 $view_query_part = " (last_read is null and unread = false) AND ";
2213 $limit_query_part = "LIMIT " . $limit;
2216 $allow_archived = false;
2218 $vfeed_query_part = "";
2220 // override query strategy and enable feed display when searching globally
2221 if ($search && $search_mode == "all_feeds") {
2222 $query_strategy_part = "true";
2223 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2225 } else if (!is_numeric($feed)) {
2226 $query_strategy_part = "true";
2227 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2228 id = feed_id) as feed_title,";
2229 } else if ($search && $search_mode == "this_cat") {
2230 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2233 if ($include_children) {
2234 $subcats = getChildCategories($link, $feed, $owner_uid);
2235 array_push($subcats, $feed);
2236 $cats_qpart = join(",", $subcats);
2238 $cats_qpart = $feed;
2241 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2244 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2247 } else if ($feed > 0) {
2252 if ($include_children) {
2254 $subcats = getChildCategories($link, $feed, $owner_uid);
2256 array_push($subcats, $feed);
2257 $query_strategy_part = "cat_id IN (".
2258 implode(",", $subcats).")";
2261 $query_strategy_part = "cat_id = '$feed'";
2265 $query_strategy_part = "cat_id IS NULL";
2268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2271 $query_strategy_part = "feed_id = '$feed'";
2273 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2274 $query_strategy_part = "feed_id IS NULL";
2275 $allow_archived = true;
2276 } else if ($feed == 0 && $cat_view) { // uncategorized
2277 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2278 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2279 } else if ($feed == -1) { // starred virtual feed
2280 $query_strategy_part = "marked = true";
2281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2282 $allow_archived = true;
2284 } else if ($feed == -2) { // published virtual feed OR labels category
2287 $query_strategy_part = "published = true";
2288 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2289 $allow_archived = true;
2291 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2293 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2295 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2297 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2298 ttrss_user_labels2.article_id = ref_id";
2301 } else if ($feed == -6) { // recently read
2302 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2303 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2304 $allow_archived = true;
2306 if (!$override_order) $override_order = "last_read DESC";
2307 } else if ($feed == -3) { // fresh virtual feed
2308 $query_strategy_part = "unread = true AND score >= 0";
2310 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2312 if (DB_TYPE
== "pgsql") {
2313 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2315 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2318 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2319 } else if ($feed == -4) { // all articles virtual feed
2320 $query_strategy_part = "true";
2321 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2322 } else if ($feed <= -10) { // labels
2323 $label_id = -$feed - 11;
2325 $query_strategy_part = "label_id = '$label_id' AND
2326 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2327 ttrss_user_labels2.article_id = ref_id";
2329 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2330 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2331 $allow_archived = true;
2334 $query_strategy_part = "true";
2337 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2338 $date_sort_field = "updated";
2340 $date_sort_field = "date_entered";
2343 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2344 $order_by = "$date_sort_field";
2346 $order_by = "$date_sort_field DESC";
2349 if ($view_mode != "noscores") {
2350 $order_by = "score DESC, $order_by";
2353 if ($override_order) {
2354 $order_by = $override_order;
2360 $feed_title = T_sprintf("Search results: %s", $search);
2363 $feed_title = getCategoryTitle($link, $feed);
2365 if (is_numeric($feed) && $feed > 0) {
2366 $result = db_query($link, "SELECT title,site_url,last_error
2367 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2369 $feed_title = db_fetch_result($result, 0, "title");
2370 $feed_site_url = db_fetch_result($result, 0, "site_url");
2371 $last_error = db_fetch_result($result, 0, "last_error");
2373 $feed_title = getFeedTitle($link, $feed);
2378 $content_query_part = "content as content_preview, cached_content, ";
2380 if (is_numeric($feed)) {
2383 $feed_kind = "Feeds";
2385 $feed_kind = "Labels";
2388 if ($limit_query_part) {
2389 $offset_query_part = "OFFSET $offset";
2392 // proper override_order applied above
2393 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2394 if (!$override_order) {
2395 $order_by = "ttrss_feeds.title, $order_by";
2397 $order_by = "ttrss_feeds.title, $override_order";
2401 if (!$allow_archived) {
2402 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2403 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2406 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2407 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2410 $query = "SELECT DISTINCT
2413 ttrss_entries.id,ttrss_entries.title,
2417 always_display_enclosures,
2423 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2424 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2427 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2433 ttrss_user_entries.ref_id = ttrss_entries.id AND
2434 ttrss_user_entries.owner_uid = '$owner_uid' AND
2439 $query_strategy_part ORDER BY $order_by
2440 $limit_query_part $offset_query_part";
2442 if ($_REQUEST["debug"]) print $query;
2444 $result = db_query($link, $query);
2449 $select_qpart = "SELECT DISTINCT " .
2453 "ttrss_entries.id as id," .
2466 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2469 $content_query_part .
2470 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2473 $feed_kind = "Tags";
2474 $all_tags = explode(",", $feed);
2475 if ($search_mode == 'any') {
2476 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2477 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2478 $where_qpart = " WHERE " .
2479 "ref_id = ttrss_entries.id AND " .
2480 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2481 "post_int_id = int_id AND $tag_sql AND " .
2483 $search_query_part .
2484 $query_strategy_part . " ORDER BY $order_by " .
2489 $sub_selects = array();
2490 $sub_ands = array();
2491 foreach ($all_tags as $term) {
2492 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");
2499 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2504 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2505 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2506 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2507 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2509 // error_log("TAG SQL: " . $tag_sql);
2510 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2512 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2513 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2516 return array($result, $feed_title, $feed_site_url, $last_error);
2520 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2521 if (!$owner) $owner = $_SESSION["uid"];
2523 $res = trim($str); if (!$res) return '';
2525 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
2526 $res = htmLawed($res, $config);
2528 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2529 $res = preg_replace('/<img[^>]+>/is', '', $res);
2532 if (strpos($res, "href=") === false)
2533 $res = rewrite_urls($res);
2535 $charset_hack = '<head>
2536 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2539 $res = trim($res); if (!$res) return '';
2541 libxml_use_internal_errors(true);
2543 $doc = new DOMDocument();
2544 $doc->loadHTML($charset_hack . $res);
2545 $xpath = new DOMXPath($doc);
2547 $entries = $xpath->query('(//a[@href]|//img[@src])');
2550 foreach ($entries as $entry) {
2554 if ($entry->hasAttribute('href'))
2555 $entry->setAttribute('href',
2556 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2558 if ($entry->hasAttribute('src'))
2559 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2560 $entry->setAttribute('src',
2561 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2564 if (strtolower($entry->nodeName
) == "a") {
2565 $entry->setAttribute("target", "_blank");
2568 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2569 $br = $doc->createElement("br");
2571 if ($entry->parentNode
->nextSibling
) {
2572 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2579 $node = $doc->getElementsByTagName('body')->item(0);
2581 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2585 * Send by mail a digest of last articles.
2587 * @param mixed $link The database connection.
2588 * @param integer $limit The maximum number of articles by digest.
2589 * @return boolean Return false if digests are not enabled.
2591 function send_headlines_digests($link, $debug = false) {
2593 require_once 'lib/phpmailer/class.phpmailer.php';
2595 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2596 $limit = 1000; // maximum amount of headlines to include
2598 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2600 if (DB_TYPE
== "pgsql") {
2601 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2602 } else if (DB_TYPE
== "mysql") {
2603 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2606 $result = db_query($link, "SELECT id,email FROM ttrss_users
2607 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2609 while ($line = db_fetch_assoc($result)) {
2611 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2612 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2614 // try to send digests within 2 hours of preferred time
2615 if ($preferred_ts && time() >= $preferred_ts &&
2616 time() - $preferred_ts <= 7200) {
2618 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2620 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2624 // reset tz_offset global to prevent tz cache clash between users
2627 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2628 $digest = $tuple[0];
2629 $headlines_count = $tuple[1];
2630 $affected_ids = $tuple[2];
2631 $digest_text = $tuple[3];
2633 if ($headlines_count > 0) {
2635 $mail = new PHPMailer();
2637 $mail->PluginDir
= "lib/phpmailer/";
2638 $mail->SetLanguage("en", "lib/phpmailer/language/");
2640 $mail->CharSet
= "UTF-8";
2642 $mail->From
= SMTP_FROM_ADDRESS
;
2643 $mail->FromName
= SMTP_FROM_NAME
;
2644 $mail->AddAddress($line["email"], $line["login"]);
2647 $mail->Host
= SMTP_HOST
;
2648 $mail->Mailer
= "smtp";
2649 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2650 $mail->Username
= SMTP_LOGIN
;
2651 $mail->Password
= SMTP_PASSWORD
;
2654 $mail->IsHTML(true);
2655 $mail->Subject
= DIGEST_SUBJECT
;
2656 $mail->Body
= $digest;
2657 $mail->AltBody
= $digest_text;
2659 $rc = $mail->Send();
2661 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2663 if ($debug) print "RC=$rc\n";
2665 if ($rc && $do_catchup) {
2666 if ($debug) print "Marking affected articles as read...\n";
2667 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2670 if ($debug) print "No headlines\n";
2673 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2674 WHERE id = " . $line["id"]);
2680 if ($debug) _debug("All done.");
2684 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2686 require_once "lib/MiniTemplator.class.php";
2688 $tpl = new MiniTemplator
;
2689 $tpl_t = new MiniTemplator
;
2691 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2692 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2694 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2695 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2697 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2698 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2700 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2701 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2703 $affected_ids = array();
2705 if (DB_TYPE
== "pgsql") {
2706 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2707 } else if (DB_TYPE
== "mysql") {
2708 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2711 $result = db_query($link, "SELECT ttrss_entries.title,
2712 ttrss_feeds.title AS feed_title,
2713 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2715 ttrss_user_entries.ref_id,
2719 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2721 ttrss_user_entries,ttrss_entries,ttrss_feeds
2723 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2725 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2726 AND include_in_digest = true
2728 AND ttrss_user_entries.owner_uid = $user_id
2731 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2734 $cur_feed_title = "";
2736 $headlines_count = db_num_rows($result);
2738 $headlines = array();
2740 while ($line = db_fetch_assoc($result)) {
2741 array_push($headlines, $line);
2744 for ($i = 0; $i < sizeof($headlines); $i++
) {
2746 $line = $headlines[$i];
2748 array_push($affected_ids, $line["ref_id"]);
2750 $updated = make_local_datetime($link, $line['last_updated'], false,
2753 /* if ($line["score"] != 0) {
2754 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2756 $line["title"] .= " (".$line['score'].")";
2759 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2760 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2763 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2764 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2765 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2766 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2767 $tpl->setVariable('ARTICLE_EXCERPT',
2768 truncate_string(strip_tags($line["content"]), 300));
2769 // $tpl->setVariable('ARTICLE_CONTENT',
2770 // strip_tags($article_content));
2772 $tpl->addBlock('article');
2774 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2775 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2776 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2777 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2778 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2779 // truncate_string(strip_tags($line["excerpt"]), 100));
2781 $tpl_t->addBlock('article');
2783 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2784 $tpl->addBlock('feed');
2785 $tpl_t->addBlock('feed');
2790 $tpl->addBlock('digest');
2791 $tpl->generateOutputToString($tmp);
2793 $tpl_t->addBlock('digest');
2794 $tpl_t->generateOutputToString($tmp_t);
2796 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2799 function check_for_update($link) {
2800 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2801 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2803 $version_data = @fetch_file_contents
($version_url);
2805 if ($version_data) {
2806 $version_data = json_decode($version_data, true);
2807 if ($version_data && $version_data['version']) {
2809 if (version_compare(VERSION
, $version_data['version']) == -1) {
2810 return $version_data;
2818 function markArticlesById($link, $ids, $cmode) {
2822 foreach ($ids as $id) {
2823 array_push($tmp_ids, "ref_id = '$id'");
2826 $ids_qpart = join(" OR ", $tmp_ids);
2829 db_query($link, "UPDATE ttrss_user_entries SET
2830 marked = false,last_read = NOW()
2831 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2832 } else if ($cmode == 1) {
2833 db_query($link, "UPDATE ttrss_user_entries SET
2835 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2837 db_query($link, "UPDATE ttrss_user_entries SET
2838 marked = NOT marked,last_read = NOW()
2839 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2843 function publishArticlesById($link, $ids, $cmode) {
2847 foreach ($ids as $id) {
2848 array_push($tmp_ids, "ref_id = '$id'");
2851 $ids_qpart = join(" OR ", $tmp_ids);
2854 db_query($link, "UPDATE ttrss_user_entries SET
2855 published = false,last_read = NOW()
2856 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2857 } else if ($cmode == 1) {
2858 db_query($link, "UPDATE ttrss_user_entries SET
2859 published = true,last_read = NOW()
2860 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2862 db_query($link, "UPDATE ttrss_user_entries SET
2863 published = NOT published,last_read = NOW()
2864 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2867 if (PUBSUBHUBBUB_HUB
) {
2868 $rss_link = get_self_url_prefix() .
2869 "/public.php?op=rss&id=-2&key=" .
2870 get_feed_access_key($link, -2, false);
2872 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2874 $pubsub_result = $p->publish_update($rss_link);
2878 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2880 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2881 if (count($ids) == 0) return;
2885 foreach ($ids as $id) {
2886 array_push($tmp_ids, "ref_id = '$id'");
2889 $ids_qpart = join(" OR ", $tmp_ids);
2892 db_query($link, "UPDATE ttrss_user_entries SET
2893 unread = false,last_read = NOW()
2894 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2895 } else if ($cmode == 1) {
2896 db_query($link, "UPDATE ttrss_user_entries SET
2898 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2900 db_query($link, "UPDATE ttrss_user_entries SET
2901 unread = NOT unread,last_read = NOW()
2902 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2907 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2908 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2910 while ($line = db_fetch_assoc($result)) {
2911 ccache_update($link, $line["feed_id"], $owner_uid);
2915 function catchupArticleById($link, $id, $cmode) {
2918 db_query($link, "UPDATE ttrss_user_entries SET
2919 unread = false,last_read = NOW()
2920 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2921 } else if ($cmode == 1) {
2922 db_query($link, "UPDATE ttrss_user_entries SET
2924 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2926 db_query($link, "UPDATE ttrss_user_entries SET
2927 unread = NOT unread,last_read = NOW()
2928 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2931 $feed_id = getArticleFeed($link, $id);
2932 ccache_update($link, $feed_id, $_SESSION["uid"]);
2935 function make_guid_from_title($title) {
2936 return preg_replace("/[ \"\',.:;]/", "-",
2937 mb_strtolower(strip_tags($title), 'utf-8'));
2940 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2942 $a_id = db_escape_string($id);
2944 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2946 $query = "SELECT DISTINCT tag_name,
2947 owner_uid as owner FROM
2948 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2949 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2951 $obj_id = md5("TAGS:$owner_uid:$id");
2954 /* check cache first */
2956 if ($tag_cache === false) {
2957 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2958 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2960 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2964 $tags = explode(",", $tag_cache);
2967 /* do it the hard way */
2969 $tmp_result = db_query($link, $query);
2971 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2972 array_push($tags, $tmp_line["tag_name"]);
2975 /* update the cache */
2977 $tags_str = db_escape_string(join(",", $tags));
2979 db_query($link, "UPDATE ttrss_user_entries
2980 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2981 AND owner_uid = $owner_uid");
2987 function trim_array($array) {
2989 array_walk($tmp, 'trim');
2993 function tag_is_valid($tag) {
2994 if ($tag == '') return false;
2995 if (preg_match("/^[0-9]*$/", $tag)) return false;
2996 if (mb_strlen($tag) > 250) return false;
2998 if (function_exists('iconv')) {
2999 $tag = iconv("utf-8", "utf-8", $tag);
3002 if (!$tag) return false;
3007 function render_login_form($link, $form_id = 0) {
3010 require_once "login_form.php";
3013 require_once "mobile/login_form.php";
3019 // from http://developer.apple.com/internet/safari/faq.html
3020 function no_cache_incantation() {
3021 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3022 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3023 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3024 header("Cache-Control: post-check=0, pre-check=0", false);
3025 header("Pragma: no-cache"); // HTTP/1.0
3028 function format_warning($msg, $id = "") {
3030 return "<div class=\"warning\" id=\"$id\">
3031 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3034 function format_notice($msg, $id = "") {
3036 return "<div class=\"notice\" id=\"$id\">
3037 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3040 function format_error($msg, $id = "") {
3042 return "<div class=\"error\" id=\"$id\">
3043 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3046 function print_notice($msg) {
3047 return print format_notice($msg);
3050 function print_warning($msg) {
3051 return print format_warning($msg);
3054 function print_error($msg) {
3055 return print format_error($msg);
3059 function T_sprintf() {
3060 $args = func_get_args();
3061 return vsprintf(__(array_shift($args)), $args);
3064 function format_inline_player($link, $url, $ctype) {
3068 if (strpos($ctype, "audio/") === 0) {
3070 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3071 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3072 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3074 $id = 'AUDIO-' . uniqid();
3076 $entry .= "<audio id=\"$id\"\">
3077 <source src=\"$url\"></source>
3080 $entry .= "<span onclick=\"player(this)\"
3081 title=\"".__("Click to play")."\" status=\"0\"
3082 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3086 $entry .= "<object type=\"application/x-shockwave-flash\"
3087 data=\"lib/button/musicplayer.swf?song_url=$url\"
3088 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3089 <param name=\"movie\"
3090 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3095 $filename = substr($url, strrpos($url, "/")+
1);
3097 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3098 $filename . " (" . $ctype . ")" . "</a>";
3103 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3104 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3110 /* we can figure out feed_id from article id anyway, why do we
3111 * pass feed_id here? let's ignore the argument :( */
3113 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3114 WHERE ref_id = '$id'");
3116 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3118 $rv['feed_id'] = $feed_id;
3120 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3122 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
3123 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3125 if (db_num_rows($result) == 1) {
3126 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3127 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3128 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
3130 $rtl_content = false;
3131 $always_display_enclosures = false;
3132 $cache_content = false;
3136 $rtl_tag = "dir=\"RTL\"";
3143 if ($mark_as_read) {
3144 $result = db_query($link, "UPDATE ttrss_user_entries
3145 SET unread = false,last_read = NOW()
3146 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3148 ccache_update($link, $feed_id, $owner_uid);
3151 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3152 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3153 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3154 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3161 FROM ttrss_entries,ttrss_user_entries
3162 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3166 $line = db_fetch_assoc($result);
3168 if ($line["icon_url"]) {
3169 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3171 $feed_icon = " ";
3174 $feed_site_url = $line['site_url'];
3176 $num_comments = $line["num_comments"];
3177 $entry_comments = "";
3179 if ($num_comments > 0) {
3180 if ($line["comments"]) {
3181 $comments_url = htmlspecialchars($line["comments"]);
3183 $comments_url = htmlspecialchars($line["link"]);
3185 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3187 if ($line["comments"] && $line["link"] != $line["comments"]) {
3188 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
3193 header("Content-Type: text/html");
3194 $rv['content'] .= "<html><head>
3195 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3196 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3197 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3201 $title_escaped = htmlspecialchars($line['title']);
3203 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3204 truncate_string(strip_tags($line['title']), 15) . "</div>";
3206 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3207 strip_tags($line['title']) . "</div>";
3209 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3211 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3212 class=\"postHeader\" id=\"POSTHDR-$id\">";
3214 $entry_author = $line["author"];
3216 if ($entry_author) {
3217 $entry_author = __(" - ") . $entry_author;
3220 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3223 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3225 if ($line["link"]) {
3226 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3227 title=\"".htmlspecialchars($line['title'])."\"
3229 htmlspecialchars($line["link"]) . "\">" .
3231 "<span class='author'>$entry_author</span></a></div>";
3233 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3236 $tag_cache = $line["tag_cache"];
3239 $tags = get_article_tags($link, $id, $owner_uid);
3241 $tags = explode(",", $tag_cache);
3243 $tags_str = format_tags_string($tags, $id);
3244 $tags_str_full = join(", ", $tags);
3246 if (!$tags_str_full) $tags_str_full = __("no tags");
3248 if (!$entry_comments) $entry_comments = " "; # placeholder
3250 $rv['content'] .= "<div class='postTags' style='float : right'>
3251 <img src='".theme_image($link, 'images/tag.png')."'
3252 class='tagsPic' alt='Tags' title='Tags'> ";
3255 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3256 <a title=\"".__('Edit tags for this article')."\"
3257 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3259 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3260 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3261 position=\"below\">$tags_str_full</div>";
3263 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3264 class='tagsPic' style=\"cursor : pointer\"
3265 onclick=\"postOpenInNewTab(event, $id)\"
3266 alt='Zoom' title='".__('Open article in new tab')."'>";
3268 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3270 foreach ($button_plugins as $p) {
3271 $pclass = "button_" . trim($p);
3273 if (class_exists($pclass)) {
3274 $plugin = new $pclass($link);
3275 $rv['content'] .= $plugin->render($id, $line);
3279 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3280 class='tagsPic' style=\"cursor : pointer\"
3281 onclick=\"closeArticlePanel($id)\"
3282 title='".__('Close article')."'>";
3285 $tags_str = strip_tags($tags_str);
3286 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3288 $rv['content'] .= "</div>";
3289 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3291 if ($line["orig_feed_id"]) {
3293 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3294 WHERE id = ".$line["orig_feed_id"]);
3296 if (db_num_rows($tmp_result) != 0) {
3298 $rv['content'] .= "<div clear='both'>";
3299 $rv['content'] .= __("Originally from:");
3301 $rv['content'] .= " ";
3303 $tmp_line = db_fetch_assoc($tmp_result);
3305 $rv['content'] .= "<a target='_blank'
3306 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3307 $tmp_line['title'] . "</a>";
3309 $rv['content'] .= " ";
3311 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3312 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3314 $rv['content'] .= "</div>";
3318 $rv['content'] .= "</div>";
3320 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3321 if ($line['note']) {
3322 $rv['content'] .= format_article_note($id, $line['note']);
3324 $rv['content'] .= "</div>";
3326 $rv['content'] .= "<div class=\"postIcon\">" .
3327 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3328 href=\"".htmlspecialchars($feed_site_url)."\">".
3329 $feed_icon . "</a></div>";
3331 $rv['content'] .= "<div class=\"postContent\">";
3335 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3337 $ngram_result = db_query($link, "SELECT id,title FROM
3338 ttrss_entries,ttrss_user_entries
3339 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3340 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3341 AND title != '$title_escaped'
3342 AND owner_uid = $owner_uid");
3344 if (db_num_rows($ngram_result) > 0) {
3345 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3346 "<span>" . __('Related')."</span>";
3347 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3349 while ($nline = db_fetch_assoc($ngram_result)) {
3350 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3351 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3354 $rv['content'] .= "</div></div><br/";
3358 if ($cache_content && $line["cached_content"] != "") {
3359 $line["content"] =& $line["cached_content"];
3362 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3365 $rv['content'] .= $article_content;
3367 $rv['content'] .= format_article_enclosures($link, $id,
3368 $always_display_enclosures, $article_content);
3370 $rv['content'] .= "</div>";
3372 $rv['content'] .= "</div>";
3378 <div style=\"text-align : center\">
3379 <button onclick=\"return window.close()\">".
3380 __("Close this window")."</button></div>";
3381 $rv['content'] .= "</body></html>";
3388 function print_checkpoint($n, $s) {
3389 $ts = getmicrotime();
3390 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3394 function sanitize_tag($tag) {
3397 $tag = mb_strtolower($tag, 'utf-8');
3399 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3401 // $tag = str_replace('"', "", $tag);
3402 // $tag = str_replace("+", " ", $tag);
3403 $tag = str_replace("technorati tag: ", "", $tag);
3408 function get_self_url_prefix() {
3409 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3410 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3412 return SELF_URL_PATH
;
3416 function opml_publish_url($link){
3418 $url_path = get_self_url_prefix();
3419 $url_path .= "/opml.php?op=publish&key=" .
3420 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3426 * Purge a feed contents, marked articles excepted.
3428 * @param mixed $link The database connection.
3429 * @param integer $id The id of the feed to purge.
3432 function clear_feed_articles($link, $id) {
3435 $result = db_query($link, "DELETE FROM ttrss_user_entries
3436 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3438 $result = db_query($link, "DELETE FROM ttrss_user_entries
3439 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3442 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3443 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3445 ccache_update($link, $id, $_SESSION['uid']);
3446 } // function clear_feed_articles
3449 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3451 * @return string The Mozilla Firefox feed adding URL.
3453 function add_feed_url() {
3454 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3456 $url_path = get_self_url_prefix() .
3457 "/public.php?op=subscribe&feed_url=%s";
3459 } // function add_feed_url
3461 function encrypt_password($pass, $salt = '', $mode2 = false) {
3462 if ($salt && $mode2) {
3463 return "MODE2:" . hash('sha256', $salt . $pass);
3465 return "SHA1X:" . sha1("$salt:$pass");
3467 return "SHA1:" . sha1($pass);
3469 } // function encrypt_password
3471 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3474 $cat_id = (int)getFeedCategory($link, $feed_id);
3476 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3477 owner_uid = $owner_uid AND enabled = true");
3479 $check_cats = join(",", array_merge(
3480 getParentCategories($link, $cat_id, $owner_uid),
3483 while ($line = db_fetch_assoc($result)) {
3484 $filter_id = $line["id"];
3486 $result2 = db_query($link, "SELECT
3487 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3488 FROM ttrss_filters2_rules AS r,
3489 ttrss_filter_types AS t
3491 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3492 (feed_id IS NULL OR feed_id = '$feed_id') AND
3493 filter_type = t.id AND filter_id = '$filter_id'");
3498 while ($rule_line = db_fetch_assoc($result2)) {
3499 # print_r($rule_line);
3502 $rule["reg_exp"] = $rule_line["reg_exp"];
3503 $rule["type"] = $rule_line["type_name"];
3505 array_push($rules, $rule);
3508 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3509 FROM ttrss_filters2_actions AS a,
3510 ttrss_filter_actions AS t
3512 action_id = t.id AND filter_id = '$filter_id'");
3514 while ($action_line = db_fetch_assoc($result2)) {
3515 # print_r($action_line);
3518 $action["type"] = $action_line["type_name"];
3519 $action["param"] = $action_line["action_param"];
3521 array_push($actions, $action);
3526 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3527 $filter["rules"] = $rules;
3528 $filter["actions"] = $actions;
3530 if (count($rules) > 0 && count($actions) > 0) {
3531 array_push($filters, $filter);
3538 function get_score_pic($score) {
3540 return "score_high.png";
3541 } else if ($score > 0) {
3542 return "score_half_high.png";
3543 } else if ($score < -100) {
3544 return "score_low.png";
3545 } else if ($score < 0) {
3546 return "score_half_low.png";
3548 return "score_neutral.png";
3552 function feed_has_icon($id) {
3553 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3556 function init_connection($link) {
3559 if (DB_TYPE
== "pgsql") {
3560 pg_query($link, "set client_encoding = 'UTF-8'");
3561 pg_set_client_encoding("UNICODE");
3562 pg_query($link, "set datestyle = 'ISO, european'");
3563 pg_query($link, "set TIME ZONE 0");
3565 db_query($link, "SET time_zone = '+0:0'");
3567 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3568 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3573 print "Unable to connect to database:" . db_last_error();
3578 /* function ccache_zero($link, $feed_id, $owner_uid) {
3579 db_query($link, "UPDATE ttrss_counters_cache SET
3580 value = 0, updated = NOW() WHERE
3581 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3584 function ccache_zero_all($link, $owner_uid) {
3585 db_query($link, "UPDATE ttrss_counters_cache SET
3586 value = 0 WHERE owner_uid = '$owner_uid'");
3588 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3589 value = 0 WHERE owner_uid = '$owner_uid'");
3592 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3595 $table = "ttrss_counters_cache";
3597 $table = "ttrss_cat_counters_cache";
3600 db_query($link, "DELETE FROM $table WHERE
3601 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3605 function ccache_update_all($link, $owner_uid) {
3607 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3609 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3610 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3612 while ($line = db_fetch_assoc($result)) {
3613 ccache_update($link, $line["feed_id"], $owner_uid, true);
3616 /* We have to manually include category 0 */
3618 ccache_update($link, 0, $owner_uid, true);
3621 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3622 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3624 while ($line = db_fetch_assoc($result)) {
3625 print ccache_update($link, $line["feed_id"], $owner_uid);
3632 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3633 $no_update = false) {
3635 if (!is_numeric($feed_id)) return;
3638 $table = "ttrss_counters_cache";
3640 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3641 WHERE id = '$feed_id'");
3642 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3645 $table = "ttrss_cat_counters_cache";
3648 if (DB_TYPE
== "pgsql") {
3649 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3650 } else if (DB_TYPE
== "mysql") {
3651 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3654 $result = db_query($link, "SELECT value FROM $table
3655 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3658 if (db_num_rows($result) == 1) {
3659 return db_fetch_result($result, 0, "value");
3664 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3670 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3671 $update_pcat = true) {
3673 if (!is_numeric($feed_id)) return;
3675 if (!$is_cat && $feed_id > 0) {
3676 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3677 WHERE id = '$feed_id'");
3678 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3681 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3683 /* When updating a label, all we need to do is recalculate feed counters
3684 * because labels are not cached */
3687 ccache_update_all($link, $owner_uid);
3692 $table = "ttrss_counters_cache";
3694 $table = "ttrss_cat_counters_cache";
3697 if ($is_cat && $feed_id >= 0) {
3698 if ($feed_id != 0) {
3699 $cat_qpart = "cat_id = '$feed_id'";
3701 $cat_qpart = "cat_id IS NULL";
3704 /* Recalculate counters for child feeds */
3706 $result = db_query($link, "SELECT id FROM ttrss_feeds
3707 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3709 while ($line = db_fetch_assoc($result)) {
3710 ccache_update($link, $line["id"], $owner_uid, false, false);
3713 $result = db_query($link, "SELECT SUM(value) AS sv
3714 FROM ttrss_counters_cache, ttrss_feeds
3715 WHERE id = feed_id AND $cat_qpart AND
3716 ttrss_feeds.owner_uid = '$owner_uid'");
3718 $unread = (int) db_fetch_result($result, 0, "sv");
3721 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3724 db_query($link, "BEGIN");
3726 $result = db_query($link, "SELECT feed_id FROM $table
3727 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3729 if (db_num_rows($result) == 1) {
3730 db_query($link, "UPDATE $table SET
3731 value = '$unread', updated = NOW() WHERE
3732 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3735 db_query($link, "INSERT INTO $table
3736 (feed_id, value, owner_uid, updated)
3738 ($feed_id, $unread, $owner_uid, NOW())");
3741 db_query($link, "COMMIT");
3743 if ($feed_id > 0 && $prev_unread != $unread) {
3747 /* Update parent category */
3751 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3752 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3754 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3756 ccache_update($link, $cat_id, $owner_uid, true);
3760 } else if ($feed_id < 0) {
3761 ccache_update_all($link, $owner_uid);
3767 /* function ccache_cleanup($link, $owner_uid) {
3769 if (DB_TYPE == "pgsql") {
3770 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3771 (SELECT count(*) FROM ttrss_counters_cache AS c2
3772 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3773 AND owner_uid = '$owner_uid'");
3775 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3776 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3777 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3778 AND owner_uid = '$owner_uid'");
3780 db_query($link, "DELETE c1 FROM
3781 ttrss_counters_cache AS c1,
3782 ttrss_counters_cache AS c2
3784 c1.owner_uid = '$owner_uid' AND
3785 c1.owner_uid = c2.owner_uid AND
3786 c1.feed_id = c2.feed_id");
3788 db_query($link, "DELETE c1 FROM
3789 ttrss_cat_counters_cache AS c1,
3790 ttrss_cat_counters_cache AS c2
3792 c1.owner_uid = '$owner_uid' AND
3793 c1.owner_uid = c2.owner_uid AND
3794 c1.feed_id = c2.feed_id");
3799 function label_find_id($link, $label, $owner_uid) {
3800 $result = db_query($link,
3801 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3802 AND owner_uid = '$owner_uid' LIMIT 1");
3804 if (db_num_rows($result) == 1) {
3805 return db_fetch_result($result, 0, "id");
3811 function get_article_labels($link, $id, $owner_uid = false) {
3814 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3816 $result = db_query($link, "SELECT label_cache FROM
3817 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3820 if (db_num_rows($result) > 0) {
3821 $label_cache = db_fetch_result($result, 0, "label_cache");
3824 $label_cache = json_decode($label_cache, true);
3826 if ($label_cache["no-labels"] == 1)
3829 return $label_cache;
3833 $result = db_query($link,
3834 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3835 FROM ttrss_labels2, ttrss_user_labels2
3837 AND article_id = '$id'
3838 AND owner_uid = ". $owner_uid . "
3841 while ($line = db_fetch_assoc($result)) {
3842 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3844 array_push($rv, $rk);
3848 label_update_cache($link, $owner_uid, $id, $rv);
3850 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3856 function label_find_caption($link, $label, $owner_uid) {
3857 $result = db_query($link,
3858 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3859 AND owner_uid = '$owner_uid' LIMIT 1");
3861 if (db_num_rows($result) == 1) {
3862 return db_fetch_result($result, 0, "caption");
3868 function get_all_labels($link, $owner_uid) {
3871 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3873 while ($line = db_fetch_assoc($result)) {
3874 array_push($rv, $line);
3880 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3883 label_clear_cache($link, $id);
3886 $labels = get_article_labels($link, $id);
3888 $labels = db_escape_string(json_encode($labels));
3890 db_query($link, "UPDATE ttrss_user_entries SET
3891 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3895 function label_clear_cache($link, $id) {
3897 db_query($link, "UPDATE ttrss_user_entries SET
3898 label_cache = '' WHERE ref_id = '$id'");
3902 function label_remove_article($link, $id, $label, $owner_uid) {
3904 $label_id = label_find_id($link, $label, $owner_uid);
3906 if (!$label_id) return;
3908 $result = db_query($link,
3909 "DELETE FROM ttrss_user_labels2
3911 label_id = '$label_id' AND
3912 article_id = '$id'");
3914 label_clear_cache($link, $id);
3917 function label_add_article($link, $id, $label, $owner_uid) {
3919 $label_id = label_find_id($link, $label, $owner_uid);
3921 if (!$label_id) return;
3923 $result = db_query($link,
3925 article_id FROM ttrss_labels2, ttrss_user_labels2
3928 label_id = '$label_id' AND
3929 article_id = '$id' AND owner_uid = '$owner_uid'
3932 if (db_num_rows($result) == 0) {
3933 db_query($link, "INSERT INTO ttrss_user_labels2
3934 (label_id, article_id) VALUES ('$label_id', '$id')");
3937 label_clear_cache($link, $id);
3941 function label_remove($link, $id, $owner_uid) {
3942 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3944 db_query($link, "BEGIN");
3946 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3949 $caption = db_fetch_result($result, 0, "caption");
3951 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3952 AND owner_uid = " . $owner_uid);
3954 if (db_affected_rows($link, $result) != 0 && $caption) {
3956 /* Remove access key for the label */
3958 $ext_id = -11 - $id;
3960 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3961 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3963 /* Disable filters that reference label being removed */
3965 db_query($link, "UPDATE ttrss_filters SET
3966 enabled = false WHERE action_param = '$caption'
3968 AND owner_uid = " . $owner_uid);
3970 /* Remove cached data */
3972 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3973 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3977 db_query($link, "COMMIT");
3980 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3982 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3984 db_query($link, "BEGIN");
3988 $result = db_query($link, "SELECT id FROM ttrss_labels2
3989 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3991 if (db_num_rows($result) == 0) {
3992 $result = db_query($link,
3993 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3994 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3996 $result = db_affected_rows($link, $result) != 0;
3999 db_query($link, "COMMIT");
4004 function format_tags_string($tags, $id) {
4007 $tags_nolinks_str = "";
4013 $formatted_tags = array();
4015 foreach ($tags as $tag) {
4017 $tag_escaped = str_replace("'", "\\'", $tag);
4019 if (mb_strlen($tag) > 30) {
4020 $tag = truncate_string($tag, 30);
4023 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4025 array_push($formatted_tags, $tag_str);
4027 $tmp_tags_str = implode(", ", $formatted_tags);
4029 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4034 $tags_str = implode(", ", $formatted_tags);
4036 if ($num_tags < count($tags)) {
4037 $tags_str .= ", …";
4040 if ($num_tags == 0) {
4041 $tags_str = __("no tags");
4048 function format_article_labels($labels, $id) {
4052 foreach ($labels as $l) {
4053 $labels_str .= sprintf("<span class='hlLabelRef'
4054 style='color : %s; background-color : %s'>%s</span>",
4055 $l[2], $l[3], $l[1]);
4062 function format_article_note($id, $note) {
4064 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4065 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4066 __('(edit note)')."</div>$note</div>";
4071 function toggle_collapse_cat($link, $cat_id, $mode) {
4073 $mode = bool_to_sql_bool($mode);
4075 db_query($link, "UPDATE ttrss_feed_categories SET
4076 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4083 $pref_name = '_COLLAPSED_SPECIAL';
4086 $pref_name = '_COLLAPSED_LABELS';
4089 $pref_name = '_COLLAPSED_UNCAT';
4095 set_pref($link, $pref_name, 'true');
4097 set_pref($link, $pref_name, 'false');
4103 function remove_feed($link, $id, $owner_uid) {
4107 /* save starred articles in Archived feed */
4109 db_query($link, "BEGIN");
4111 /* prepare feed if necessary */
4113 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4116 if (db_num_rows($result) == 0) {
4117 db_query($link, "INSERT INTO ttrss_archived_feeds
4118 (id, owner_uid, title, feed_url, site_url)
4119 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4123 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4124 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4125 marked = true AND owner_uid = $owner_uid");
4127 /* Remove access key for the feed */
4129 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4130 feed_id = '$id' AND owner_uid = $owner_uid");
4132 /* remove the feed */
4134 db_query($link, "DELETE FROM ttrss_feeds
4135 WHERE id = '$id' AND owner_uid = $owner_uid");
4137 db_query($link, "COMMIT");
4139 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4140 unlink(ICONS_DIR
. "/$id.ico");
4143 ccache_remove($link, $id, $owner_uid);
4146 label_remove($link, -11-$id, $owner_uid);
4147 ccache_remove($link, -11-$id, $owner_uid);
4151 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
4152 if ($parent_cat_id) {
4153 $parent_qpart = "parent_cat = '$parent_cat_id'";
4154 $parent_insert = "'$parent_cat_id'";
4156 $parent_qpart = "parent_cat IS NULL";
4157 $parent_insert = "NULL";
4160 $result = db_query($link,
4161 "SELECT id FROM ttrss_feed_categories
4162 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4164 if (db_num_rows($result) == 0) {
4167 return db_fetch_result($result, 0, "id");
4171 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
4173 if (!$feed_cat) return false;
4175 db_query($link, "BEGIN");
4177 if ($parent_cat_id) {
4178 $parent_qpart = "parent_cat = '$parent_cat_id'";
4179 $parent_insert = "'$parent_cat_id'";
4181 $parent_qpart = "parent_cat IS NULL";
4182 $parent_insert = "NULL";
4185 $result = db_query($link,
4186 "SELECT id FROM ttrss_feed_categories
4187 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4189 if (db_num_rows($result) == 0) {
4191 $result = db_query($link,
4192 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4193 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
4195 db_query($link, "COMMIT");
4203 function remove_feed_category($link, $id, $owner_uid) {
4205 db_query($link, "DELETE FROM ttrss_feed_categories
4206 WHERE id = '$id' AND owner_uid = $owner_uid");
4208 ccache_remove($link, $id, $owner_uid, true);
4211 function archive_article($link, $id, $owner_uid) {
4212 db_query($link, "BEGIN");
4214 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4215 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4217 if (db_num_rows($result) != 0) {
4219 /* prepare the archived table */
4221 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4224 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4225 WHERE id = '$feed_id'");
4227 if (db_num_rows($result) == 0) {
4228 db_query($link, "INSERT INTO ttrss_archived_feeds
4229 (id, owner_uid, title, feed_url, site_url)
4230 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4231 WHERE id = '$feed_id'");
4234 db_query($link, "UPDATE ttrss_user_entries
4235 SET orig_feed_id = feed_id, feed_id = NULL
4236 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4240 db_query($link, "COMMIT");
4243 function getArticleFeed($link, $id) {
4244 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4245 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4247 if (db_num_rows($result) != 0) {
4248 return db_fetch_result($result, 0, "feed_id");
4255 * Fixes incomplete URLs by prepending "http://".
4256 * Also replaces feed:// with http://, and
4257 * prepends a trailing slash if the url is a domain name only.
4259 * @param string $url Possibly incomplete URL
4261 * @return string Fixed URL.
4263 function fix_url($url) {
4264 if (strpos($url, '://') === false) {
4265 $url = 'http://' . $url;
4266 } else if (substr($url, 0, 5) == 'feed:') {
4267 $url = 'http:' . substr($url, 5);
4270 //prepend slash if the URL has no slash in it
4271 // "http://www.example" -> "http://www.example/"
4272 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4276 if ($url != "http:///")
4282 function validate_feed_url($url) {
4283 $parts = parse_url($url);
4285 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4289 function get_article_enclosures($link, $id) {
4291 $query = "SELECT * FROM ttrss_enclosures
4292 WHERE post_id = '$id' AND content_url != ''";
4296 $result = db_query($link, $query);
4298 if (db_num_rows($result) > 0) {
4299 while ($line = db_fetch_assoc($result)) {
4300 array_push($rv, $line);
4307 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4313 if ($cat_id == -4 ||
$cat_id == -2) {
4314 $counters = getLabelCounters($link, true);
4316 foreach (array_values($counters) as $cv) {
4318 $unread = $cv["counter"];
4320 if ($unread ||
!$unread_only) {
4324 "title" => $cv["description"],
4325 "unread" => $cv["counter"],
4329 array_push($feeds, $row);
4336 if ($cat_id == -4 ||
$cat_id == -1) {
4337 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4338 $unread = getFeedUnread($link, $i);
4340 if ($unread ||
!$unread_only) {
4341 $title = getFeedTitle($link, $i);
4346 "unread" => $unread,
4349 array_push($feeds, $row);
4357 if ($include_nested && $cat_id) {
4358 $result = db_query($link, "SELECT
4359 id, title FROM ttrss_feed_categories
4360 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4361 " ORDER BY id, title");
4363 while ($line = db_fetch_assoc($result)) {
4364 $unread = getFeedUnread($link, $line["id"], true) +
4365 getCategoryChildrenUnread($link, $line["id"]);
4367 if ($unread ||
!$unread_only) {
4369 "id" => $line["id"],
4370 "title" => $line["title"],
4371 "unread" => $unread,
4374 array_push($feeds, $row);
4382 $limit_qpart = "LIMIT $limit OFFSET $offset";
4387 if ($cat_id == -4 ||
$cat_id == -3) {
4388 $result = db_query($link, "SELECT
4389 id, feed_url, cat_id, title, order_id, ".
4390 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4391 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4392 " ORDER BY cat_id, title " . $limit_qpart);
4396 $cat_qpart = "cat_id = '$cat_id'";
4398 $cat_qpart = "cat_id IS NULL";
4400 $result = db_query($link, "SELECT
4401 id, feed_url, cat_id, title, order_id, ".
4402 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4403 FROM ttrss_feeds WHERE
4404 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4405 " ORDER BY cat_id, title " . $limit_qpart);
4408 while ($line = db_fetch_assoc($result)) {
4410 $unread = getFeedUnread($link, $line["id"]);
4412 $has_icon = feed_has_icon($line['id']);
4414 if ($unread ||
!$unread_only) {
4417 "feed_url" => $line["feed_url"],
4418 "title" => $line["title"],
4419 "id" => (int)$line["id"],
4420 "unread" => (int)$unread,
4421 "has_icon" => $has_icon,
4422 "cat_id" => (int)$line["cat_id"],
4423 "last_updated" => strtotime($line["last_updated"]),
4424 "order_id" => (int) $line["order_id"],
4427 array_push($feeds, $row);
4434 function api_get_headlines($link, $feed_id, $limit, $offset,
4435 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4436 $include_attachments, $since_id,
4437 $search = "", $search_mode = "", $match_on = "",
4438 $include_nested = false, $sanitize_content = true) {
4440 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4441 $view_mode, $is_cat, $search, $search_mode, $match_on,
4442 $order, $offset, 0, false, $since_id, $include_nested);
4444 $result = $qfh_ret[0];
4445 $feed_title = $qfh_ret[1];
4447 $headlines = array();
4449 while ($line = db_fetch_assoc($result)) {
4450 $is_updated = ($line["last_read"] == "" &&
4451 ($line["unread"] != "t" && $line["unread"] != "1"));
4453 $tags = explode(",", $line["tag_cache"]);
4454 $labels = json_decode($line["label_cache"], true);
4456 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4457 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4459 $headline_row = array(
4460 "id" => (int)$line["id"],
4461 "unread" => sql_bool_to_bool($line["unread"]),
4462 "marked" => sql_bool_to_bool($line["marked"]),
4463 "published" => sql_bool_to_bool($line["published"]),
4464 "updated" => strtotime($line["updated"]),
4465 "is_updated" => $is_updated,
4466 "title" => $line["title"],
4467 "link" => $line["link"],
4468 "feed_id" => $line["feed_id"],
4472 if ($include_attachments)
4473 $headline_row['attachments'] = get_article_enclosures($link,
4476 if ($show_excerpt) {
4477 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4478 $headline_row["excerpt"] = $excerpt;
4481 if ($show_content) {
4483 if ($line["cached_content"] != "") {
4484 $line["content_preview"] =& $line["cached_content"];
4487 if ($sanitize_content) {
4488 $headline_row["content"] = sanitize($link,
4489 $line["content_preview"], false, false, $line["site_url"]);
4491 $headline_row["content"] = $line["content_preview"];
4495 // unify label output to ease parsing
4496 if ($labels["no-labels"] == 1) $labels = array();
4498 $headline_row["labels"] = $labels;
4500 $headline_row["feed_title"] = $line["feed_title"];
4502 $headline_row["comments_count"] = (int)$line["num_comments"];
4503 $headline_row["comments_link"] = $line["comments"];
4505 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4507 array_push($headlines, $headline_row);
4513 function generate_error_feed($link, $error) {
4516 $reply['headlines']['id'] = -6;
4517 $reply['headlines']['is_cat'] = false;
4519 $reply['headlines']['toolbar'] = '';
4520 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4522 $reply['headlines-info'] = array("count" => 0,
4523 "vgroup_last_feed" => '',
4525 "disable_cache" => true);
4531 function generate_dashboard_feed($link) {
4534 $reply['headlines']['id'] = -5;
4535 $reply['headlines']['is_cat'] = false;
4537 $reply['headlines']['toolbar'] = '';
4538 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4540 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4542 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4543 WHERE owner_uid = " . $_SESSION['uid']);
4545 $last_updated = db_fetch_result($result, 0, "last_updated");
4546 $last_updated = make_local_datetime($link, $last_updated, false);
4548 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4550 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4551 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4553 $num_errors = db_fetch_result($result, 0, "num_errors");
4555 if ($num_errors > 0) {
4556 $reply['headlines']['content'] .= "<br/>";
4557 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4558 __('Some feeds have update errors (click for details)')."</a>";
4560 $reply['headlines']['content'] .= "</span></p>";
4562 $reply['headlines-info'] = array("count" => 0,
4563 "vgroup_last_feed" => '',
4565 "disable_cache" => true);
4570 function save_email_address($link, $email) {
4571 // FIXME: implement persistent storage of emails
4573 if (!$_SESSION['stored_emails'])
4574 $_SESSION['stored_emails'] = array();
4576 if (!in_array($email, $_SESSION['stored_emails']))
4577 array_push($_SESSION['stored_emails'], $email);
4580 function update_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 $key = db_escape_string(sha1(uniqid(rand(), true)));
4592 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4593 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4594 AND owner_uid = " . $owner_uid);
4599 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4603 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4605 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4607 $sql_is_cat = bool_to_sql_bool($is_cat);
4609 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4610 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4611 AND owner_uid = " . $owner_uid);
4613 if (db_num_rows($result) == 1) {
4614 return db_fetch_result($result, 0, "access_key");
4616 $key = db_escape_string(sha1(uniqid(rand(), true)));
4618 $result = db_query($link, "INSERT INTO ttrss_access_keys
4619 (access_key, feed_id, is_cat, owner_uid)
4620 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4627 function get_feeds_from_html($url, $content)
4629 $url = fix_url($url);
4630 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4632 libxml_use_internal_errors(true);
4634 $doc = new DOMDocument();
4635 $doc->loadHTML($content);
4636 $xpath = new DOMXPath($doc);
4637 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4638 $feedUrls = array();
4639 foreach ($entries as $entry) {
4640 if ($entry->hasAttribute('href')) {
4641 $title = $entry->getAttribute('title');
4643 $title = $entry->getAttribute('type');
4645 $feedUrl = rewrite_relative_url(
4646 $baseUrl, $entry->getAttribute('href')
4648 $feedUrls[$feedUrl] = $title;
4654 function is_html($content) {
4655 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4658 function url_is_html($url, $login = false, $pass = false) {
4659 return is_html(fetch_file_contents($url, false, $login, $pass));
4662 function print_label_select($link, $name, $value, $attributes = "") {
4664 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4665 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4667 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4668 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4670 while ($line = db_fetch_assoc($result)) {
4672 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4674 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4675 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4679 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4686 function format_article_enclosures($link, $id, $always_display_enclosures,
4689 $result = get_article_enclosures($link, $id);
4692 if (count($result) > 0) {
4694 $entries_html = array();
4697 foreach ($result as $line) {
4699 $url = $line["content_url"];
4700 $ctype = $line["content_type"];
4702 if (!$ctype) $ctype = __("unknown type");
4704 $filename = substr($url, strrpos($url, "/")+
1);
4706 # $player = format_inline_player($link, $url, $ctype);
4708 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4709 # $filename . " (" . $ctype . ")" . "</a>";
4711 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4712 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4714 array_push($entries_html, $entry);
4718 $entry["type"] = $ctype;
4719 $entry["filename"] = $filename;
4720 $entry["url"] = $url;
4722 array_push($entries, $entry);
4725 if (!get_pref($link, "STRIP_IMAGES")) {
4726 if ($always_display_enclosures ||
4727 !preg_match("/<img/i", $article_content)) {
4729 foreach ($entries as $entry) {
4731 if (preg_match("/image/", $entry["type"]) ||
4732 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4735 alt=\"".htmlspecialchars($entry["filename"])."\"
4736 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4743 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4744 "<span>" . __('Attachments')."</span>";
4745 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4747 foreach ($entries_html as $entry) { $rv .= $entry; };
4749 $rv .= "</div></div>";
4755 function getLastArticleId($link) {
4756 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4757 WHERE owner_uid = " . $_SESSION["uid"]);
4759 if (db_num_rows($result) == 1) {
4760 return db_fetch_result($result, 0, "id");
4766 function build_url($parts) {
4767 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4771 * Converts a (possibly) relative URL to a absolute one.
4773 * @param string $url Base URL (i.e. from where the document is)
4774 * @param string $rel_url Possibly relative URL in the document
4776 * @return string Absolute URL
4778 function rewrite_relative_url($url, $rel_url) {
4779 if (strpos($rel_url, "magnet:") === 0) {
4781 } else if (strpos($rel_url, "://") !== false) {
4783 } else if (strpos($rel_url, "//") === 0) {
4784 # protocol-relative URL (rare but they exist)
4786 } else if (strpos($rel_url, "/") === 0)
4788 $parts = parse_url($url);
4789 $parts['path'] = $rel_url;
4791 return build_url($parts);
4794 $parts = parse_url($url);
4795 if (!isset($parts['path'])) {
4796 $parts['path'] = '/';
4798 $dir = $parts['path'];
4799 if (substr($dir, -1) !== '/') {
4800 $dir = dirname($parts['path']);
4801 $dir !== '/' && $dir .= '/';
4803 $parts['path'] = $dir . $rel_url;
4805 return build_url($parts);
4809 function sphinx_search($query, $offset = 0, $limit = 30) {
4810 require_once 'lib/sphinxapi.php';
4812 $sphinxClient = new SphinxClient();
4814 $sphinxClient->SetServer('localhost', 9312);
4815 $sphinxClient->SetConnectTimeout(1);
4817 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4818 'feed_title' => 20));
4820 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4821 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4822 $sphinxClient->SetLimits($offset, $limit, 1000);
4823 $sphinxClient->SetArrayResult(false);
4824 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4826 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4830 if (is_array($result['matches'])) {
4831 foreach (array_keys($result['matches']) as $int_id) {
4832 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4833 array_push($ids, $ref_id);
4840 function cleanup_tags($link, $days = 14, $limit = 1000) {
4842 if (DB_TYPE
== "pgsql") {
4843 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4844 } else if (DB_TYPE
== "mysql") {
4845 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4850 while ($limit > 0) {
4853 $query = "SELECT ttrss_tags.id AS id
4854 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4855 WHERE post_int_id = int_id AND $interval_query AND
4856 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4858 $result = db_query($link, $query);
4862 while ($line = db_fetch_assoc($result)) {
4863 array_push($ids, $line['id']);
4866 if (count($ids) > 0) {
4867 $ids = join(",", $ids);
4870 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4871 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4876 $limit -= $limit_part;
4881 return $tags_deleted;
4884 function print_user_stylesheet($link) {
4885 $value = get_pref($link, 'USER_STYLESHEET');
4888 print "<style type=\"text/css\">";
4889 print str_replace("<br/>", "\n", $value);
4895 /* function rewrite_urls($line) {
4900 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4901 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4906 function rewrite_urls($html) {
4907 libxml_use_internal_errors(true);
4909 $charset_hack = '<head>
4910 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4913 $doc = new DOMDocument();
4914 $doc->loadHTML($charset_hack . $html);
4915 $xpath = new DOMXPath($doc);
4917 $entries = $xpath->query('//*/text()');
4919 foreach ($entries as $entry) {
4920 if (strstr($entry->wholeText
, "://") !== false) {
4921 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4922 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4924 if ($text != $entry->wholeText
) {
4925 $cdoc = new DOMDocument();
4926 $cdoc->loadHTML($charset_hack . $text);
4929 foreach ($cdoc->childNodes
as $cnode) {
4930 $cnode = $doc->importNode($cnode, true);
4933 $entry->parentNode
->insertBefore($cnode);
4937 $entry->parentNode
->removeChild($entry);
4943 $node = $doc->getElementsByTagName('body')->item(0);
4945 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4947 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4952 function filter_to_sql($link, $filter, $owner_uid) {
4955 if (DB_TYPE
== "pgsql")
4958 $reg_qpart = "REGEXP";
4960 foreach ($filter["rules"] AS $rule) {
4961 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4962 $rule['reg_exp']) !== FALSE;
4964 if ($regexp_valid) {
4966 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4968 switch ($rule["type"]) {
4970 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4971 $rule['reg_exp'] . "')";
4974 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4975 $rule['reg_exp'] . "')";
4978 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4979 $rule['reg_exp'] . "') OR LOWER(" .
4980 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4983 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4984 $rule['reg_exp'] . "')";
4987 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4988 $rule['reg_exp'] . "')";
4991 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4992 $rule['reg_exp'] . "')";
4996 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4997 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
5000 if (isset($rule["cat_id"])) {
5002 if ($rule["cat_id"] > 0) {
5003 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
5004 array_push($children, $rule["cat_id"]);
5006 $children = join(",", $children);
5008 $cat_qpart = "cat_id IN ($children)";
5010 $cat_qpart = "cat_id IS NULL";
5013 $qpart .= " AND $cat_qpart";
5016 array_push($query, "($qpart)");
5021 if (count($query) > 0) {
5022 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
5029 // -1 - never connected
5030 // 0 - no data received
5031 // 1 - data received successfully
5032 // 2 - did not receive valid data
5033 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5035 function get_linked_feeds($link, $instance_id = false) {
5037 $instance_qpart = "id = '$instance_id' AND ";
5039 $instance_qpart = "";
5041 if (DB_TYPE
== "pgsql") {
5042 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5044 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5047 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5048 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5050 while ($line = db_fetch_assoc($result)) {
5053 _debug("Updating: " . $line['access_url'] . " ($id)");
5055 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5056 $post_query = 'key=' . $line['access_key'];
5058 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5060 // try doing it the old way
5062 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5063 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5067 $feeds = json_decode($feeds, true);
5070 if ($feeds['error']) {
5071 $status = $feeds['error']['code'] +
10;
5074 if ($status == 16) {
5075 db_query($link, "DELETE FROM ttrss_linked_feeds
5076 WHERE instance_id = '$id'");
5081 if (count($feeds['feeds']) > 0) {
5083 db_query($link, "DELETE FROM ttrss_linked_feeds
5084 WHERE instance_id = '$id'");
5086 foreach ($feeds['feeds'] as $feed) {
5087 $feed_url = db_escape_string($feed['feed_url']);
5088 $title = db_escape_string($feed['title']);
5089 $subscribers = db_escape_string($feed['subscribers']);
5090 $site_url = db_escape_string($feed['site_url']);
5092 db_query($link, "INSERT INTO ttrss_linked_feeds
5093 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5095 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5098 // received 0 feeds, this might indicate that
5099 // the instance on the other hand is rebuilding feedbrowser cache
5100 // we will try again later
5102 // TODO: maybe perform expiration based on updated here?
5105 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5115 _debug("Status: $status");
5117 db_query($link, "UPDATE ttrss_linked_instances SET
5118 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5123 function make_feed_browser($link, $search, $limit, $mode = 1) {
5125 $owner_uid = $_SESSION["uid"];
5129 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5130 UPPER(title) LIKE UPPER('%$search%'))";
5136 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5137 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5138 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5139 AND owner_uid = '$owner_uid') $search_qpart
5140 ORDER BY subscribers DESC LIMIT $limit"); */
5142 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5143 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5144 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5146 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5147 WHERE tf.feed_url = qqq.feed_url
5148 AND owner_uid = '$owner_uid') $search_qpart
5149 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5151 } else if ($mode == 2) {
5152 $result = db_query($link, "SELECT *,
5153 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5154 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5156 ttrss_archived_feeds
5158 (SELECT COUNT(*) FROM ttrss_feeds
5159 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5160 owner_uid = '$owner_uid') = 0 AND
5161 owner_uid = '$owner_uid' $search_qpart
5162 ORDER BY id DESC LIMIT $limit");
5167 while ($line = db_fetch_assoc($result)) {
5171 $feed_url = htmlspecialchars($line["feed_url"]);
5172 $site_url = htmlspecialchars($line["site_url"]);
5173 $subscribers = $line["subscribers"];
5175 $check_box = "<input onclick='toggleSelectListRow2(this)'
5176 dojoType=\"dijit.form.CheckBox\"
5177 type=\"checkbox\" \">";
5179 $class = ($feedctr %
2) ?
"even" : "odd";
5181 $site_url = "<a target=\"_blank\"
5183 <span class=\"fb_feedTitle\">".
5184 htmlspecialchars($line["title"])."</span></a>";
5186 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5187 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5188 style='vertical-align : middle'></a>";
5190 $rv .= "<li>$check_box $feed_url $site_url".
5191 " <span class='subscribers'>($subscribers)</span></li>";
5193 } else if ($mode == 2) {
5194 $feed_url = htmlspecialchars($line["feed_url"]);
5195 $site_url = htmlspecialchars($line["site_url"]);
5196 $title = htmlspecialchars($line["title"]);
5198 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5199 type=\"checkbox\">";
5201 $class = ($feedctr %
2) ?
"even" : "odd";
5203 if ($line['articles_archived'] > 0) {
5204 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5205 $archived = " <span class='subscribers'>($archived)</span>";
5210 $site_url = "<a target=\"_blank\"
5212 <span class=\"fb_feedTitle\">".
5213 htmlspecialchars($line["title"])."</span></a>";
5215 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5216 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5217 style='vertical-align : middle'></a>";
5220 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5221 "$check_box $feed_url $site_url $archived</li>";
5227 if ($feedctr == 0) {
5228 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5234 if (!function_exists('gzdecode')) {
5235 function gzdecode($string) { // no support for 2nd argument
5236 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5237 base64_encode($string));
5241 function perform_data_import($link, $filename, $owner_uid) {
5245 $num_feeds_created = 0;
5247 $doc = @DOMDocument
::load($filename);
5250 $contents = file_get_contents($filename);
5253 $data = @gzuncompress
($contents);
5257 $data = @gzdecode
($contents);
5261 $doc = DOMDocument
::loadXML($data);
5266 $xpath = new DOMXpath($doc);
5268 $container = $doc->firstChild
;
5270 if ($container && $container->hasAttribute('schema-version')) {
5271 $schema_version = $container->getAttribute('schema-version');
5273 if ($schema_version != SCHEMA_VERSION
) {
5274 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5279 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5283 $articles = $xpath->query("//article");
5285 foreach ($articles as $article_node) {
5286 if ($article_node->childNodes
) {
5292 foreach ($article_node->childNodes
as $child) {
5293 if ($child->nodeName
!= 'label_cache')
5294 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5296 $article[$child->nodeName
] = $child->nodeValue
;
5299 //print_r($article);
5301 if ($article['guid']) {
5305 //db_query($link, "BEGIN");
5307 //print 'GUID:' . $article['guid'] . "\n";
5309 $result = db_query($link, "SELECT id FROM ttrss_entries
5310 WHERE guid = '".$article['guid']."'");
5312 if (db_num_rows($result) == 0) {
5314 $result = db_query($link,
5315 "INSERT INTO ttrss_entries
5329 ('".$article['title']."',
5330 '".$article['guid']."',
5331 '".$article['link']."',
5332 '".$article['updated']."',
5333 '".$article['content']."',
5334 '".sha1($article['content'])."',
5342 $result = db_query($link, "SELECT id FROM ttrss_entries
5343 WHERE guid = '".$article['guid']."'");
5345 if (db_num_rows($result) != 0) {
5346 $ref_id = db_fetch_result($result, 0, "id");
5350 $ref_id = db_fetch_result($result, 0, "id");
5353 //print "Got ref ID: $ref_id\n";
5357 $feed_url = $article['feed_url'];
5358 $feed_title = $article['feed_title'];
5362 if ($feed_url && $feed_title) {
5363 $result = db_query($link, "SELECT id FROM ttrss_feeds
5364 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5366 if (db_num_rows($result) != 0) {
5367 $feed = db_fetch_result($result, 0, "id");
5369 // try autocreating feed in Uncategorized...
5371 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5372 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5374 $result = db_query($link, "SELECT id FROM ttrss_feeds
5375 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5377 if (db_num_rows($result) != 0) {
5378 ++
$num_feeds_created;
5380 $feed = db_fetch_result($result, 0, "id");
5385 if ($feed != 'NULL')
5386 $feed_qpart = "feed_id = $feed";
5388 $feed_qpart = "feed_id IS NULL";
5390 //print "$ref_id / $feed / " . $article['title'] . "\n";
5392 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5393 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5395 if (db_num_rows($result) == 0) {
5397 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5398 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5399 $score = (int) $article['score'];
5401 $tag_cache = $article['tag_cache'];
5402 $label_cache = db_escape_string($article['label_cache']);
5403 $note = $article['note'];
5405 //print "Importing " . $article['title'] . "<br/>";
5409 $result = db_query($link,
5410 "INSERT INTO ttrss_user_entries
5411 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5412 published, score, tag_cache, label_cache, uuid, note)
5413 VALUES ($ref_id, $owner_uid, $feed, false,
5414 NULL, $marked, $published, $score, '$tag_cache',
5415 '$label_cache', '', '$note')");
5417 $label_cache = json_decode($label_cache, true);
5419 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5420 foreach ($label_cache as $label) {
5422 label_create($link, $label[1],
5423 $label[2], $label[3], $owner_uid);
5425 label_add_article($link, $ref_id, $label[1], $owner_uid);
5430 //db_query($link, "COMMIT");
5438 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5439 $num_processed, $num_imported, $num_feeds_created) .
5444 print "<p>" . __("Could not load XML document.") . "</p>";
5449 function get_random_bytes($length) {
5450 if (function_exists('openssl_random_pseudo_bytes')) {
5451 return openssl_random_pseudo_bytes($length);
5455 for ($i = 0; $i < $length; $i++
)
5456 $output .= chr(mt_rand(0, 255));
5462 function read_stdin() {
5463 $fp = fopen("php://stdin", "r");
5466 $line = trim(fgets($fp));
5474 function tmpdirname($path, $prefix) {
5475 // Use PHP's tmpfile function to create a temporary
5476 // directory name. Delete the file and keep the name.
5477 $tempname = tempnam($path,$prefix);
5481 if (!unlink($tempname))
5487 function getFeedCategory($link, $feed) {
5488 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5489 WHERE id = '$feed'");
5491 if (db_num_rows($result) > 0) {
5492 return db_fetch_result($result, 0, "cat_id");
5499 function create_published_article($link, $title, $url, $content, $labels_str,
5502 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
5503 $content_hash = sha1($content);
5505 if ($labels_str != "") {
5506 $labels = explode(",", $labels_str);
5513 if (!$title) $title = $url;
5514 if (!$title && !$url) return false;
5516 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
5518 db_query($link, "BEGIN");
5520 // only check for our user data here, others might have shared this with different content etc
5521 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
5522 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
5524 if (db_num_rows($result) != 0) {
5525 $ref_id = db_fetch_result($result, 0, "id");
5527 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
5528 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
5530 if (db_num_rows($result) != 0) {
5531 $int_id = db_fetch_result($result, 0, "int_id");
5533 db_query($link, "UPDATE ttrss_entries SET
5534 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
5536 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
5537 int_id = '$int_id' AND owner_uid = '$owner_uid'");
5540 db_query($link, "INSERT INTO ttrss_user_entries
5541 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5543 ('$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);
5555 $result = db_query($link, "INSERT INTO ttrss_entries
5556 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
5558 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
5560 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
5562 if (db_num_rows($result) != 0) {
5563 $ref_id = db_fetch_result($result, 0, "id");
5565 db_query($link, "INSERT INTO ttrss_user_entries
5566 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5568 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5570 if (count($labels) != 0) {
5571 foreach ($labels as $label) {
5572 label_add_article($link, $ref_id, trim($label), $owner_uid);
5580 db_query($link, "COMMIT");