1
0
mirror of https://github.com/vrana/adminer.git synced 2025-09-05 20:02:54 +02:00

Compare commits

...

27 Commits

Author SHA1 Message Date
Peter Knut
0797cb6a10 Release 4.9.4 2024-10-09 22:09:31 +02:00
Peter Knut
dd122a1056 Clean up the code for PHP < 5.6 2024-10-09 22:00:13 +02:00
Peter Knut
96c0177422 Editor: Fix building links with array parameters
This solves a situation when enum data type has a foreign key to another table.
2024-10-09 09:19:37 +02:00
Peter Knut
7d6c7998d8 Editor: Fix array conversion to string (issue #3) 2024-10-08 22:59:57 +02:00
Peter Knut
3df88d4a24 Refactor opening adminer.sql[.gz] file 2024-10-07 23:58:10 +02:00
Peter Knut
2d4b73653b Refactor generating of private key and random strings
Generating of private key is atomic now.
More secure random strings on PHP 7+.
2024-10-07 23:38:33 +02:00
Peter Knut
a63fadd503 Refactor working with a locked file 2024-10-07 22:20:32 +02:00
Peter Knut
a494827dc5 Remove suppressing errors while reading local files with file_get_contents (issue #1) 2024-10-07 13:32:24 +02:00
Peter Knut
8ac486a57c Firefox: Fix opening a database to the new browser's tab with Ctrl+click 2024-10-06 00:44:02 +02:00
Peter Knut
bfcc6d8297 Better default value for object definition (*.*) while creating new database user 2024-10-04 10:03:00 +02:00
Peter Knut
29fd200ef5 Unify displaying of 'New item' action based on privileges 2024-10-04 00:44:39 +02:00
Peter Knut
b6058368d3 Fix the width of inline edit field 2024-10-03 23:33:34 +02:00
Peter Knut
fd38c4261a Bump version to 4.9.4-dev 2024-10-03 23:33:34 +02:00
Peter Knut
507f335371 Release 4.9.3 2024-10-02 17:07:09 +02:00
Peter Knut
ea314b8103 Hide invalid edit form if table record is not found 2024-10-02 09:35:59 +02:00
Peter Knut
e250470768 PostgreSQL: Fix editing record that contains a field with GENERATED ALWAYS default value
Fields with GENERATED ALWAYS default values are also disabled.

Thanks to PurpleTape (https://github.com/adminerevo/adminerevo/issues/201).
2024-10-02 00:29:24 +02:00
Peter Knut
2fa42d50eb Fix using undefined Min_DB::info property 2024-10-01 23:37:07 +02:00
Peter Knut
a366b7af09 MySQL: Fix editing user's proxy privilege, refactoring
- Uncheck all other priviledges if 'All privileges' is checked.
- Refactor related functions.
2024-10-01 23:22:26 +02:00
Peter Knut
b039a39e4d Bigger font size for code blocks 2024-10-01 09:07:21 +02:00
SeaEagle
08e48c8641 MySQL: Fix where clause for JSON column
Issue: https://github.com/adminerevo/adminerevo/issues/175
2024-10-01 09:06:20 +02:00
Peter Knut
78c2041cfd Fix background color of <pre> used as edit field 2024-10-01 00:33:47 +02:00
Peter Knut
5d7c5fa268 Do not include unchanged PARTITION BY definition into ALTER TABLE query 2024-09-22 00:33:55 +02:00
Peter Knut
8f1db4cf6f Add helper methods for dumping variable to the output 2024-09-21 22:34:38 +02:00
Peter Knut
9daa88acca MariaDB: Fix comparing CURRENT_TIMESTAMP definition while altering a table 2024-09-21 22:20:08 +02:00
Peter Knut
aa519b78ca MySQL, PostgreSQL: Fix queries splitting and string constants
Thanks to alxivnov (https://github.com/vrana/adminer/pull/490).
2024-09-21 09:28:50 +02:00
Michael Graß
aee800efed Do not limit unlimited memory, fix number conversion warning 2024-09-20 22:28:46 +02:00
Peter Knut
06d0f957d5 Bump version to 4.9.3-dev 2024-09-18 10:57:48 +02:00
26 changed files with 526 additions and 237 deletions

View File

@@ -82,21 +82,40 @@ if ($_POST && !process_fields($row["fields"]) && !$error) {
} }
$partitioning = ""; $partitioning = "";
if ($partition_by[$row["partition_by"]]) { if (support("partitioning")) {
$partitions = array(); if (isset($partition_by[$row["partition_by"]])) {
if ($row["partition_by"] == 'RANGE' || $row["partition_by"] == 'LIST') { $params = array_filter($row, function ($key) {
foreach (array_filter($row["partition_names"]) as $key => $val) { return preg_match('~^partition~', $key);
$value = $row["partition_values"][$key]; }, ARRAY_FILTER_USE_KEY);
$partitions[] = "\n PARTITION " . idf_escape($val) . " VALUES " . ($row["partition_by"] == 'RANGE' ? "LESS THAN" : "IN") . ($value != "" ? " ($value)" : " MAXVALUE"); //! SQL injection
foreach ($params["partition_names"] as $key => $name) {
if ($name === "") {
unset($params["partition_names"][$key]);
unset($params["partition_values"][$key]);
} }
} }
$partitioning .= "\nPARTITION BY $row[partition_by]($row[partition])" . ($partitions // $row["partition"] can be expression, not only column
? " (" . implode(",", $partitions) . "\n)" if ($params != get_partitions_info($TABLE)) {
: ($row["partitions"] ? " PARTITIONS " . (+$row["partitions"]) : "") $partitions = [];
); if ($params["partition_by"] == 'RANGE' || $params["partition_by"] == 'LIST') {
} elseif (support("partitioning") && preg_match("~partitioned~", $table_status["Create_options"])) { foreach ($params["partition_names"] as $key => $name) {
$value = $params["partition_values"][$key];
$partitions[] = "\n PARTITION " . idf_escape($name) . " VALUES " . ($params["partition_by"] == 'RANGE' ? "LESS THAN" : "IN") . ($value != "" ? " ($value)" : " MAXVALUE"); //! SQL injection
}
}
// $params["partition"] can be expression, not only column
$partitioning .= "\nPARTITION BY {$params["partition_by"]}({$params["partition"]})";
if ($partitions) {
$partitioning .= " (" . implode(",", $partitions) . "\n)";
} elseif ($params["partitions"]) {
$partitioning .= " PARTITIONS " . (int)$params["partitions"];
}
}
} elseif (preg_match("~partitioned~", $table_status["Create_options"])) {
$partitioning .= "\nREMOVE PARTITIONING"; $partitioning .= "\nREMOVE PARTITIONING";
} }
}
$message = lang('Table has been altered.'); $message = lang('Table has been altered.');
if ($TABLE == "") { if ($TABLE == "") {
@@ -141,13 +160,9 @@ if (!$_POST) {
} }
if (support("partitioning")) { if (support("partitioning")) {
$from = "FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = " . q(DB) . " AND TABLE_NAME = " . q($TABLE); $row += get_partitions_info($TABLE);
$result = $connection->query("SELECT PARTITION_METHOD, PARTITION_ORDINAL_POSITION, PARTITION_EXPRESSION $from ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1"); $row["partition_names"][] = "";
list($row["partition_by"], $row["partitions"], $row["partition"]) = $result->fetch_row(); $row["partition_values"][] = "";
$partitions = get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $from AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");
$partitions[""] = "";
$row["partition_names"] = array_keys($partitions);
$row["partition_values"] = array_values($partitions);
} }
} }
} }

View File

