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__
)."/../classes/$class_file.php";
12 if (file_exists($file)) {
18 mb_internal_encoding("UTF-8");
19 date_default_timezone_set('UTC');
20 if (defined('E_DEPRECATED')) {
21 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
23 error_reporting(E_ALL
& ~E_NOTICE
);
26 require_once 'config.php';
28 if (DB_TYPE
== "pgsql") {
29 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
31 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
34 define('THEME_VERSION_REQUIRED', 1.1);
37 * Return available translations names.
40 * @return array A array of available translations.
42 function get_translations() {
44 "auto" => "Detect automatically",
49 "fr_FR" => "Français",
50 "hu_HU" => "Magyar (Hungarian)",
51 "it_IT" => "Italiano",
52 "ja_JP" => "日本語 (Japanese)",
53 "nb_NO" => "Norwegian bokmål",
56 "pt_BR" => "Portuguese/Brazil",
57 "zh_CN" => "Simplified Chinese");
62 require_once "lib/accept-to-gettext.php";
63 require_once "lib/gettext/gettext.inc";
65 function startup_gettext() {
67 # Get locale from Accept-Language header
68 $lang = al2gt(array_keys(get_translations()), "text/html");
70 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
71 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
74 /* In login action of mobile version */
75 if ($_POST["language"] && defined('MOBILE_VERSION')) {
76 $lang = $_POST["language"];
78 $lang = $_SESSION["language"];
82 if (defined('LC_MESSAGES')) {
83 _setlocale(LC_MESSAGES
, $lang);
84 } else if (defined('LC_ALL')) {
85 _setlocale(LC_ALL
, $lang);
88 if (defined('MOBILE_VERSION')) {
89 _bindtextdomain("messages", "../locale");
91 _bindtextdomain("messages", "locale");
94 _textdomain("messages");
95 _bind_textdomain_codeset("messages", "UTF-8");
101 require_once 'db-prefs.php';
102 require_once 'version.php';
104 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
106 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
107 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
109 ini_set('user_agent', SELF_USER_AGENT
);
111 require_once 'lib/pubsubhubbub/publisher.php';
112 require_once 'lib/htmLawed.php';
115 $utc_tz = new DateTimeZone('UTC');
116 $schema_version = false;
119 * Print a timestamped debug message.
121 * @param string $msg The debug message.
124 function _debug($msg) {
125 if (defined('QUIET') && QUIET
) {
128 $ts = strftime("%H:%M:%S", time());
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
132 print "[$ts] $msg\n";
136 * Purge a feed old posts.
138 * @param mixed $link A database connection.
139 * @param mixed $feed_id The id of the purged feed.
140 * @param mixed $purge_interval Olderness of purged posts.
141 * @param boolean $debug Set to True to enable the debug. False by default.
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
151 $result = db_query($link,
152 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
156 if (db_num_rows($result) == 1) {
157 $owner_uid = db_fetch_result($result, 0, "owner_uid");
160 if ($purge_interval == -1 ||
!$purge_interval) {
162 ccache_update($link, $feed_id, $owner_uid);
167 if (!$owner_uid) return;
169 if (FORCE_ARTICLE_PURGE
== 0) {
170 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
173 $purge_unread = true;
174 $purge_interval = FORCE_ARTICLE_PURGE
;
177 if (!$purge_unread) $query_limit = " unread = false AND ";
179 if (DB_TYPE
== "pgsql") {
180 $pg_version = get_pgsql_version($link);
182 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
184 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
185 ttrss_entries.id = ref_id AND
187 feed_id = '$feed_id' AND
189 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
193 $result = db_query($link, "DELETE FROM ttrss_user_entries
195 WHERE ttrss_entries.id = ref_id AND
197 feed_id = '$feed_id' AND
199 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
202 $rows = pg_affected_rows($result);
206 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
207 marked = false AND feed_id = '$feed_id' AND
208 (SELECT date_updated FROM ttrss_entries WHERE
209 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
211 $result = db_query($link, "DELETE FROM ttrss_user_entries
212 USING ttrss_user_entries, ttrss_entries
213 WHERE ttrss_entries.id = ref_id AND
215 feed_id = '$feed_id' AND
217 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
219 $rows = mysql_affected_rows($link);
223 ccache_update($link, $feed_id, $owner_uid);
226 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
228 } // function purge_feed
230 function feed_purge_interval($link, $feed_id) {
232 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
233 WHERE id = '$feed_id'");
235 if (db_num_rows($result) == 1) {
236 $purge_interval = db_fetch_result($result, 0, "purge_interval");
237 $owner_uid = db_fetch_result($result, 0, "owner_uid");
239 if ($purge_interval == 0) $purge_interval = get_pref($link,
240 'PURGE_OLD_DAYS', $owner_uid);
242 return $purge_interval;
249 function purge_orphans($link, $do_output = false) {
251 // purge orphaned posts in main content table
252 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
253 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
256 $rows = db_affected_rows($link, $result);
257 _debug("Purged $rows orphaned posts.");
261 function get_feed_update_interval($link, $feed_id) {
262 $result = db_query($link, "SELECT owner_uid, update_interval FROM
263 ttrss_feeds WHERE id = '$feed_id'");
265 if (db_num_rows($result) == 1) {
266 $update_interval = db_fetch_result($result, 0, "update_interval");
267 $owner_uid = db_fetch_result($result, 0, "owner_uid");
269 if ($update_interval != 0) {
270 return $update_interval;
272 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
280 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
281 $login = urlencode($login);
282 $pass = urlencode($pass);
284 global $fetch_last_error;
286 if (function_exists('curl_init') && !ini_get("open_basedir")) {
287 $ch = curl_init($url);
289 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
290 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
291 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
292 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
293 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
294 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
295 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
296 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
297 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
298 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
301 curl_setopt($ch, CURLOPT_POST
, true);
302 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
306 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
308 $contents = @curl_exec
($ch);
310 if ($contents === false) {
311 $fetch_last_error = curl_error($ch);
316 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
317 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
320 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
326 if ($login && $pass ){
327 $url_parts = array();
329 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
331 if ($url_parts[1] && $url_parts[2]) {
332 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
336 $data = @file_get_contents
($url);
338 if (!$data && function_exists('error_get_last')) {
339 $error = error_get_last();
340 $fetch_last_error = $error["message"];
348 * Try to determine the favicon URL for a feed.
349 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
350 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
352 * @param string $url A feed or page URL
354 * @return mixed The favicon URL, or false if none was found.
356 function get_favicon_url($url) {
358 $favicon_url = false;
360 if ($html = @fetch_file_contents
($url)) {
362 libxml_use_internal_errors(true);
364 $doc = new DOMDocument();
365 $doc->loadHTML($html);
366 $xpath = new DOMXPath($doc);
368 $base = $xpath->query('/html/head/base');
369 foreach ($base as $b) {
370 $url = $b->getAttribute("href");
374 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
375 if (count($entries) > 0) {
376 foreach ($entries as $entry) {
377 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
384 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
387 } // function get_favicon_url
389 function check_feed_favicon($site_url, $feed, $link) {
390 # print "FAVICON [$site_url]: $favicon_url\n";
392 $icon_file = ICONS_DIR
. "/$feed.ico";
394 if (!file_exists($icon_file)) {
395 $favicon_url = get_favicon_url($site_url);
398 // Limiting to "image" type misses those served with text/plain
399 $contents = fetch_file_contents($favicon_url); // , "image");
402 // Crude image type matching.
403 // Patterns gleaned from the file(1) source code.
404 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
405 // 0 string \000\000\001\000 MS Windows icon resource
406 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
408 elseif (preg_match('/^GIF8/', $contents)) {
409 // 0 string GIF8 GIF image data
410 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
412 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
413 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
414 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
416 elseif (preg_match('/^\xff\xd8/', $contents)) {
417 // 0 beshort 0xffd8 JPEG image data
418 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
421 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
427 $fp = @fopen
($icon_file, "w");
430 fwrite($fp, $contents);
432 chmod($icon_file, 0644);
439 function print_select($id, $default, $values, $attributes = "") {
440 print "<select name=\"$id\" id=\"$id\" $attributes>";
441 foreach ($values as $v) {
443 $sel = "selected=\"1\"";
447 print "<option value=\"$v\" $sel>$v</option>";
452 function print_select_hash($id, $default, $values, $attributes = "") {
453 print "<select name=\"$id\" id='$id' $attributes>";
454 foreach (array_keys($values) as $v) {
456 $sel = 'selected="selected"';
460 print "<option $sel value=\"$v\">".$values[$v]."</option>";
466 function getmicrotime() {
467 list($usec, $sec) = explode(" ",microtime());
468 return ((float)$usec +
(float)$sec);
471 function print_radio($id, $default, $true_is, $values, $attributes = "") {
472 foreach ($values as $v) {
479 if ($v == $true_is) {
480 $sel .= " value=\"1\"";
482 $sel .= " value=\"0\"";
485 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
486 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
491 function initialize_user_prefs($link, $uid, $profile = false) {
493 $uid = db_escape_string($uid);
497 $profile_qpart = "AND profile IS NULL";
499 $profile_qpart = "AND profile = '$profile'";
502 if (get_schema_version($link) < 63) $profile_qpart = "";
504 db_query($link, "BEGIN");
506 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
508 $u_result = db_query($link, "SELECT pref_name
509 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
511 $active_prefs = array();
513 while ($line = db_fetch_assoc($u_result)) {
514 array_push($active_prefs, $line["pref_name"]);
517 while ($line = db_fetch_assoc($result)) {
518 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
519 // print "adding " . $line["pref_name"] . "<br>";
521 if (get_schema_version($link) < 63) {
522 db_query($link, "INSERT INTO ttrss_user_prefs
523 (owner_uid,pref_name,value) VALUES
524 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
527 db_query($link, "INSERT INTO ttrss_user_prefs
528 (owner_uid,pref_name,value, profile) VALUES
529 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
535 db_query($link, "COMMIT");
539 function get_ssl_certificate_id() {
540 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
541 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
542 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
543 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
544 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
549 function authenticate_user($link, $login, $password, $check_only = false) {
551 if (!SINGLE_USER_MODE
) {
554 $modules = explode(",", AUTH_MODULES
);
556 foreach ($modules as $module) {
557 $module_class = "auth_$module";
558 if (class_exists($module_class)) {
559 $authenticator = new $module_class($link);
561 $user_id = (int) $authenticator->authenticate($login, $password);
564 $_SESSION["auth_module"] = $module;
569 print T_sprintf("Fatal: authentication module %s not found.", $module);
574 if ($user_id && !$check_only) {
575 $_SESSION["uid"] = $user_id;
577 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
578 WHERE id = '$user_id'");
580 $_SESSION["name"] = db_fetch_result($result, 0, "login");
581 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
582 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
584 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
587 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
588 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
590 $_SESSION["last_version_check"] = time();
592 initialize_user_prefs($link, $_SESSION["uid"]);
601 $_SESSION["uid"] = 1;
602 $_SESSION["name"] = "admin";
603 $_SESSION["access_level"] = 10;
605 $_SESSION["hide_hello"] = true;
606 $_SESSION["hide_logout"] = true;
608 $_SESSION["auth_module"] = false;
610 if (!$_SESSION["csrf_token"]) {
611 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
614 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
616 initialize_user_prefs($link, $_SESSION["uid"]);
622 function make_password($length = 8) {
625 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
629 while ($i < $length) {
630 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
632 if (!strstr($password, $char)) {
640 // this is called after user is created to initialize default feeds, labels
643 // user preferences are checked on every login, not here
645 function initialize_user($link, $uid) {
647 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
648 values ('$uid', 'Tiny Tiny RSS: New Releases',
649 'http://tt-rss.org/releases.rss')");
651 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
652 values ('$uid', 'Tiny Tiny RSS: Forum',
653 'http://tt-rss.org/forum/rss.php')");
656 function logout_user() {
658 if (isset($_COOKIE[session_name()])) {
659 setcookie(session_name(), '', time()-42000, '/');
663 function validate_csrf($csrf_token) {
664 return $csrf_token == $_SESSION['csrf_token'];
667 function validate_session($link) {
668 if (SINGLE_USER_MODE
) return true;
670 $check_ip = $_SESSION['ip_address'];
672 switch (SESSION_CHECK_ADDRESS
) {
677 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
680 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
681 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
685 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
686 $_SESSION["login_error_msg"] =
687 __("Session failed to validate (incorrect IP)");
691 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
694 if ($_SESSION["uid"]) {
696 $result = db_query($link,
697 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
699 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
701 if ($pwd_hash != $_SESSION["pwd_hash"]) {
706 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
708 //print_r($_SESSION);
710 if (time() > $_SESSION["cookie_lifetime"]) {
718 function login_sequence($link, $login_form = 0) {
719 if (SINGLE_USER_MODE
) {
720 return authenticate_user($link, "admin", null);
722 if (!$_SESSION["uid"] ||
!validate_session($link)) {
724 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
725 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
727 authenticate_user($link, null, null, true);
730 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
733 /* bump login timestamp */
734 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
738 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
739 setcookie("ttrss_lang", $_SESSION["language"],
740 time() + SESSION_COOKIE_LIFETIME
);
745 function truncate_string($str, $max_len, $suffix = '…') {
746 if (mb_strlen($str, "utf-8") > $max_len - 3) {
747 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
753 function theme_image($link, $filename) {
755 $theme_path = get_user_theme_path($link);
757 if ($theme_path && is_file($theme_path.$filename)) {
758 return $theme_path.$filename;
767 function get_user_theme($link) {
769 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
770 $theme_name = get_pref($link, "_THEME_ID");
771 if (is_dir("themes/$theme_name")) {
782 function get_user_theme_path($link) {
785 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
786 $theme_name = get_pref($link, "_THEME_ID");
788 if ($theme_name && is_dir("themes/$theme_name")) {
789 $theme_path = "themes/$theme_name/";
798 if (is_file("$theme_path/theme.ini")) {
799 $ini = parse_ini_file("$theme_path/theme.ini", true);
800 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
808 function get_user_theme_options($link) {
809 $t = get_user_theme_path($link);
812 if (is_file("$t/theme.ini")) {
813 $ini = parse_ini_file("$t/theme.ini", true);
814 if ($ini['theme']['version']) {
815 return $ini['theme']['options'];
822 function print_theme_includes($link) {
824 $t = get_user_theme_path($link);
828 print "<link rel=\"stylesheet\" type=\"text/css\"
829 href=\"$t/theme.css?$time \">";
830 if (file_exists("$t/theme.js")) {
831 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
837 function get_all_themes() {
838 $themes = glob("themes/*");
844 foreach ($themes as $t) {
845 if (is_file("$t/theme.ini")) {
846 $ini = parse_ini_file("$t/theme.ini", true);
847 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
848 !$ini['theme']['disabled']) {
851 $entry["base"] = basename($t);
852 $entry["name"] = $ini['theme']['name'];
853 $entry["version"] = $ini['theme']['version'];
854 $entry["author"] = $ini['theme']['author'];
855 $entry["options"] = $ini['theme']['options'];
856 array_push($rv, $entry);
864 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
867 $source_tz = new DateTimeZone($source_tz);
868 } catch (Exception
$e) {
869 $source_tz = new DateTimeZone('UTC');
873 $dest_tz = new DateTimeZone($dest_tz);
874 } catch (Exception
$e) {
875 $dest_tz = new DateTimeZone('UTC');
878 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
879 return $dt->format('U') +
$dest_tz->getOffset($dt);
882 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
883 $no_smart_dt = false) {
885 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
886 if (!$timestamp) $timestamp = '1970-01-01 0:00';
891 # We store date in UTC internally
892 $dt = new DateTime($timestamp, $utc_tz);
894 if ($tz_offset == -1) {
896 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
899 $user_tz = new DateTimeZone($user_tz_string);
900 } catch (Exception
$e) {
904 $tz_offset = $user_tz->getOffset($dt);
907 $user_timestamp = $dt->format('U') +
$tz_offset;
910 return smart_date_time($link, $user_timestamp,
911 $tz_offset, $owner_uid);
914 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
916 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
918 return date($format, $user_timestamp);
922 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
923 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
925 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
926 return date("G:i", $timestamp);
927 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
928 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
929 return date($format, $timestamp);
931 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
932 return date($format, $timestamp);
936 function sql_bool_to_bool($s) {
937 if ($s == "t" ||
$s == "1" ||
$s == "true") {
944 function bool_to_sql_bool($s) {
952 // Session caching removed due to causing wrong redirects to upgrade
953 // script when get_schema_version() is called on an obsolete session
954 // created on a previous schema version.
955 function get_schema_version($link, $nocache = false) {
956 global $schema_version;
958 if (!$schema_version) {
959 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
960 $version = db_fetch_result($result, 0, "schema_version");
961 $schema_version = $version;
964 return $schema_version;
968 function sanity_check($link) {
969 require_once 'errors.php';
972 $schema_version = get_schema_version($link, true);
974 if ($schema_version != SCHEMA_VERSION
) {
978 if (DB_TYPE
== "mysql") {
979 $result = db_query($link, "SELECT true", false);
980 if (db_num_rows($result) != 1) {
985 if (db_escape_string("testTEST") != "testTEST") {
989 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
992 function file_is_locked($filename) {
993 if (function_exists('flock')) {
994 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
996 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1007 return true; // consider the file always locked and skip the test
1010 function make_lockfile($filename) {
1011 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1013 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1014 if (function_exists('posix_getpid')) {
1015 fwrite($fp, posix_getpid() . "\n");
1023 function make_stampfile($filename) {
1024 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1026 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1027 fwrite($fp, time() . "\n");
1028 flock($fp, LOCK_UN
);
1036 function sql_random_function() {
1037 if (DB_TYPE
== "mysql") {
1044 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1046 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1048 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1050 $ref_check_qpart = ($max_id &&
1051 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1053 if (is_numeric($feed)) {
1059 $children = getChildCategories($link, $feed, $owner_uid);
1060 array_push($children, $feed);
1062 $children = join(",", $children);
1064 $cat_qpart = "cat_id IN ($children)";
1066 $cat_qpart = "cat_id IS NULL";
1069 db_query($link, "UPDATE ttrss_user_entries
1070 SET unread = false,last_read = NOW()
1071 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1072 AND $ref_check_qpart
1073 AND owner_uid = $owner_uid");
1075 } else if ($feed == -2) {
1077 db_query($link, "UPDATE ttrss_user_entries
1078 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1079 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1080 AND $ref_check_qpart
1081 AND unread = true AND owner_uid = $owner_uid");
1084 } else if ($feed > 0) {
1086 db_query($link, "UPDATE ttrss_user_entries
1087 SET unread = false,last_read = NOW()
1088 WHERE feed_id = '$feed'
1089 AND $ref_check_qpart
1090 AND owner_uid = $owner_uid");
1092 } else if ($feed < 0 && $feed > -10) { // special, like starred
1095 db_query($link, "UPDATE ttrss_user_entries
1096 SET unread = false,last_read = NOW()
1098 AND $ref_check_qpart
1099 AND owner_uid = $owner_uid");
1103 db_query($link, "UPDATE ttrss_user_entries
1104 SET unread = false,last_read = NOW()
1105 WHERE published = true
1106 AND $ref_check_qpart
1107 AND owner_uid = $owner_uid");
1112 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1114 if (DB_TYPE
== "pgsql") {
1115 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1117 $match_part = "updated > DATE_SUB(NOW(),
1118 INTERVAL $intl HOUR) ";
1121 $result = db_query($link, "SELECT id FROM ttrss_entries,
1122 ttrss_user_entries WHERE $match_part AND
1124 ttrss_user_entries.ref_id = ttrss_entries.id AND
1125 owner_uid = $owner_uid");
1127 $affected_ids = array();
1129 while ($line = db_fetch_assoc($result)) {
1130 array_push($affected_ids, $line["id"]);
1133 catchupArticlesById($link, $affected_ids, 0);
1137 db_query($link, "UPDATE ttrss_user_entries
1138 SET unread = false,last_read = NOW()
1139 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1142 } else if ($feed < -10) { // label
1144 $label_id = -$feed - 11;
1146 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1147 SET unread = false, last_read = NOW()
1148 WHERE label_id = '$label_id' AND unread = true
1149 AND $ref_check_qpart
1150 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1154 ccache_update($link, $feed, $owner_uid, $cat_view);
1157 db_query($link, "BEGIN");
1159 $tag_name = db_escape_string($feed);
1161 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1162 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1164 while ($line = db_fetch_assoc($result)) {
1165 db_query($link, "UPDATE ttrss_user_entries SET
1166 unread = false, last_read = NOW()
1167 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1169 db_query($link, "COMMIT");
1173 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1175 if (!$omode) $omode = "flc";
1177 $data = getGlobalCounters($link);
1179 $data = array_merge($data, getVirtCounters($link));
1181 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1182 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1183 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1184 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1189 function getCategoryTitle($link, $cat_id) {
1191 if ($cat_id == -1) {
1192 return __("Special");
1193 } else if ($cat_id == -2) {
1194 return __("Labels");
1197 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1200 if (db_num_rows($result) == 1) {
1201 return db_fetch_result($result, 0, "title");
1203 return __("Uncategorized");
1209 function getCategoryCounters($link) {
1212 /* Labels category */
1214 $cv = array("id" => -2, "kind" => "cat",
1215 "counter" => getCategoryUnread($link, -2));
1217 array_push($ret_arr, $cv);
1219 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1220 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1221 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1222 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1223 WHERE ttrss_cat_counters_cache.feed_id = id AND
1224 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1225 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1227 while ($line = db_fetch_assoc($result)) {
1228 $line["cat_id"] = (int) $line["cat_id"];
1230 if ($line["num_children"] > 0) {
1231 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1236 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1237 "counter" => $line["unread"] +
$child_counter);
1239 array_push($ret_arr, $cv);
1242 /* Special case: NULL category doesn't actually exist in the DB */
1244 $cv = array("id" => 0, "kind" => "cat",
1245 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1247 array_push($ret_arr, $cv);
1252 // only accepts real cats (>= 0)
1253 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1254 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1256 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1257 AND owner_uid = $owner_uid");
1261 while ($line = db_fetch_assoc($result)) {
1262 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1263 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1269 function getCategoryUnread($link, $cat, $owner_uid = false) {
1271 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1276 $cat_query = "cat_id = '$cat'";
1278 $cat_query = "cat_id IS NULL";
1281 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1282 AND owner_uid = " . $owner_uid);
1284 $cat_feeds = array();
1285 while ($line = db_fetch_assoc($result)) {
1286 array_push($cat_feeds, "feed_id = " . $line["id"]);
1289 if (count($cat_feeds) == 0) return 0;
1291 $match_part = implode(" OR ", $cat_feeds);
1293 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1294 FROM ttrss_user_entries
1295 WHERE unread = true AND ($match_part)
1296 AND owner_uid = " . $owner_uid);
1300 # this needs to be rewritten
1301 while ($line = db_fetch_assoc($result)) {
1302 $unread +
= $line["unread"];
1306 } else if ($cat == -1) {
1307 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1308 } else if ($cat == -2) {
1310 $result = db_query($link, "
1311 SELECT COUNT(unread) AS unread FROM
1312 ttrss_user_entries, ttrss_user_labels2
1313 WHERE article_id = ref_id AND unread = true
1314 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1316 $unread = db_fetch_result($result, 0, "unread");
1323 function getFeedUnread($link, $feed, $is_cat = false) {
1324 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1327 function getLabelUnread($link, $label_id, $owner_uid = false) {
1328 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1330 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1331 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1333 if (db_num_rows($result) != 0) {
1334 return db_fetch_result($result, 0, "unread");
1340 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1341 $owner_uid = false) {
1343 $n_feed = (int) $feed;
1344 $need_entries = false;
1346 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1349 $unread_qpart = "unread = true";
1351 $unread_qpart = "true";
1355 return getCategoryUnread($link, $n_feed, $owner_uid);
1356 } else if ($n_feed == -6) {
1358 } else if ($feed != "0" && $n_feed == 0) {
1360 $feed = db_escape_string($feed);
1362 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1363 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1364 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1365 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1366 return db_fetch_result($result, 0, "count");
1368 } else if ($n_feed == -1) {
1369 $match_part = "marked = true";
1370 } else if ($n_feed == -2) {
1371 $match_part = "published = true";
1372 } else if ($n_feed == -3) {
1373 $match_part = "unread = true AND score >= 0";
1375 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1377 if (DB_TYPE
== "pgsql") {
1378 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1380 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1383 $need_entries = true;
1385 } else if ($n_feed == -4) {
1386 $match_part = "true";
1387 } else if ($n_feed >= 0) {
1390 $match_part = "feed_id = '$n_feed'";
1392 $match_part = "feed_id IS NULL";
1395 } else if ($feed < -10) {
1397 $label_id = -$feed - 11;
1399 return getLabelUnread($link, $label_id, $owner_uid);
1405 if ($need_entries) {
1406 $from_qpart = "ttrss_user_entries,ttrss_entries";
1407 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1409 $from_qpart = "ttrss_user_entries";
1412 $query = "SELECT count(int_id) AS unread
1413 FROM $from_qpart WHERE
1414 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1416 //echo "[$feed/$query]\n";
1418 $result = db_query($link, $query);
1422 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1423 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1424 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1425 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1428 $unread = db_fetch_result($result, 0, "unread");
1433 function getGlobalUnread($link, $user_id = false) {
1436 $user_id = $_SESSION["uid"];
1439 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1440 WHERE owner_uid = '$user_id' AND feed_id > 0");
1442 $c_id = db_fetch_result($result, 0, "c_id");
1447 function getGlobalCounters($link, $global_unread = -1) {
1450 if ($global_unread == -1) {
1451 $global_unread = getGlobalUnread($link);
1454 $cv = array("id" => "global-unread",
1455 "counter" => (int) $global_unread);
1457 array_push($ret_arr, $cv);
1459 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1460 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1462 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1464 $cv = array("id" => "subscribed-feeds",
1465 "counter" => (int) $subscribed_feeds);
1467 array_push($ret_arr, $cv);
1472 function getTagCounters($link) {
1476 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1477 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1478 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1479 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1480 ORDER BY count DESC LIMIT 55");
1484 while ($line = db_fetch_assoc($result)) {
1485 $tags[$line["tag_name"]] +
= $line["count"];
1488 foreach (array_keys($tags) as $tag) {
1489 $unread = $tags[$tag];
1490 $tag = htmlspecialchars($tag);
1492 $cv = array("id" => $tag,
1494 "counter" => $unread);
1496 array_push($ret_arr, $cv);
1502 function getVirtCounters($link) {
1506 for ($i = 0; $i >= -4; $i--) {
1508 $count = getFeedUnread($link, $i);
1510 $cv = array("id" => $i,
1511 "counter" => (int) $count);
1513 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1514 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1516 array_push($ret_arr, $cv);
1522 function getLabelCounters($link, $descriptions = false) {
1526 $owner_uid = $_SESSION["uid"];
1528 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1529 WHERE owner_uid = '$owner_uid'");
1531 while ($line = db_fetch_assoc($result)) {
1533 $id = -$line["id"] - 11;
1535 $label_name = $line["caption"];
1536 $count = getFeedUnread($link, $id);
1538 $cv = array("id" => $id,
1539 "counter" => (int) $count);
1542 $cv["description"] = $label_name;
1544 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1545 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1547 array_push($ret_arr, $cv);
1553 function getFeedCounters($link, $active_feed = false) {
1557 $query = "SELECT ttrss_feeds.id,
1559 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1560 last_error, value AS count
1561 FROM ttrss_feeds, ttrss_counters_cache
1562 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1563 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1564 AND ttrss_counters_cache.feed_id = id";
1566 $result = db_query($link, $query);
1567 $fctrs_modified = false;
1569 while ($line = db_fetch_assoc($result)) {
1572 $count = $line["count"];
1573 $last_error = htmlspecialchars($line["last_error"]);
1575 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1577 $has_img = feed_has_icon($id);
1579 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1582 $cv = array("id" => $id,
1583 "updated" => $last_updated,
1584 "counter" => (int) $count,
1585 "has_img" => (int) $has_img);
1588 $cv["error"] = $last_error;
1590 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1591 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1593 if ($active_feed && $id == $active_feed)
1594 $cv["title"] = truncate_string($line["title"], 30);
1596 array_push($ret_arr, $cv);
1603 function get_pgsql_version($link) {
1604 $result = db_query($link, "SELECT version() AS version");
1605 $version = explode(" ", db_fetch_result($result, 0, "version"));
1610 * @return array (code => Status code, message => error message if available)
1612 * 0 - OK, Feed already exists
1613 * 1 - OK, Feed added
1615 * 3 - URL content is HTML, no feeds available
1616 * 4 - URL content is HTML which contains multiple feeds.
1617 * Here you should call extractfeedurls in rpc-backend
1618 * to get all possible feeds.
1619 * 5 - Couldn't download the URL content.
1621 function subscribe_to_feed($link, $url, $cat_id = 0,
1622 $auth_login = '', $auth_pass = '', $need_auth = false) {
1624 global $fetch_last_error;
1626 require_once "include/rssfuncs.php";
1628 $url = fix_url($url);
1630 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1634 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1637 return array("code" => 5, "message" => $fetch_last_error);
1640 if (is_html($contents)) {
1641 $feedUrls = get_feeds_from_html($url, $contents);
1643 if (count($feedUrls) == 0) {
1644 return array("code" => 3);
1645 } else if (count($feedUrls) > 1) {
1646 return array("code" => 4, "feeds" => $feedUrls);
1648 //use feed url as new URL
1649 $url = key($feedUrls);
1652 if ($cat_id == "0" ||
!$cat_id) {
1653 $cat_qpart = "NULL";
1655 $cat_qpart = "'$cat_id'";
1658 $result = db_query($link,
1659 "SELECT id FROM ttrss_feeds
1660 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1662 if (db_num_rows($result) == 0) {
1663 $result = db_query($link,
1664 "INSERT INTO ttrss_feeds
1665 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1666 VALUES ('".$_SESSION["uid"]."', '$url',
1667 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1669 $result = db_query($link,
1670 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1671 AND owner_uid = " . $_SESSION["uid"]);
1673 $feed_id = db_fetch_result($result, 0, "id");
1676 update_rss_feed($link, $feed_id, true);
1679 return array("code" => 1);
1681 return array("code" => 0);
1685 function print_feed_select($link, $id, $default_id = "",
1686 $attributes = "", $include_all_feeds = true,
1687 $root_id = false, $nest_level = 0) {
1690 print "<select id=\"$id\" name=\"$id\" $attributes>";
1691 if ($include_all_feeds) {
1692 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1693 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1697 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1700 $parent_qpart = "parent_cat = '$root_id'";
1702 $parent_qpart = "parent_cat IS NULL";
1704 $result = db_query($link, "SELECT id,title,
1705 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1706 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1707 FROM ttrss_feed_categories
1708 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1710 while ($line = db_fetch_assoc($result)) {
1712 for ($i = 0; $i < $nest_level; $i++
)
1713 $line["title"] = " - " . $line["title"];
1715 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1717 printf("<option $is_selected value='CAT:%d'>%s</option>",
1718 $line["id"], htmlspecialchars($line["title"]));
1720 if ($line["num_children"] > 0)
1721 print_feed_select($link, $id, $default_id, $attributes,
1722 $include_all_feeds, $line["id"], $nest_level+
1);
1724 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1725 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1727 while ($fline = db_fetch_assoc($feed_result)) {
1728 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1730 $fline["title"] = " + " . $fline["title"];
1732 for ($i = 0; $i < $nest_level; $i++
)
1733 $fline["title"] = " - " . $fline["title"];
1735 printf("<option $is_selected value='%d'>%s</option>",
1736 $fline["id"], htmlspecialchars($fline["title"]));
1741 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1743 printf("<option $is_selected value='CAT:0'>%s</option>",
1744 __("Uncategorized"));
1746 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1747 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1749 while ($fline = db_fetch_assoc($feed_result)) {
1750 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1752 $fline["title"] = " + " . $fline["title"];
1754 for ($i = 0; $i < $nest_level; $i++
)
1755 $fline["title"] = " - " . $fline["title"];
1757 printf("<option $is_selected value='%d'>%s</option>",
1758 $fline["id"], htmlspecialchars($fline["title"]));
1763 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1764 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1766 while ($line = db_fetch_assoc($result)) {
1768 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1770 printf("<option $is_selected value='%d'>%s</option>",
1771 $line["id"], htmlspecialchars($line["title"]));
1780 function print_feed_cat_select($link, $id, $default_id,
1781 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1784 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1788 $parent_qpart = "parent_cat = '$root_id'";
1790 $parent_qpart = "parent_cat IS NULL";
1792 $result = db_query($link, "SELECT id,title,
1793 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1794 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1795 FROM ttrss_feed_categories
1796 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1798 while ($line = db_fetch_assoc($result)) {
1799 if ($line["id"] == $default_id) {
1800 $is_selected = "selected=\"1\"";
1805 for ($i = 0; $i < $nest_level; $i++
)
1806 $line["title"] = " - " . $line["title"];
1809 printf("<option $is_selected value='%d'>%s</option>",
1810 $line["id"], htmlspecialchars($line["title"]));
1812 if ($line["num_children"] > 0)
1813 print_feed_cat_select($link, $id, $default_id, $attributes,
1814 $include_all_cats, $line["id"], $nest_level+
1);
1818 if ($include_all_cats) {
1819 if (db_num_rows($result) > 0) {
1820 print "<option disabled=\"1\">--------</option>";
1823 if ($default_id == 0) {
1824 $is_selected = "selected=\"1\"";
1829 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1835 function checkbox_to_sql_bool($val) {
1836 return ($val == "on") ?
"true" : "false";
1839 function getFeedCatTitle($link, $id) {
1841 return __("Special");
1842 } else if ($id < -10) {
1843 return __("Labels");
1844 } else if ($id > 0) {
1845 $result = db_query($link, "SELECT ttrss_feed_categories.title
1846 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1847 cat_id = ttrss_feed_categories.id");
1848 if (db_num_rows($result) == 1) {
1849 return db_fetch_result($result, 0, "title");
1851 return __("Uncategorized");
1854 return "getFeedCatTitle($id) failed";
1859 function getFeedIcon($id) {
1862 return "images/archive.png";
1865 return "images/mark_set.png";
1868 return "images/pub_set.png";
1871 return "images/fresh.png";
1874 return "images/tag.png";
1877 return "images/recently_read.png";
1881 return "images/label.png";
1883 if (file_exists(ICONS_DIR
. "/$id.ico"))
1884 return ICONS_URL
. "/$id.ico";
1890 function getFeedTitle($link, $id, $cat = false) {
1892 return getCategoryTitle($link, $id);
1893 } else if ($id == -1) {
1894 return __("Starred articles");
1895 } else if ($id == -2) {
1896 return __("Published articles");
1897 } else if ($id == -3) {
1898 return __("Fresh articles");
1899 } else if ($id == -4) {
1900 return __("All articles");
1901 } else if ($id === 0 ||
$id === "0") {
1902 return __("Archived articles");
1903 } else if ($id == -6) {
1904 return __("Recently read");
1905 } else if ($id < -10) {
1906 $label_id = -$id - 11;
1907 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1908 if (db_num_rows($result) == 1) {
1909 return db_fetch_result($result, 0, "caption");
1911 return "Unknown label ($label_id)";
1914 } else if (is_numeric($id) && $id > 0) {
1915 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1916 if (db_num_rows($result) == 1) {
1917 return db_fetch_result($result, 0, "title");
1919 return "Unknown feed ($id)";
1926 function make_init_params($link) {
1929 $params["theme"] = get_user_theme($link);
1930 $params["theme_options"] = get_user_theme_options($link);
1932 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1933 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1934 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
1935 $params["sign_info"] = theme_image($link, "images/sign_info.png");
1937 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1938 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1939 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1940 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1942 $params[strtolower($param)] = (int) get_pref($link, $param);
1945 $params["icons_url"] = ICONS_URL
;
1946 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1947 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1948 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1949 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1950 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1952 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1953 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1955 $max_feed_id = db_fetch_result($result, 0, "mid");
1956 $num_feeds = db_fetch_result($result, 0, "nf");
1958 $params["max_feed_id"] = (int) $max_feed_id;
1959 $params["num_feeds"] = (int) $num_feeds;
1961 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1963 $params["csrf_token"] = $_SESSION["csrf_token"];
1968 function make_runtime_info($link) {
1971 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1972 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1974 $max_feed_id = db_fetch_result($result, 0, "mid");
1975 $num_feeds = db_fetch_result($result, 0, "nf");
1977 $data["max_feed_id"] = (int) $max_feed_id;
1978 $data["num_feeds"] = (int) $num_feeds;
1980 $data['last_article_id'] = getLastArticleId($link);
1981 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1983 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1985 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1987 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1989 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1992 $stamp_delta = time() - $stamp;
1994 if ($stamp_delta > 1800) {
1998 $_SESSION["daemon_stamp_check"] = time();
2001 $data['daemon_stamp_ok'] = $stamp_check;
2003 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2005 $data['daemon_stamp'] = $stamp_fmt;
2010 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2011 $new_version_details = @check_for_update
($link);
2013 $data['new_version_available'] = (int) ($new_version_details != false);
2015 $_SESSION["last_version_check"] = time();
2016 $_SESSION["version_data"] = $new_version_details;
2022 function search_to_sql($link, $search, $match_on) {
2024 $search_query_part = "";
2026 $keywords = explode(" ", $search);
2027 $query_keywords = array();
2029 foreach ($keywords as $k) {
2030 if (strpos($k, "-") === 0) {
2037 $commandpair = explode(":", mb_strtolower($k), 2);
2039 if ($commandpair[0] == "note" && $commandpair[1]) {
2041 if ($commandpair[1] == "true")
2042 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2044 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2046 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2048 if ($commandpair[1] == "true")
2049 array_push($query_keywords, "($not (marked = true))");
2051 array_push($query_keywords, "($not (marked = false))");
2053 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2055 if ($commandpair[1] == "true")
2056 array_push($query_keywords, "($not (published = true))");
2058 array_push($query_keywords, "($not (published = false))");
2060 } else if (strpos($k, "@") === 0) {
2062 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2063 $orig_ts = strtotime(substr($k, 1));
2064 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2066 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2068 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2069 } else if ($match_on == "both") {
2070 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2071 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2072 } else if ($match_on == "title") {
2073 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2074 } else if ($match_on == "content") {
2075 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2079 $search_query_part = implode("AND", $query_keywords);
2081 return $search_query_part;
2084 function getParentCategories($link, $cat, $owner_uid) {
2087 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2088 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2090 while ($line = db_fetch_assoc($result)) {
2091 array_push($rv, $line["parent_cat"]);
2092 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2098 function getChildCategories($link, $cat, $owner_uid) {
2101 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2102 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2104 while ($line = db_fetch_assoc($result)) {
2105 array_push($rv, $line["id"]);
2106 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2112 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) {
2114 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2116 $ext_tables_part = "";
2120 if (SPHINX_ENABLED
) {
2121 $ids = join(",", @sphinx_search
($search, 0, 500));
2124 $search_query_part = "ref_id IN ($ids) AND ";
2126 $search_query_part = "ref_id = -1 AND ";
2129 $search_query_part = search_to_sql($link, $search, $match_on);
2130 $search_query_part .= " AND ";
2134 $search_query_part = "";
2139 if (DB_TYPE
== "pgsql") {
2140 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2142 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2145 $override_order = "updated DESC";
2147 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2149 // Try to check if SQL regexp implementation chokes on a valid regexp
2150 $result = db_query($link, "SELECT true AS true FROM ttrss_entries,
2151 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2152 WHERE $filter_query_part LIMIT 1", false);
2154 $test = db_fetch_result($result, 0, "true");
2157 $filter_query_part = "false AND";
2159 $filter_query_part .= " AND";
2163 $filter_query_part = "";
2167 $since_id_part = "ttrss_entries.id > $since_id AND ";
2169 $since_id_part = "";
2172 $view_query_part = "";
2174 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2176 $view_query_part = " ";
2177 } else if ($feed != -1) {
2178 $unread = getFeedUnread($link, $feed, $cat_view);
2180 if ($cat_view && $feed > 0 && $include_children)
2181 $unread +
= getCategoryChildrenUnread($link, $feed);
2184 $view_query_part = " unread = true AND ";
2189 if ($view_mode == "marked") {
2190 $view_query_part = " marked = true AND ";
2193 if ($view_mode == "published") {
2194 $view_query_part = " published = true AND ";
2197 if ($view_mode == "unread") {
2198 $view_query_part = " unread = true AND ";
2201 if ($view_mode == "updated") {
2202 $view_query_part = " (last_read is null and unread = false) AND ";
2206 $limit_query_part = "LIMIT " . $limit;
2209 $allow_archived = false;
2211 $vfeed_query_part = "";
2213 // override query strategy and enable feed display when searching globally
2214 if ($search && $search_mode == "all_feeds") {
2215 $query_strategy_part = "true";
2216 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2218 } else if (!is_numeric($feed)) {
2219 $query_strategy_part = "true";
2220 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2221 id = feed_id) as feed_title,";
2222 } else if ($search && $search_mode == "this_cat") {
2223 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2226 if ($include_children) {
2227 $subcats = getChildCategories($link, $feed, $owner_uid);
2228 array_push($subcats, $feed);
2229 $cats_qpart = join(",", $subcats);
2231 $cats_qpart = $feed;
2234 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2237 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2240 } else if ($feed > 0) {
2245 if ($include_children) {
2247 $subcats = getChildCategories($link, $feed, $owner_uid);
2249 array_push($subcats, $feed);
2250 $query_strategy_part = "cat_id IN (".
2251 implode(",", $subcats).")";
2254 $query_strategy_part = "cat_id = '$feed'";
2258 $query_strategy_part = "cat_id IS NULL";
2261 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2264 $query_strategy_part = "feed_id = '$feed'";
2266 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2267 $query_strategy_part = "feed_id IS NULL";
2268 $allow_archived = true;
2269 } else if ($feed == 0 && $cat_view) { // uncategorized
2270 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2271 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2272 } else if ($feed == -1) { // starred virtual feed
2273 $query_strategy_part = "marked = true";
2274 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2275 $allow_archived = true;
2277 } else if ($feed == -2) { // published virtual feed OR labels category
2280 $query_strategy_part = "published = true";
2281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2282 $allow_archived = true;
2284 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2286 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2288 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2290 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2291 ttrss_user_labels2.article_id = ref_id";
2294 } else if ($feed == -6) { // recently read
2295 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2296 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2297 $allow_archived = true;
2299 if (!$override_order) $override_order = "last_read DESC";
2300 } else if ($feed == -3) { // fresh virtual feed
2301 $query_strategy_part = "unread = true AND score >= 0";
2303 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2305 if (DB_TYPE
== "pgsql") {
2306 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2308 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2311 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2312 } else if ($feed == -4) { // all articles virtual feed
2313 $query_strategy_part = "true";
2314 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2315 } else if ($feed <= -10) { // labels
2316 $label_id = -$feed - 11;
2318 $query_strategy_part = "label_id = '$label_id' AND
2319 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2320 ttrss_user_labels2.article_id = ref_id";
2322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2323 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2324 $allow_archived = true;
2327 $query_strategy_part = "true";
2330 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2331 $date_sort_field = "updated";
2333 $date_sort_field = "date_entered";
2336 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2337 $order_by = "$date_sort_field";
2339 $order_by = "$date_sort_field DESC";
2342 if ($view_mode != "noscores") {
2343 $order_by = "score DESC, $order_by";
2346 if ($override_order) {
2347 $order_by = $override_order;
2353 $feed_title = T_sprintf("Search results: %s", $search);
2356 $feed_title = getCategoryTitle($link, $feed);
2358 if (is_numeric($feed) && $feed > 0) {
2359 $result = db_query($link, "SELECT title,site_url,last_error
2360 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2362 $feed_title = db_fetch_result($result, 0, "title");
2363 $feed_site_url = db_fetch_result($result, 0, "site_url");
2364 $last_error = db_fetch_result($result, 0, "last_error");
2366 $feed_title = getFeedTitle($link, $feed);
2371 $content_query_part = "content as content_preview, cached_content, ";
2373 if (is_numeric($feed)) {
2376 $feed_kind = "Feeds";
2378 $feed_kind = "Labels";
2381 if ($limit_query_part) {
2382 $offset_query_part = "OFFSET $offset";
2385 // proper override_order applied above
2386 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2387 if (!$override_order) {
2388 $order_by = "ttrss_feeds.title, $order_by";
2390 $order_by = "ttrss_feeds.title, $override_order";
2394 if (!$allow_archived) {
2395 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2396 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2399 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2400 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2403 $query = "SELECT DISTINCT
2406 ttrss_entries.id,ttrss_entries.title,
2410 always_display_enclosures,
2416 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2417 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2420 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2426 ttrss_user_entries.ref_id = ttrss_entries.id AND
2427 ttrss_user_entries.owner_uid = '$owner_uid' AND
2432 $query_strategy_part ORDER BY $order_by
2433 $limit_query_part $offset_query_part";
2435 if ($_REQUEST["debug"]) print $query;
2437 $result = db_query($link, $query);
2442 $select_qpart = "SELECT DISTINCT " .
2446 "ttrss_entries.id as id," .
2459 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2462 $content_query_part .
2463 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2466 $feed_kind = "Tags";
2467 $all_tags = explode(",", $feed);
2468 if ($search_mode == 'any') {
2469 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2470 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2471 $where_qpart = " WHERE " .
2472 "ref_id = ttrss_entries.id AND " .
2473 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2474 "post_int_id = int_id AND $tag_sql AND " .
2476 $search_query_part .
2477 $query_strategy_part . " ORDER BY $order_by " .
2482 $sub_selects = array();
2483 $sub_ands = array();
2484 foreach ($all_tags as $term) {
2485 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");
2492 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2497 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2498 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2499 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2500 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2502 // error_log("TAG SQL: " . $tag_sql);
2503 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2505 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2506 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2509 return array($result, $feed_title, $feed_site_url, $last_error);
2513 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2514 if (!$owner) $owner = $_SESSION["uid"];
2516 $res = trim($str); if (!$res) return '';
2518 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1);
2519 $res = htmLawed($res, $config);
2521 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2522 $res = preg_replace('/<img[^>]+>/is', '', $res);
2525 if (strpos($res, "href=") === false)
2526 $res = rewrite_urls($res);
2528 $charset_hack = '<head>
2529 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2532 $res = trim($res); if (!$res) return '';
2534 libxml_use_internal_errors(true);
2536 $doc = new DOMDocument();
2537 $doc->loadHTML($charset_hack . $res);
2538 $xpath = new DOMXPath($doc);
2540 $entries = $xpath->query('(//a[@href]|//img[@src])');
2543 foreach ($entries as $entry) {
2547 if ($entry->hasAttribute('href'))
2548 $entry->setAttribute('href',
2549 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2551 if ($entry->hasAttribute('src'))
2552 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2553 $entry->setAttribute('src',
2554 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2557 if (strtolower($entry->nodeName
) == "a") {
2558 $entry->setAttribute("target", "_blank");
2561 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2562 $br = $doc->createElement("br");
2564 if ($entry->parentNode
->nextSibling
) {
2565 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2572 $node = $doc->getElementsByTagName('body')->item(0);
2574 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2578 * Send by mail a digest of last articles.
2580 * @param mixed $link The database connection.
2581 * @param integer $limit The maximum number of articles by digest.
2582 * @return boolean Return false if digests are not enabled.
2584 function send_headlines_digests($link, $debug = false) {
2586 require_once 'lib/phpmailer/class.phpmailer.php';
2588 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2589 $limit = 1000; // maximum amount of headlines to include
2591 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2593 if (DB_TYPE
== "pgsql") {
2594 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2595 } else if (DB_TYPE
== "mysql") {
2596 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2599 $result = db_query($link, "SELECT id,email FROM ttrss_users
2600 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2602 while ($line = db_fetch_assoc($result)) {
2604 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2605 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2607 // try to send digests within 2 hours of preferred time
2608 if ($preferred_ts && time() >= $preferred_ts &&
2609 time() - $preferred_ts <= 7200) {
2611 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2613 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2617 // reset tz_offset global to prevent tz cache clash between users
2620 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2621 $digest = $tuple[0];
2622 $headlines_count = $tuple[1];
2623 $affected_ids = $tuple[2];
2624 $digest_text = $tuple[3];
2626 if ($headlines_count > 0) {
2628 $mail = new PHPMailer();
2630 $mail->PluginDir
= "lib/phpmailer/";
2631 $mail->SetLanguage("en", "lib/phpmailer/language/");
2633 $mail->CharSet
= "UTF-8";
2635 $mail->From
= SMTP_FROM_ADDRESS
;
2636 $mail->FromName
= SMTP_FROM_NAME
;
2637 $mail->AddAddress($line["email"], $line["login"]);
2640 $mail->Host
= SMTP_HOST
;
2641 $mail->Mailer
= "smtp";
2642 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2643 $mail->Username
= SMTP_LOGIN
;
2644 $mail->Password
= SMTP_PASSWORD
;
2647 $mail->IsHTML(true);
2648 $mail->Subject
= DIGEST_SUBJECT
;
2649 $mail->Body
= $digest;
2650 $mail->AltBody
= $digest_text;
2652 $rc = $mail->Send();
2654 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2656 if ($debug) print "RC=$rc\n";
2658 if ($rc && $do_catchup) {
2659 if ($debug) print "Marking affected articles as read...\n";
2660 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2663 if ($debug) print "No headlines\n";
2666 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2667 WHERE id = " . $line["id"]);
2673 if ($debug) _debug("All done.");
2677 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2679 require_once "lib/MiniTemplator.class.php";
2681 $tpl = new MiniTemplator
;
2682 $tpl_t = new MiniTemplator
;
2684 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2685 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2687 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2688 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2690 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2691 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2693 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2694 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2696 $affected_ids = array();
2698 if (DB_TYPE
== "pgsql") {
2699 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2700 } else if (DB_TYPE
== "mysql") {
2701 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2704 $result = db_query($link, "SELECT ttrss_entries.title,
2705 ttrss_feeds.title AS feed_title,
2706 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2708 ttrss_user_entries.ref_id,
2712 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2714 ttrss_user_entries,ttrss_entries,ttrss_feeds
2716 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2718 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2719 AND include_in_digest = true
2721 AND ttrss_user_entries.owner_uid = $user_id
2724 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2727 $cur_feed_title = "";
2729 $headlines_count = db_num_rows($result);
2731 $headlines = array();
2733 while ($line = db_fetch_assoc($result)) {
2734 array_push($headlines, $line);
2737 for ($i = 0; $i < sizeof($headlines); $i++
) {
2739 $line = $headlines[$i];
2741 array_push($affected_ids, $line["ref_id"]);
2743 $updated = make_local_datetime($link, $line['last_updated'], false,
2746 /* if ($line["score"] != 0) {
2747 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2749 $line["title"] .= " (".$line['score'].")";
2752 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2753 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2756 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2757 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2758 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2759 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2760 $tpl->setVariable('ARTICLE_EXCERPT',
2761 truncate_string(strip_tags($line["content"]), 300));
2762 // $tpl->setVariable('ARTICLE_CONTENT',
2763 // strip_tags($article_content));
2765 $tpl->addBlock('article');
2767 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2768 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2769 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2770 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2771 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2772 // truncate_string(strip_tags($line["excerpt"]), 100));
2774 $tpl_t->addBlock('article');
2776 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2777 $tpl->addBlock('feed');
2778 $tpl_t->addBlock('feed');
2783 $tpl->addBlock('digest');
2784 $tpl->generateOutputToString($tmp);
2786 $tpl_t->addBlock('digest');
2787 $tpl_t->generateOutputToString($tmp_t);
2789 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2792 function check_for_update($link) {
2793 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2794 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2796 $version_data = @fetch_file_contents
($version_url);
2798 if ($version_data) {
2799 $version_data = json_decode($version_data, true);
2800 if ($version_data && $version_data['version']) {
2802 if (version_compare(VERSION
, $version_data['version']) == -1) {
2803 return $version_data;
2811 function markArticlesById($link, $ids, $cmode) {
2815 foreach ($ids as $id) {
2816 array_push($tmp_ids, "ref_id = '$id'");
2819 $ids_qpart = join(" OR ", $tmp_ids);
2822 db_query($link, "UPDATE ttrss_user_entries SET
2823 marked = false,last_read = NOW()
2824 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2825 } else if ($cmode == 1) {
2826 db_query($link, "UPDATE ttrss_user_entries SET
2828 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2830 db_query($link, "UPDATE ttrss_user_entries SET
2831 marked = NOT marked,last_read = NOW()
2832 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2836 function publishArticlesById($link, $ids, $cmode) {
2840 foreach ($ids as $id) {
2841 array_push($tmp_ids, "ref_id = '$id'");
2844 $ids_qpart = join(" OR ", $tmp_ids);
2847 db_query($link, "UPDATE ttrss_user_entries SET
2848 published = false,last_read = NOW()
2849 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2850 } else if ($cmode == 1) {
2851 db_query($link, "UPDATE ttrss_user_entries SET
2852 published = true,last_read = NOW()
2853 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2855 db_query($link, "UPDATE ttrss_user_entries SET
2856 published = NOT published,last_read = NOW()
2857 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2860 if (PUBSUBHUBBUB_HUB
) {
2861 $rss_link = get_self_url_prefix() .
2862 "/public.php?op=rss&id=-2&key=" .
2863 get_feed_access_key($link, -2, false);
2865 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2867 $pubsub_result = $p->publish_update($rss_link);
2871 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2873 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2874 if (count($ids) == 0) return;
2878 foreach ($ids as $id) {
2879 array_push($tmp_ids, "ref_id = '$id'");
2882 $ids_qpart = join(" OR ", $tmp_ids);
2885 db_query($link, "UPDATE ttrss_user_entries SET
2886 unread = false,last_read = NOW()
2887 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2888 } else if ($cmode == 1) {
2889 db_query($link, "UPDATE ttrss_user_entries SET
2891 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2893 db_query($link, "UPDATE ttrss_user_entries SET
2894 unread = NOT unread,last_read = NOW()
2895 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2900 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2901 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2903 while ($line = db_fetch_assoc($result)) {
2904 ccache_update($link, $line["feed_id"], $owner_uid);
2908 function catchupArticleById($link, $id, $cmode) {
2911 db_query($link, "UPDATE ttrss_user_entries SET
2912 unread = false,last_read = NOW()
2913 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2914 } else if ($cmode == 1) {
2915 db_query($link, "UPDATE ttrss_user_entries SET
2917 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2919 db_query($link, "UPDATE ttrss_user_entries SET
2920 unread = NOT unread,last_read = NOW()
2921 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2924 $feed_id = getArticleFeed($link, $id);
2925 ccache_update($link, $feed_id, $_SESSION["uid"]);
2928 function make_guid_from_title($title) {
2929 return preg_replace("/[ \"\',.:;]/", "-",
2930 mb_strtolower(strip_tags($title), 'utf-8'));
2933 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2935 $a_id = db_escape_string($id);
2937 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2939 $query = "SELECT DISTINCT tag_name,
2940 owner_uid as owner FROM
2941 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2942 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2944 $obj_id = md5("TAGS:$owner_uid:$id");
2947 /* check cache first */
2949 if ($tag_cache === false) {
2950 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2951 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2953 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2957 $tags = explode(",", $tag_cache);
2960 /* do it the hard way */
2962 $tmp_result = db_query($link, $query);
2964 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2965 array_push($tags, $tmp_line["tag_name"]);
2968 /* update the cache */
2970 $tags_str = db_escape_string(join(",", $tags));
2972 db_query($link, "UPDATE ttrss_user_entries
2973 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2974 AND owner_uid = $owner_uid");
2980 function trim_array($array) {
2982 array_walk($tmp, 'trim');
2986 function tag_is_valid($tag) {
2987 if ($tag == '') return false;
2988 if (preg_match("/^[0-9]*$/", $tag)) return false;
2989 if (mb_strlen($tag) > 250) return false;
2991 if (function_exists('iconv')) {
2992 $tag = iconv("utf-8", "utf-8", $tag);
2995 if (!$tag) return false;
3000 function render_login_form($link, $form_id = 0) {
3003 require_once "login_form.php";
3006 require_once "mobile/login_form.php";
3012 // from http://developer.apple.com/internet/safari/faq.html
3013 function no_cache_incantation() {
3014 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3015 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3016 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3017 header("Cache-Control: post-check=0, pre-check=0", false);
3018 header("Pragma: no-cache"); // HTTP/1.0
3021 function format_warning($msg, $id = "") {
3023 return "<div class=\"warning\" id=\"$id\">
3024 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3027 function format_notice($msg, $id = "") {
3029 return "<div class=\"notice\" id=\"$id\">
3030 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3033 function format_error($msg, $id = "") {
3035 return "<div class=\"error\" id=\"$id\">
3036 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3039 function print_notice($msg) {
3040 return print format_notice($msg);
3043 function print_warning($msg) {
3044 return print format_warning($msg);
3047 function print_error($msg) {
3048 return print format_error($msg);
3052 function T_sprintf() {
3053 $args = func_get_args();
3054 return vsprintf(__(array_shift($args)), $args);
3057 function format_inline_player($link, $url, $ctype) {
3061 if (strpos($ctype, "audio/") === 0) {
3063 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3064 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3065 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3067 $id = 'AUDIO-' . uniqid();
3069 $entry .= "<audio id=\"$id\"\">
3070 <source src=\"$url\"></source>
3073 $entry .= "<span onclick=\"player(this)\"
3074 title=\"".__("Click to play")."\" status=\"0\"
3075 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3079 $entry .= "<object type=\"application/x-shockwave-flash\"
3080 data=\"lib/button/musicplayer.swf?song_url=$url\"
3081 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3082 <param name=\"movie\"
3083 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3088 $filename = substr($url, strrpos($url, "/")+
1);
3090 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3091 $filename . " (" . $ctype . ")" . "</a>";
3096 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3097 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3103 /* we can figure out feed_id from article id anyway, why do we
3104 * pass feed_id here? let's ignore the argument :( */
3106 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3107 WHERE ref_id = '$id'");
3109 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3111 $rv['feed_id'] = $feed_id;
3113 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3115 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
3116 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3118 if (db_num_rows($result) == 1) {
3119 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3120 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3121 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
3123 $rtl_content = false;
3124 $always_display_enclosures = false;
3125 $cache_content = false;
3129 $rtl_tag = "dir=\"RTL\"";
3136 if ($mark_as_read) {
3137 $result = db_query($link, "UPDATE ttrss_user_entries
3138 SET unread = false,last_read = NOW()
3139 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3141 ccache_update($link, $feed_id, $owner_uid);
3144 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3145 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3146 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3147 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3154 FROM ttrss_entries,ttrss_user_entries
3155 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3159 $line = db_fetch_assoc($result);
3161 if ($line["icon_url"]) {
3162 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3164 $feed_icon = " ";
3167 $feed_site_url = $line['site_url'];
3169 $num_comments = $line["num_comments"];
3170 $entry_comments = "";
3172 if ($num_comments > 0) {
3173 if ($line["comments"]) {
3174 $comments_url = htmlspecialchars($line["comments"]);
3176 $comments_url = htmlspecialchars($line["link"]);
3178 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3180 if ($line["comments"] && $line["link"] != $line["comments"]) {
3181 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
3186 header("Content-Type: text/html");
3187 $rv['content'] .= "<html><head>
3188 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3189 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3190 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3194 $title_escaped = htmlspecialchars($line['title']);
3196 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3197 truncate_string(strip_tags($line['title']), 15) . "</div>";
3199 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3200 strip_tags($line['title']) . "</div>";
3202 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3204 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3205 class=\"postHeader\" id=\"POSTHDR-$id\">";
3207 $entry_author = $line["author"];
3209 if ($entry_author) {
3210 $entry_author = __(" - ") . $entry_author;
3213 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3216 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3218 if ($line["link"]) {
3219 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3220 title=\"".htmlspecialchars($line['title'])."\"
3222 htmlspecialchars($line["link"]) . "\">" .
3224 "<span class='author'>$entry_author</span></a></div>";
3226 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3229 $tag_cache = $line["tag_cache"];
3232 $tags = get_article_tags($link, $id, $owner_uid);
3234 $tags = explode(",", $tag_cache);
3236 $tags_str = format_tags_string($tags, $id);
3237 $tags_str_full = join(", ", $tags);
3239 if (!$tags_str_full) $tags_str_full = __("no tags");
3241 if (!$entry_comments) $entry_comments = " "; # placeholder
3243 $rv['content'] .= "<div class='postTags' style='float : right'>
3244 <img src='".theme_image($link, 'images/tag.png')."'
3245 class='tagsPic' alt='Tags' title='Tags'> ";
3248 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3249 <a title=\"".__('Edit tags for this article')."\"
3250 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3252 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3253 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3254 position=\"below\">$tags_str_full</div>";
3256 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3257 class='tagsPic' style=\"cursor : pointer\"
3258 onclick=\"postOpenInNewTab(event, $id)\"
3259 alt='Zoom' title='".__('Open article in new tab')."'>";
3263 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
3264 $rv['content'] .= $p->hook_article_button($line);
3267 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3268 class='tagsPic' style=\"cursor : pointer\"
3269 onclick=\"closeArticlePanel($id)\"
3270 title='".__('Close article')."'>";
3273 $tags_str = strip_tags($tags_str);
3274 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3276 $rv['content'] .= "</div>";
3277 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3279 if ($line["orig_feed_id"]) {
3281 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3282 WHERE id = ".$line["orig_feed_id"]);
3284 if (db_num_rows($tmp_result) != 0) {
3286 $rv['content'] .= "<div clear='both'>";
3287 $rv['content'] .= __("Originally from:");
3289 $rv['content'] .= " ";
3291 $tmp_line = db_fetch_assoc($tmp_result);
3293 $rv['content'] .= "<a target='_blank'
3294 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3295 $tmp_line['title'] . "</a>";
3297 $rv['content'] .= " ";
3299 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3300 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3302 $rv['content'] .= "</div>";
3306 $rv['content'] .= "</div>";
3308 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3309 if ($line['note']) {
3310 $rv['content'] .= format_article_note($id, $line['note']);
3312 $rv['content'] .= "</div>";
3314 $rv['content'] .= "<div class=\"postIcon\">" .
3315 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3316 href=\"".htmlspecialchars($feed_site_url)."\">".
3317 $feed_icon . "</a></div>";
3319 $rv['content'] .= "<div class=\"postContent\">";
3323 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3325 $ngram_result = db_query($link, "SELECT id,title FROM
3326 ttrss_entries,ttrss_user_entries
3327 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3328 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3329 AND title != '$title_escaped'
3330 AND owner_uid = $owner_uid");
3332 if (db_num_rows($ngram_result) > 0) {
3333 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3334 "<span>" . __('Related')."</span>";
3335 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3337 while ($nline = db_fetch_assoc($ngram_result)) {
3338 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3339 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3342 $rv['content'] .= "</div></div><br/";
3346 if ($cache_content && $line["cached_content"] != "") {
3347 $line["content"] =& $line["cached_content"];
3350 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3353 $rv['content'] .= $article_content;
3355 $rv['content'] .= format_article_enclosures($link, $id,
3356 $always_display_enclosures, $article_content);
3358 $rv['content'] .= "</div>";
3360 $rv['content'] .= "</div>";
3366 <div style=\"text-align : center\">
3367 <button onclick=\"return window.close()\">".
3368 __("Close this window")."</button></div>";
3369 $rv['content'] .= "</body></html>";
3376 function print_checkpoint($n, $s) {
3377 $ts = getmicrotime();
3378 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3382 function sanitize_tag($tag) {
3385 $tag = mb_strtolower($tag, 'utf-8');
3387 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3389 // $tag = str_replace('"', "", $tag);
3390 // $tag = str_replace("+", " ", $tag);
3391 $tag = str_replace("technorati tag: ", "", $tag);
3396 function get_self_url_prefix() {
3397 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3398 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3400 return SELF_URL_PATH
;
3404 function opml_publish_url($link){
3406 $url_path = get_self_url_prefix();
3407 $url_path .= "/opml.php?op=publish&key=" .
3408 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3414 * Purge a feed contents, marked articles excepted.
3416 * @param mixed $link The database connection.
3417 * @param integer $id The id of the feed to purge.
3420 function clear_feed_articles($link, $id) {
3423 $result = db_query($link, "DELETE FROM ttrss_user_entries
3424 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3426 $result = db_query($link, "DELETE FROM ttrss_user_entries
3427 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3430 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3431 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3433 ccache_update($link, $id, $_SESSION['uid']);
3434 } // function clear_feed_articles
3437 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3439 * @return string The Mozilla Firefox feed adding URL.
3441 function add_feed_url() {
3442 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3444 $url_path = get_self_url_prefix() .
3445 "/public.php?op=subscribe&feed_url=%s";
3447 } // function add_feed_url
3449 function encrypt_password($pass, $salt = '', $mode2 = false) {
3450 if ($salt && $mode2) {
3451 return "MODE2:" . hash('sha256', $salt . $pass);
3453 return "SHA1X:" . sha1("$salt:$pass");
3455 return "SHA1:" . sha1($pass);
3457 } // function encrypt_password
3459 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3462 $cat_id = (int)getFeedCategory($link, $feed_id);
3464 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3465 owner_uid = $owner_uid AND enabled = true");
3467 $check_cats = join(",", array_merge(
3468 getParentCategories($link, $cat_id, $owner_uid),
3471 while ($line = db_fetch_assoc($result)) {
3472 $filter_id = $line["id"];
3474 $result2 = db_query($link, "SELECT
3475 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3476 FROM ttrss_filters2_rules AS r,
3477 ttrss_filter_types AS t
3479 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3480 (feed_id IS NULL OR feed_id = '$feed_id') AND
3481 filter_type = t.id AND filter_id = '$filter_id'");
3486 while ($rule_line = db_fetch_assoc($result2)) {
3487 # print_r($rule_line);
3490 $rule["reg_exp"] = $rule_line["reg_exp"];
3491 $rule["type"] = $rule_line["type_name"];
3493 array_push($rules, $rule);
3496 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3497 FROM ttrss_filters2_actions AS a,
3498 ttrss_filter_actions AS t
3500 action_id = t.id AND filter_id = '$filter_id'");
3502 while ($action_line = db_fetch_assoc($result2)) {
3503 # print_r($action_line);
3506 $action["type"] = $action_line["type_name"];
3507 $action["param"] = $action_line["action_param"];
3509 array_push($actions, $action);
3514 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3515 $filter["rules"] = $rules;
3516 $filter["actions"] = $actions;
3518 if (count($rules) > 0 && count($actions) > 0) {
3519 array_push($filters, $filter);
3526 function get_score_pic($score) {
3528 return "score_high.png";
3529 } else if ($score > 0) {
3530 return "score_half_high.png";
3531 } else if ($score < -100) {
3532 return "score_low.png";
3533 } else if ($score < 0) {
3534 return "score_half_low.png";
3536 return "score_neutral.png";
3540 function feed_has_icon($id) {
3541 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3544 function init_connection($link) {
3547 if (DB_TYPE
== "pgsql") {
3548 pg_query($link, "set client_encoding = 'UTF-8'");
3549 pg_set_client_encoding("UNICODE");
3550 pg_query($link, "set datestyle = 'ISO, european'");
3551 pg_query($link, "set TIME ZONE 0");
3553 db_query($link, "SET time_zone = '+0:0'");
3555 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3556 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3562 $pluginhost = new PluginHost($link);
3563 $pluginhost->load(PLUGINS
);
3567 print "Unable to connect to database:" . db_last_error();
3572 /* function ccache_zero($link, $feed_id, $owner_uid) {
3573 db_query($link, "UPDATE ttrss_counters_cache SET
3574 value = 0, updated = NOW() WHERE
3575 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3578 function ccache_zero_all($link, $owner_uid) {
3579 db_query($link, "UPDATE ttrss_counters_cache SET
3580 value = 0 WHERE owner_uid = '$owner_uid'");
3582 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3583 value = 0 WHERE owner_uid = '$owner_uid'");
3586 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3589 $table = "ttrss_counters_cache";
3591 $table = "ttrss_cat_counters_cache";
3594 db_query($link, "DELETE FROM $table WHERE
3595 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3599 function ccache_update_all($link, $owner_uid) {
3601 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3603 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3604 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3606 while ($line = db_fetch_assoc($result)) {
3607 ccache_update($link, $line["feed_id"], $owner_uid, true);
3610 /* We have to manually include category 0 */
3612 ccache_update($link, 0, $owner_uid, true);
3615 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3616 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3618 while ($line = db_fetch_assoc($result)) {
3619 print ccache_update($link, $line["feed_id"], $owner_uid);
3626 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3627 $no_update = false) {
3629 if (!is_numeric($feed_id)) return;
3632 $table = "ttrss_counters_cache";
3634 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3635 WHERE id = '$feed_id'");
3636 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3639 $table = "ttrss_cat_counters_cache";
3642 if (DB_TYPE
== "pgsql") {
3643 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3644 } else if (DB_TYPE
== "mysql") {
3645 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3648 $result = db_query($link, "SELECT value FROM $table
3649 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3652 if (db_num_rows($result) == 1) {
3653 return db_fetch_result($result, 0, "value");
3658 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3664 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3665 $update_pcat = true) {
3667 if (!is_numeric($feed_id)) return;
3669 if (!$is_cat && $feed_id > 0) {
3670 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3671 WHERE id = '$feed_id'");
3672 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3675 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3677 /* When updating a label, all we need to do is recalculate feed counters
3678 * because labels are not cached */
3681 ccache_update_all($link, $owner_uid);
3686 $table = "ttrss_counters_cache";
3688 $table = "ttrss_cat_counters_cache";
3691 if ($is_cat && $feed_id >= 0) {
3692 if ($feed_id != 0) {
3693 $cat_qpart = "cat_id = '$feed_id'";
3695 $cat_qpart = "cat_id IS NULL";
3698 /* Recalculate counters for child feeds */
3700 $result = db_query($link, "SELECT id FROM ttrss_feeds
3701 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3703 while ($line = db_fetch_assoc($result)) {
3704 ccache_update($link, $line["id"], $owner_uid, false, false);
3707 $result = db_query($link, "SELECT SUM(value) AS sv
3708 FROM ttrss_counters_cache, ttrss_feeds
3709 WHERE id = feed_id AND $cat_qpart AND
3710 ttrss_feeds.owner_uid = '$owner_uid'");
3712 $unread = (int) db_fetch_result($result, 0, "sv");
3715 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3718 db_query($link, "BEGIN");
3720 $result = db_query($link, "SELECT feed_id FROM $table
3721 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3723 if (db_num_rows($result) == 1) {
3724 db_query($link, "UPDATE $table SET
3725 value = '$unread', updated = NOW() WHERE
3726 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3729 db_query($link, "INSERT INTO $table
3730 (feed_id, value, owner_uid, updated)
3732 ($feed_id, $unread, $owner_uid, NOW())");
3735 db_query($link, "COMMIT");
3737 if ($feed_id > 0 && $prev_unread != $unread) {
3741 /* Update parent category */
3745 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3746 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3748 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3750 ccache_update($link, $cat_id, $owner_uid, true);
3754 } else if ($feed_id < 0) {
3755 ccache_update_all($link, $owner_uid);
3761 /* function ccache_cleanup($link, $owner_uid) {
3763 if (DB_TYPE == "pgsql") {
3764 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3765 (SELECT count(*) FROM ttrss_counters_cache AS c2
3766 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3767 AND owner_uid = '$owner_uid'");
3769 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3770 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3771 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3772 AND owner_uid = '$owner_uid'");
3774 db_query($link, "DELETE c1 FROM
3775 ttrss_counters_cache AS c1,
3776 ttrss_counters_cache AS c2
3778 c1.owner_uid = '$owner_uid' AND
3779 c1.owner_uid = c2.owner_uid AND
3780 c1.feed_id = c2.feed_id");
3782 db_query($link, "DELETE c1 FROM
3783 ttrss_cat_counters_cache AS c1,
3784 ttrss_cat_counters_cache AS c2
3786 c1.owner_uid = '$owner_uid' AND
3787 c1.owner_uid = c2.owner_uid AND
3788 c1.feed_id = c2.feed_id");
3793 function label_find_id($link, $label, $owner_uid) {
3794 $result = db_query($link,
3795 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3796 AND owner_uid = '$owner_uid' LIMIT 1");
3798 if (db_num_rows($result) == 1) {
3799 return db_fetch_result($result, 0, "id");
3805 function get_article_labels($link, $id, $owner_uid = false) {
3808 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3810 $result = db_query($link, "SELECT label_cache FROM
3811 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3814 if (db_num_rows($result) > 0) {
3815 $label_cache = db_fetch_result($result, 0, "label_cache");
3818 $label_cache = json_decode($label_cache, true);
3820 if ($label_cache["no-labels"] == 1)
3823 return $label_cache;
3827 $result = db_query($link,
3828 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3829 FROM ttrss_labels2, ttrss_user_labels2
3831 AND article_id = '$id'
3832 AND owner_uid = ". $owner_uid . "
3835 while ($line = db_fetch_assoc($result)) {
3836 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3838 array_push($rv, $rk);
3842 label_update_cache($link, $owner_uid, $id, $rv);
3844 label_update_cache($link, $owner_uid, $id, array("no-labels" => 1));
3850 function label_find_caption($link, $label, $owner_uid) {
3851 $result = db_query($link,
3852 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3853 AND owner_uid = '$owner_uid' LIMIT 1");
3855 if (db_num_rows($result) == 1) {
3856 return db_fetch_result($result, 0, "caption");
3862 function get_all_labels($link, $owner_uid) {
3865 $result = db_query($link, "SELECT fg_color, bg_color, caption FROM ttrss_labels2 WHERE owner_uid = " . $owner_uid);
3867 while ($line = db_fetch_assoc($result)) {
3868 array_push($rv, $line);
3874 function label_update_cache($link, $owner_uid, $id, $labels = false, $force = false) {
3877 label_clear_cache($link, $id);
3880 $labels = get_article_labels($link, $id);
3882 $labels = db_escape_string(json_encode($labels));
3884 db_query($link, "UPDATE ttrss_user_entries SET
3885 label_cache = '$labels' WHERE ref_id = '$id' AND owner_uid = '$owner_uid'");
3889 function label_clear_cache($link, $id) {
3891 db_query($link, "UPDATE ttrss_user_entries SET
3892 label_cache = '' WHERE ref_id = '$id'");
3896 function label_remove_article($link, $id, $label, $owner_uid) {
3898 $label_id = label_find_id($link, $label, $owner_uid);
3900 if (!$label_id) return;
3902 $result = db_query($link,
3903 "DELETE FROM ttrss_user_labels2
3905 label_id = '$label_id' AND
3906 article_id = '$id'");
3908 label_clear_cache($link, $id);
3911 function label_add_article($link, $id, $label, $owner_uid) {
3913 $label_id = label_find_id($link, $label, $owner_uid);
3915 if (!$label_id) return;
3917 $result = db_query($link,
3919 article_id FROM ttrss_labels2, ttrss_user_labels2
3922 label_id = '$label_id' AND
3923 article_id = '$id' AND owner_uid = '$owner_uid'
3926 if (db_num_rows($result) == 0) {
3927 db_query($link, "INSERT INTO ttrss_user_labels2
3928 (label_id, article_id) VALUES ('$label_id', '$id')");
3931 label_clear_cache($link, $id);
3935 function label_remove($link, $id, $owner_uid) {
3936 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3938 db_query($link, "BEGIN");
3940 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3943 $caption = db_fetch_result($result, 0, "caption");
3945 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3946 AND owner_uid = " . $owner_uid);
3948 if (db_affected_rows($link, $result) != 0 && $caption) {
3950 /* Remove access key for the label */
3952 $ext_id = -11 - $id;
3954 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3955 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3957 /* Disable filters that reference label being removed */
3959 db_query($link, "UPDATE ttrss_filters SET
3960 enabled = false WHERE action_param = '$caption'
3962 AND owner_uid = " . $owner_uid);
3964 /* Remove cached data */
3966 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3967 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3971 db_query($link, "COMMIT");
3974 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
3976 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
3978 db_query($link, "BEGIN");
3982 $result = db_query($link, "SELECT id FROM ttrss_labels2
3983 WHERE caption = '$caption' AND owner_uid = $owner_uid");
3985 if (db_num_rows($result) == 0) {
3986 $result = db_query($link,
3987 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
3988 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
3990 $result = db_affected_rows($link, $result) != 0;
3993 db_query($link, "COMMIT");
3998 function format_tags_string($tags, $id) {
4001 $tags_nolinks_str = "";
4007 $formatted_tags = array();
4009 foreach ($tags as $tag) {
4011 $tag_escaped = str_replace("'", "\\'", $tag);
4013 if (mb_strlen($tag) > 30) {
4014 $tag = truncate_string($tag, 30);
4017 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4019 array_push($formatted_tags, $tag_str);
4021 $tmp_tags_str = implode(", ", $formatted_tags);
4023 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4028 $tags_str = implode(", ", $formatted_tags);
4030 if ($num_tags < count($tags)) {
4031 $tags_str .= ", …";
4034 if ($num_tags == 0) {
4035 $tags_str = __("no tags");
4042 function format_article_labels($labels, $id) {
4046 foreach ($labels as $l) {
4047 $labels_str .= sprintf("<span class='hlLabelRef'
4048 style='color : %s; background-color : %s'>%s</span>",
4049 $l[2], $l[3], $l[1]);
4056 function format_article_note($id, $note) {
4058 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4059 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4060 __('(edit note)')."</div>$note</div>";
4065 function toggle_collapse_cat($link, $cat_id, $mode) {
4067 $mode = bool_to_sql_bool($mode);
4069 db_query($link, "UPDATE ttrss_feed_categories SET
4070 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4077 $pref_name = '_COLLAPSED_SPECIAL';
4080 $pref_name = '_COLLAPSED_LABELS';
4083 $pref_name = '_COLLAPSED_UNCAT';
4089 set_pref($link, $pref_name, 'true');
4091 set_pref($link, $pref_name, 'false');
4097 function remove_feed($link, $id, $owner_uid) {
4101 /* save starred articles in Archived feed */
4103 db_query($link, "BEGIN");
4105 /* prepare feed if necessary */
4107 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4110 if (db_num_rows($result) == 0) {
4111 db_query($link, "INSERT INTO ttrss_archived_feeds
4112 (id, owner_uid, title, feed_url, site_url)
4113 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4117 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4118 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4119 marked = true AND owner_uid = $owner_uid");
4121 /* Remove access key for the feed */
4123 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4124 feed_id = '$id' AND owner_uid = $owner_uid");
4126 /* remove the feed */
4128 db_query($link, "DELETE FROM ttrss_feeds
4129 WHERE id = '$id' AND owner_uid = $owner_uid");
4131 db_query($link, "COMMIT");
4133 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4134 unlink(ICONS_DIR
. "/$id.ico");
4137 ccache_remove($link, $id, $owner_uid);
4140 label_remove($link, -11-$id, $owner_uid);
4141 ccache_remove($link, -11-$id, $owner_uid);
4145 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
4146 if ($parent_cat_id) {
4147 $parent_qpart = "parent_cat = '$parent_cat_id'";
4148 $parent_insert = "'$parent_cat_id'";
4150 $parent_qpart = "parent_cat IS NULL";
4151 $parent_insert = "NULL";
4154 $result = db_query($link,
4155 "SELECT id FROM ttrss_feed_categories
4156 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4158 if (db_num_rows($result) == 0) {
4161 return db_fetch_result($result, 0, "id");
4165 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
4167 if (!$feed_cat) return false;
4169 db_query($link, "BEGIN");
4171 if ($parent_cat_id) {
4172 $parent_qpart = "parent_cat = '$parent_cat_id'";
4173 $parent_insert = "'$parent_cat_id'";
4175 $parent_qpart = "parent_cat IS NULL";
4176 $parent_insert = "NULL";
4179 $result = db_query($link,
4180 "SELECT id FROM ttrss_feed_categories
4181 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4183 if (db_num_rows($result) == 0) {
4185 $result = db_query($link,
4186 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
4187 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
4189 db_query($link, "COMMIT");
4197 function remove_feed_category($link, $id, $owner_uid) {
4199 db_query($link, "DELETE FROM ttrss_feed_categories
4200 WHERE id = '$id' AND owner_uid = $owner_uid");
4202 ccache_remove($link, $id, $owner_uid, true);
4205 function archive_article($link, $id, $owner_uid) {
4206 db_query($link, "BEGIN");
4208 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4209 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4211 if (db_num_rows($result) != 0) {
4213 /* prepare the archived table */
4215 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4218 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4219 WHERE id = '$feed_id'");
4221 if (db_num_rows($result) == 0) {
4222 db_query($link, "INSERT INTO ttrss_archived_feeds
4223 (id, owner_uid, title, feed_url, site_url)
4224 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4225 WHERE id = '$feed_id'");
4228 db_query($link, "UPDATE ttrss_user_entries
4229 SET orig_feed_id = feed_id, feed_id = NULL
4230 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4234 db_query($link, "COMMIT");
4237 function getArticleFeed($link, $id) {
4238 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4239 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4241 if (db_num_rows($result) != 0) {
4242 return db_fetch_result($result, 0, "feed_id");
4249 * Fixes incomplete URLs by prepending "http://".
4250 * Also replaces feed:// with http://, and
4251 * prepends a trailing slash if the url is a domain name only.
4253 * @param string $url Possibly incomplete URL
4255 * @return string Fixed URL.
4257 function fix_url($url) {
4258 if (strpos($url, '://') === false) {
4259 $url = 'http://' . $url;
4260 } else if (substr($url, 0, 5) == 'feed:') {
4261 $url = 'http:' . substr($url, 5);
4264 //prepend slash if the URL has no slash in it
4265 // "http://www.example" -> "http://www.example/"
4266 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4270 if ($url != "http:///")
4276 function validate_feed_url($url) {
4277 $parts = parse_url($url);
4279 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4283 function get_article_enclosures($link, $id) {
4285 $query = "SELECT * FROM ttrss_enclosures
4286 WHERE post_id = '$id' AND content_url != ''";
4290 $result = db_query($link, $query);
4292 if (db_num_rows($result) > 0) {
4293 while ($line = db_fetch_assoc($result)) {
4294 array_push($rv, $line);
4301 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset, $include_nested = false) {
4307 if ($cat_id == -4 ||
$cat_id == -2) {
4308 $counters = getLabelCounters($link, true);
4310 foreach (array_values($counters) as $cv) {
4312 $unread = $cv["counter"];
4314 if ($unread ||
!$unread_only) {
4318 "title" => $cv["description"],
4319 "unread" => $cv["counter"],
4323 array_push($feeds, $row);
4330 if ($cat_id == -4 ||
$cat_id == -1) {
4331 foreach (array(-1, -2, -3, -4, -6, 0) as $i) {
4332 $unread = getFeedUnread($link, $i);
4334 if ($unread ||
!$unread_only) {
4335 $title = getFeedTitle($link, $i);
4340 "unread" => $unread,
4343 array_push($feeds, $row);
4351 if ($include_nested && $cat_id) {
4352 $result = db_query($link, "SELECT
4353 id, title FROM ttrss_feed_categories
4354 WHERE parent_cat = '$cat_id' AND owner_uid = " . $_SESSION["uid"] .
4355 " ORDER BY id, title");
4357 while ($line = db_fetch_assoc($result)) {
4358 $unread = getFeedUnread($link, $line["id"], true) +
4359 getCategoryChildrenUnread($link, $line["id"]);
4361 if ($unread ||
!$unread_only) {
4363 "id" => $line["id"],
4364 "title" => $line["title"],
4365 "unread" => $unread,
4368 array_push($feeds, $row);
4376 $limit_qpart = "LIMIT $limit OFFSET $offset";
4381 if ($cat_id == -4 ||
$cat_id == -3) {
4382 $result = db_query($link, "SELECT
4383 id, feed_url, cat_id, title, order_id, ".
4384 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4385 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4386 " ORDER BY cat_id, title " . $limit_qpart);
4390 $cat_qpart = "cat_id = '$cat_id'";
4392 $cat_qpart = "cat_id IS NULL";
4394 $result = db_query($link, "SELECT
4395 id, feed_url, cat_id, title, order_id, ".
4396 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4397 FROM ttrss_feeds WHERE
4398 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4399 " ORDER BY cat_id, title " . $limit_qpart);
4402 while ($line = db_fetch_assoc($result)) {
4404 $unread = getFeedUnread($link, $line["id"]);
4406 $has_icon = feed_has_icon($line['id']);
4408 if ($unread ||
!$unread_only) {
4411 "feed_url" => $line["feed_url"],
4412 "title" => $line["title"],
4413 "id" => (int)$line["id"],
4414 "unread" => (int)$unread,
4415 "has_icon" => $has_icon,
4416 "cat_id" => (int)$line["cat_id"],
4417 "last_updated" => strtotime($line["last_updated"]),
4418 "order_id" => (int) $line["order_id"],
4421 array_push($feeds, $row);
4428 function api_get_headlines($link, $feed_id, $limit, $offset,
4429 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4430 $include_attachments, $since_id,
4431 $search = "", $search_mode = "", $match_on = "",
4432 $include_nested = false, $sanitize_content = true) {
4434 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4435 $view_mode, $is_cat, $search, $search_mode, $match_on,
4436 $order, $offset, 0, false, $since_id, $include_nested);
4438 $result = $qfh_ret[0];
4439 $feed_title = $qfh_ret[1];
4441 $headlines = array();
4443 while ($line = db_fetch_assoc($result)) {
4444 $is_updated = ($line["last_read"] == "" &&
4445 ($line["unread"] != "t" && $line["unread"] != "1"));
4447 $tags = explode(",", $line["tag_cache"]);
4448 $labels = json_decode($line["label_cache"], true);
4450 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4451 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4453 $headline_row = array(
4454 "id" => (int)$line["id"],
4455 "unread" => sql_bool_to_bool($line["unread"]),
4456 "marked" => sql_bool_to_bool($line["marked"]),
4457 "published" => sql_bool_to_bool($line["published"]),
4458 "updated" => strtotime($line["updated"]),
4459 "is_updated" => $is_updated,
4460 "title" => $line["title"],
4461 "link" => $line["link"],
4462 "feed_id" => $line["feed_id"],
4466 if ($include_attachments)
4467 $headline_row['attachments'] = get_article_enclosures($link,
4470 if ($show_excerpt) {
4471 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4472 $headline_row["excerpt"] = $excerpt;
4475 if ($show_content) {
4477 if ($line["cached_content"] != "") {
4478 $line["content_preview"] =& $line["cached_content"];
4481 if ($sanitize_content) {
4482 $headline_row["content"] = sanitize($link,
4483 $line["content_preview"], false, false, $line["site_url"]);
4485 $headline_row["content"] = $line["content_preview"];
4489 // unify label output to ease parsing
4490 if ($labels["no-labels"] == 1) $labels = array();
4492 $headline_row["labels"] = $labels;
4494 $headline_row["feed_title"] = $line["feed_title"];
4496 $headline_row["comments_count"] = (int)$line["num_comments"];
4497 $headline_row["comments_link"] = $line["comments"];
4499 $headline_row["always_display_attachments"] = sql_bool_to_bool($line["always_display_enclosures"]);
4501 array_push($headlines, $headline_row);
4507 function generate_error_feed($link, $error) {
4510 $reply['headlines']['id'] = -6;
4511 $reply['headlines']['is_cat'] = false;
4513 $reply['headlines']['toolbar'] = '';
4514 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4516 $reply['headlines-info'] = array("count" => 0,
4517 "vgroup_last_feed" => '',
4519 "disable_cache" => true);
4525 function generate_dashboard_feed($link) {
4528 $reply['headlines']['id'] = -5;
4529 $reply['headlines']['is_cat'] = false;
4531 $reply['headlines']['toolbar'] = '';
4532 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4534 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4536 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4537 WHERE owner_uid = " . $_SESSION['uid']);
4539 $last_updated = db_fetch_result($result, 0, "last_updated");
4540 $last_updated = make_local_datetime($link, $last_updated, false);
4542 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4544 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4545 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4547 $num_errors = db_fetch_result($result, 0, "num_errors");
4549 if ($num_errors > 0) {
4550 $reply['headlines']['content'] .= "<br/>";
4551 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4552 __('Some feeds have update errors (click for details)')."</a>";
4554 $reply['headlines']['content'] .= "</span></p>";
4556 $reply['headlines-info'] = array("count" => 0,
4557 "vgroup_last_feed" => '',
4559 "disable_cache" => true);
4564 function save_email_address($link, $email) {
4565 // FIXME: implement persistent storage of emails
4567 if (!$_SESSION['stored_emails'])
4568 $_SESSION['stored_emails'] = array();
4570 if (!in_array($email, $_SESSION['stored_emails']))
4571 array_push($_SESSION['stored_emails'], $email);
4574 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4575 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4577 $sql_is_cat = bool_to_sql_bool($is_cat);
4579 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4580 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4581 AND owner_uid = " . $owner_uid);
4583 if (db_num_rows($result) == 1) {
4584 $key = db_escape_string(sha1(uniqid(rand(), true)));
4586 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4587 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4588 AND owner_uid = " . $owner_uid);
4593 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4597 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4599 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4601 $sql_is_cat = bool_to_sql_bool($is_cat);
4603 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4604 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4605 AND owner_uid = " . $owner_uid);
4607 if (db_num_rows($result) == 1) {
4608 return db_fetch_result($result, 0, "access_key");
4610 $key = db_escape_string(sha1(uniqid(rand(), true)));
4612 $result = db_query($link, "INSERT INTO ttrss_access_keys
4613 (access_key, feed_id, is_cat, owner_uid)
4614 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4621 function get_feeds_from_html($url, $content)
4623 $url = fix_url($url);
4624 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4626 libxml_use_internal_errors(true);
4628 $doc = new DOMDocument();
4629 $doc->loadHTML($content);
4630 $xpath = new DOMXPath($doc);
4631 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4632 $feedUrls = array();
4633 foreach ($entries as $entry) {
4634 if ($entry->hasAttribute('href')) {
4635 $title = $entry->getAttribute('title');
4637 $title = $entry->getAttribute('type');
4639 $feedUrl = rewrite_relative_url(
4640 $baseUrl, $entry->getAttribute('href')
4642 $feedUrls[$feedUrl] = $title;
4648 function is_html($content) {
4649 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
4652 function url_is_html($url, $login = false, $pass = false) {
4653 return is_html(fetch_file_contents($url, false, $login, $pass));
4656 function print_label_select($link, $name, $value, $attributes = "") {
4658 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4659 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4661 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4662 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4664 while ($line = db_fetch_assoc($result)) {
4666 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4668 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4669 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4673 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4680 function format_article_enclosures($link, $id, $always_display_enclosures,
4683 $result = get_article_enclosures($link, $id);
4686 if (count($result) > 0) {
4688 $entries_html = array();
4691 foreach ($result as $line) {
4693 $url = $line["content_url"];
4694 $ctype = $line["content_type"];
4696 if (!$ctype) $ctype = __("unknown type");
4698 $filename = substr($url, strrpos($url, "/")+
1);
4700 # $player = format_inline_player($link, $url, $ctype);
4702 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4703 # $filename . " (" . $ctype . ")" . "</a>";
4705 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4706 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4708 array_push($entries_html, $entry);
4712 $entry["type"] = $ctype;
4713 $entry["filename"] = $filename;
4714 $entry["url"] = $url;
4716 array_push($entries, $entry);
4719 if (!get_pref($link, "STRIP_IMAGES")) {
4720 if ($always_display_enclosures ||
4721 !preg_match("/<img/i", $article_content)) {
4723 foreach ($entries as $entry) {
4725 if (preg_match("/image/", $entry["type"]) ||
4726 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4729 alt=\"".htmlspecialchars($entry["filename"])."\"
4730 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4737 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
4738 "<span>" . __('Attachments')."</span>";
4739 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4741 foreach ($entries_html as $entry) { $rv .= $entry; };
4743 $rv .= "</div></div>";
4749 function getLastArticleId($link) {
4750 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4751 WHERE owner_uid = " . $_SESSION["uid"]);
4753 if (db_num_rows($result) == 1) {
4754 return db_fetch_result($result, 0, "id");
4760 function build_url($parts) {
4761 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4765 * Converts a (possibly) relative URL to a absolute one.
4767 * @param string $url Base URL (i.e. from where the document is)
4768 * @param string $rel_url Possibly relative URL in the document
4770 * @return string Absolute URL
4772 function rewrite_relative_url($url, $rel_url) {
4773 if (strpos($rel_url, "magnet:") === 0) {
4775 } else if (strpos($rel_url, "://") !== false) {
4777 } else if (strpos($rel_url, "//") === 0) {
4778 # protocol-relative URL (rare but they exist)
4780 } else if (strpos($rel_url, "/") === 0)
4782 $parts = parse_url($url);
4783 $parts['path'] = $rel_url;
4785 return build_url($parts);
4788 $parts = parse_url($url);
4789 if (!isset($parts['path'])) {
4790 $parts['path'] = '/';
4792 $dir = $parts['path'];
4793 if (substr($dir, -1) !== '/') {
4794 $dir = dirname($parts['path']);
4795 $dir !== '/' && $dir .= '/';
4797 $parts['path'] = $dir . $rel_url;
4799 return build_url($parts);
4803 function sphinx_search($query, $offset = 0, $limit = 30) {
4804 require_once 'lib/sphinxapi.php';
4806 $sphinxClient = new SphinxClient();
4808 $sphinxClient->SetServer('localhost', 9312);
4809 $sphinxClient->SetConnectTimeout(1);
4811 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4812 'feed_title' => 20));
4814 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4815 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4816 $sphinxClient->SetLimits($offset, $limit, 1000);
4817 $sphinxClient->SetArrayResult(false);
4818 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4820 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4824 if (is_array($result['matches'])) {
4825 foreach (array_keys($result['matches']) as $int_id) {
4826 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4827 array_push($ids, $ref_id);
4834 function cleanup_tags($link, $days = 14, $limit = 1000) {
4836 if (DB_TYPE
== "pgsql") {
4837 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4838 } else if (DB_TYPE
== "mysql") {
4839 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4844 while ($limit > 0) {
4847 $query = "SELECT ttrss_tags.id AS id
4848 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4849 WHERE post_int_id = int_id AND $interval_query AND
4850 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4852 $result = db_query($link, $query);
4856 while ($line = db_fetch_assoc($result)) {
4857 array_push($ids, $line['id']);
4860 if (count($ids) > 0) {
4861 $ids = join(",", $ids);
4864 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4865 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4870 $limit -= $limit_part;
4875 return $tags_deleted;
4878 function print_user_stylesheet($link) {
4879 $value = get_pref($link, 'USER_STYLESHEET');
4882 print "<style type=\"text/css\">";
4883 print str_replace("<br/>", "\n", $value);
4889 /* function rewrite_urls($line) {
4894 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4895 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4900 function rewrite_urls($html) {
4901 libxml_use_internal_errors(true);
4903 $charset_hack = '<head>
4904 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4907 $doc = new DOMDocument();
4908 $doc->loadHTML($charset_hack . $html);
4909 $xpath = new DOMXPath($doc);
4911 $entries = $xpath->query('//*/text()');
4913 foreach ($entries as $entry) {
4914 if (strstr($entry->wholeText
, "://") !== false) {
4915 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4916 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4918 if ($text != $entry->wholeText
) {
4919 $cdoc = new DOMDocument();
4920 $cdoc->loadHTML($charset_hack . $text);
4923 foreach ($cdoc->childNodes
as $cnode) {
4924 $cnode = $doc->importNode($cnode, true);
4927 $entry->parentNode
->insertBefore($cnode);
4931 $entry->parentNode
->removeChild($entry);
4937 $node = $doc->getElementsByTagName('body')->item(0);
4939 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4941 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4946 function filter_to_sql($link, $filter, $owner_uid) {
4949 if (DB_TYPE
== "pgsql")
4952 $reg_qpart = "REGEXP";
4954 foreach ($filter["rules"] AS $rule) {
4955 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4956 $rule['reg_exp']) !== FALSE;
4958 if ($regexp_valid) {
4960 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
4962 switch ($rule["type"]) {
4964 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4965 $rule['reg_exp'] . "')";
4968 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4969 $rule['reg_exp'] . "')";
4972 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4973 $rule['reg_exp'] . "') OR LOWER(" .
4974 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4977 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4978 $rule['reg_exp'] . "')";
4981 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4982 $rule['reg_exp'] . "')";
4985 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4986 $rule['reg_exp'] . "')";
4990 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4991 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4994 if (isset($rule["cat_id"])) {
4996 if ($rule["cat_id"] > 0) {
4997 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4998 array_push($children, $rule["cat_id"]);
5000 $children = join(",", $children);
5002 $cat_qpart = "cat_id IN ($children)";
5004 $cat_qpart = "cat_id IS NULL";
5007 $qpart .= " AND $cat_qpart";
5010 array_push($query, "($qpart)");
5015 if (count($query) > 0) {
5016 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
5023 // -1 - never connected
5024 // 0 - no data received
5025 // 1 - data received successfully
5026 // 2 - did not receive valid data
5027 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5029 function get_linked_feeds($link, $instance_id = false) {
5031 $instance_qpart = "id = '$instance_id' AND ";
5033 $instance_qpart = "";
5035 if (DB_TYPE
== "pgsql") {
5036 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5038 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5041 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5042 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5044 while ($line = db_fetch_assoc($result)) {
5047 _debug("Updating: " . $line['access_url'] . " ($id)");
5049 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5050 $post_query = 'key=' . $line['access_key'];
5052 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5054 // try doing it the old way
5056 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5057 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5061 $feeds = json_decode($feeds, true);
5064 if ($feeds['error']) {
5065 $status = $feeds['error']['code'] +
10;
5068 if ($status == 16) {
5069 db_query($link, "DELETE FROM ttrss_linked_feeds
5070 WHERE instance_id = '$id'");
5075 if (count($feeds['feeds']) > 0) {
5077 db_query($link, "DELETE FROM ttrss_linked_feeds
5078 WHERE instance_id = '$id'");
5080 foreach ($feeds['feeds'] as $feed) {
5081 $feed_url = db_escape_string($feed['feed_url']);
5082 $title = db_escape_string($feed['title']);
5083 $subscribers = db_escape_string($feed['subscribers']);
5084 $site_url = db_escape_string($feed['site_url']);
5086 db_query($link, "INSERT INTO ttrss_linked_feeds
5087 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5089 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5092 // received 0 feeds, this might indicate that
5093 // the instance on the other hand is rebuilding feedbrowser cache
5094 // we will try again later
5096 // TODO: maybe perform expiration based on updated here?
5099 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5109 _debug("Status: $status");
5111 db_query($link, "UPDATE ttrss_linked_instances SET
5112 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5117 function make_feed_browser($link, $search, $limit, $mode = 1) {
5119 $owner_uid = $_SESSION["uid"];
5123 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5124 UPPER(title) LIKE UPPER('%$search%'))";
5130 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5131 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5132 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5133 AND owner_uid = '$owner_uid') $search_qpart
5134 ORDER BY subscribers DESC LIMIT $limit"); */
5136 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5137 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5138 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5140 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5141 WHERE tf.feed_url = qqq.feed_url
5142 AND owner_uid = '$owner_uid') $search_qpart
5143 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5145 } else if ($mode == 2) {
5146 $result = db_query($link, "SELECT *,
5147 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5148 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5150 ttrss_archived_feeds
5152 (SELECT COUNT(*) FROM ttrss_feeds
5153 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5154 owner_uid = '$owner_uid') = 0 AND
5155 owner_uid = '$owner_uid' $search_qpart
5156 ORDER BY id DESC LIMIT $limit");
5161 while ($line = db_fetch_assoc($result)) {
5165 $feed_url = htmlspecialchars($line["feed_url"]);
5166 $site_url = htmlspecialchars($line["site_url"]);
5167 $subscribers = $line["subscribers"];
5169 $check_box = "<input onclick='toggleSelectListRow2(this)'
5170 dojoType=\"dijit.form.CheckBox\"
5171 type=\"checkbox\" \">";
5173 $class = ($feedctr %
2) ?
"even" : "odd";
5175 $site_url = "<a target=\"_blank\"
5177 <span class=\"fb_feedTitle\">".
5178 htmlspecialchars($line["title"])."</span></a>";
5180 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5181 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5182 style='vertical-align : middle'></a>";
5184 $rv .= "<li>$check_box $feed_url $site_url".
5185 " <span class='subscribers'>($subscribers)</span></li>";
5187 } else if ($mode == 2) {
5188 $feed_url = htmlspecialchars($line["feed_url"]);
5189 $site_url = htmlspecialchars($line["site_url"]);
5190 $title = htmlspecialchars($line["title"]);
5192 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5193 type=\"checkbox\">";
5195 $class = ($feedctr %
2) ?
"even" : "odd";
5197 if ($line['articles_archived'] > 0) {
5198 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5199 $archived = " <span class='subscribers'>($archived)</span>";
5204 $site_url = "<a target=\"_blank\"
5206 <span class=\"fb_feedTitle\">".
5207 htmlspecialchars($line["title"])."</span></a>";
5209 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5210 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5211 style='vertical-align : middle'></a>";
5214 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5215 "$check_box $feed_url $site_url $archived</li>";
5221 if ($feedctr == 0) {
5222 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5228 if (!function_exists('gzdecode')) {
5229 function gzdecode($string) { // no support for 2nd argument
5230 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5231 base64_encode($string));
5235 function perform_data_import($link, $filename, $owner_uid) {
5239 $num_feeds_created = 0;
5241 $doc = @DOMDocument
::load($filename);
5244 $contents = file_get_contents($filename);
5247 $data = @gzuncompress
($contents);
5251 $data = @gzdecode
($contents);
5255 $doc = DOMDocument
::loadXML($data);
5260 $xpath = new DOMXpath($doc);
5262 $container = $doc->firstChild
;
5264 if ($container && $container->hasAttribute('schema-version')) {
5265 $schema_version = $container->getAttribute('schema-version');
5267 if ($schema_version != SCHEMA_VERSION
) {
5268 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5273 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5277 $articles = $xpath->query("//article");
5279 foreach ($articles as $article_node) {
5280 if ($article_node->childNodes
) {
5286 foreach ($article_node->childNodes
as $child) {
5287 if ($child->nodeName
!= 'label_cache')
5288 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5290 $article[$child->nodeName
] = $child->nodeValue
;
5293 //print_r($article);
5295 if ($article['guid']) {
5299 //db_query($link, "BEGIN");
5301 //print 'GUID:' . $article['guid'] . "\n";
5303 $result = db_query($link, "SELECT id FROM ttrss_entries
5304 WHERE guid = '".$article['guid']."'");
5306 if (db_num_rows($result) == 0) {
5308 $result = db_query($link,
5309 "INSERT INTO ttrss_entries
5323 ('".$article['title']."',
5324 '".$article['guid']."',
5325 '".$article['link']."',
5326 '".$article['updated']."',
5327 '".$article['content']."',
5328 '".sha1($article['content'])."',
5336 $result = db_query($link, "SELECT id FROM ttrss_entries
5337 WHERE guid = '".$article['guid']."'");
5339 if (db_num_rows($result) != 0) {
5340 $ref_id = db_fetch_result($result, 0, "id");
5344 $ref_id = db_fetch_result($result, 0, "id");
5347 //print "Got ref ID: $ref_id\n";
5351 $feed_url = $article['feed_url'];
5352 $feed_title = $article['feed_title'];
5356 if ($feed_url && $feed_title) {
5357 $result = db_query($link, "SELECT id FROM ttrss_feeds
5358 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5360 if (db_num_rows($result) != 0) {
5361 $feed = db_fetch_result($result, 0, "id");
5363 // try autocreating feed in Uncategorized...
5365 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5366 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5368 $result = db_query($link, "SELECT id FROM ttrss_feeds
5369 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5371 if (db_num_rows($result) != 0) {
5372 ++
$num_feeds_created;
5374 $feed = db_fetch_result($result, 0, "id");
5379 if ($feed != 'NULL')
5380 $feed_qpart = "feed_id = $feed";
5382 $feed_qpart = "feed_id IS NULL";
5384 //print "$ref_id / $feed / " . $article['title'] . "\n";
5386 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5387 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5389 if (db_num_rows($result) == 0) {
5391 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5392 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5393 $score = (int) $article['score'];
5395 $tag_cache = $article['tag_cache'];
5396 $label_cache = db_escape_string($article['label_cache']);
5397 $note = $article['note'];
5399 //print "Importing " . $article['title'] . "<br/>";
5403 $result = db_query($link,
5404 "INSERT INTO ttrss_user_entries
5405 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5406 published, score, tag_cache, label_cache, uuid, note)
5407 VALUES ($ref_id, $owner_uid, $feed, false,
5408 NULL, $marked, $published, $score, '$tag_cache',
5409 '$label_cache', '', '$note')");
5411 $label_cache = json_decode($label_cache, true);
5413 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5414 foreach ($label_cache as $label) {
5416 label_create($link, $label[1],
5417 $label[2], $label[3], $owner_uid);
5419 label_add_article($link, $ref_id, $label[1], $owner_uid);
5424 //db_query($link, "COMMIT");
5432 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5433 $num_processed, $num_imported, $num_feeds_created) .
5438 print "<p>" . __("Could not load XML document.") . "</p>";
5443 function get_random_bytes($length) {
5444 if (function_exists('openssl_random_pseudo_bytes')) {
5445 return openssl_random_pseudo_bytes($length);
5449 for ($i = 0; $i < $length; $i++
)
5450 $output .= chr(mt_rand(0, 255));
5456 function read_stdin() {
5457 $fp = fopen("php://stdin", "r");
5460 $line = trim(fgets($fp));
5468 function tmpdirname($path, $prefix) {
5469 // Use PHP's tmpfile function to create a temporary
5470 // directory name. Delete the file and keep the name.
5471 $tempname = tempnam($path,$prefix);
5475 if (!unlink($tempname))
5481 function getFeedCategory($link, $feed) {
5482 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5483 WHERE id = '$feed'");
5485 if (db_num_rows($result) > 0) {
5486 return db_fetch_result($result, 0, "cat_id");
5493 function create_published_article($link, $title, $url, $content, $labels_str,
5496 $guid = sha1($url . $owner_uid); // include owner_uid to prevent global GUID clash
5497 $content_hash = sha1($content);
5499 if ($labels_str != "") {
5500 $labels = explode(",", $labels_str);
5507 if (!$title) $title = $url;
5508 if (!$title && !$url) return false;
5510 if (filter_var($url, FILTER_VALIDATE_URL
) === FALSE) return false;
5512 db_query($link, "BEGIN");
5514 // only check for our user data here, others might have shared this with different content etc
5515 $result = db_query($link, "SELECT id FROM ttrss_entries, ttrss_user_entries WHERE
5516 link = '$url' AND ref_id = id AND owner_uid = '$owner_uid' LIMIT 1");
5518 if (db_num_rows($result) != 0) {
5519 $ref_id = db_fetch_result($result, 0, "id");
5521 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries WHERE
5522 ref_id = '$ref_id' AND owner_uid = '$owner_uid' LIMIT 1");
5524 if (db_num_rows($result) != 0) {
5525 $int_id = db_fetch_result($result, 0, "int_id");
5527 db_query($link, "UPDATE ttrss_entries SET
5528 content = '$content', content_hash = '$content_hash' WHERE id = '$ref_id'");
5530 db_query($link, "UPDATE ttrss_user_entries SET published = true WHERE
5531 int_id = '$int_id' AND owner_uid = '$owner_uid'");
5534 db_query($link, "INSERT INTO ttrss_user_entries
5535 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5537 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5540 if (count($labels) != 0) {
5541 foreach ($labels as $label) {
5542 label_add_article($link, $ref_id, trim($label), $owner_uid);
5549 $result = db_query($link, "INSERT INTO ttrss_entries
5550 (title, guid, link, updated, content, content_hash, date_entered, date_updated)
5552 ('$title', '$guid', '$url', NOW(), '$content', '$content_hash', NOW(), NOW())");
5554 $result = db_query($link, "SELECT id FROM ttrss_entries WHERE guid = '$guid'");
5556 if (db_num_rows($result) != 0) {
5557 $ref_id = db_fetch_result($result, 0, "id");
5559 db_query($link, "INSERT INTO ttrss_user_entries
5560 (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, last_read, note, unread)
5562 ('$ref_id', '', NULL, NULL, $owner_uid, true, '', '', NOW(), '', false)");
5564 if (count($labels) != 0) {
5565 foreach ($labels as $label) {
5566 label_add_article($link, $ref_id, trim($label), $owner_uid);
5574 db_query($link, "COMMIT");