\n";
}
/** Return class='active' if $bold is true
* @param bool
* @param string
* @return string
*/
function bold($bold, $class = "") {
return ($bold ? " class='active $class'" : ($class ? " class='$class'" : ""));
}
/** Generate class for odd rows
* @param string return this for odd rows, empty to reset counter
* @return string
*/
function odd($return = ' class="odd"') {
static $i = 0;
if (!$return) { // reset counter
$i = -1;
}
return ($i++ % 2 ? $return : '');
}
/** Escape string for JavaScript apostrophes
* @param string
* @return string
*/
function js_escape($string) {
return addcslashes($string, "\r\n'\\/"); // slash for "
: nbsp(reset($functions))
) . '
';
$input = $adminer->editInput($_GET["edit"], $field, $attrs, $value); // usage in call is without a table
if ($input != "") {
echo $input;
} elseif (preg_match('~bool~', $field["type"])) {
echo "" .
"";
} elseif ($field["type"] == "set") { //! 64 bits
preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
foreach ($matches[1] as $i => $val) {
$val = stripcslashes(str_replace("''", "'", $val));
$checked = (is_int($value) ? ($value >> $i) & 1 : in_array($val, explode(",", $value), true));
echo " ';
}
} elseif (preg_match('~blob|bytea|raw|file~', $field["type"]) && ini_bool("file_uploads")) {
echo "";
} elseif (($text = preg_match('~text|lob~', $field["type"])) || preg_match("~\n~", $value)) {
if ($text && $jush != "sqlite") {
$attrs .= " cols='50' rows='12'";
} else {
$rows = min(12, substr_count($value, "\n") + 1);
$attrs .= " cols='30' rows='$rows'" . ($rows == 1 ? " style='height: 1.2em;'" : ""); // 1.2em - line-height
}
echo "';
} elseif ($function == "json" || preg_match('~^jsonb?$~', $field["type"])) {
echo "';
} else {
// int(3) is only a display hint
$maxlength = (!preg_match('~int~', $field["type"]) && preg_match('~^(\\d+)(,(\\d+))?$~', $field["length"], $match) ? ((preg_match("~binary~", $field["type"]) ? 2 : 1) * $match[1] + ($match[3] ? 1 : 0) + ($match[2] && !$field["unsigned"] ? 1 : 0)) : ($types[$field["type"]] ? $types[$field["type"]] + ($field["unsigned"] ? 0 : 1) : 0));
if ($jush == 'sql' && $connection->server_info >= 5.6 && preg_match('~time~', $field["type"])) {
$maxlength += 7; // microtime
}
// type='date' and type='time' display localized value which may be confusing, type='datetime' uses 'T' as date and time separator
echo " 20 ? " size='40'" : "")
. "$attrs>"
;
}
echo $adminer->editHint($_GET["edit"], $field, $value);
}
}
/** Process edit input field
* @param one field from fields()
* @return string or false to leave the original value
*/
function process_input($field) {
global $adminer;
$idf = bracket_escape($field["field"]);
$function = $_POST["function"][$idf];
$value = $_POST["fields"][$idf];
if ($field["type"] == "enum") {
if ($value == -1) {
return false;
}
if ($value == "") {
return "NULL";
}
return +$value;
}
if ($field["auto_increment"] && $value == "") {
return null;
}
if ($function == "orig") {
return ($field["on_update"] == "CURRENT_TIMESTAMP" ? idf_escape($field["field"]) : false);
}
if ($function == "NULL") {
return "NULL";
}
if ($field["type"] == "set") {
return array_sum((array) $value);
}
if ($function == "json") {
$function = "";
$value = json_decode($value, true);
if (!is_array($value)) {
return false; //! report errors
}
return $value;
}
if (preg_match('~blob|bytea|raw|file~', $field["type"]) && ini_bool("file_uploads")) {
$file = get_file("fields-$idf");
if (!is_string($file)) {
return false; //! report errors
}
return q($file);
}
return $adminer->processInput($field, $value, $function);
}
/** Compute fields() from $_POST edit data
* @return array
*/
function fields_from_edit() {
global $driver;
$return = array();
foreach ((array) $_POST["field_keys"] as $key => $val) {
if ($val != "") {
$val = bracket_escape($val);
$_POST["function"][$val] = $_POST["field_funs"][$key];
$_POST["fields"][$val] = $_POST["field_vals"][$key];
}
}
foreach ((array) $_POST["fields"] as $key => $val) {
$name = bracket_escape($key, 1); // 1 - back
$return[$name] = array(
"field" => $name,
"privileges" => array("insert" => 1, "update" => 1),
"null" => 1,
"auto_increment" => ($key == $driver->primary),
);
}
return $return;
}
/** Print results of search in all tables
* @uses $_GET["where"][0]
* @uses $_POST["tables"]
* @return null
*/
function search_tables() {
global $adminer, $connection;
$_GET["where"][0]["op"] = "LIKE %%";
$_GET["where"][0]["val"] = $_POST["query"];
$found = false;
foreach (table_status('', true) as $table => $table_status) {
$name = $adminer->tableName($table_status);
if (isset($table_status["Engine"]) && $name != "" && (!$_POST["tables"] || in_array($table, $_POST["tables"]))) {
$result = $connection->query("SELECT" . limit("1 FROM " . table($table), " WHERE " . implode(" AND ", $adminer->selectSearchProcess(fields($table), array())), 1));
if (!$result || $result->fetch_row()) {
if (!$found) {
echo "\n";
$found = true;
}
echo "- " . ($result
? "$name\n"
: "$name: " . error() . "\n");
}
}
}
echo ($found ? "
" : "" . lang('No tables.')) . "\n";
}
/** Send headers for export
* @param string
* @param bool
* @return string extension
*/
function dump_headers($identifier, $multi_table = false) {
global $adminer;
$return = $adminer->dumpHeaders($identifier, $multi_table);
$output = $_POST["output"];
if ($output != "text") {
header("Content-Disposition: attachment; filename=" . $adminer->dumpFilename($identifier) . ".$return" . ($output != "file" && !preg_match('~[^0-9a-z]~', $output) ? ".$output" : ""));
}
session_write_close();
ob_flush();
flush();
return $return;
}
/** Print CSV row
* @param array
* @return null
*/
function dump_csv($row) {
foreach ($row as $key => $val) {
if (preg_match("~[\"\n,;\t]~", $val) || $val === "") {
$row[$key] = '"' . str_replace('"', '""', $val) . '"';
}
}
echo implode(($_POST["format"] == "csv" ? "," : ($_POST["format"] == "tsv" ? "\t" : ";")), $row) . "\r\n";
}
/** Apply SQL function
* @param string
* @param string escaped column identifier
* @return string
*/
function apply_sql_function($function, $column) {
return ($function ? ($function == "unixepoch" ? "DATETIME($column, '$function')" : ($function == "count distinct" ? "COUNT(DISTINCT " : strtoupper("$function(")) . "$column)") : $column);
}
/** Get path of the temporary directory
* @return string
*/
function get_temp_dir() {
$return = ini_get("upload_tmp_dir"); // session_save_path() may contain other storage path
if (!$return) {
if (function_exists('sys_get_temp_dir')) {
$return = sys_get_temp_dir();
} else {
$filename = @tempnam("", ""); // @ - temp directory can be disabled by open_basedir
if (!$filename) {
return false;
}
$return = dirname($filename);
unlink($filename);
}
}
return $return;
}
/** Read password from file adminer.key in temporary directory or create one
* @param bool
* @return string or false if the file can not be created
*/
function password_file($create) {
$filename = get_temp_dir() . "/adminer.key";
$return = @file_get_contents($filename); // @ - may not exist
if ($return || !$create) {
return $return;
}
$fp = @fopen($filename, "w"); // @ - can have insufficient rights //! is not atomic
if ($fp) {
chmod($filename, 0660);
$return = rand_string();
fwrite($fp, $return);
fclose($fp);
}
return $return;
}
/** Get a random string
* @return string 32 hexadecimal characters
*/
function rand_string() {
return md5(uniqid(mt_rand(), true));
}
/** Format value to use in select
* @param string
* @param string
* @param array
* @param int
* @return string HTML
*/
function select_value($val, $link, $field, $text_length) {
global $adminer, $HTTPS;
if (is_array($val)) {
$return = "";
foreach ($val as $k => $v) {
$return .= " | "
. ($val != array_values($val) ? "" . h($k) : "")
. " | " . select_value($v, $link, $field, $text_length)
;
}
return "";
}
if (!$link) {
$link = $adminer->selectLink($val, $field);
}
if ($link === null) {
if (is_mail($val)) {
$link = "mailto:$val";
}
if ($protocol = is_url($val)) {
$link = (($protocol == "http" && $HTTPS) || preg_match('~WebKit|Firefox~i', $_SERVER["HTTP_USER_AGENT"]) // WebKit supports noreferrer since 2009, Firefox since version 38
? $val // HTTP links from HTTPS pages don't receive Referer automatically
: "https://www.adminer.org/redirect/?url=" . urlencode($val) // intermediate page to hide Referer
);
}
}
$return = $adminer->editVal($val, $field);
if ($return !== null) {
if ($return === "") { // === - may be int
$return = " ";
} elseif (!is_utf8($return)) {
$return = "\0"; // htmlspecialchars of binary data returns an empty string
} elseif ($text_length != "" && is_shortable($field)) {
$return = shorten_utf8($return, max(0, +$text_length)); // usage of LEFT() would reduce traffic but complicate query - expected average speedup: .001 s VS .01 s on local network
} else {
$return = h($return);
}
}
return $adminer->selectVal($return, $link, $field, $val);
}
/** Check whether the string is e-mail address
* @param string
* @return bool
*/
function is_mail($email) {
$atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // characters of local-name
$domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component
$pattern = "$atom+(\\.$atom+)*@($domain?\\.)+$domain";
return is_string($email) && preg_match("(^$pattern(,\\s*$pattern)*\$)i", $email);
}
/** Check whether the string is URL address
* @param string
* @return string "http", "https" or ""
*/
function is_url($string) {
$domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component //! IDN
return (preg_match("~^(https?)://($domain?\\.)+$domain(:\\d+)?(/.*)?(\\?.*)?(#.*)?\$~i", $string, $match) ? strtolower($match[1]) : ""); //! restrict path, query and fragment characters
}
/** Check if field should be shortened
* @param array
* @return bool
*/
function is_shortable($field) {
return preg_match('~char|text|lob|geometry|point|linestring|polygon|string|bytea~', $field["type"]);
}
/** Get query to compute number of found rows
* @param string
* @param array
* @param bool
* @param array
* @return string
*/
function count_rows($table, $where, $is_group, $group) {
global $jush;
$query = " FROM " . table($table) . ($where ? " WHERE " . implode(" AND ", $where) : "");
return ($is_group && ($jush == "sql" || count($group) == 1)
? "SELECT COUNT(DISTINCT " . implode(", ", $group) . ")$query"
: "SELECT COUNT(*)" . ($is_group ? " FROM (SELECT 1$query$group_by) x" : $query)
);
}
/** Run query which can be killed by AJAX call after timing out
* @param string
* @return array of strings
*/
function slow_query($query) {
global $adminer, $token;
$db = $adminer->database();
$timeout = $adminer->queryTimeout();
if (support("kill") && is_object($connection2 = connect()) && ($db == "" || $connection2->select_db($db))) {
$kill = $connection2->result(connection_id()); // MySQL and MySQLi can use thread_id but it's not in PDO_MySQL
?>
clearTimeout(timeout);\n";
ob_flush();
flush();
}
return array_keys($return);
}
/** Generate BREACH resistant CSRF token
* @return string
*/
function get_token() {
$rand = rand(1, 1e6);
return ($rand ^ $_SESSION["token"]) . ":$rand";
}
/** Verify if supplied CSRF token is valid
* @return bool
*/
function verify_token() {
list($token, $rand) = explode(":", $_POST["token"]);
return ($rand ^ $_SESSION["token"]) == $token;
}
// used in compiled version
function lzw_decompress($binary) {
// convert binary string to codes
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$codes = array();
$rest = 0;
$rest_length = 0;
for ($i=0; $i < strlen($binary); $i++) {
$rest = ($rest << 8) + ord($binary[$i]);
$rest_length += 8;
if ($rest_length >= $bits) {
$rest_length -= $bits;
$codes[] = $rest >> $rest_length;
$rest &= (1 << $rest_length) - 1;
$dictionary_count++;
if ($dictionary_count >> $bits) {
$bits++;
}
}
}
// decompression
$dictionary = range("\0", "\xFF");
$return = "";
foreach ($codes as $i => $code) {
$element = $dictionary[$code];
if (!isset($element)) {
$element = $word . $word[0];
}
$return .= $element;
if ($i) {
$dictionary[] = $word . $element[0];
}
$word = $element;
}
return $return;
}
/** Return events to display help on mouse over
* @param string JS expression
* @param bool JS expression
* @return string
*/
function on_help($command, $side = 0) {
return " onmouseover='helpMouseover.call(this, event, " . h($command) . ", $side);' onmouseout='helpMouseout.call(this, event);'";
}
/** Print edit data form
* @param string
* @param array
* @param mixed
* @param bool
* @return null
*/
function edit_form($TABLE, $fields, $row, $update) {
global $adminer, $jush, $token, $error;
$table_name = $adminer->tableName(table_status1($TABLE, true));
page_header(
($update ? lang('Edit') : lang('Insert')),
$error,
array("select" => array($TABLE, $table_name)),
$table_name
);
if ($row === false) {
echo " " . lang('No rows.') . "\n";
}
?>
|