@@ -432,7 +432,7 @@ WHERE OBJECT_NAME(i.object_id) = " . q($table)
function error() { function error() {
global $connection; global $connection;
return nl_br(h(preg_replace('~^(\[[^]]*])+~m', '', $connection->error))); return nl2br(h(preg_replace('~^(\[[^]]*])+~m', '', $connection->error)));
} }
function create_database($db, $collation) { function create_database($db, $collation) {
@@ -637,6 +637,10 @@ WHERE sys1.xtype = 'TR' AND sys2.name = " . q($table)
return false; return false;
} }
function is_c_style_escapes() {
return true;
}
function show_status() { function show_status() {
return array(); return array();
} }

View File

@@ -14,7 +14,7 @@ if (!defined("DRIVER")) {
function connect($server = "", $username = "", $password = "", $database = null, $port = null, $socket = null) { function connect($server = "", $username = "", $password = "", $database = null, $port = null, $socket = null) {
global $adminer; global $adminer;
mysqli_report(MYSQLI_REPORT_OFF); // stays between requests, not required since PHP 5.3.4 mysqli_report(MYSQLI_REPORT_OFF);
list($host, $port) = explode(":", $server, 2); // part after : is used for port or socket list($host, $port) = explode(":", $server, 2); // part after : is used for port or socket
$ssl = $adminer->connectSsl(); $ssl = $adminer->connectSsl();
@@ -34,7 +34,7 @@ if (!defined("DRIVER")) {
$database, $database,
(is_numeric($port) ? $port : ini_get("mysqli.default_port")), (is_numeric($port) ? $port : ini_get("mysqli.default_port")),
(!is_numeric($port) ? $port : $socket), (!is_numeric($port) ? $port : $socket),
($ssl ? 64 : 0) // 64 - MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT (not available before PHP 5.6.16) ($ssl ? MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT : 0)
); );
$this->options(MYSQLI_OPT_LOCAL_INFILE, false); $this->options(MYSQLI_OPT_LOCAL_INFILE, false);
return $return; return $return;
@@ -262,7 +262,7 @@ if (!defined("DRIVER")) {
} }
function set_charset($charset) { function set_charset($charset) {
$this->query("SET NAMES $charset"); // charset in DSN is ignored before PHP 5.3.6 $this->query("SET NAMES $charset");
} }
function select_db($database) { function select_db($database) {
@@ -375,7 +375,7 @@ if (!defined("DRIVER")) {
$connection = new Min_DB; $connection = new Min_DB;
$credentials = $adminer->credentials(); $credentials = $adminer->credentials();
if ($connection->connect($credentials[0], $credentials[1], $credentials[2])) { if ($connection->connect($credentials[0], $credentials[1], $credentials[2])) {
$connection->set_charset(charset($connection)); // available in MySQLi since PHP 5.0.5 $connection->set_charset(charset($connection));
$connection->query("SET sql_quote_show_create = 1, autocommit = 1"); $connection->query("SET sql_quote_show_create = 1, autocommit = 1");
if (min_version('5.7.8', 10.2, $connection)) { if (min_version('5.7.8', 10.2, $connection)) {
$structured_types[lang('Strings')][] = "json"; $structured_types[lang('Strings')][] = "json";
@@ -1074,6 +1074,16 @@ if (!defined("DRIVER")) {
return $strictMode; return $strictMode;
} }
function is_c_style_escapes() {
static $c_style = null;
if ($c_style === null) {
$c_style = strpos(get_key_vals("SHOW VARIABLES LIKE 'sql_mode'")["sql_mode"], 'NO_BACKSLASH_ESCAPES') === false;
}
return $c_style;
}
/** Get process list /** Get process list
* @return array ($row) * @return array ($row)
*/ */

View File

@@ -493,6 +493,10 @@ AND c_src.TABLE_NAME = " . q($table);
return false; return false;
} }
function is_c_style_escapes() {
return true;
}
function process_list() { function process_list() {
return get_rows('SELECT sess.process AS "process", sess.username AS "user", sess.schemaname AS "schema", sess.status AS "status", sess.wait_class AS "wait_class", sess.seconds_in_wait AS "seconds_in_wait", sql.sql_text AS "sql_text", sess.machine AS "machine", sess.port AS "port" return get_rows('SELECT sess.process AS "process", sess.username AS "user", sess.schemaname AS "schema", sess.status AS "status", sess.wait_class AS "wait_class", sess.seconds_in_wait AS "seconds_in_wait", sql.sql_text AS "sql_text", sess.machine AS "machine", sess.port AS "port"
FROM v$session sess LEFT OUTER JOIN v$sql sql FROM v$session sess LEFT OUTER JOIN v$sql sql

View File

@@ -488,7 +488,7 @@ ORDER BY connamespace, conname") as $row) {
if (preg_match('~^(.*\n)?([^\n]*)\n( *)\^(\n.*)?$~s', $return, $match)) { if (preg_match('~^(.*\n)?([^\n]*)\n( *)\^(\n.*)?$~s', $return, $match)) {
$return = $match[1] . preg_replace('~((?:[^&]|&[^;]*;){' . strlen($match[3]) . '})(.*)~', '\1<b>\2</b>', $match[2]) . $match[4]; $return = $match[1] . preg_replace('~((?:[^&]|&[^;]*;){' . strlen($match[3]) . '})(.*)~', '\1<b>\2</b>', $match[2]) . $match[4];
} }
return nl_br($return); return nl2br($return);
} }
function create_database($db, $collation) { function create_database($db, $collation) {
@@ -885,6 +885,16 @@ AND typelem = 0"
return false; return false;
} }
function is_c_style_escapes() {
static $c_style = null;
if ($c_style === null) {
$c_style = get_vals("SHOW standard_conforming_strings")[0] == "off";
}
return $c_style;
}
function process_list() { function process_list() {
return get_rows("SELECT * FROM pg_stat_activity ORDER BY " . (min_version(9.2) ? "pid" : "procpid")); return get_rows("SELECT * FROM pg_stat_activity ORDER BY " . (min_version(9.2) ? "pid" : "procpid"));
} }
@@ -949,6 +959,7 @@ AND typelem = 0"
"char|text" => "||", "char|text" => "||",
) )
), ),
'c_style_escapes' => true,
); );
} }
} }

View File

@@ -771,6 +771,10 @@ if (isset($_GET["sqlite"]) || isset($_GET["sqlite2"])) {
return false; return false;
} }
function is_c_style_escapes() {
return true;
}
function show_status() { function show_status() {
$return = array(); $return = array();
foreach (get_vals("PRAGMA compile_options") as $option) { foreach (get_vals("PRAGMA compile_options") as $option) {

View File

@@ -25,12 +25,16 @@ class Adminer {
function connectSsl() { function connectSsl() {
} }
/** Get key used for permanent login /**
* @param bool * Gets a private key used for permanent login.
* @return string cryptic string which gets combined with password or false in case of an error *
* @param bool $create
*
* @return string|false Cryptic string which gets combined with password or false in case of an error.
* @throws \Random\RandomException
*/ */
function permanentLogin($create = false) { function permanentLogin($create = false) {
return password_file($create); return get_private_key($create);
} }
/** Return key used to group brute force attacks; behind a reverse proxy, you want to return the last part of X-Forwarded-For /** Return key used to group brute force attacks; behind a reverse proxy, you want to return the last part of X-Forwarded-For
@@ -937,8 +941,10 @@ class Adminer {
return $ext; return $ext;
} }
/** Set the path of the file for webserver load /**
* @return string path of the sql dump file * Gets the path of the file for webserver load.
*
* @return string Path of the sql import file.
*/ */
function importServerPath() { function importServerPath() {
return "adminer.sql"; return "adminer.sql";

View File

@@ -1,4 +1,5 @@
<?php <?php
$connection = ''; $connection = '';
$has_token = $_SESSION["token"]; $has_token = $_SESSION["token"];
@@ -82,11 +83,11 @@ function build_http_url($server, $username, $password, $defaultServer, $defaultP
function add_invalid_login() { function add_invalid_login() {
global $adminer; global $adminer;
$fp = file_open_lock(get_temp_dir() . "/adminer.invalid"); $file = open_file_with_lock(get_temp_dir() . "/adminer.invalid");
if (!$fp) { if (!$file) {
return; return;
} }
$invalids = unserialize(stream_get_contents($fp)); $invalids = unserialize(stream_get_contents($file));
$time = time(); $time = time();
if ($invalids) { if ($invalids) {
foreach ($invalids as $ip => $val) { foreach ($invalids as $ip => $val) {
@@ -100,13 +101,16 @@ function add_invalid_login() {
$invalid = array($time + 30*60, 0); // active for 30 minutes $invalid = array($time + 30*60, 0); // active for 30 minutes
} }
$invalid[1]++; $invalid[1]++;
file_write_unlock($fp, serialize($invalids)); write_and_unlock_file($file, serialize($invalids));
} }
function check_invalid_login() { function check_invalid_login() {
global $adminer; global $adminer;
$invalids = unserialize(@file_get_contents(get_temp_dir() . "/adminer.invalid")); // @ - may not exist
$invalid = ($invalids ? $invalids[$adminer->bruteForceKey()] : array()); $filename = get_temp_dir() . "/adminer.invalid";
$invalids = file_exists($filename) ? unserialize(file_get_contents($filename)) : [];
$invalid = ($invalids ? $invalids[$adminer->bruteForceKey()] : []);
$next_attempt = ($invalid[1] > 29 ? $invalid[0] - time() : 0); // allow 30 invalid attempts $next_attempt = ($invalid[1] > 29 ? $invalid[0] - time() : 0); // allow 30 invalid attempts
if ($next_attempt > 0) { //! do the same with permanent login if ($next_attempt > 0) { //! do the same with permanent login
auth_error(lang('Too many unsuccessful logins, try again in %d minute(s).', ceil($next_attempt / 60))); auth_error(lang('Too many unsuccessful logins, try again in %d minute(s).', ceil($next_attempt / 60)));
@@ -168,9 +172,10 @@ function unset_permanent() {
} }
/** Renders an error message and a login form /** Renders an error message and a login form
* @param string plain text * @param string plain text
* @return null exits * @return null exits
*/ * @throws \Random\RandomException
*/
function auth_error($error) { function auth_error($error) {
global $adminer, $has_token; global $adminer, $has_token;
$session_name = session_name(); $session_name = session_name();
@@ -195,7 +200,7 @@ function auth_error($error) {
$error = lang('Session support must be enabled.'); $error = lang('Session support must be enabled.');
} }
$params = session_get_cookie_params(); $params = session_get_cookie_params();
cookie("adminer_key", ($_COOKIE["adminer_key"] ? $_COOKIE["adminer_key"] : rand_string()), $params["lifetime"]); cookie("adminer_key", ($_COOKIE["adminer_key"] ?: get_random_string()), $params["lifetime"]);
page_header(lang('Login'), $error, null); page_header(lang('Login'), $error, null);
echo "<form action='' method='post'>\n"; echo "<form action='' method='post'>\n";
echo "<div>"; echo "<div>";

View File

@@ -6,6 +6,7 @@ function adminer_errors($errno, $errstr) {
error_reporting(6135); // errors and warnings error_reporting(6135); // errors and warnings
set_error_handler('adminer_errors', E_WARNING); set_error_handler('adminer_errors', E_WARNING);
include "../adminer/include/debug.inc.php";
include "../adminer/include/coverage.inc.php"; include "../adminer/include/coverage.inc.php";
// disable filter.default // disable filter.default
@@ -31,9 +32,9 @@ if (isset($_GET["file"])) {
} }
if ($_GET["script"] == "version") { if ($_GET["script"] == "version") {
$fp = file_open_lock(get_temp_dir() . "/adminer.version"); $file = open_file_with_lock(get_temp_dir() . "/adminer.version");
if ($fp) { if ($file) {
file_write_unlock($fp, serialize(array("signature" => $_POST["signature"], "version" => $_POST["version"]))); write_and_unlock_file($file, serialize(["signature" => $_POST["signature"], "version" => $_POST["version"]]));
} }
exit; exit;
} }

View File

@@ -0,0 +1,14 @@
<?php
function dump($value)
{
echo "<pre>";
var_export($value);
echo "</pre>\n";
}
function dumpe($value)
{
dump($value);
exit;
}

View File

@@ -142,14 +142,20 @@ function csp() {
); );
} }
/** Get a CSP nonce /**
* @return string Base64 value * Gets a CSP nonce.
*/ *
function get_nonce() { * @return string Base64 value.
* @throws \Random\RandomException
*/
function get_nonce()
{
static $nonce; static $nonce;
if (!$nonce) { if (!$nonce) {
$nonce = base64_encode(rand_string()); $nonce = base64_encode(get_random_string(true));
} }
return $nonce; return $nonce;
} }

View File

@@ -221,12 +221,17 @@ function process_type($field, $collate = "COLLATE") {
* @return array array("field", "type", "NULL", "DEFAULT", "ON UPDATE", "COMMENT", "AUTO_INCREMENT") * @return array array("field", "type", "NULL", "DEFAULT", "ON UPDATE", "COMMENT", "AUTO_INCREMENT")
*/ */
function process_field($field, $type_field) { function process_field($field, $type_field) {
// MariaDB exports CURRENT_TIMESTAMP as a function.
if ($field["on_update"]) {
$field["on_update"] = str_ireplace("current_timestamp()", "CURRENT_TIMESTAMP", $field["on_update"]);
}
return array( return array(
idf_escape(trim($field["field"])), idf_escape(trim($field["field"])),
process_type($type_field), process_type($type_field),
($field["null"] ? " NULL" : " NOT NULL"), // NULL for timestamp ($field["null"] ? " NULL" : " NOT NULL"), // NULL for timestamp
default_value($field), default_value($field),
(preg_match('~timestamp|datetime~', $field["type"]) && $field["on_update"] ? " ON UPDATE $field[on_update]" : ""), (preg_match('~timestamp|datetime~', $field["type"]) && $field["on_update"] ? " ON UPDATE " . $field["on_update"] : ""),
(support("comment") && $field["comment"] != "" ? " COMMENT " . q($field["comment"]) : ""), (support("comment") && $field["comment"] != "" ? " COMMENT " . q($field["comment"]) : ""),
($field["auto_increment"] ? auto_increment() : null), ($field["auto_increment"] ? auto_increment() : null),
); );
@@ -240,10 +245,13 @@ function default_value($field) {
$default = $field["default"]; $default = $field["default"];
if ($default === null) return ""; if ($default === null) return "";
if (preg_match('~^GENERATED ~i', $default)) { if (stripos($default, "GENERATED ") === 0) {
return " $default"; return " $default";
} }
// MariaDB exports CURRENT_TIMESTAMP as a function.
$default = str_ireplace("current_timestamp()", "CURRENT_TIMESTAMP", $default);
$quote = preg_match('~char|binary|text|enum|set~', $field["type"]) || preg_match('~^(?![a-z])~i', $default); $quote = preg_match('~char|binary|text|enum|set~', $field["type"]) || preg_match('~^(?![a-z])~i', $default);
return " DEFAULT " . ($quote ? q($default) : $default); return " DEFAULT " . ($quote ? q($default) : $default);
@@ -376,25 +384,43 @@ function normalize_enum($match) {
return "'" . str_replace("'", "''", addcslashes(stripcslashes(str_replace($match[0][0] . $match[0][0], $match[0][0], substr($match[0], 1, -1))), '\\')) . "'"; return "'" . str_replace("'", "''", addcslashes(stripcslashes(str_replace($match[0][0] . $match[0][0], $match[0][0], substr($match[0], 1, -1))), '\\')) . "'";
} }
/** Issue grant or revoke commands /**
* @param string GRANT or REVOKE * Issue grant or revoke commands.
* @param array *
* @param string * @param bool $grant
* @param string * @param array $privileges
* @return bool * @param string $columns
*/ * @param string $on
function grant($grant, $privileges, $columns, $on) { * @param string $user
if (!$privileges) { *
return true; * @return bool
*/
function grant($grant, array $privileges, $columns, $on, $user) {
if (!$privileges) return true;
if ($privileges == ["ALL PRIVILEGES", "GRANT OPTION"]) {
if ($grant) {
return (bool) queries("GRANT ALL PRIVILEGES ON $on TO $user WITH GRANT OPTION");
} else {
return queries("REVOKE ALL PRIVILEGES ON $on FROM $user") &&
queries("REVOKE GRANT OPTION ON $on FROM $user");
} }
if ($privileges == array("ALL PRIVILEGES", "GRANT OPTION")) { }
// can't be granted or revoked together
return ($grant == "GRANT" if ($privileges == ["GRANT OPTION", "PROXY"]) {
? queries("$grant ALL PRIVILEGES$on WITH GRANT OPTION") if ($grant) {
: queries("$grant ALL PRIVILEGES$on") && queries("$grant GRANT OPTION$on") return (bool) queries("GRANT PROXY ON $on TO $user WITH GRANT OPTION");
} else {
return (bool) queries("REVOKE PROXY ON $on FROM $user");
}
}
return (bool) queries(
($grant ? "GRANT " : "REVOKE ") .
preg_replace('~(GRANT OPTION)\([^)]*\)~', '$1', implode("$columns, ", $privileges) . $columns) .
" ON $on " .
($grant ? "TO " : "FROM ") . $user
); );
}
return queries("$grant " . preg_replace('~(GRANT OPTION)\([^)]*\)~', '\1', implode("$columns, ", $privileges) . $columns) . $on);
} }
/** Drop old object and create a new one /** Drop old object and create a new one
@@ -523,9 +549,9 @@ function tar_file($filename, $tmp_file) {
function ini_bytes($ini) { function ini_bytes($ini) {
$val = ini_get($ini); $val = ini_get($ini);
switch (strtolower(substr($val, -1))) { switch (strtolower(substr($val, -1))) {
case 'g': $val *= 1024; // no break case 'g': $val = (int)$val * 1024; // no break
case 'm': $val *= 1024; // no break case 'm': $val = (int)$val * 1024; // no break
case 'k': $val *= 1024; case 'k': $val = (int)$val * 1024;
} }
return $val; return $val;
} }

View File

@@ -1,4 +1,5 @@
<?php <?php
/** Get database connection /** Get database connection
* @return Min_DB * @return Min_DB
*/ */
@@ -157,14 +158,6 @@ function h($string) {
return str_replace("\0", "&#0;", htmlspecialchars($string, ENT_QUOTES, 'utf-8')); return str_replace("\0", "&#0;", htmlspecialchars($string, ENT_QUOTES, 'utf-8'));
} }
/** Convert \n to <br>
* @param string
* @return string
*/
function nl_br($string) {
return str_replace("\n", "<br>", $string); // nl2br() uses XHTML before PHP 5.3
}
/** Generate HTML checkbox /** Generate HTML checkbox
* @param string * @param string
* @param string * @param string
@@ -477,24 +470,36 @@ function escape_key($key) {
*/ */
function where($where, $fields = array()) { function where($where, $fields = array()) {
global $connection, $jush; global $connection, $jush;
$return = array();
$conditions = [];
foreach ((array) $where["where"] as $key => $val) { foreach ((array) $where["where"] as $key => $val) {
$key = bracket_escape($key, 1); // 1 - back $key = bracket_escape($key, 1); // 1 - back
$column = escape_key($key); $column = escape_key($key);
$return[] = $column
. ($jush == "sql" && is_numeric($val) && preg_match('~\.~', $val) ? " LIKE " . q($val) // LIKE because of floats but slow with ints if ($jush == "sql" && $fields[$key]["type"] == "json") {
: ($jush == "mssql" ? " LIKE " . q(preg_replace('~[_%[]~', '[\0]', $val)) // LIKE because of text $conditions[] = "$column = CAST(" . q($val) . " AS JSON)";
: " = " . unconvert_field($fields[$key], q($val)) } elseif ($jush == "sql" && is_numeric($val) && strpos($val, ".") !== false) {
)) // LIKE because of floats but slow with ints.
; //! enum and set $conditions[] = "$column LIKE " . q($val);
if ($jush == "sql" && preg_match('~char|text~', $fields[$key]["type"]) && preg_match("~[^ -@]~", $val)) { // not just [a-z] to catch non-ASCII characters } elseif ($jush == "mssql") {
$return[] = "$column = " . q($val) . " COLLATE " . charset($connection) . "_bin"; // LIKE because of text.
$conditions[] = "$column LIKE " . q(preg_replace('~[_%[]~', '[\0]', $val));
} else {
$conditions[] = "$column = " . unconvert_field($fields[$key], q($val));
}
// Not just [a-z] to catch non-ASCII characters.
if ($jush == "sql" && preg_match('~char|text~', $fields[$key]["type"]) && preg_match("~[^ -@]~", $val)) {
$conditions[] = "$column = " . q($val) . " COLLATE " . charset($connection) . "_bin";
} }
} }
foreach ((array) $where["null"] as $key) { foreach ((array) $where["null"] as $key) {
$return[] = escape_key($key) . " IS NULL"; $conditions[] = escape_key($key) . " IS NULL";
} }
return implode(" AND ", $return);
return implode(" AND ", $conditions);
} }
/** Create SQL condition from query string /** Create SQL condition from query string
@@ -935,14 +940,15 @@ function enum_input($type, $attrs, $field, $value, $empty = null) {
*/ */
function input($field, $value, $function) { function input($field, $value, $function) {
global $types, $adminer, $jush; global $types, $adminer, $jush;
$name = h(bracket_escape($field["field"])); $name = h(bracket_escape($field["field"]));
echo "<td class='function'>";
if (is_array($value) && !$function) { if (is_array($value) && !$function) {
$args = array($value); $args = array($value);
if (version_compare(PHP_VERSION, 5.4) >= 0) { if (version_compare(PHP_VERSION, 5.4) >= 0) {
$args[] = JSON_PRETTY_PRINT; $args[] = JSON_PRETTY_PRINT;
} }
$value = call_user_func_array('json_encode', $args); //! requires PHP 5.2 $value = call_user_func_array('json_encode', $args);
$function = "json"; $function = "json";
} }
$reset = ($jush == "mssql" && $field["auto_increment"]); $reset = ($jush == "mssql" && $field["auto_increment"]);
@@ -950,13 +956,18 @@ function input($field, $value, $function) {
$function = null; $function = null;
} }
$functions = (isset($_GET["select"]) || $reset ? array("orig" => lang('original')) : array()) + $adminer->editFunctions($field); $functions = (isset($_GET["select"]) || $reset ? array("orig" => lang('original')) : array()) + $adminer->editFunctions($field);
$attrs = " name='fields[$name]'";
$disabled = stripos($field["default"], "GENERATED ALWAYS AS ") === 0 ? " disabled=''" : "";
$attrs = " name='fields[$name]' $disabled";
echo "<td class='function'>";
if ($field["type"] == "enum") { if ($field["type"] == "enum") {
echo h($functions[""]) . "<td>" . $adminer->editInput($_GET["edit"], $field, $attrs, $value); echo h($functions[""]) . "<td>" . $adminer->editInput($_GET["edit"], $field, $attrs, $value);
} else { } else {
$has_function = (in_array($function, $functions) || isset($functions[$function])); $has_function = (in_array($function, $functions) || isset($functions[$function]));
echo (count($functions) > 1 echo (count($functions) > 1
? "<select name='function[$name]'>" . optionlist($functions, $function === null || $has_function ? $function : "") . "</select>" ? "<select name='function[$name]' $disabled>" . optionlist($functions, $function === null || $has_function ? $function : "") . "</select>"
. on_help("getTarget(event).value.replace(/^SQL\$/, '')", 1) . on_help("getTarget(event).value.replace(/^SQL\$/, '')", 1)
. script("qsl('select').onchange = functionChange;", "") . script("qsl('select').onchange = functionChange;", "")
: h(reset($functions)) : h(reset($functions))
@@ -1021,6 +1032,11 @@ function input($field, $value, $function) {
*/ */
function process_input($field) { function process_input($field) {
global $adminer, $driver; global $adminer, $driver;
if (stripos($field["default"], "GENERATED ALWAYS AS ") === 0) {
return null;
}
$idf = bracket_escape($field["field"]); $idf = bracket_escape($field["field"]);
$function = $_POST["function"][$idf]; $function = $_POST["function"][$idf];
$value = $_POST["fields"][$idf]; $value = $_POST["fields"][$idf];
@@ -1111,6 +1127,27 @@ function search_tables() {
echo ($sep ? "<p class='message'>" . lang('No tables.') : "</ul>") . "\n"; echo ($sep ? "<p class='message'>" . lang('No tables.') : "</ul>") . "\n";
} }
/**
* @param string $table
* @return array
*/
function get_partitions_info($table) {
global $connection;
$from = "FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = " . q(DB) . " AND TABLE_NAME = " . q($table);
$result = $connection->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $from ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");
$info = [];
list($info["partition_by"], $info["partition"], $info["partitions"]) = $result->fetch_row();
$partitions = get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $from AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");
$info["partition_names"] = array_keys($partitions);
$info["partition_values"] = array_values($partitions);
return $info;
}
/** Send headers for export /** Send headers for export
* @param string * @param string
* @param bool * @param bool
@@ -1171,60 +1208,98 @@ function get_temp_dir() {
return $return; return $return;
} }
/** Open and exclusively lock a file /**
* @param string * Opens and exclusively lock a file.
* @return resource or null for error *
*/ * @param string $filename
function file_open_lock($filename) { * @return resource|null
$fp = @fopen($filename, "r+"); // @ - may not exist */
if (!$fp) { // c+ is available since PHP 5.2.6 function open_file_with_lock($filename)
$fp = @fopen($filename, "w"); // @ - may not be writable {
if (!$fp) { $file = fopen($filename, "c+");
return; if (!$file) {
return null;
} }
chmod($filename, 0660); chmod($filename, 0660);
if (!flock($file, LOCK_EX)) {
fclose($file);
return null;
} }
flock($fp, LOCK_EX);
return $fp; return $file;
} }
/** Write and unlock a file /**
* @param resource * Writes and unlocks a file.
* @param string *
*/ * @param resource $file
function file_write_unlock($fp, $data) { * @param string $data
rewind($fp); */
fwrite($fp, $data); function write_and_unlock_file($file, $data)
ftruncate($fp, strlen($data)); {
flock($fp, LOCK_UN); rewind($file);
fclose($fp); fwrite($file, $data);
ftruncate($file, strlen($data));
unlock_file($file);
} }
/** Read password from file adminer.key in temporary directory or create one /**
* @param bool * Unlocks and closes the file.
* @return string or false if the file can not be created *
*/ * @param resource $file
function password_file($create) { */
function unlock_file($file)
{
flock($file, LOCK_UN);
fclose($file);
}
/**
* Reads password from file adminer.key in temporary directory or create one.
*
* @param $create bool
* @return string|false Returns false if the file can not be created.
* @throws \Random\RandomException
*/
function get_private_key($create)
{
$filename = get_temp_dir() . "/adminer.key"; $filename = get_temp_dir() . "/adminer.key";
$return = @file_get_contents($filename); // @ - may not exist
if ($return || !$create) { if (!$create && !file_exists($filename)) {
return $return; return false;
} }
$fp = @fopen($filename, "w"); // @ - can have insufficient rights //! is not atomic
if ($fp) { $file = open_file_with_lock($filename);
chmod($filename, 0660); if (!$file) {
$return = rand_string(); return false;
fwrite($fp, $return);
fclose($fp);
} }
return $return;
$key = stream_get_contents($file);
if (!$key) {
$key = get_random_string();
write_and_unlock_file($file, $key);
} else {
unlock_file($file);
}
return $key;
} }
/** Get a random string /**
* @return string 32 hexadecimal characters * Returns a random 32 characters long string.
*/ *
function rand_string() { * @param $binary bool
return md5(uniqid(mt_rand(), true)); * @return string
* @throws \Random\RandomException
*/
function get_random_string($binary = false)
{
$bytes = function_exists('random_bytes') ? random_bytes(32) : uniqid(mt_rand(), true);
return $binary ? $bytes : md5($bytes);
} }
/** Format value to use in select /** Format value to use in select
@@ -1441,6 +1516,7 @@ function edit_form($table, $fields, $row, $update) {
$adminer->editRowPrint($table, $fields, $row, $update); $adminer->editRowPrint($table, $fields, $row, $update);
if ($row === false) { if ($row === false) {
echo "<p class='error'>" . lang('No rows.') . "\n"; echo "<p class='error'>" . lang('No rows.') . "\n";
return;
} }
?> ?>
<form action="" method="post" enctype="multipart/form-data" id="form"> <form action="" method="post" enctype="multipart/form-data" id="form">

View File

@@ -1,2 +1,2 @@
<?php <?php
$VERSION = "4.9.2"; $VERSION = "4.9.4";

View File

@@ -232,14 +232,16 @@ if (is_ajax()) {
$set = null; $set = null;
if (isset($rights["insert"]) || !support("table")) { if (isset($rights["insert"]) || !support("table")) {
$set = ""; $params = [];
foreach ((array) $_GET["where"] as $val) { foreach ((array) $_GET["where"] as $val) {
if ($foreign_keys[$val["col"]] && count($foreign_keys[$val["col"]]) == 1 && ($val["op"] == "=" if (isset($foreign_keys[$val["col"]]) && count($foreign_keys[$val["col"]]) == 1
|| (!$val["op"] && !preg_match('~[_%]~', $val["val"])) // LIKE in Editor && ($val["op"] == "=" || (!$val["op"] && (is_array($val["val"]) || !preg_match('~[_%]~', $val["val"]))) // LIKE in Editor
)) { )) {
$set .= "&set" . urlencode("[" . bracket_escape($val["col"]) . "]") . "=" . urlencode($val["val"]); $params["set" . "[" . bracket_escape($val["col"]) . "]"] = $val["val"];
} }
} }
$set = $params ? "&" . http_build_query($params) : "";
} }
$adminer->selectLinks($table_status, $set); $adminer->selectLinks($table_status, $set);

View File

@@ -21,19 +21,25 @@ if (!$error && $_POST) {
if (!isset($_GET["import"])) { if (!isset($_GET["import"])) {
$query = $_POST["query"]; $query = $_POST["query"];
} elseif ($_POST["webfile"]) { } elseif ($_POST["webfile"]) {
$sql_file_path = $adminer->importServerPath(); $import_file_path = $adminer->importServerPath();
$fp = @fopen((file_exists($sql_file_path) if (!$import_file_path) {
? $sql_file_path $fp = false;
: "compress.zlib://$sql_file_path.gz" } elseif (file_exists($import_file_path)) {
), "rb"); $fp = fopen($import_file_path, "rb");
$query = ($fp ? fread($fp, 1e6) : false); } elseif (file_exists("$import_file_path.gz")) {
$fp = fopen("compress.zlib://$import_file_path.gz", "rb");
} else {
$fp = false;
}
$query = $fp ? fread($fp, 1e6) : false;
} else { } else {
$query = get_file("sql_file", true); $query = get_file("sql_file", true);
} }
if (is_string($query)) { // get_file() returns error as number, fread() as false if (is_string($query)) { // get_file() returns error as number, fread() as false
if (function_exists('memory_get_usage')) { if (function_exists('memory_get_usage') && ($memory_limit = ini_bytes("memory_limit")) != "-1") {
@ini_set("memory_limit", max(ini_bytes("memory_limit"), 2 * strlen($query) + memory_get_usage() + 8e6)); // @ - may be disabled, 2 - substr and trim, 8e6 - other variables @ini_set("memory_limit", max($memory_limit, 2 * strlen($query) + memory_get_usage() + 8e6)); // @ - may be disabled, 2 - substr and trim, 8e6 - other variables
} }
if ($query != "" && strlen($query) < 1e6) { // don't add big queries if ($query != "" && strlen($query) < 1e6) { // don't add big queries
@@ -81,7 +87,21 @@ if (!$error && $_POST) {
$offset = $pos + strlen($found); $offset = $pos + strlen($found);
if ($found && rtrim($found) != $delimiter) { // find matching quote or comment end if ($found && rtrim($found) != $delimiter) { // find matching quote or comment end
while (preg_match('(' . ($found == '/*' ? '\*/' : ($found == '[' ? ']' : (preg_match('~^-- |^#~', $found) ? "\n" : preg_quote($found) . "|\\\\."))) . '|$)s', $query, $match, PREG_OFFSET_CAPTURE, $offset)) { //! respect sql_mode NO_BACKSLASH_ESCAPES $c_style_escapes = is_c_style_escapes() || ($jush == "pgsql" && ($pos > 0 && strtolower($query[$pos - 1]) == "e"));
$pattern = '(';
if ($found == '/*') {
$pattern .= '\*/';
} elseif ($found == '[') {
$pattern .= ']';
} elseif (preg_match('~^-- |^#~', $found)) {
$pattern .= "\n";
} else {
$pattern .= preg_quote($found) . ($c_style_escapes ? "|\\\\." : "");
}
$pattern .= '|$)s';
while (preg_match($pattern, $query, $match, PREG_OFFSET_CAPTURE, $offset)) {
$s = $match[0][0]; $s = $match[0][0];
if (!$s && $fp && !feof($fp)) { if (!$s && $fp && !feof($fp)) {
$query .= fread($fp, 1e5); $query .= fread($fp, 1e5);
@@ -169,7 +189,8 @@ if (!$error && $_POST) {
stop_session(); stop_session();
} }
if (!$_POST["only_errors"]) { if (!$_POST["only_errors"]) {
echo "<p class='message' title='" . h($connection->info) . "'>" . lang('Query executed OK, %d row(s) affected.', $affected) . "$time\n"; $title = isset($connection->info) ? "title='" . h($connection->info) . "'" : "";
echo "<p class='message' $title>" . lang('Query executed OK, %d row(s) affected.', $affected) . "$time\n";
} }
} }
echo ($warnings ? "<div id='$warnings_id' class='hidden'>\n$warnings</div>\n" : ""); echo ($warnings ? "<div id='$warnings_id' class='hidden'>\n$warnings</div>\n" : "");
@@ -234,10 +255,10 @@ if (!isset($_GET["import"])) {
: lang('File uploads are disabled.') : lang('File uploads are disabled.')
); );
echo "</div></fieldset>\n"; echo "</div></fieldset>\n";
$importServerPath = $adminer->importServerPath(); $import_file_path = $adminer->importServerPath();
if ($importServerPath) { if ($import_file_path) {
echo "<fieldset><legend>" . lang('From server') . "</legend><div>"; echo "<fieldset><legend>" . lang('From server') . "</legend><div>";
echo lang('Webserver file %s', "<code>" . h($importServerPath) . "$gz</code>"); echo lang('Webserver file %s', "<code>" . h($import_file_path) . "$gz</code>");
echo ' <input type="submit" name="webfile" value="' . lang('Run file') . '">'; echo ' <input type="submit" name="webfile" value="' . lang('Run file') . '">';
echo "</div></fieldset>\n"; echo "</div></fieldset>\n";
} }

View File

@@ -19,15 +19,19 @@ fieldset { display: inline; vertical-align: top; padding: .5em .8em; margin: .8e
p { margin: .8em 20px 0 0; } p { margin: .8em 20px 0 0; }
img { vertical-align: middle; border: 0; } img { vertical-align: middle; border: 0; }
td img { max-width: 200px; max-height: 200px; } td img { max-width: 200px; max-height: 200px; }
code { background: #eee; }
tbody tr:hover td, tbody tr:hover th { background: #eee; } tbody tr:hover td, tbody tr:hover th { background: #eee; }
code { font-size: 110%; padding: 1px 2px; background: #eee; }
pre { margin: 1em 0 0; } pre { margin: 1em 0 0; }
pre, textarea { font: 100%/1.25 monospace; } pre code { display: block; font-size: 100%; }
pre, textarea { font: 110%/1.25 monospace; }
pre.jush { background: #fff; }
input, textarea { box-sizing: border-box; }
input, select { vertical-align: middle; } input, select { vertical-align: middle; }
input.default { box-shadow: 1px 1px 1px #777; } input.default { box-shadow: 1px 1px 1px #777; }
input.required { box-shadow: 1px 1px 1px red; } input.required { box-shadow: 1px 1px 1px red; }
input.maxlength { box-shadow: 1px 1px 1px red; } input.maxlength { box-shadow: 1px 1px 1px red; }
input.wayoff { left: -1000px; position: absolute; } input.wayoff { left: -1000px; position: absolute; }
.center { text-align: center; }
.block { display: block; } .block { display: block; }
.version { color: #777; font-size: 67%; } .version { color: #777; font-size: 67%; }
.js .hidden, .nojs .jsonly { display: none; } .js .hidden, .nojs .jsonly { display: none; }

View File

@@ -103,6 +103,11 @@ var dbPrevious = {};
* @this HTMLSelectElement * @this HTMLSelectElement
*/ */
function dbMouseDown(event) { function dbMouseDown(event) {
// Firefox: mouse-down event does not contain pressed key information for OPTION.
// Chrome: mouse-down event has inherited key information from SELECT.
// So we ignore the event for OPTION to work Ctrl+click correctly everywhere.
if (event.target.tagName === "OPTION") return;
dbCtrl = isCtrl(event); dbCtrl = isCtrl(event);
if (dbPrevious[this.name] === undefined) { if (dbPrevious[this.name] === undefined) {
dbPrevious[this.name] = this.value; dbPrevious[this.name] = this.value;

View File

@@ -211,13 +211,21 @@ function tableCheck() {
} }
} }
/** Uncheck single element /**
* @param string * Uncheck single element.
*/ */
function formUncheck(id) { function formUncheck(id) {
var el = qs('#' + id); formUncheckAll("#" + id);
el.checked = false; }
trCheck(el);
/**
* Uncheck elements matched by selector.
*/
function formUncheckAll(selector) {
for (const element of qsa(selector)) {
element.checked = false;
trCheck(element);
}
} }
/** Get number of checked elements matching given name /** Get number of checked elements matching given name
@@ -708,9 +716,13 @@ function selectClick(event, text, warning) {
td.innerHTML = original; td.innerHTML = original;
} }
}; };
var pos = event.rangeOffset;
var value = (td.firstChild && td.firstChild.alt) || td.textContent || td.innerText; let pos = event.rangeOffset;
input.style.width = Math.max(td.clientWidth - 14, 20) + 'px'; // 14 = 2 * (td.border + td.padding + input.border) let value = (td.firstChild && td.firstChild.alt) || td.textContent || td.innerText;
const tdStyle = window.getComputedStyle(td, null);
input.style.width = Math.max(td.clientWidth - parseFloat(tdStyle.paddingLeft) - parseFloat(tdStyle.paddingRight), 20) + 'px';
if (text) { if (text) {
var rows = 1; var rows = 1;
value.replace(/\n/g, function () { value.replace(/\n/g, function () {

View File

@@ -7,9 +7,19 @@ if (!$fields) {
$table_status = table_status1($TABLE, true); $table_status = table_status1($TABLE, true);
$name = $adminer->tableName($table_status); $name = $adminer->tableName($table_status);
$rights = [];
foreach ($fields as $key => $field) {
$rights += $field["privileges"];
}
page_header(($fields && is_view($table_status) ? $table_status['Engine'] == 'materialized view' ? lang('Materialized view') : lang('View') : lang('Table')) . ": " . ($name != "" ? $name : h($TABLE)), $error); page_header(($fields && is_view($table_status) ? $table_status['Engine'] == 'materialized view' ? lang('Materialized view') : lang('View') : lang('Table')) . ": " . ($name != "" ? $name : h($TABLE)), $error);
$adminer->selectLinks($table_status); $set = null;
if (isset($rights["insert"]) || !support("table")) {
$set = "";
}
$adminer->selectLinks($table_status, $set);
$comment = $table_status["Comment"]; $comment = $table_status["Comment"];
if ($comment != "") { if ($comment != "") {
echo "<p class='nowrap'>" . lang('Comment') . ": " . h($comment) . "\n"; echo "<p class='nowrap'>" . lang('Comment') . ": " . h($comment) . "\n";

View File

@@ -85,8 +85,8 @@ if ($_POST && !$error) {
unset($grants[$object]); unset($grants[$object]);
} }
if (preg_match('~^(.+)\s*(\(.*\))?$~U', $object, $match) && ( if (preg_match('~^(.+)\s*(\(.*\))?$~U', $object, $match) && (
!grant("REVOKE", $revoke, $match[2], " ON $match[1] FROM $new_user") //! SQL injection !grant(false, $revoke, $match[2], $match[1], $new_user) //! SQL injection
|| !grant("GRANT", $grant, $match[2], " ON $match[1] TO $new_user") || !grant(true, $grant, $match[2], $match[1], $new_user)
)) { )) {
$error = true; $error = true;
break; break;
@@ -100,7 +100,7 @@ if ($_POST && !$error) {
} elseif (!isset($_GET["grant"])) { } elseif (!isset($_GET["grant"])) {
foreach ($grants as $object => $revoke) { foreach ($grants as $object => $revoke) {
if (preg_match('~^(.+)(\(.*\))?$~U', $object, $match)) { if (preg_match('~^(.+)(\(.*\))?$~U', $object, $match)) {
grant("REVOKE", array_keys($revoke), $match[2], " ON $match[1] FROM $new_user"); grant(false, array_keys($revoke), $match[2], $match[1], $new_user);
} }
} }
} }
@@ -126,7 +126,14 @@ if ($_POST) {
if ($old_pass != "") { if ($old_pass != "") {
$row["hashed"] = true; $row["hashed"] = true;
} }
$grants[(DB == "" || $grants ? "" : idf_escape(addcslashes(DB, "%_\\"))) . ".*"] = array();
if ($grants) {
$grants[".*"] = [];
} elseif (DB != "") {
$grants[idf_escape(addcslashes(DB, "%_\\")) . ".*"] = [];
} else {
$grants["*.* "] = []; // Space is added to force editing mode.
}
} }
?> ?>
@@ -142,41 +149,79 @@ if ($_POST) {
<?php <?php
//! MAX_* limits, REQUIRE //! MAX_* limits, REQUIRE
echo "<table cellspacing='0'>\n"; echo "<table cellspacing='0'>\n";
echo "<thead><tr><th colspan='2'>" . lang('Privileges') . doc_link(array('sql' => "grant.html#priv_level"));
echo "<thead><tr><th colspan='2'>" . lang('Privileges') . doc_link(array('sql' => "grant.html#priv_level")) . "</th>";
$i = 0; $i = 0;
foreach ($grants as $object => $grant) { foreach ($grants as $object => $grant) {
echo '<th>' . ($object != "*.*" ? "<input name='objects[$i]' value='" . h($object) . "' size='10' autocapitalize='off'>" : "<input type='hidden' name='objects[$i]' value='*.*' size='10'>*.*"); //! separate db, table, columns, PROCEDURE|FUNCTION, routine echo "<th>";
//! separate db, table, columns, PROCEDURE|FUNCTION, routine
if ($object == "*.*") {
echo "<input type='hidden' name='objects[$i]' value='*.*' size='10'>*.*";
} else {
echo "<input name='objects[$i]' value='" . h(trim($object)) . "' size='10' autocapitalize='off'>";
}
echo "</th>";
$i++; $i++;
} }
echo "</thead>\n"; echo "</tr></thead>\n";
foreach (array( foreach ([
"" => "", "" => "",
"Server Admin" => lang('Server'), "Server Admin" => lang('Server'),
"Databases" => lang('Database'), "Databases" => lang('Database'),
"Tables" => lang('Table'), "Tables" => lang('Table'),
"Columns" => lang('Column'), "Columns" => lang('Column'),
"Procedures" => lang('Routine'), "Procedures" => lang('Routine'),
) as $context => $desc) { ] as $context => $desc) {
foreach ((array) $privileges[$context] as $privilege => $comment) { foreach ((array) $privileges[$context] as $privilege => $comment) {
echo "<tr" . odd() . "><td" . ($desc ? ">$desc<td" : " colspan='2'") . ' lang="en" title="' . h($comment) . '">' . h($privilege); echo "<tr" . odd() . ">";
if ($desc) {
echo "<td>$desc</td>";
}
echo "<td" . (!$desc ? " colspan='2'" : "") . ' lang="en" title="' . h($comment) . '">' . h($privilege) . "</td>";
$i = 0; $i = 0;
foreach ($grants as $object => $grant) { foreach ($grants as $object => $grant) {
$name = "'grants[$i][" . h(strtoupper($privilege)) . "]'"; $name = "'grants[$i][" . h(strtoupper($privilege)) . "]'";
$value = $grant[strtoupper($privilege)]; $value = $grant[strtoupper($privilege)];
if ($context == "Server Admin" && $object != (isset($grants["*.*"]) ? "*.*" : ".*")) {
echo "<td>"; $proxiedUser = strpos($object, "@") !== false;
$newObject = $object == ".*";
$allPrivileges = $privilege == "All privileges";
$grantOption = $privilege == "Grant option";
if ($object == "*.*" && $privilege == "Proxy") {
echo "<td></td>";
} elseif ($proxiedUser && $privilege != "Proxy" && !$grantOption) {
echo "<td></td>";
} elseif ($context == "Server Admin" && $object != (isset($grants["*.*"]) ? "*.*" : ".*") && !(($proxiedUser || $newObject) && $privilege == "Proxy")) {
echo "<td></td>";
} elseif (isset($_GET["grant"])) { } elseif (isset($_GET["grant"])) {
echo "<td><select name=$name><option><option value='1'" . ($value ? " selected" : "") . ">" . lang('Grant') . "<option value='0'" . ($value == "0" ? " selected" : "") . ">" . lang('Revoke') . "</select>"; echo "<td><select name=$name>" .
"<option></option>" .
"<option value='1'" . ($value ? " selected" : "") . ">" . lang('Grant') . "</option>" .
"<option value='0'" . ($value == "0" ? " selected" : "") . ">" . lang('Revoke') . "</option>" .
"</select></td>";
} else { } else {
echo "<td align='center'><label class='block'>"; echo "<td class='center'><label class='block'>";
echo "<input type='checkbox' name=$name value='1'" . ($value ? " checked" : "") . ($privilege == "All privileges" echo "<input type='checkbox' name=$name value='1'" .
? " id='grants-$i-all'>" //! uncheck all except grant if all is checked ($value ? " checked" : "") .
: ">" . ($privilege == "Grant option" ? "" : script("qsl('input').onclick = function () { if (this.checked) formUncheck('grants-$i-all'); };"))); ($allPrivileges ? " id='grants-$i-all'" : (!$grantOption ? " class='grants-$i'" : "")) .
">";
if ($allPrivileges) {
echo script("qsl('input').onclick = function () { if (this.checked) formUncheckAll('.grants-$i'); };");
} elseif (!$grantOption) {
echo script("qsl('input').onclick = function () { if (this.checked) formUncheck('grants-$i-all'); };");
}
echo "</label>"; echo "</label>";
} }
$i++; $i++;
} }
echo "</tr>";
} }
} }

View File

@@ -1,3 +1,28 @@
Adminer 4.9.4 (released 2024-10-09):
- Fix the width of inline edit field.
- Unify displaying of 'New item' action based on privileges.
- Better default value for object definition (*.*) while creating new database user.
- Firefox: Fix opening a database to the new browser's tab with Ctrl+click.
- Remove suppressing errors while reading local files.
- More secure random strings on PHP 7+.
- Editor: Fix array conversion to string (issue #3).
- Editor: Fix building links with array parameters.
- Clean up the code for PHP < 5.6.
Adminer 4.9.3 (released 2024-10-02):
- MySQL, PostgreSQL: Fix queries splitting and string constants.
- MySQL: Fix where clause for JSON column.
- MySQL: Fix editing user's proxy privilege, refactoring.
- MariaDB: Fix comparing CURRENT_TIMESTAMP definition while altering a table.
- PostgreSQL: Fix editing record that contains a field with GENERATED ALWAYS default value.
- Fix using undefined Min_DB::info property.
- Do not include unchanged PARTITION BY definition into ALTER TABLE query.
- Do not limit unlimited memory while executing queries.
- Fix number conversion warning while reading INI settings.
- Hide invalid edit form if table record is not found.
- CSS: Fix background color of <pre> used as edit field.
- CSS: Bigger font size for code blocks.
Adminer 4.9.2 (released 2024-09-18): Adminer 4.9.2 (released 2024-09-18):
- Fix textarea height for single-line inputs (used typically for SQLite text field). - Fix textarea height for single-line inputs (used typically for SQLite text field).
- Fix undefined property in error message if driver does not support error number (e.g. PostgreSQL). - Fix undefined property in error message if driver does not support error number (e.g. PostgreSQL).

View File

@@ -16,8 +16,11 @@ class Adminer {
function connectSsl() { function connectSsl() {
} }
/**
* @throws \Random\RandomException
*/
function permanentLogin($create = false) { function permanentLogin($create = false) {
return password_file($create); return get_private_key($create);
} }
function bruteForceKey() { function bruteForceKey() {
@@ -350,10 +353,10 @@ ORDER BY ORDINAL_POSITION", null, "") as $row) { //! requires MySQL 5
$op = $where["op"]; $op = $where["op"];
$val = $where["val"]; $val = $where["val"];
if (($key < 0 ? "" : $col) . $val != "") { if (($key >= 0 && $col != "") || $val != "") {
$conds = array(); $conds = [];
foreach (($col != "" ? array($col => $fields[$col]) : $fields) as $name => $field) { foreach (($col != "" ? [$col => $fields[$col]] : $fields) as $name => $field) {
if ($col != "" || is_numeric($val) || !preg_match(number_type(), $field["type"])) { if ($col != "" || is_numeric($val) || !preg_match(number_type(), $field["type"])) {
$name = idf_escape($name); $name = idf_escape($name);
@@ -579,6 +582,7 @@ qsl('div').onclick = whisperClick;", "")
} }
function importServerPath() { function importServerPath() {
return null;
} }
function homepage() { function homepage() {

View File

@@ -17,7 +17,7 @@ function email_header($header) {
* @return bool * @return bool
*/ */
function send_mail($email, $subject, $message, $from = "", $files = array()) { function send_mail($email, $subject, $message, $from = "", $files = array()) {
$eol = (DIRECTORY_SEPARATOR == "/" ? "\n" : "\r\n"); // PHP_EOL available since PHP 5.0.2 $eol = "\r\n";
$message = str_replace("\n", $eol, wordwrap(str_replace("\r", "", "$message\n"))); $message = str_replace("\n", $eol, wordwrap(str_replace("\r", "", "$message\n")));
$boundary = uniqid("boundary"); $boundary = uniqid("boundary");
$attachments = ""; $attachments = "";

View File

@@ -437,22 +437,6 @@ if (isset($_GET["simpledb"])) {
function last_id() { function last_id() {
} }
function hmac($algo, $data, $key, $raw_output = false) {
// can use hash_hmac() since PHP 5.1.2
$blocksize = 64;
if (strlen($key) > $blocksize) {
$key = pack("H*", $algo($key));
}
$key = str_pad($key, $blocksize, "\0");
$k_ipad = $key ^ str_repeat("\x36", $blocksize);
$k_opad = $key ^ str_repeat("\x5C", $blocksize);
$return = $algo($k_opad . pack("H*", $algo($k_ipad . $data)));
if ($raw_output) {
$return = pack("H*", $return);
}
return $return;
}
function sdb_request($action, $params = array()) { function sdb_request($action, $params = array()) {
global $adminer, $connection; global $adminer, $connection;
list($host, $params['AWSAccessKeyId'], $secret) = $adminer->credentials(); list($host, $params['AWSAccessKeyId'], $secret) = $adminer->credentials();
@@ -467,7 +451,7 @@ if (isset($_GET["simpledb"])) {
$query .= '&' . rawurlencode($key) . '=' . rawurlencode($val); $query .= '&' . rawurlencode($key) . '=' . rawurlencode($val);
} }
$query = str_replace('%7E', '~', substr($query, 1)); $query = str_replace('%7E', '~', substr($query, 1));
$query .= "&Signature=" . urlencode(base64_encode(hmac('sha1', "POST\n" . preg_replace('~^https?://~', '', $host) . "\n/\n$query", $secret, true))); $query .= "&Signature=" . urlencode(base64_encode(hash_hmac('sha1', "POST\n" . preg_replace('~^https?://~', '', $host) . "\n/\n$query", $secret, true)));
@ini_set('track_errors', 1); // @ - may be disabled @ini_set('track_errors', 1); // @ - may be disabled
$file = @file_get_contents($connection->_url, false, stream_context_create(array('http' => array( $file = @file_get_contents($connection->_url, false, stream_context_create(array('http' => array(

View File

@@ -7,28 +7,23 @@
* @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other) * @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
*/ */
class AdminerPlugin extends Adminer { class AdminerPlugin extends Adminer {
/** @access protected */ protected $plugins;
var $plugins;
function _findRootClass($class) { // is_subclass_of(string, string) is available since PHP 5.0.3 /**
do { * Registers plugins.
$return = $class; * @param array $plugins Object instances or null to register all classes starting by 'Adminer'.
} while ($class = get_parent_class($class));
return $return;
}
/** Register plugins
* @param array object instances or null to register all classes starting by 'Adminer'
*/ */
function __construct($plugins) { function __construct(array $plugins = null)
{
if ($plugins === null) { if ($plugins === null) {
$plugins = array(); $plugins = [];
foreach (get_declared_classes() as $class) { foreach (get_declared_classes() as $class) {
if (preg_match('~^Adminer.~i', $class) && strcasecmp($this->_findRootClass($class), 'Adminer')) { //! can use interface if (preg_match('~^Adminer.~i', $class) && !is_subclass_of($class, 'Adminer')) { //! can use interface
$plugins[$class] = new $class; $plugins[$class] = new $class;
} }
} }
} }
$this->plugins = $plugins; $this->plugins = $plugins;
//! it is possible to use ReflectionObject to find out which plugins defines which methods at once //! it is possible to use ReflectionObject to find out which plugins defines which methods at once
} }