1
0
mirror of https://github.com/vrana/adminer.git synced 2025-08-06 14:46:36 +02:00

Doc-comments: Move param types to declaration

This commit is contained in:
Jakub Vrana
2025-03-28 08:23:20 +01:00
parent 69073d9d54
commit 641ee4ff26
38 changed files with 271 additions and 553 deletions

View File

@@ -92,10 +92,9 @@ if ($in) {
<pre> <pre>
<?php <?php
/** Format string as table row /** Format string as table row
* @param string $s
* @return string HTML * @return string HTML
*/ */
function pre_tr($s) { function pre_tr(string $s) {
return preg_replace('~^~m', '<tr>', preg_replace('~\|~', '<td>', preg_replace('~\|$~m', "", rtrim($s)))); return preg_replace('~^~m', '<tr>', preg_replace('~\|~', '<td>', preg_replace('~\|$~m', "", rtrim($s))));
} }

View File

@@ -84,10 +84,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Set the client character set /** Set the client character set
* @param string $charset
* @return bool * @return bool
*/ */
function set_charset($charset) { function set_charset(string $charset) {
if (function_exists('mysql_set_charset')) { if (function_exists('mysql_set_charset')) {
if (mysql_set_charset($charset, $this->link)) { if (mysql_set_charset($charset, $this->link)) {
return true; return true;
@@ -129,9 +128,8 @@ if (!defined('Adminer\DRIVER')) {
/** @var int */ private $offset = 0; /** @var int */ private $offset = 0;
/** Constructor /** Constructor
* @param resource $result
*/ */
function __construct($result) { function __construct(resource $result) {
$this->result = $result; $this->result = $result;
$this->num_rows = mysql_num_rows($result); $this->num_rows = mysql_num_rows($result);
} }
@@ -359,18 +357,16 @@ if (!defined('Adminer\DRIVER')) {
/** Escape database identifier /** Escape database identifier
* @param string $idf
* @return string * @return string
*/ */
function idf_escape($idf) { function idf_escape(string $idf) {
return "`" . str_replace("`", "``", $idf) . "`"; return "`" . str_replace("`", "``", $idf) . "`";
} }
/** Get escaped table name /** Get escaped table name
* @param string $idf
* @return string * @return string
*/ */
function table($idf) { function table(string $idf) {
return idf_escape($idf); return idf_escape($idf);
} }
@@ -378,7 +374,7 @@ if (!defined('Adminer\DRIVER')) {
* @param array{string, string, string} $credentials [$server, $username, $password] * @param array{string, string, string} $credentials [$server, $username, $password]
* @return string|Db string for error * @return string|Db string for error
*/ */
function connect($credentials) { function connect(array $credentials) {
global $drivers; global $drivers;
$connection = new Db; $connection = new Db;
if ($connection->connect($credentials[0], $credentials[1], $credentials[2])) { if ($connection->connect($credentials[0], $credentials[1], $credentials[2])) {
@@ -396,10 +392,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get cached list of databases /** Get cached list of databases
* @param bool $flush
* @return list<string> * @return list<string>
*/ */
function get_databases($flush) { function get_databases(bool $flush) {
// SHOW DATABASES can take a very long time so it is cached // SHOW DATABASES can take a very long time so it is cached
$return = get_session("dbs"); $return = get_session("dbs");
if ($return === null) { if ($return === null) {
@@ -415,32 +410,25 @@ if (!defined('Adminer\DRIVER')) {
/** Formulate SQL query with limit /** Formulate SQL query with limit
* @param string $query everything after SELECT * @param string $query everything after SELECT
* @param string $where including WHERE * @param string $where including WHERE
* @param int $limit
* @param int $offset
* @param string $separator
* @return string * @return string
*/ */
function limit($query, $where, $limit, $offset = 0, $separator = " ") { function limit(string $query, string $where, int $limit, int $offset = 0, string $separator = " ") {
return " $query$where" . ($limit !== null ? $separator . "LIMIT $limit" . ($offset ? " OFFSET $offset" : "") : ""); return " $query$where" . ($limit !== null ? $separator . "LIMIT $limit" . ($offset ? " OFFSET $offset" : "") : "");
} }
/** Formulate SQL modification query with limit 1 /** Formulate SQL modification query with limit 1
* @param string $table
* @param string $query everything after UPDATE or DELETE * @param string $query everything after UPDATE or DELETE
* @param string $where
* @param string $separator
* @return string * @return string
*/ */
function limit1($table, $query, $where, $separator = "\n") { function limit1(string $table, string $query, string $where, string $separator = "\n") {
return limit($query, $where, 1, 0, $separator); return limit($query, $where, 1, 0, $separator);
} }
/** Get database collation /** Get database collation
* @param string $db
* @param string[][] $collations result of collations() * @param string[][] $collations result of collations()
* @return string * @return string
*/ */
function db_collation($db, $collations) { function db_collation(string $db, array $collations) {
$return = null; $return = null;
$create = get_val("SHOW CREATE DATABASE " . idf_escape($db), 1); $create = get_val("SHOW CREATE DATABASE " . idf_escape($db), 1);
if (preg_match('~ COLLATE ([^ ]+)~', $create, $match)) { if (preg_match('~ COLLATE ([^ ]+)~', $create, $match)) {
@@ -470,7 +458,7 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $databases * @param list<string> $databases
* @return int[] [$db => $tables] * @return int[] [$db => $tables]
*/ */
function count_tables($databases) { function count_tables(array $databases) {
$return = array(); $return = array();
foreach ($databases as $db) { foreach ($databases as $db) {
$return[$db] = count(get_vals("SHOW TABLES IN " . idf_escape($db))); $return[$db] = count(get_vals("SHOW TABLES IN " . idf_escape($db)));
@@ -479,11 +467,10 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get table status /** Get table status
* @param string $name
* @param bool $fast return only "Name", "Engine" and "Comment" fields * @param bool $fast return only "Name", "Engine" and "Comment" fields
* @return TableStatus[] * @return TableStatus[]
*/ */
function table_status($name = "", $fast = false) { function table_status(string $name = "", bool $fast = false) {
$return = array(); $return = array();
foreach ( foreach (
get_rows( get_rows(
@@ -512,7 +499,7 @@ if (!defined('Adminer\DRIVER')) {
* @param TableStatus $table_status * @param TableStatus $table_status
* @return bool * @return bool
*/ */
function is_view($table_status) { function is_view(array $table_status) {
return $table_status["Engine"] === null; return $table_status["Engine"] === null;
} }
@@ -520,15 +507,14 @@ if (!defined('Adminer\DRIVER')) {
* @param TableStatus $table_status result of table_status1() * @param TableStatus $table_status result of table_status1()
* @return bool * @return bool
*/ */
function fk_support($table_status) { function fk_support(array $table_status) {
return preg_match('~InnoDB|IBMDB2I' . (min_version(5.6) ? '|NDB' : '') . '~i', $table_status["Engine"]); return preg_match('~InnoDB|IBMDB2I' . (min_version(5.6) ? '|NDB' : '') . '~i', $table_status["Engine"]);
} }
/** Get information about fields /** Get information about fields
* @param string $table
* @return Field[] * @return Field[]
*/ */
function fields($table) { function fields(string $table) {
global $connection; global $connection;
$maria = ($connection->flavor == 'maria'); $maria = ($connection->flavor == 'maria');
$return = array(); $return = array();
@@ -580,11 +566,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get table indexes /** Get table indexes
* @param string $table
* @param ?Db $connection2
* @return Index[] * @return Index[]
*/ */
function indexes($table, $connection2 = null) { function indexes(string $table, ?Db $connection2 = null) {
$return = array(); $return = array();
foreach (get_rows("SHOW INDEX FROM " . table($table), $connection2) as $row) { foreach (get_rows("SHOW INDEX FROM " . table($table), $connection2) as $row) {
$name = $row["Key_name"]; $name = $row["Key_name"];
@@ -597,10 +581,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get foreign keys in table /** Get foreign keys in table
* @param string $table
* @return ForeignKey[] * @return ForeignKey[]
*/ */
function foreign_keys($table) { function foreign_keys(string $table) {
global $driver; global $driver;
static $pattern = '(?:`(?:[^`]|``)+`|"(?:[^"]|"")+")'; static $pattern = '(?:`(?:[^`]|``)+`|"(?:[^"]|"")+")';
$return = array(); $return = array();
@@ -629,10 +612,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get view SELECT /** Get view SELECT
* @param string $name
* @return array{select:string} * @return array{select:string}
*/ */
function view($name) { function view(string $name) {
return array("select" => preg_replace('~^(?:[^`]|`[^`]*`)*\s+AS\s+~isU', '', get_val("SHOW CREATE VIEW " . table($name), 1))); return array("select" => preg_replace('~^(?:[^`]|`[^`]*`)*\s+AS\s+~isU', '', get_val("SHOW CREATE VIEW " . table($name), 1)));
} }
@@ -656,10 +638,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Find out if database is information_schema /** Find out if database is information_schema
* @param string $db
* @return bool * @return bool
*/ */
function information_schema($db) { function information_schema(string $db) {
return ($db == "information_schema") return ($db == "information_schema")
|| (min_version(5.5) && $db == "performance_schema"); || (min_version(5.5) && $db == "performance_schema");
} }
@@ -673,11 +654,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Create database /** Create database
* @param string $db
* @param string $collation
* @return Result * @return Result
*/ */
function create_database($db, $collation) { function create_database(string $db, string $collation) {
return queries("CREATE DATABASE " . idf_escape($db) . ($collation ? " COLLATE " . q($collation) : "")); return queries("CREATE DATABASE " . idf_escape($db) . ($collation ? " COLLATE " . q($collation) : ""));
} }
@@ -685,7 +664,7 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $databases * @param list<string> $databases
* @return bool * @return bool
*/ */
function drop_databases($databases) { function drop_databases(array $databases) {
$return = apply_queries("DROP DATABASE", $databases, 'Adminer\idf_escape'); $return = apply_queries("DROP DATABASE", $databases, 'Adminer\idf_escape');
restart_session(); restart_session();
set_session("dbs", null); set_session("dbs", null);
@@ -694,10 +673,9 @@ if (!defined('Adminer\DRIVER')) {
/** Rename database from DB /** Rename database from DB
* @param string $name new name * @param string $name new name
* @param string $collation
* @return bool * @return bool
*/ */
function rename_database($name, $collation) { function rename_database(string $name, string $collation) {
$return = false; $return = false;
if (create_database($name, $collation)) { if (create_database($name, $collation)) {
$tables = array(); $tables = array();
@@ -740,14 +718,10 @@ if (!defined('Adminer\DRIVER')) {
* @param string $name new name * @param string $name new name
* @param list<array{string, list<string>, string}> $fields of [$orig, $process_field, $after] * @param list<array{string, list<string>, string}> $fields of [$orig, $process_field, $after]
* @param string[] $foreign * @param string[] $foreign
* @param string $comment
* @param string $engine
* @param string $collation
* @param string $auto_increment number * @param string $auto_increment number
* @param string $partitioning
* @return Result|bool * @return Result|bool
*/ */
function alter_table($table, $name, $fields, $foreign, $comment, $engine, $collation, $auto_increment, $partitioning) { function alter_table(string $table, string $name, array $fields, array $foreign, string $comment, string $engine, string $collation, string $auto_increment, string $partitioning) {
global $connection; global $connection;
$alter = array(); $alter = array();
foreach ($fields as $field) { foreach ($fields as $field) {
@@ -786,7 +760,7 @@ if (!defined('Adminer\DRIVER')) {
* @param list<array{string, string, 'DROP'|list<string>}> $alter of ["index type", "name", ["column definition", ...]] or ["index type", "name", "DROP"] * @param list<array{string, string, 'DROP'|list<string>}> $alter of ["index type", "name", ["column definition", ...]] or ["index type", "name", "DROP"]
* @return Result|bool * @return Result|bool
*/ */
function alter_indexes($table, $alter) { function alter_indexes(string $table, $alter) {
$changes = array(); $changes = array();
foreach ($alter as $val) { foreach ($alter as $val) {
$changes[] = ($val[2] == "DROP" $changes[] = ($val[2] == "DROP"
@@ -801,7 +775,7 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $tables * @param list<string> $tables
* @return bool * @return bool
*/ */
function truncate_tables($tables) { function truncate_tables(array $tables) {
return apply_queries("TRUNCATE TABLE", $tables); return apply_queries("TRUNCATE TABLE", $tables);
} }
@@ -809,7 +783,7 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $views * @param list<string> $views
* @return Result|bool * @return Result|bool
*/ */
function drop_views($views) { function drop_views(array $views) {
return queries("DROP VIEW " . implode(", ", array_map('Adminer\table', $views))); return queries("DROP VIEW " . implode(", ", array_map('Adminer\table', $views)));
} }
@@ -817,17 +791,16 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $tables * @param list<string> $tables
* @return Result|bool * @return Result|bool
*/ */
function drop_tables($tables) { function drop_tables(array $tables) {
return queries("DROP TABLE " . implode(", ", array_map('Adminer\table', $tables))); return queries("DROP TABLE " . implode(", ", array_map('Adminer\table', $tables)));
} }
/** Move tables to other schema /** Move tables to other schema
* @param list<string> $tables * @param list<string> $tables
* @param list<string> $views * @param list<string> $views
* @param string $target
* @return bool * @return bool
*/ */
function move_tables($tables, $views, $target) { function move_tables(array $tables, array $views, string $target) {
global $connection; global $connection;
$rename = array(); $rename = array();
foreach ($tables as $table) { foreach ($tables as $table) {
@@ -854,10 +827,9 @@ if (!defined('Adminer\DRIVER')) {
/** Copy tables to other schema /** Copy tables to other schema
* @param list<string> $tables * @param list<string> $tables
* @param list<string> $views * @param list<string> $views
* @param string $target
* @return bool * @return bool
*/ */
function copy_tables($tables, $views, $target) { function copy_tables(array $tables, array $views, string $target) {
queries("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'"); queries("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'");
foreach ($tables as $table) { foreach ($tables as $table) {
$name = ($target == DB ? table("copy_$table") : idf_escape($target) . "." . table($table)); $name = ($target == DB ? table("copy_$table") : idf_escape($target) . "." . table($table));
@@ -890,10 +862,9 @@ if (!defined('Adminer\DRIVER')) {
/** Get information about trigger /** Get information about trigger
* @param string $name trigger name * @param string $name trigger name
* @param string $table
* @return Trigger * @return Trigger
*/ */
function trigger($name, $table) { function trigger(string $name, string $table) {
if ($name == "") { if ($name == "") {
return array(); return array();
} }
@@ -902,10 +873,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get defined triggers /** Get defined triggers
* @param string $table
* @return array{string, string}[] * @return array{string, string}[]
*/ */
function triggers($table) { function triggers(string $table) {
$return = array(); $return = array();
foreach (get_rows("SHOW TRIGGERS LIKE " . q(addcslashes($table, "%_\\"))) as $row) { foreach (get_rows("SHOW TRIGGERS LIKE " . q(addcslashes($table, "%_\\"))) as $row) {
$return[$row["Trigger"]] = array($row["Timing"], $row["Event"]); $return[$row["Trigger"]] = array($row["Timing"], $row["Event"]);
@@ -925,11 +895,10 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get information about stored routine /** Get information about stored routine
* @param string $name
* @param 'FUNCTION'|'PROCEDURE' $type * @param 'FUNCTION'|'PROCEDURE' $type
* @return Routine * @return Routine
*/ */
function routine($name, $type) { function routine(string $name, $type) {
global $driver; global $driver;
$aliases = array("bool", "boolean", "integer", "double precision", "real", "dec", "numeric", "fixed", "national char", "national varchar"); $aliases = array("bool", "boolean", "integer", "double precision", "real", "dec", "numeric", "fixed", "national char", "national varchar");
$space = "(?:\\s|/\\*[\s\S]*?\\*/|(?:#|-- )[^\n]*\n?|--\r?\n)"; $space = "(?:\\s|/\\*[\s\S]*?\\*/|(?:#|-- )[^\n]*\n?|--\r?\n)";
@@ -978,11 +947,10 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get routine signature /** Get routine signature
* @param string $name
* @param Routine $row result of routine() * @param Routine $row result of routine()
* @return string * @return string
*/ */
function routine_id($name, $row) { function routine_id(string $name, array $row) {
return idf_escape($name); return idf_escape($name);
} }
@@ -995,11 +963,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Explain select /** Explain select
* @param Db $connection
* @param string $query
* @return Result * @return Result
*/ */
function explain($connection, $query) { function explain(Db $connection, string $query) {
return $connection->query("EXPLAIN " . (min_version(5.1) && !min_version(5.7) ? "PARTITIONS " : "") . $query); return $connection->query("EXPLAIN " . (min_version(5.1) && !min_version(5.7) ? "PARTITIONS " : "") . $query);
} }
@@ -1008,17 +974,14 @@ if (!defined('Adminer\DRIVER')) {
* @param list<string> $where * @param list<string> $where
* @return numeric-string|null null if approximate number can't be retrieved * @return numeric-string|null null if approximate number can't be retrieved
*/ */
function found_rows($table_status, $where) { function found_rows(array $table_status, array $where) {
return ($where || $table_status["Engine"] != "InnoDB" ? null : $table_status["Rows"]); return ($where || $table_status["Engine"] != "InnoDB" ? null : $table_status["Rows"]);
} }
/** Get SQL command to create table /** Get SQL command to create table
* @param string $table
* @param bool $auto_increment
* @param string $style
* @return string * @return string
*/ */
function create_sql($table, $auto_increment, $style) { function create_sql(string $table, bool $auto_increment, string $style) {
$return = get_val("SHOW CREATE TABLE " . table($table), 1); $return = get_val("SHOW CREATE TABLE " . table($table), 1);
if (!$auto_increment) { if (!$auto_increment) {
$return = preg_replace('~ AUTO_INCREMENT=\d+~', '', $return); //! skip comments $return = preg_replace('~ AUTO_INCREMENT=\d+~', '', $return); //! skip comments
@@ -1027,26 +990,23 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get SQL command to truncate table /** Get SQL command to truncate table
* @param string $table
* @return string * @return string
*/ */
function truncate_sql($table) { function truncate_sql(string $table) {
return "TRUNCATE " . table($table); return "TRUNCATE " . table($table);
} }
/** Get SQL command to change database /** Get SQL command to change database
* @param string $database
* @return string * @return string
*/ */
function use_sql($database) { function use_sql(string $database) {
return "USE " . idf_escape($database); return "USE " . idf_escape($database);
} }
/** Get SQL commands to create triggers /** Get SQL commands to create triggers
* @param string $table
* @return string * @return string
*/ */
function trigger_sql($table) { function trigger_sql(string $table) {
$return = ""; $return = "";
foreach (get_rows("SHOW TRIGGERS LIKE " . q(addcslashes($table, "%_\\")), null, "-- ") as $row) { foreach (get_rows("SHOW TRIGGERS LIKE " . q(addcslashes($table, "%_\\")), null, "-- ") as $row) {
$return .= "\nCREATE TRIGGER " . idf_escape($row["Trigger"]) . " $row[Timing] $row[Event] ON " . table($row["Table"]) . " FOR EACH ROW\n$row[Statement];;\n"; $return .= "\nCREATE TRIGGER " . idf_escape($row["Trigger"]) . " $row[Timing] $row[Event] ON " . table($row["Table"]) . " FOR EACH ROW\n$row[Statement];;\n";
@@ -1079,7 +1039,7 @@ if (!defined('Adminer\DRIVER')) {
* @param Field $field one element from fields() * @param Field $field one element from fields()
* @return string|void * @return string|void
*/ */
function convert_field($field) { function convert_field(array $field) {
if (preg_match("~binary~", $field["type"])) { if (preg_match("~binary~", $field["type"])) {
return "HEX(" . idf_escape($field["field"]) . ")"; return "HEX(" . idf_escape($field["field"]) . ")";
} }
@@ -1096,7 +1056,7 @@ if (!defined('Adminer\DRIVER')) {
* @param string $return SQL expression * @param string $return SQL expression
* @return string * @return string
*/ */
function unconvert_field($field, $return) { function unconvert_field(array $field, string $return) {
if (preg_match("~binary~", $field["type"])) { if (preg_match("~binary~", $field["type"])) {
$return = "UNHEX($return)"; $return = "UNHEX($return)";
} }
@@ -1114,7 +1074,7 @@ if (!defined('Adminer\DRIVER')) {
* @param literal-string $feature "check|comment|copy|database|descidx|drop_col|dump|event|indexes|kill|materializedview|partitioning|privileges|procedure|processlist|routine|scheme|sequence|status|table|trigger|type|variables|view|view_trigger" * @param literal-string $feature "check|comment|copy|database|descidx|drop_col|dump|event|indexes|kill|materializedview|partitioning|privileges|procedure|processlist|routine|scheme|sequence|status|table|trigger|type|variables|view|view_trigger"
* @return bool * @return bool
*/ */
function support($feature) { function support(string $feature) {
return !preg_match("~scheme|sequence|type|view_trigger|materializedview" . (min_version(8) ? "" : "|descidx" . (min_version(5.1) ? "" : "|event|partitioning")) . (min_version('8.0.16', '10.2.1') ? "" : "|check") . "~", $feature); return !preg_match("~scheme|sequence|type|view_trigger|materializedview" . (min_version(8) ? "" : "|descidx" . (min_version(5.1) ? "" : "|event|partitioning")) . (min_version('8.0.16', '10.2.1') ? "" : "|check") . "~", $feature);
} }
@@ -1122,7 +1082,7 @@ if (!defined('Adminer\DRIVER')) {
* @param numeric-string $val * @param numeric-string $val
* @return Result|bool * @return Result|bool
*/ */
function kill_process($val) { function kill_process(string $val) {
return queries("KILL " . number($val)); return queries("KILL " . number($val));
} }
@@ -1150,10 +1110,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Get values of user defined type /** Get values of user defined type
* @param int $id
* @return string * @return string
*/ */
function type_values($id) { function type_values(int $id) {
return ""; return "";
} }
@@ -1172,11 +1131,9 @@ if (!defined('Adminer\DRIVER')) {
} }
/** Set current schema /** Set current schema
* @param string $schema
* @param Db $connection2
* @return bool * @return bool
*/ */
function set_schema($schema, $connection2 = null) { function set_schema(string $schema, Db $connection2 = null) {
return true; return true;
} }
} }

View File

@@ -463,7 +463,7 @@ if (isset($_GET["sqlite"])) {
* @param string $add_check CHECK constraint to add * @param string $add_check CHECK constraint to add
* @return bool * @return bool
*/ */
function recreate_table($table, $name, $fields, $originals, $foreign, $auto_increment = 0, $indexes = array(), $drop_check = "", $add_check = "") { function recreate_table(string $table, string $name, array $fields, array $originals, array $foreign, int $auto_increment = 0, $indexes = array(), string $drop_check = "", string $add_check = "") {
global $driver; global $driver;
if ($table != "") { if ($table != "") {
if (!$fields) { if (!$fields) {

View File

@@ -28,10 +28,9 @@ class Adminer {
} }
/** Get key used for permanent login /** Get key used for permanent login
* @param bool $create
* @return string cryptic string which gets combined with password or false in case of an error * @return string cryptic string which gets combined with password or false in case of an error
*/ */
function permanentLogin($create = false) { function permanentLogin(bool $create = false) {
return password_file($create); return password_file($create);
} }
@@ -43,10 +42,9 @@ class Adminer {
} }
/** Get server name displayed in breadcrumbs /** Get server name displayed in breadcrumbs
* @param string $server
* @return string HTML code or null * @return string HTML code or null
*/ */
function serverName($server) { function serverName(string $server) {
return h($server); return h($server);
} }
@@ -59,10 +57,9 @@ class Adminer {
} }
/** Get cached list of databases /** Get cached list of databases
* @param bool $flush
* @return list<string> * @return list<string>
*/ */
function databases($flush = true) { function databases(bool $flush = true) {
return get_databases($flush); return get_databases($flush);
} }
@@ -97,7 +94,7 @@ class Adminer {
* @param bool $dark dark CSS: false to disable, true to force, null to base on user preferences * @param bool $dark dark CSS: false to disable, true to force, null to base on user preferences
* @return bool true to link favicon.ico * @return bool true to link favicon.ico
*/ */
function head($dark = null) { function head(bool $dark = null) {
// this is matched by compile.php // this is matched by compile.php
echo "<link rel='stylesheet' href='../externals/jush/jush.css'>\n"; echo "<link rel='stylesheet' href='../externals/jush/jush.css'>\n";
echo ($dark !== false ? "<link rel='stylesheet'" . ($dark ? "" : " media='(prefers-color-scheme: dark)'") . " href='../externals/jush/jush-dark.css'>\n" : ""); echo ($dark !== false ? "<link rel='stylesheet'" . ($dark ? "" : " media='(prefers-color-scheme: dark)'") . " href='../externals/jush/jush-dark.css'>\n" : "");
@@ -137,21 +134,18 @@ class Adminer {
} }
/** Get login form field /** Get login form field
* @param string $name
* @param string $heading HTML * @param string $heading HTML
* @param string $value HTML * @param string $value HTML
* @return string * @return string
*/ */
function loginFormField($name, $heading, $value) { function loginFormField(string $name, string $heading, string $value) {
return $heading . $value . "\n"; return $heading . $value . "\n";
} }
/** Authorize the user /** Authorize the user
* @param string $login
* @param string $password
* @return mixed true for success, string for error message, false for unknown error * @return mixed true for success, string for error message, false for unknown error
*/ */
function login($login, $password) { function login(string $login, string $password) {
if ($password == "") { if ($password == "") {
return lang('Adminer does not support accessing a database without a password, <a href="https://www.adminer.org/en/password/"%s>more information</a>.', target_blank()); return lang('Adminer does not support accessing a database without a password, <a href="https://www.adminer.org/en/password/"%s>more information</a>.', target_blank());
} }
@@ -162,7 +156,7 @@ class Adminer {
* @param TableStatus $tableStatus result of table_status1() * @param TableStatus $tableStatus result of table_status1()
* @return string HTML code, "" to ignore table * @return string HTML code, "" to ignore table
*/ */
function tableName($tableStatus) { function tableName(array $tableStatus) {
return h($tableStatus["Name"]); return h($tableStatus["Name"]);
} }
@@ -171,7 +165,7 @@ class Adminer {
* @param int $order order of column in select * @param int $order order of column in select
* @return string HTML code, "" to ignore field * @return string HTML code, "" to ignore field
*/ */
function fieldName($field, $order = 0) { function fieldName(array $field, int $order = 0) {
$type = $field["full_type"]; $type = $field["full_type"];
$comment = $field["comment"]; $comment = $field["comment"];
return '<span title="' . h($type . ($comment != "" ? ($type ? ": " : "") . $comment : '')) . '">' . h($field["field"]) . '</span>'; return '<span title="' . h($type . ($comment != "" ? ($type ? ": " : "") . $comment : '')) . '">' . h($field["field"]) . '</span>';
@@ -182,7 +176,7 @@ class Adminer {
* @param string $set new item options, NULL for no new item * @param string $set new item options, NULL for no new item
* @return void * @return void
*/ */
function selectLinks($tableStatus, $set = "") { function selectLinks(array $tableStatus, string $set = "") {
global $driver; global $driver;
echo '<p class="links">'; echo '<p class="links">';
$links = array("select" => lang('Select data')); $links = array("select" => lang('Select data'));
@@ -210,19 +204,16 @@ class Adminer {
} }
/** Get foreign keys for table /** Get foreign keys for table
* @param string $table
* @return ForeignKey[] same format as foreign_keys() * @return ForeignKey[] same format as foreign_keys()
*/ */
function foreignKeys($table) { function foreignKeys(string $table) {
return foreign_keys($table); return foreign_keys($table);
} }
/** Find backward keys for table /** Find backward keys for table
* @param string $table
* @param string $tableName
* @return BackwardKey[] * @return BackwardKey[]
*/ */
function backwardKeys($table, $tableName) { function backwardKeys(string $table, string $tableName) {
return array(); return array();
} }
@@ -231,16 +222,15 @@ class Adminer {
* @param string[] $row * @param string[] $row
* @return void * @return void
*/ */
function backwardKeysPrint($backwardKeys, $row) { function backwardKeysPrint(array $backwardKeys, array $row) {
} }
/** Query printed in select before execution /** Query printed in select before execution
* @param string $query query to be executed * @param string $query query to be executed
* @param float $start start time of the query * @param float $start start time of the query
* @param bool $failed
* @return string * @return string
*/ */
function selectQuery($query, $start, $failed = false) { function selectQuery(string $query, float $start, bool $failed = false) {
global $driver; global $driver;
$return = "</p>\n"; // required for IE9 inline edit $return = "</p>\n"; // required for IE9 inline edit
if (!$failed && ($warnings = $driver->warnings())) { if (!$failed && ($warnings = $driver->warnings())) {
@@ -259,7 +249,7 @@ class Adminer {
* @param string $query query to be executed * @param string $query query to be executed
* @return string escaped query to be printed * @return string escaped query to be printed
*/ */
function sqlCommandQuery($query) { function sqlCommandQuery(string $query) {
return shorten_utf8(trim($query), 1000); return shorten_utf8(trim($query), 1000);
} }
@@ -270,10 +260,9 @@ class Adminer {
} }
/** Description of a row in a table /** Description of a row in a table
* @param string $table
* @return string SQL expression, empty string for no description * @return string SQL expression, empty string for no description
*/ */
function rowDescription($table) { function rowDescription(string $table) {
return ""; return "";
} }
@@ -282,7 +271,7 @@ class Adminer {
* @param ForeignKey[] $foreignKeys * @param ForeignKey[] $foreignKeys
* @return list<string[]> * @return list<string[]>
*/ */
function rowDescriptions($rows, $foreignKeys) { function rowDescriptions(array $rows, array $foreignKeys) {
return $rows; return $rows;
} }
@@ -291,7 +280,7 @@ class Adminer {
* @param Field $field single field returned from fields() * @param Field $field single field returned from fields()
* @return string|void null to create the default link * @return string|void null to create the default link
*/ */
function selectLink($val, $field) { function selectLink(string $val, array $field) {
} }
/** Value printed in select table /** Value printed in select table
@@ -301,7 +290,7 @@ class Adminer {
* @param string $original original value before applying editVal() and escaping * @param string $original original value before applying editVal() and escaping
* @return string * @return string
*/ */
function selectVal($val, $link, $field, $original) { function selectVal(string $val, string $link, array $field, string $original) {
$return = ($val === null ? "<i>NULL</i>" $return = ($val === null ? "<i>NULL</i>"
: (preg_match("~char|binary|boolean~", $field["type"]) && !preg_match("~var~", $field["type"]) ? "<code>$val</code>" : (preg_match("~char|binary|boolean~", $field["type"]) && !preg_match("~var~", $field["type"]) ? "<code>$val</code>"
: (preg_match('~json~', $field["type"]) ? "<code class='jush-js'>$val</code>" : (preg_match('~json~', $field["type"]) ? "<code class='jush-js'>$val</code>"
@@ -314,11 +303,10 @@ class Adminer {
} }
/** Value conversion used in select and edit /** Value conversion used in select and edit
* @param string $val
* @param Field $field single field returned from fields() * @param Field $field single field returned from fields()
* @return string * @return string
*/ */
function editVal($val, $field) { function editVal(string $val, array $field) {
return $val; return $val;
} }
@@ -327,7 +315,7 @@ class Adminer {
* @param TableStatus $tableStatus * @param TableStatus $tableStatus
* @return void * @return void
*/ */
function tableStructurePrint($fields, $tableStatus = null) { function tableStructurePrint(array $fields, array $tableStatus = null) {
global $driver; global $driver;
echo "<div class='scrollable'>\n"; echo "<div class='scrollable'>\n";
echo "<table class='nowrap odds'>\n"; echo "<table class='nowrap odds'>\n";
@@ -358,7 +346,7 @@ class Adminer {
* @param Index[] $indexes data about all indexes on a table * @param Index[] $indexes data about all indexes on a table
* @return void * @return void
*/ */
function tableIndexesPrint($indexes) { function tableIndexesPrint(array $indexes) {
echo "<table>\n"; echo "<table>\n";
foreach ($indexes as $name => $index) { foreach ($indexes as $name => $index) {
ksort($index["columns"]); // enforce correct columns order ksort($index["columns"]); // enforce correct columns order
@@ -379,7 +367,7 @@ class Adminer {
* @param string[] $columns selectable columns * @param string[] $columns selectable columns
* @return void * @return void
*/ */
function selectColumnsPrint($select, $columns) { function selectColumnsPrint(array $select, array $columns) {
global $driver; global $driver;
print_fieldset("select", lang('Select'), $select); print_fieldset("select", lang('Select'), $select);
$i = 0; $i = 0;
@@ -407,7 +395,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return void * @return void
*/ */
function selectSearchPrint($where, $columns, $indexes) { function selectSearchPrint(array $where, array $columns, array $indexes) {
print_fieldset("search", lang('Search'), $where); print_fieldset("search", lang('Search'), $where);
foreach ($indexes as $i => $index) { foreach ($indexes as $i => $index) {
if ($index["type"] == "FULLTEXT") { if ($index["type"] == "FULLTEXT") {
@@ -443,7 +431,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return void * @return void
*/ */
function selectOrderPrint($order, $columns, $indexes) { function selectOrderPrint(array $order, array $columns, array $indexes) {
print_fieldset("sort", lang('Sort'), $order); print_fieldset("sort", lang('Sort'), $order);
$i = 0; $i = 0;
foreach ((array) $_GET["order"] as $key => $val) { foreach ((array) $_GET["order"] as $key => $val) {
@@ -462,7 +450,7 @@ class Adminer {
* @param string $limit result of selectLimitProcess() * @param string $limit result of selectLimitProcess()
* @return void * @return void
*/ */
function selectLimitPrint($limit) { function selectLimitPrint(string $limit) {
echo "<fieldset><legend>" . lang('Limit') . "</legend><div>"; // <div> for easy styling echo "<fieldset><legend>" . lang('Limit') . "</legend><div>"; // <div> for easy styling
echo "<input type='number' name='limit' class='size' value='" . h($limit) . "'>"; echo "<input type='number' name='limit' class='size' value='" . h($limit) . "'>";
echo script("qsl('input').oninput = selectFieldChange;", ""); echo script("qsl('input').oninput = selectFieldChange;", "");
@@ -473,7 +461,7 @@ class Adminer {
* @param string $text_length result of selectLengthProcess() * @param string $text_length result of selectLengthProcess()
* @return void * @return void
*/ */
function selectLengthPrint($text_length) { function selectLengthPrint(string $text_length) {
if ($text_length !== null) { if ($text_length !== null) {
echo "<fieldset><legend>" . lang('Text length') . "</legend><div>"; echo "<fieldset><legend>" . lang('Text length') . "</legend><div>";
echo "<input type='number' name='text_length' class='size' value='" . h($text_length) . "'>"; echo "<input type='number' name='text_length' class='size' value='" . h($text_length) . "'>";
@@ -485,7 +473,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return void * @return void
*/ */
function selectActionPrint($indexes) { function selectActionPrint(array $indexes) {
echo "<fieldset><legend>" . lang('Action') . "</legend><div>"; echo "<fieldset><legend>" . lang('Action') . "</legend><div>";
echo "<input type='submit' value='" . lang('Select') . "'>"; echo "<input type='submit' value='" . lang('Select') . "'>";
echo " <span id='noindex' title='" . lang('Full table scan') . "'></span>"; echo " <span id='noindex' title='" . lang('Full table scan') . "'></span>";
@@ -527,7 +515,7 @@ class Adminer {
* @param string[] $columns selectable columns * @param string[] $columns selectable columns
* @return void * @return void
*/ */
function selectEmailPrint($emailFields, $columns) { function selectEmailPrint(array $emailFields, array $columns) {
} }
/** Process columns box in select /** Process columns box in select
@@ -535,7 +523,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return list<list<string>> [[select_expressions], [group_expressions]] * @return list<list<string>> [[select_expressions], [group_expressions]]
*/ */
function selectColumnsProcess($columns, $indexes) { function selectColumnsProcess(array $columns, array $indexes) {
global $driver; global $driver;
$select = array(); // select expressions, empty for * $select = array(); // select expressions, empty for *
$group = array(); // expressions without aggregation - will be used for GROUP BY if an aggregation function is used $group = array(); // expressions without aggregation - will be used for GROUP BY if an aggregation function is used
@@ -555,7 +543,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return list<string> expressions to join by AND * @return list<string> expressions to join by AND
*/ */
function selectSearchProcess($fields, $indexes) { function selectSearchProcess(array $fields, array $indexes) {
global $connection, $driver; global $connection, $driver;
$return = array(); $return = array();
foreach ($indexes as $i => $index) { foreach ($indexes as $i => $index) {
@@ -609,7 +597,7 @@ class Adminer {
* @param Index[] $indexes * @param Index[] $indexes
* @return list<string> expressions to join by comma * @return list<string> expressions to join by comma
*/ */
function selectOrderProcess($fields, $indexes) { function selectOrderProcess(array $fields, array $indexes) {
$return = array(); $return = array();
foreach ((array) $_GET["order"] as $key => $val) { foreach ((array) $_GET["order"] as $key => $val) {
if ($val != "") { if ($val != "") {
@@ -640,7 +628,7 @@ class Adminer {
* @param ForeignKey[] $foreignKeys * @param ForeignKey[] $foreignKeys
* @return bool true if processed, false to process other parts of form * @return bool true if processed, false to process other parts of form
*/ */
function selectEmailProcess($where, $foreignKeys) { function selectEmailProcess(array $where, array $foreignKeys) {
return false; return false;
} }
@@ -653,17 +641,16 @@ class Adminer {
* @param int $page index of page starting at zero * @param int $page index of page starting at zero
* @return string empty string to use default query * @return string empty string to use default query
*/ */
function selectQueryBuild($select, $where, $group, $order, $limit, $page) { function selectQueryBuild(array $select, array $where, array $group, array $order, int $limit, int $page) {
return ""; return "";
} }
/** Query printed after execution in the message /** Query printed after execution in the message
* @param string $query executed query * @param string $query executed query
* @param string $time elapsed time * @param string $time elapsed time
* @param bool $failed
* @return string * @return string
*/ */
function messageQuery($query, $time, $failed = false) { function messageQuery(string $query, string $time, bool $failed = false) {
global $driver; global $driver;
restart_session(); restart_session();
$history = &get_session("queries"); $history = &get_session("queries");
@@ -689,20 +676,18 @@ class Adminer {
} }
/** Print before edit form /** Print before edit form
* @param string $table
* @param Field[] $fields * @param Field[] $fields
* @param mixed $row * @param mixed $row
* @param bool $update
* @return void * @return void
*/ */
function editRowPrint($table, $fields, $row, $update) { function editRowPrint(string $table, array $fields, $row, bool $update) {
} }
/** Functions displayed in edit form /** Functions displayed in edit form
* @param Field $field single field from fields() * @param Field $field single field from fields()
* @return list<string> * @return list<string>
*/ */
function editFunctions($field) { function editFunctions(array $field) {
global $driver; global $driver;
$return = ($field["null"] ? "NULL/" : ""); $return = ($field["null"] ? "NULL/" : "");
$update = isset($_GET["select"]) || where($_GET); $update = isset($_GET["select"]) || where($_GET);
@@ -728,10 +713,9 @@ class Adminer {
* @param string $table table name * @param string $table table name
* @param Field $field single field from fields() * @param Field $field single field from fields()
* @param string $attrs attributes to use inside the tag * @param string $attrs attributes to use inside the tag
* @param string $value
* @return string custom input field or empty string for default * @return string custom input field or empty string for default
*/ */
function editInput($table, $field, $attrs, $value) { function editInput(string $table, array $field, string $attrs, string $value) {
if ($field["type"] == "enum") { if ($field["type"] == "enum") {
return (isset($_GET["select"]) ? "<label><input type='radio'$attrs value='-1' checked><i>" . lang('original') . "</i></label> " : "") return (isset($_GET["select"]) ? "<label><input type='radio'$attrs value='-1' checked><i>" . lang('original') . "</i></label> " : "")
. ($field["null"] ? "<label><input type='radio'$attrs value=''" . ($value !== null || isset($_GET["select"]) ? "" : " checked") . "><i>NULL</i></label> " : "") . ($field["null"] ? "<label><input type='radio'$attrs value=''" . ($value !== null || isset($_GET["select"]) ? "" : " checked") . "><i>NULL</i></label> " : "")
@@ -744,20 +728,17 @@ class Adminer {
/** Get hint for edit field /** Get hint for edit field
* @param string $table table name * @param string $table table name
* @param Field $field single field from fields() * @param Field $field single field from fields()
* @param string $value
* @return string * @return string
*/ */
function editHint($table, $field, $value) { function editHint(string $table, array $field, string $value) {
return ""; return "";
} }
/** Process sent input /** Process sent input
* @param Field $field single field from fields() * @param Field $field single field from fields()
* @param string $value
* @param string $function
* @return string expression to use in a query * @return string expression to use in a query
*/ */
function processInput($field, $value, $function = "") { function processInput(array $field, string $value, string $function = "") {
if ($function == "SQL") { if ($function == "SQL") {
return $value; // SQL injection return $value; // SQL injection
} }
@@ -798,19 +779,16 @@ class Adminer {
} }
/** Export database structure /** Export database structure
* @param string $db
* @return void prints data * @return void prints data
*/ */
function dumpDatabase($db) { function dumpDatabase(string $db) {
} }
/** Export table structure /** Export table structure
* @param string $table
* @param string $style
* @param int $is_view 0 table, 1 view, 2 temporary view table * @param int $is_view 0 table, 1 view, 2 temporary view table
* @return void prints data * @return void prints data
*/ */
function dumpTable($table, $style, $is_view = 0) { function dumpTable(string $table, string $style, int $is_view = 0) {
if ($_POST["format"] != "sql") { if ($_POST["format"] != "sql") {
echo "\xef\xbb\xbf"; // UTF-8 byte order mark echo "\xef\xbb\xbf"; // UTF-8 byte order mark
if ($style) { if ($style) {
@@ -840,12 +818,9 @@ class Adminer {
} }
/** Export table data /** Export table data
* @param string $table
* @param string $style
* @param string $query
* @return void prints data * @return void prints data
*/ */
function dumpData($table, $style, $query) { function dumpData(string $table, string $style, string $query) {
global $connection; global $connection;
if ($style) { if ($style) {
$max_packet = (JUSH == "sqlite" ? 0 : 1048576); // default, minimum is 1024 $max_packet = (JUSH == "sqlite" ? 0 : 1048576); // default, minimum is 1024
@@ -934,19 +909,16 @@ class Adminer {
} }
/** Set export filename /** Set export filename
* @param string $identifier
* @return string filename without extension * @return string filename without extension
*/ */
function dumpFilename($identifier) { function dumpFilename(string $identifier) {
return friendly_url($identifier != "" ? $identifier : (SERVER != "" ? SERVER : "localhost")); return friendly_url($identifier != "" ? $identifier : (SERVER != "" ? SERVER : "localhost"));
} }
/** Send headers for export /** Send headers for export
* @param string $identifier
* @param bool $multi_table
* @return string extension * @return string extension
*/ */
function dumpHeaders($identifier, $multi_table = false) { function dumpHeaders(string $identifier, bool $multi_table = false) {
$output = $_POST["output"]; $output = $_POST["output"];
$ext = (preg_match('~sql~', $_POST["format"]) ? "sql" : ($multi_table ? "tar" : "csv")); // multiple CSV packed to TAR $ext = (preg_match('~sql~', $_POST["format"]) ? "sql" : ($multi_table ? "tar" : "csv")); // multiple CSV packed to TAR
header("Content-Type: " . header("Content-Type: " .
@@ -994,7 +966,7 @@ class Adminer {
* @param string $missing can be "auth" if there is no database connection, "db" if there is no database selected, "ns" with invalid schema * @param string $missing can be "auth" if there is no database connection, "db" if there is no database selected, "ns" with invalid schema
* @return void * @return void
*/ */
function navigation($missing) { function navigation(string $missing) {
global $VERSION, $drivers, $connection; global $VERSION, $drivers, $connection;
echo "<h1>" . $this->name() . " <span class='version'>$VERSION"; echo "<h1>" . $this->name() . " <span class='version'>$VERSION";
$new_version = $_COOKIE["adminer_version"]; $new_version = $_COOKIE["adminer_version"];
@@ -1055,7 +1027,7 @@ class Adminer {
* @param TableStatus[] $tables result of table_status('', true) * @param TableStatus[] $tables result of table_status('', true)
* @return void * @return void
*/ */
function syntaxHighlighting($tables) { function syntaxHighlighting(array $tables) {
global $connection; global $connection;
// this is matched by compile.php // this is matched by compile.php
echo script_src("../externals/jush/modules/jush.js"); echo script_src("../externals/jush/modules/jush.js");
@@ -1083,10 +1055,9 @@ class Adminer {
} }
/** Print databases list in menu /** Print databases list in menu
* @param string $missing
* @return void * @return void
*/ */
function databasesPrint($missing) { function databasesPrint(string $missing) {
global $adminer, $connection; global $adminer, $connection;
$databases = $this->databases(); $databases = $this->databases();
if (DB && $databases && !in_array(DB, $databases)) { if (DB && $databases && !in_array(DB, $databases)) {
@@ -1121,7 +1092,7 @@ class Adminer {
* @param TableStatus[] $tables result of table_status('', true) * @param TableStatus[] $tables result of table_status('', true)
* @return void * @return void
*/ */
function tablesPrint($tables) { function tablesPrint(array $tables) {
echo "<ul id='tables'>" . script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});"); echo "<ul id='tables'>" . script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");
foreach ($tables as $table => $status) { foreach ($tables as $table => $status) {
$name = $this->tableName($status); $name = $this->tableName($status);

View File

@@ -131,7 +131,7 @@ function unset_permanent() {
* @param string $error plain text * @param string $error plain text
* @return never * @return never
*/ */
function auth_error($error) { function auth_error(string $error) {
global $adminer, $has_token; global $adminer, $has_token;
$session_name = session_name(); $session_name = session_name();
if (isset($_GET["username"])) { if (isset($_GET["username"])) {

View File

@@ -14,37 +14,29 @@ abstract class SqlDb {
/** @var Result|bool */ protected $multi; // used for multiquery /** @var Result|bool */ protected $multi; // used for multiquery
/** Connect to server /** Connect to server
* @param string $server
* @param string $username
* @param string $password
* @return bool * @return bool
*/ */
abstract function connect($server, $username, $password); abstract function connect(string $server, string $username, string $password);
/** Quote string to use in SQL /** Quote string to use in SQL
* @param string $string
* @return string escaped string enclosed in ' * @return string escaped string enclosed in '
*/ */
abstract function quote($string); abstract function quote(string $string);
/** Select database /** Select database
* @param string $database
* @return bool * @return bool
*/ */
abstract function select_db($database); abstract function select_db(string $database);
/** Send query /** Send query
* @param string $query
* @param bool $unbuffered
* @return Result|bool * @return Result|bool
*/ */
abstract function query($query, $unbuffered = false); abstract function query(string $query, bool $unbuffered = false);
/** Send query with more resultsets /** Send query with more resultsets
* @param string $query
* @return Result|bool * @return Result|bool
*/ */
function multi_query($query) { function multi_query(string $query) {
return $this->multi = $this->query($query); return $this->multi = $this->query($query);
} }
@@ -63,11 +55,9 @@ abstract class SqlDb {
} }
/** Get single field from result /** Get single field from result
* @param string $query
* @param int $field
* @return string|bool * @return string|bool
*/ */
function result($query, $field = 0) { function result(string $query, int $field = 0) {
$result = $this->query($query); $result = $this->query($query);
if (!is_object($result)) { if (!is_object($result)) {
return false; return false;

View File

@@ -3,12 +3,11 @@ namespace Adminer;
/** Print HTML header /** Print HTML header
* @param string $title used in title, breadcrumb and heading, should be HTML escaped * @param string $title used in title, breadcrumb and heading, should be HTML escaped
* @param string $error
* @param mixed $breadcrumb ["key" => "link", "key2" => ["link", "desc"]], null for nothing, false for driver only, true for driver and server * @param mixed $breadcrumb ["key" => "link", "key2" => ["link", "desc"]], null for nothing, false for driver only, true for driver and server
* @param string $title2 used after colon in title and heading, should be HTML escaped * @param string $title2 used after colon in title and heading, should be HTML escaped
* @return void * @return void
*/ */
function page_header($title, $error = "", $breadcrumb = array(), $title2 = "") { function page_header(string $title, string $error = "", $breadcrumb = array(), string $title2 = "") {
global $LANG, $VERSION, $adminer, $drivers; global $LANG, $VERSION, $adminer, $drivers;
page_headers(); page_headers();
if (is_ajax() && $error) { if (is_ajax() && $error) {
@@ -176,10 +175,9 @@ function get_nonce() {
} }
/** Print flash and error messages /** Print flash and error messages
* @param string $error
* @return void * @return void
*/ */
function page_messages($error) { function page_messages(string $error) {
global $adminer; global $adminer;
$uri = preg_replace('~^[^?]*~', '', $_SERVER["REQUEST_URI"]); $uri = preg_replace('~^[^?]*~', '', $_SERVER["REQUEST_URI"]);
$messages = idx($_SESSION["messages"], $uri); $messages = idx($_SESSION["messages"], $uri);
@@ -199,7 +197,7 @@ function page_messages($error) {
* @param string $missing "auth", "db", "ns" * @param string $missing "auth", "db", "ns"
* @return void * @return void
*/ */
function page_footer($missing = "") { function page_footer(string $missing = "") {
global $adminer; global $adminer;
echo "</div>\n\n<div id='menu'>\n"; echo "</div>\n\n<div id='menu'>\n";
$adminer->navigation($missing); $adminer->navigation($missing);

View File

@@ -4,20 +4,17 @@ namespace Adminer;
$drivers = array(); $drivers = array();
/** Add a driver /** Add a driver
* @param string $id
* @param string $name
* @return void * @return void
*/ */
function add_driver($id, $name) { function add_driver(string $id, string $name) {
global $drivers; global $drivers;
$drivers[$id] = $name; $drivers[$id] = $name;
} }
/** Get driver name /** Get driver name
* @param string $id
* @return string * @return string
*/ */
function get_driver($id) { function get_driver(string $id) {
global $drivers; global $drivers;
return $drivers[$id]; return $drivers[$id];
} }
@@ -39,9 +36,8 @@ abstract class SqlDriver {
/** @var list<string> */ public $generated = array(); // allowed types of generated columns /** @var list<string> */ public $generated = array(); // allowed types of generated columns
/** Create object for performing database operations /** Create object for performing database operations
* @param Db $connection
*/ */
function __construct($connection) { function __construct(Db $connection) {
$this->conn = $connection; $this->conn = $connection;
} }
@@ -63,18 +59,17 @@ abstract class SqlDriver {
* @param Field $field * @param Field $field
* @return string|void * @return string|void
*/ */
function enumLength($field) { function enumLength(array $field) {
} }
/** Function used to convert the value inputted by user /** Function used to convert the value inputted by user
* @param Field $field * @param Field $field
* @return string|void * @return string|void
*/ */
function unconvertFunction($field) { function unconvertFunction(array $field) {
} }
/** Select data from table /** Select data from table
* @param string $table
* @param list<string> $select result of $adminer->selectColumnsProcess()[0] * @param list<string> $select result of $adminer->selectColumnsProcess()[0]
* @param list<string> $where result of $adminer->selectSearchProcess() * @param list<string> $where result of $adminer->selectSearchProcess()
* @param list<string> $group result of $adminer->selectColumnsProcess()[1] * @param list<string> $group result of $adminer->selectColumnsProcess()[1]
@@ -84,7 +79,7 @@ abstract class SqlDriver {
* @param bool $print whether to print the query * @param bool $print whether to print the query
* @return Result|false * @return Result|false
*/ */
function select($table, $select, $where, $group, $order = array(), $limit = 1, $page = 0, $print = false) { function select(string $table, array $select, array $where, array $group, array $order = array(), $limit = 1, int $page = 0, bool $print = false) {
global $adminer; global $adminer;
$is_group = (count($group) < count($select)); $is_group = (count($group) < count($select));
$query = $adminer->selectQueryBuild($select, $where, $group, $order, $limit, $page); $query = $adminer->selectQueryBuild($select, $where, $group, $order, $limit, $page);
@@ -106,25 +101,22 @@ abstract class SqlDriver {
} }
/** Delete data from table /** Delete data from table
* @param string $table
* @param string $queryWhere " WHERE ..." * @param string $queryWhere " WHERE ..."
* @param int $limit 0 or 1 * @param int $limit 0 or 1
* @return Result|bool * @return Result|bool
*/ */
function delete($table, $queryWhere, $limit = 0) { function delete(string $table, string $queryWhere, int $limit = 0) {
$query = "FROM " . table($table); $query = "FROM " . table($table);
return queries("DELETE" . ($limit ? limit1($table, $query, $queryWhere) : " $query$queryWhere")); return queries("DELETE" . ($limit ? limit1($table, $query, $queryWhere) : " $query$queryWhere"));
} }
/** Update data in table /** Update data in table
* @param string $table
* @param string[] $set escaped columns in keys, quoted data in values * @param string[] $set escaped columns in keys, quoted data in values
* @param string $queryWhere " WHERE ..." * @param string $queryWhere " WHERE ..."
* @param int $limit 0 or 1 * @param int $limit 0 or 1
* @param string $separator
* @return Result|bool * @return Result|bool
*/ */
function update($table, $set, $queryWhere, $limit = 0, $separator = "\n") { function update(string $table, array $set, string $queryWhere, int $limit = 0, string $separator = "\n") {
$values = array(); $values = array();
foreach ($set as $key => $val) { foreach ($set as $key => $val) {
$values[] = "$key = $val"; $values[] = "$key = $val";
@@ -134,11 +126,10 @@ abstract class SqlDriver {
} }
/** Insert data into table /** Insert data into table
* @param string $table
* @param string[] $set escaped columns in keys, quoted data in values * @param string[] $set escaped columns in keys, quoted data in values
* @return Result|bool * @return Result|bool
*/ */
function insert($table, $set) { function insert(string $table, array $set) {
return queries("INSERT INTO " . table($table) . ($set return queries("INSERT INTO " . table($table) . ($set
? " (" . implode(", ", array_keys($set)) . ")\nVALUES (" . implode(", ", $set) . ")" ? " (" . implode(", ", array_keys($set)) . ")\nVALUES (" . implode(", ", $set) . ")"
: " DEFAULT VALUES" : " DEFAULT VALUES"
@@ -146,20 +137,18 @@ abstract class SqlDriver {
} }
/** Get RETURNING clause for INSERT queries (PostgreSQL specific) /** Get RETURNING clause for INSERT queries (PostgreSQL specific)
* @param string $table
* @return string * @return string
*/ */
function insertReturning($table) { function insertReturning(string $table) {
return ""; return "";
} }
/** Insert or update data in table /** Insert or update data in table
* @param string $table
* @param list<string[]> $rows of arrays with escaped columns in keys and quoted data in values * @param list<string[]> $rows of arrays with escaped columns in keys and quoted data in values
* @param int[] $primary column names in keys * @param int[] $primary column names in keys
* @return Result|bool * @return Result|bool
*/ */
function insertUpdate($table, $rows, $primary) { function insertUpdate(string $table, array $rows, array $primary) {
return false; return false;
} }
@@ -185,11 +174,10 @@ abstract class SqlDriver {
} }
/** Return query with a timeout /** Return query with a timeout
* @param string $query
* @param int $timeout seconds * @param int $timeout seconds
* @return string|void null if the driver doesn't support query timeouts * @return string|void null if the driver doesn't support query timeouts
*/ */
function slowQuery($query, $timeout) { function slowQuery(string $query, int $timeout) {
} }
/** Convert column to be searchable /** Convert column to be searchable
@@ -198,24 +186,22 @@ abstract class SqlDriver {
* @param Field $field * @param Field $field
* @return string * @return string
*/ */
function convertSearch($idf, $val, $field) { function convertSearch(string $idf, array $val, array $field) {
return $idf; return $idf;
} }
/** Convert operator so it can be used in search /** Convert operator so it can be used in search
* @param string $operator
* @return string * @return string
*/ */
function convertOperator($operator) { function convertOperator(string $operator) {
return $operator; return $operator;
} }
/** Convert value returned by database to actual value /** Convert value returned by database to actual value
* @param string $val
* @param Field $field * @param Field $field
* @return string * @return string
*/ */
function value($val, $field) { function value(string $val, array $field) {
return (method_exists($this->conn, 'value') return (method_exists($this->conn, 'value')
? $this->conn->value($val, $field) ? $this->conn->value($val, $field)
: (is_resource($val) ? stream_get_contents($val) : $val) : (is_resource($val) ? stream_get_contents($val) : $val)
@@ -223,10 +209,9 @@ abstract class SqlDriver {
} }
/** Quote binary string /** Quote binary string
* @param string $s
* @return string * @return string
*/ */
function quoteBinary($s) { function quoteBinary(string $s) {
return q($s); return q($s);
} }
@@ -237,11 +222,9 @@ abstract class SqlDriver {
} }
/** Get help link for table /** Get help link for table
* @param string $name
* @param bool $is_view
* @return string|void relative URL * @return string|void relative URL
*/ */
function tableHelp($name, $is_view = false) { function tableHelp(string $name, bool $is_view = false) {
} }
/** Check if C-style escapes are supported /** Check if C-style escapes are supported
@@ -262,15 +245,14 @@ abstract class SqlDriver {
* @param TableStatus $table_status result of table_status1() * @param TableStatus $table_status result of table_status1()
* @return bool * @return bool
*/ */
function supportsIndex($table_status) { function supportsIndex(array $table_status) {
return !is_view($table_status); return !is_view($table_status);
} }
/** Get defined check constraints /** Get defined check constraints
* @param string $table
* @return string[] [$name => $clause] * @return string[] [$name => $clause]
*/ */
function checkConstraints($table) { function checkConstraints(string $table) {
// MariaDB contains CHECK_CONSTRAINTS.TABLE_NAME, MySQL and PostrgreSQL not // MariaDB contains CHECK_CONSTRAINTS.TABLE_NAME, MySQL and PostrgreSQL not
return get_key_vals("SELECT c.CONSTRAINT_NAME, CHECK_CLAUSE return get_key_vals("SELECT c.CONSTRAINT_NAME, CHECK_CLAUSE
FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS c FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS c

View File

@@ -7,10 +7,9 @@ namespace Adminer;
* @param Result $result * @param Result $result
* @param Db $connection2 connection to examine indexes * @param Db $connection2 connection to examine indexes
* @param string[] $orgtables * @param string[] $orgtables
* @param int $limit
* @return string[] $orgtables * @return string[] $orgtables
*/ */
function select($result, $connection2 = null, $orgtables = array(), $limit = 0) { function select($result, Db $connection2 = null, array $orgtables = array(), int $limit = 0) {
$links = array(); // colno => orgtable - create links from these columns $links = array(); // colno => orgtable - create links from these columns
$indexes = array(); // orgtable => array(column => colno) - primary keys $indexes = array(); // orgtable => array(column => colno) - primary keys
$columns = array(); // orgtable => array(column => ) - not selected columns in primary key $columns = array(); // orgtable => array(column => ) - not selected columns in primary key
@@ -101,10 +100,9 @@ function select($result, $connection2 = null, $orgtables = array(), $limit = 0)
} }
/** Get referencable tables with single column primary key except self /** Get referencable tables with single column primary key except self
* @param string $self
* @return array<string, Field> [$table_name => $field] * @return array<string, Field> [$table_name => $field]
*/ */
function referencable_primary($self) { function referencable_primary(string $self) {
$return = array(); // table_name => field $return = array(); // table_name => field
foreach (table_status('', true) as $table_name => $table) { foreach (table_status('', true) as $table_name => $table) {
if ($table_name != $self && fk_support($table)) { if ($table_name != $self && fk_support($table)) {
@@ -123,13 +121,10 @@ function referencable_primary($self) {
} }
/** Print SQL <textarea> tag /** Print SQL <textarea> tag
* @param string $name
* @param string|list<array{string}> $value * @param string|list<array{string}> $value
* @param int $rows
* @param int $cols
* @return void * @return void
*/ */
function textarea($name, $value, $rows = 10, $cols = 80) { function textarea(string $name, $value, int $rows = 10, int $cols = 80) {
echo "<textarea name='" . h($name) . "' rows='$rows' cols='$cols' class='sqlarea jush-" . JUSH . "' spellcheck='false' wrap='off'>"; echo "<textarea name='" . h($name) . "' rows='$rows' cols='$cols' class='sqlarea jush-" . JUSH . "' spellcheck='false' wrap='off'>";
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $val) { // not implode() to save memory foreach ($value as $val) { // not implode() to save memory
@@ -142,14 +137,10 @@ function textarea($name, $value, $rows = 10, $cols = 80) {
} }
/** Generate HTML <select> or <input> if $options are empty /** Generate HTML <select> or <input> if $options are empty
* @param string $attrs
* @param string[] $options * @param string[] $options
* @param string $value
* @param string $onchange
* @param string $placeholder
* @return string * @return string
*/ */
function select_input($attrs, $options, $value = "", $onchange = "", $placeholder = "") { function select_input(string $attrs, array $options, string $value = "", string $onchange = "", string $placeholder = "") {
$tag = ($options ? "select" : "input"); $tag = ($options ? "select" : "input");
return "<$tag$attrs" . ($options return "<$tag$attrs" . ($options
? "><option value=''>$placeholder" . optionlist($options, $value, true) . "</select>" ? "><option value=''>$placeholder" . optionlist($options, $value, true) . "</select>"
@@ -162,7 +153,7 @@ function select_input($attrs, $options, $value = "", $onchange = "", $placeholde
* @param string|int $val * @param string|int $val
* @return void * @return void
*/ */
function json_row($key, $val = null) { function json_row(string $key, $val = null) {
static $first = true; static $first = true;
if ($first) { if ($first) {
echo "{"; echo "{";
@@ -177,14 +168,13 @@ function json_row($key, $val = null) {
} }
/** Print table columns for type edit /** Print table columns for type edit
* @param string $key
* @param Field $field * @param Field $field
* @param list<string> $collations * @param list<string> $collations
* @param string[] $foreign_keys * @param string[] $foreign_keys
* @param list<string> $extra_types extra types to prepend * @param list<string> $extra_types extra types to prepend
* @return void * @return void
*/ */
function edit_type($key, $field, $collations, $foreign_keys = array(), $extra_types = array()) { function edit_type(string $key, array $field, array $collations, array $foreign_keys = array(), array $extra_types = array()) {
global $driver; global $driver;
$type = $field["type"]; $type = $field["type"];
echo "<td><select name='" . h($key) . "[type]' class='type' aria-labelledby='label-type'>"; echo "<td><select name='" . h($key) . "[type]' class='type' aria-labelledby='label-type'>";
@@ -217,10 +207,9 @@ function edit_type($key, $field, $collations, $foreign_keys = array(), $extra_ty
} }
/** Get partition info /** Get partition info
* @param string $table
* @return array{partition_by:string, partition:string, partitions:string, partition_names:list<string>, partition_values:list<string>} * @return array{partition_by:string, partition:string, partitions:string, partition_names:list<string>, partition_values:list<string>}
*/ */
function get_partitions_info($table) { function get_partitions_info(string $table) {
global $connection; global $connection;
$from = "FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = " . q(DB) . " AND TABLE_NAME = " . q($table); $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"); $result = $connection->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $from ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");
@@ -233,10 +222,9 @@ function get_partitions_info($table) {
} }
/** Filter length value including enums /** Filter length value including enums
* @param string $length
* @return string * @return string
*/ */
function process_length($length) { function process_length(string $length) {
global $driver; global $driver;
$enum_length = $driver->enumLength; $enum_length = $driver->enumLength;
return (preg_match("~^\\s*\\(?\\s*$enum_length(?:\\s*,\\s*$enum_length)*+\\s*\\)?\\s*\$~", $length) && preg_match_all("~$enum_length~", $length, $matches) return (preg_match("~^\\s*\\(?\\s*$enum_length(?:\\s*,\\s*$enum_length)*+\\s*\\)?\\s*\$~", $length) && preg_match_all("~$enum_length~", $length, $matches)
@@ -247,10 +235,9 @@ function process_length($length) {
/** Create SQL string from field type /** Create SQL string from field type
* @param FieldType $field * @param FieldType $field
* @param string $collate
* @return string * @return string
*/ */
function process_type($field, $collate = "COLLATE") { function process_type(array $field, string $collate = "COLLATE") {
global $driver; global $driver;
return " $field[type]" return " $field[type]"
. process_length($field["length"]) . process_length($field["length"])
@@ -264,7 +251,7 @@ function process_type($field, $collate = "COLLATE") {
* @param Field $type_field information about field type * @param Field $type_field information about field type
* @return list<string> ["field", "type", "NULL", "DEFAULT", "ON UPDATE", "COMMENT", "AUTO_INCREMENT"] * @return list<string> ["field", "type", "NULL", "DEFAULT", "ON UPDATE", "COMMENT", "AUTO_INCREMENT"]
*/ */
function process_field($field, $type_field) { function process_field(array $field, array $type_field) {
// MariaDB exports CURRENT_TIMESTAMP as a function. // MariaDB exports CURRENT_TIMESTAMP as a function.
if ($field["on_update"]) { if ($field["on_update"]) {
$field["on_update"] = str_ireplace("current_timestamp()", "CURRENT_TIMESTAMP", $field["on_update"]); $field["on_update"] = str_ireplace("current_timestamp()", "CURRENT_TIMESTAMP", $field["on_update"]);
@@ -284,7 +271,7 @@ function process_field($field, $type_field) {
* @param Field $field * @param Field $field
* @return string * @return string
*/ */
function default_value($field) { function default_value(array $field) {
global $driver; global $driver;
$default = $field["default"]; $default = $field["default"];
$generated = $field["generated"]; $generated = $field["generated"];
@@ -298,10 +285,9 @@ function default_value($field) {
} }
/** Get type class to use in CSS /** Get type class to use in CSS
* @param string $type
* @return string|void class='' * @return string|void class=''
*/ */
function type_class($type) { function type_class(string $type) {
foreach ( foreach (
array( array(
'char' => 'text', 'char' => 'text',
@@ -323,7 +309,7 @@ function type_class($type) {
* @param string[] $foreign_keys * @param string[] $foreign_keys
* @return void * @return void
*/ */
function edit_fields($fields, $collations, $type = "TABLE", $foreign_keys = array()) { function edit_fields(array $fields, array $collations, $type = "TABLE", array $foreign_keys = array()) {
global $driver; global $driver;
$fields = array_values($fields); $fields = array_values($fields);
$default_class = (($_POST ? $_POST["defaults"] : get_setting("defaults")) ? "" : " class='hidden'"); $default_class = (($_POST ? $_POST["defaults"] : get_setting("defaults")) ? "" : " class='hidden'");
@@ -385,7 +371,7 @@ function edit_fields($fields, $collations, $type = "TABLE", $foreign_keys = arra
* @param Field[] $fields * @param Field[] $fields
* @return bool * @return bool
*/ */
function process_fields(&$fields) { function process_fields(&array $fields) {
$offset = 0; $offset = 0;
if ($_POST["up"]) { if ($_POST["up"]) {
$last = 0; $last = 0;
@@ -426,7 +412,7 @@ function process_fields(&$fields) {
* @param list<string> $match * @param list<string> $match
* @return string * @return string
*/ */
function normalize_enum($match) { function normalize_enum(array $match) {
$val = $match[0]; $val = $match[0];
return "'" . str_replace("'", "''", addcslashes(stripcslashes(str_replace($val[0] . $val[0], $val[0], substr($val, 1, -1))), '\\')) . "'"; return "'" . str_replace("'", "''", addcslashes(stripcslashes(str_replace($val[0] . $val[0], $val[0], substr($val, 1, -1))), '\\')) . "'";
} }
@@ -434,11 +420,9 @@ function normalize_enum($match) {
/** Issue grant or revoke commands /** Issue grant or revoke commands
* @param string $grant GRANT or REVOKE * @param string $grant GRANT or REVOKE
* @param list<string> $privileges * @param list<string> $privileges
* @param string $columns
* @param string $on
* @return Result|bool * @return Result|bool
*/ */
function grant($grant, $privileges, $columns, $on) { function grant(string $grant, array $privileges, string $columns, string $on) {
if (!$privileges) { if (!$privileges) {
return true; return true;
} }
@@ -458,15 +442,9 @@ function grant($grant, $privileges, $columns, $on) {
* @param string $drop_created drop new object query * @param string $drop_created drop new object query
* @param string $test create test object query * @param string $test create test object query
* @param string $drop_test drop test object query * @param string $drop_test drop test object query
* @param string $location
* @param string $message_drop
* @param string $message_alter
* @param string $message_create
* @param string $old_name
* @param string $new_name
* @return void redirect on success * @return void redirect on success
*/ */
function drop_create($drop, $create, $drop_created, $test, $drop_test, $location, $message_drop, $message_alter, $message_create, $old_name, $new_name) { function drop_create(string $drop, string $create, string $drop_created, string $test, string $drop_test, string $location, string $message_drop, string $message_alter, string $message_create, string $old_name, string $new_name) {
if ($_POST["drop"]) { if ($_POST["drop"]) {
query_redirect($drop, $location, $message_drop); query_redirect($drop, $location, $message_drop);
} elseif ($old_name == "") { } elseif ($old_name == "") {
@@ -487,11 +465,10 @@ function drop_create($drop, $create, $drop_created, $test, $drop_test, $location
} }
/** Generate SQL query for creating trigger /** Generate SQL query for creating trigger
* @param string $on
* @param Trigger $row result of trigger() * @param Trigger $row result of trigger()
* @return string * @return string
*/ */
function create_trigger($on, $row) { function create_trigger(string $on, array $row) {
$timing_event = " $row[Timing] $row[Event]" . (preg_match('~ OF~', $row["Event"]) ? " $row[Of]" : ""); // SQL injection $timing_event = " $row[Timing] $row[Event]" . (preg_match('~ OF~', $row["Event"]) ? " $row[Of]" : ""); // SQL injection
return "CREATE TRIGGER " return "CREATE TRIGGER "
. idf_escape($row["Trigger"]) . idf_escape($row["Trigger"])
@@ -506,7 +483,7 @@ function create_trigger($on, $row) {
* @param Routine $row result of routine() * @param Routine $row result of routine()
* @return string * @return string
*/ */
function create_routine($routine, $row) { function create_routine($routine, array $row) {
global $driver; global $driver;
$set = array(); $set = array();
$fields = (array) $row["fields"]; $fields = (array) $row["fields"];
@@ -527,10 +504,9 @@ function create_routine($routine, $row) {
} }
/** Remove current user definer from SQL command /** Remove current user definer from SQL command
* @param string $query
* @return string * @return string
*/ */
function remove_definer($query) { function remove_definer(string $query) {
return preg_replace('~^([A-Z =]+) DEFINER=`' . preg_replace('~@(.*)~', '`@`(%|\1)', logged_user()) . '`~', '\1', $query); //! proper escaping of user return preg_replace('~^([A-Z =]+) DEFINER=`' . preg_replace('~@(.*)~', '`@`(%|\1)', logged_user()) . '`~', '\1', $query); //! proper escaping of user
} }
@@ -538,7 +514,7 @@ function remove_definer($query) {
* @param ForeignKey $foreign_key * @param ForeignKey $foreign_key
* @return string * @return string
*/ */
function format_foreign_key($foreign_key) { function format_foreign_key(array $foreign_key) {
global $driver; global $driver;
$db = $foreign_key["db"]; $db = $foreign_key["db"];
$ns = $foreign_key["ns"]; $ns = $foreign_key["ns"];
@@ -553,11 +529,10 @@ function format_foreign_key($foreign_key) {
} }
/** Add a file to TAR /** Add a file to TAR
* @param string $filename
* @param TmpFile $tmp_file * @param TmpFile $tmp_file
* @return void prints the output * @return void prints the output
*/ */
function tar_file($filename, $tmp_file) { function tar_file(string $filename, $tmp_file) {
$return = pack("a100a8a8a8a12a12", $filename, 644, 0, 0, decoct($tmp_file->size), decoct(time())); $return = pack("a100a8a8a8a12a12", $filename, 644, 0, 0, decoct($tmp_file->size), decoct(time()));
$checksum = 8*32; // space for checksum itself $checksum = 8*32; // space for checksum itself
for ($i=0; $i < strlen($return); $i++) { for ($i=0; $i < strlen($return); $i++) {
@@ -571,10 +546,9 @@ function tar_file($filename, $tmp_file) {
} }
/** Get INI bytes value /** Get INI bytes value
* @param string $ini
* @return int * @return int
*/ */
function ini_bytes($ini) { function ini_bytes(string $ini) {
$val = ini_get($ini); $val = ini_get($ini);
switch (strtolower(substr($val, -1))) { switch (strtolower(substr($val, -1))) {
case 'g': case 'g':
@@ -592,7 +566,7 @@ function ini_bytes($ini) {
* @param string $text HTML code * @param string $text HTML code
* @return string HTML code * @return string HTML code
*/ */
function doc_link($paths, $text = "<sup>?</sup>") { function doc_link(array $paths, string $text = "<sup>?</sup>") {
global $connection; global $connection;
$server_info = $connection->server_info; $server_info = $connection->server_info;
$version = preg_replace('~^(\d\.?\d).*~s', '\1', $server_info); // two most significant digits $version = preg_replace('~^(\d\.?\d).*~s', '\1', $server_info); // two most significant digits
@@ -611,10 +585,9 @@ function doc_link($paths, $text = "<sup>?</sup>") {
} }
/** Compute size of database /** Compute size of database
* @param string $db
* @return string formatted * @return string formatted
*/ */
function db_size($db) { function db_size(string $db) {
global $connection; global $connection;
if (!$connection->select_db($db)) { if (!$connection->select_db($db)) {
return "?"; return "?";
@@ -627,10 +600,9 @@ function db_size($db) {
} }
/** Print SET NAMES if utf8mb4 might be needed /** Print SET NAMES if utf8mb4 might be needed
* @param string $create
* @return void * @return void
*/ */
function set_utf8mb4($create) { function set_utf8mb4(string $create) {
global $connection; global $connection;
static $set = false; static $set = false;
if (!$set && preg_match('~\butf8mb4~i', $create)) { // possible false positive if (!$set && preg_match('~\butf8mb4~i', $create)) { // possible false positive

View File

@@ -40,7 +40,7 @@ function version() {
* @param string $idf text inside `` * @param string $idf text inside ``
* @return string * @return string
*/ */
function idf_unescape($idf) { function idf_unescape(string $idf) {
if (!preg_match('~^[`\'"[]~', $idf)) { if (!preg_match('~^[`\'"[]~', $idf)) {
return $idf; return $idf;
} }
@@ -49,19 +49,17 @@ function idf_unescape($idf) {
} }
/** Shortcut for $connection->quote($string) /** Shortcut for $connection->quote($string)
* @param string $string
* @return string * @return string
*/ */
function q($string) { function q(string $string) {
global $connection; global $connection;
return $connection->quote($string); return $connection->quote($string);
} }
/** Escape string to use inside '' /** Escape string to use inside ''
* @param string $val
* @return string * @return string
*/ */
function escape_string($val) { function escape_string(string $val) {
return substr(q($val), 1, -1); return substr(q($val), 1, -1);
} }
@@ -72,15 +70,14 @@ function escape_string($val) {
* @param mixed $default * @param mixed $default
* @return mixed * @return mixed
*/ */
function idx($array, $key, $default = null) { function idx(?array $array, $key, $default = null) {
return ($array && array_key_exists($key, $array) ? $array[$key] : $default); return ($array && array_key_exists($key, $array) ? $array[$key] : $default);
} }
/** Remove non-digits from a string /** Remove non-digits from a string
* @param string $val
* @return string * @return string
*/ */
function number($val) { function number(string $val) {
return preg_replace('~[^0-9]+~', '', $val); return preg_replace('~[^0-9]+~', '', $val);
} }
@@ -96,7 +93,7 @@ function number_type() {
* @param bool $filter whether to leave values as is * @param bool $filter whether to leave values as is
* @return void modified in place * @return void modified in place
*/ */
function remove_slashes($process, $filter = false) { function remove_slashes(array $process, bool $filter = false) {
if (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()) { if (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()) {
while (list($key, $val) = each($process)) { while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) { foreach ($val as $k => $v) {
@@ -113,11 +110,9 @@ function remove_slashes($process, $filter = false) {
} }
/** Escape or unescape string to use inside form [] /** Escape or unescape string to use inside form []
* @param string $idf
* @param bool $back
* @return string * @return string
*/ */
function bracket_escape($idf, $back = false) { function bracket_escape(string $idf, bool $back = false) {
// escape brackets inside name="x[]" // escape brackets inside name="x[]"
static $trans = array(':' => ':1', ']' => ':2', '[' => ':3', '"' => ':4'); static $trans = array(':' => ':1', ']' => ':2', '[' => ':3', '"' => ':4');
return strtr($idf, ($back ? array_flip($trans) : $trans)); return strtr($idf, ($back ? array_flip($trans) : $trans));
@@ -129,7 +124,7 @@ function bracket_escape($idf, $back = false) {
* @param Db $connection2 defaults to $connection * @param Db $connection2 defaults to $connection
* @return bool * @return bool
*/ */
function min_version($version, $maria_db = "", $connection2 = null) { function min_version($version, $maria_db = "", Db $connection2 = null) {
global $connection; global $connection;
if (!$connection2) { if (!$connection2) {
$connection2 = $connection; $connection2 = $connection;
@@ -143,18 +138,16 @@ function min_version($version, $maria_db = "", $connection2 = null) {
} }
/** Get connection charset /** Get connection charset
* @param Db $connection
* @return string * @return string
*/ */
function charset($connection) { function charset(Db $connection) {
return (min_version("5.5.3", 0, $connection) ? "utf8mb4" : "utf8"); // SHOW CHARSET would require an extra query return (min_version("5.5.3", 0, $connection) ? "utf8mb4" : "utf8"); // SHOW CHARSET would require an extra query
} }
/** Get INI boolean value /** Get INI boolean value
* @param string $ini
* @return bool * @return bool
*/ */
function ini_bool($ini) { function ini_bool(string $ini) {
$val = ini_get($ini); $val = ini_get($ini);
return (preg_match('~^(on|true|yes)$~i', $val) || (int) $val); // boolean values set by php_value are strings return (preg_match('~^(on|true|yes)$~i', $val) || (int) $val); // boolean values set by php_value are strings
} }
@@ -171,13 +164,9 @@ function sid() {
} }
/** Set password to session /** Set password to session
* @param string $vendor
* @param string $server
* @param string $username
* @param ?string $password
* @return void * @return void
*/ */
function set_password($vendor, $server, $username, $password) { function set_password(string $vendor, string $server, string $username, ?string $password) {
$_SESSION["pwds"][$vendor][$server][$username] = ($_COOKIE["adminer_key"] && is_string($password) $_SESSION["pwds"][$vendor][$server][$username] = ($_COOKIE["adminer_key"] && is_string($password)
? array(encrypt_string($password, $_COOKIE["adminer_key"])) ? array(encrypt_string($password, $_COOKIE["adminer_key"]))
: $password : $password
@@ -199,21 +188,18 @@ function get_password() {
} }
/** Get single value from database /** Get single value from database
* @param string $query
* @param int $field
* @return string or false if error * @return string or false if error
*/ */
function get_val($query, $field = 0) { function get_val(string $query, int $field = 0) {
global $connection; global $connection;
return $connection->result($query, $field); return $connection->result($query, $field);
} }
/** Get list of values from database /** Get list of values from database
* @param string $query
* @param mixed $column * @param mixed $column
* @return list<string> * @return list<string>
*/ */
function get_vals($query, $column = 0) { function get_vals(string $query, $column = 0) {
global $connection; global $connection;
$return = array(); $return = array();
$result = $connection->query($query); $result = $connection->query($query);
@@ -226,12 +212,9 @@ function get_vals($query, $column = 0) {
} }
/** Get keys from first column and values from second /** Get keys from first column and values from second
* @param string $query
* @param Db $connection2
* @param bool $set_keys
* @return string[] * @return string[]
*/ */
function get_key_vals($query, $connection2 = null, $set_keys = true) { function get_key_vals(string $query, Db $connection2 = null, bool $set_keys = true) {
global $connection; global $connection;
if (!is_object($connection2)) { if (!is_object($connection2)) {
$connection2 = $connection; $connection2 = $connection;
@@ -251,12 +234,9 @@ function get_key_vals($query, $connection2 = null, $set_keys = true) {
} }
/** Get all rows of result /** Get all rows of result
* @param string $query
* @param Db $connection2
* @param string $error
* @return list<string[]> of associative arrays * @return list<string[]> of associative arrays
*/ */
function get_rows($query, $connection2 = null, $error = "<p class='error'>") { function get_rows(string $query, Db $connection2 = null, string $error = "<p class='error'>") {
global $connection; global $connection;
$conn = (is_object($connection2) ? $connection2 : $connection); $conn = (is_object($connection2) ? $connection2 : $connection);
$return = array(); $return = array();
@@ -276,7 +256,7 @@ function get_rows($query, $connection2 = null, $error = "<p class='error'>") {
* @param Index[] $indexes result of indexes() * @param Index[] $indexes result of indexes()
* @return string[]|void null if there is no unique identifier * @return string[]|void null if there is no unique identifier
*/ */
function unique_array($row, $indexes) { function unique_array(array $row, array $indexes) {
foreach ($indexes as $index) { foreach ($indexes as $index) {
if (preg_match("~PRIMARY|UNIQUE~", $index["type"])) { if (preg_match("~PRIMARY|UNIQUE~", $index["type"])) {
$return = array(); $return = array();
@@ -292,10 +272,9 @@ function unique_array($row, $indexes) {
} }
/** Escape column key used in where() /** Escape column key used in where()
* @param string $key
* @return string * @return string
*/ */
function escape_key($key) { function escape_key(string $key) {
if (preg_match('(^([\w(]+)(' . str_replace("_", ".*", preg_quote(idf_escape("_"))) . ')([ \w)]+)$)', $key, $match)) { //! columns looking like functions if (preg_match('(^([\w(]+)(' . str_replace("_", ".*", preg_quote(idf_escape("_"))) . ')([ \w)]+)$)', $key, $match)) { //! columns looking like functions
return $match[1] . idf_escape(idf_unescape($match[2])) . $match[3]; //! SQL injection return $match[1] . idf_escape(idf_unescape($match[2])) . $match[3]; //! SQL injection
} }
@@ -307,7 +286,7 @@ function escape_key($key) {
* @param Field[] $fields * @param Field[] $fields
* @return string * @return string
*/ */
function where($where, $fields = array()) { function where(array $where, array $fields = array()) {
global $connection; global $connection;
$return = array(); $return = array();
foreach ((array) $where["where"] as $key => $val) { foreach ((array) $where["where"] as $key => $val) {
@@ -332,11 +311,10 @@ function where($where, $fields = array()) {
} }
/** Create SQL condition from query string /** Create SQL condition from query string
* @param string $val
* @param Field[] $fields * @param Field[] $fields
* @return string * @return string
*/ */
function where_check($val, $fields = array()) { function where_check(string $val, array $fields = array()) {
parse_str($val, $check); parse_str($val, $check);
remove_slashes(array(&$check)); remove_slashes(array(&$check));
return where($check, $fields); return where($check, $fields);
@@ -345,11 +323,9 @@ function where_check($val, $fields = array()) {
/** Create query string where condition from value /** Create query string where condition from value
* @param int $i condition order * @param int $i condition order
* @param string $column column identifier * @param string $column column identifier
* @param string $value
* @param string $operator
* @return string * @return string
*/ */
function where_link($i, $column, $value, $operator = "=") { function where_link(int $i, string $column, string $value, string $operator = "=") {
return "&where%5B$i%5D%5Bcol%5D=" . urlencode($column) . "&where%5B$i%5D%5Bop%5D=" . urlencode(($value !== null ? $operator : "IS NULL")) . "&where%5B$i%5D%5Bval%5D=" . urlencode($value); return "&where%5B$i%5D%5Bcol%5D=" . urlencode($column) . "&where%5B$i%5D%5Bop%5D=" . urlencode(($value !== null ? $operator : "IS NULL")) . "&where%5B$i%5D%5Bval%5D=" . urlencode($value);
} }
@@ -359,7 +335,7 @@ function where_link($i, $column, $value, $operator = "=") {
* @param list<string> $select * @param list<string> $select
* @return string * @return string
*/ */
function convert_fields($columns, $fields, $select = array()) { function convert_fields(array $columns, array $fields, array $select = array()) {
$return = ""; $return = "";
foreach ($columns as $key => $val) { foreach ($columns as $key => $val) {
if ($select && !in_array(idf_escape($key), $select)) { if ($select && !in_array(idf_escape($key), $select)) {
@@ -374,12 +350,10 @@ function convert_fields($columns, $fields, $select = array()) {
} }
/** Set cookie valid on current path /** Set cookie valid on current path
* @param string $name
* @param string $value
* @param int $lifetime number of seconds, 0 for session cookie, 2592000 - 30 days * @param int $lifetime number of seconds, 0 for session cookie, 2592000 - 30 days
* @return void * @return void
*/ */
function cookie($name, $value, $lifetime = 2592000) { function cookie(string $name, string $value, int $lifetime = 2592000) {
global $HTTPS; global $HTTPS;
header( header(
"Set-Cookie: $name=" . urlencode($value) "Set-Cookie: $name=" . urlencode($value)
@@ -392,30 +366,26 @@ function cookie($name, $value, $lifetime = 2592000) {
} }
/** Get settings stored in a cookie /** Get settings stored in a cookie
* @param string $cookie
* @return mixed[] * @return mixed[]
*/ */
function get_settings($cookie) { function get_settings(string $cookie) {
parse_str($_COOKIE[$cookie], $settings); parse_str($_COOKIE[$cookie], $settings);
return $settings; return $settings;
} }
/** Get setting stored in a cookie /** Get setting stored in a cookie
* @param string $key
* @param string $cookie
* @return mixed * @return mixed
*/ */
function get_setting($key, $cookie = "adminer_settings") { function get_setting(string $key, string $cookie = "adminer_settings") {
$settings = get_settings($cookie); $settings = get_settings($cookie);
return $settings[$key]; return $settings[$key];
} }
/** Store settings to a cookie /** Store settings to a cookie
* @param mixed[] $settings * @param mixed[] $settings
* @param string $cookie
* @return void * @return void
*/ */
function save_settings($settings, $cookie = "adminer_settings") { function save_settings(array $settings, string $cookie = "adminer_settings") {
cookie($cookie, http_build_query($settings + get_settings($cookie))); cookie($cookie, http_build_query($settings + get_settings($cookie)));
} }
@@ -429,10 +399,9 @@ function restart_session() {
} }
/** Stop session if possible /** Stop session if possible
* @param bool $force
* @return void * @return void
*/ */
function stop_session($force = false) { function stop_session(bool $force = false) {
$use_cookies = ini_bool("session.use_cookies"); $use_cookies = ini_bool("session.use_cookies");
if (!$use_cookies || $force) { if (!$use_cookies || $force) {
session_write_close(); // improves concurrency if a user opens several pages at once, may be restarted later session_write_close(); // improves concurrency if a user opens several pages at once, may be restarted later
@@ -443,30 +412,24 @@ function stop_session($force = false) {
} }
/** Get session variable for current server /** Get session variable for current server
* @param string $key
* @return mixed * @return mixed
*/ */
function &get_session($key) { function &get_session(string $key) {
return $_SESSION[$key][DRIVER][SERVER][$_GET["username"]]; return $_SESSION[$key][DRIVER][SERVER][$_GET["username"]];
} }
/** Set session variable for current server /** Set session variable for current server
* @param string $key
* @param mixed $val * @param mixed $val
* @return mixed * @return mixed
*/ */
function set_session($key, $val) { function set_session(string $key, $val) {
$_SESSION[$key][DRIVER][SERVER][$_GET["username"]] = $val; // used also in auth.inc.php $_SESSION[$key][DRIVER][SERVER][$_GET["username"]] = $val; // used also in auth.inc.php
} }
/** Get authenticated URL /** Get authenticated URL
* @param string $vendor
* @param string $server
* @param string $username
* @param string $db
* @return string * @return string
*/ */
function auth_url($vendor, $server, $username, $db = null) { function auth_url(string $vendor, string $server, string $username, string $db = null) {
global $drivers; global $drivers;
$uri = remove_from_uri(implode("|", array_keys($drivers)) $uri = remove_from_uri(implode("|", array_keys($drivers))
. "|username|ext|" . "|username|ext|"
@@ -494,10 +457,9 @@ function is_ajax() {
/** Send Location header and exit /** Send Location header and exit
* @param string $location null to only set a message * @param string $location null to only set a message
* @param string $message
* @return void * @return void
*/ */
function redirect($location, $message = null) { function redirect(string $location, string $message = null) {
if ($message !== null) { if ($message !== null) {
restart_session(); restart_session();
$_SESSION["messages"][preg_replace('~^[^?]*~', '', ($location !== null ? $location : $_SERVER["REQUEST_URI"]))][] = $message; $_SESSION["messages"][preg_replace('~^[^?]*~', '', ($location !== null ? $location : $_SERVER["REQUEST_URI"]))][] = $message;
@@ -512,16 +474,9 @@ function redirect($location, $message = null) {
} }
/** Execute query and redirect if successful /** Execute query and redirect if successful
* @param string $query
* @param string $location
* @param string $message
* @param bool $redirect
* @param bool $execute
* @param bool $failed
* @param string $time
* @return bool * @return bool
*/ */
function query_redirect($query, $location, $message, $redirect = true, $execute = true, $failed = false, $time = "") { function query_redirect(string $query, string $location, string $message, bool $redirect = true, bool $execute = true, bool $failed = false, string $time = "") {
global $connection, $error, $adminer; global $connection, $error, $adminer;
if ($execute) { if ($execute) {
$start = microtime(true); $start = microtime(true);
@@ -551,7 +506,7 @@ class Queries {
* @param string $query end with ';' to use DELIMITER * @param string $query end with ';' to use DELIMITER
* @return Result|bool * @return Result|bool
*/ */
function queries($query) { function queries(string $query) {
global $connection; global $connection;
if (!Queries::$start) { if (!Queries::$start) {
Queries::$start = microtime(true); Queries::$start = microtime(true);
@@ -561,12 +516,11 @@ function queries($query) {
} }
/** Apply command to all array items /** Apply command to all array items
* @param string $query
* @param list<string> $tables * @param list<string> $tables
* @param callable(string):string $escape * @param callable(string):string $escape
* @return bool * @return bool
*/ */
function apply_queries($query, $tables, $escape = 'Adminer\table') { function apply_queries(string $query, array $tables, callable $escape = 'Adminer\table') {
foreach ($tables as $table) { foreach ($tables as $table) {
if (!queries("$query " . $escape($table))) { if (!queries("$query " . $escape($table))) {
return false; return false;
@@ -576,12 +530,9 @@ function apply_queries($query, $tables, $escape = 'Adminer\table') {
} }
/** Redirect by remembered queries /** Redirect by remembered queries
* @param string $location
* @param string $message
* @param bool $redirect
* @return bool * @return bool
*/ */
function queries_redirect($location, $message, $redirect) { function queries_redirect(string $location, string $message, bool $redirect) {
$queries = implode("\n", Queries::$queries); $queries = implode("\n", Queries::$queries);
$time = format_time(Queries::$start); $time = format_time(Queries::$start);
return query_redirect($queries, $location, $message, $redirect, false, !$redirect, $time); return query_redirect($queries, $location, $message, $redirect, false, !$redirect, $time);
@@ -591,7 +542,7 @@ function queries_redirect($location, $message, $redirect) {
* @param float $start output of microtime(true) * @param float $start output of microtime(true)
* @return string HTML code * @return string HTML code
*/ */
function format_time($start) { function format_time(float $start) {
return lang('%.3f s', max(0, microtime(true) - $start)); return lang('%.3f s', max(0, microtime(true) - $start));
} }
@@ -603,20 +554,16 @@ function relative_uri() {
} }
/** Remove parameter from query string /** Remove parameter from query string
* @param string $param
* @return string * @return string
*/ */
function remove_from_uri($param = "") { function remove_from_uri(string $param = "") {
return substr(preg_replace("~(?<=[?&])($param" . (SID ? "" : "|" . session_name()) . ")=[^&]*&~", '', relative_uri() . "&"), 0, -1); return substr(preg_replace("~(?<=[?&])($param" . (SID ? "" : "|" . session_name()) . ")=[^&]*&~", '', relative_uri() . "&"), 0, -1);
} }
/** Get file contents from $_FILES /** Get file contents from $_FILES
* @param string $key
* @param bool $decompress
* @param string $delimiter
* @return mixed int for error, string otherwise * @return mixed int for error, string otherwise
*/ */
function get_file($key, $decompress = false, $delimiter = "") { function get_file(string $key, bool $decompress = false, string $delimiter = "") {
$file = $_FILES[$key]; $file = $_FILES[$key];
if (!$file) { if (!$file) {
return null; return null;
@@ -653,40 +600,33 @@ function get_file($key, $decompress = false, $delimiter = "") {
} }
/** Determine upload error /** Determine upload error
* @param int $error
* @return string * @return string
*/ */
function upload_error($error) { function upload_error(int $error) {
$max_size = ($error == UPLOAD_ERR_INI_SIZE ? ini_get("upload_max_filesize") : 0); // post_max_size is checked in index.php $max_size = ($error == UPLOAD_ERR_INI_SIZE ? ini_get("upload_max_filesize") : 0); // post_max_size is checked in index.php
return ($error ? lang('Unable to upload a file.') . ($max_size ? " " . lang('Maximum allowed file size is %sB.', $max_size) : "") : lang('File does not exist.')); return ($error ? lang('Unable to upload a file.') . ($max_size ? " " . lang('Maximum allowed file size is %sB.', $max_size) : "") : lang('File does not exist.'));
} }
/** Create repeat pattern for preg /** Create repeat pattern for preg
* @param string $pattern
* @param int $length
* @return string * @return string
*/ */
function repeat_pattern($pattern, $length) { function repeat_pattern(string $pattern, int $length) {
// fix for Compilation failed: number too big in {} quantifier // fix for Compilation failed: number too big in {} quantifier
return str_repeat("$pattern{0,65535}", $length / 65535) . "$pattern{0," . ($length % 65535) . "}"; // can create {0,0} which is OK return str_repeat("$pattern{0,65535}", $length / 65535) . "$pattern{0," . ($length % 65535) . "}"; // can create {0,0} which is OK
} }
/** Check whether the string is in UTF-8 /** Check whether the string is in UTF-8
* @param string $val
* @return bool * @return bool
*/ */
function is_utf8($val) { function is_utf8(string $val) {
// don't print control chars except \t\r\n // don't print control chars except \t\r\n
return (preg_match('~~u', $val) && !preg_match('~[\0-\x8\xB\xC\xE-\x1F]~', $val)); return (preg_match('~~u', $val) && !preg_match('~[\0-\x8\xB\xC\xE-\x1F]~', $val));
} }
/** Shorten UTF-8 string /** Shorten UTF-8 string
* @param string $string
* @param int $length
* @param string $suffix
* @return string escaped string with appended ... * @return string escaped string with appended ...
*/ */
function shorten_utf8($string, $length = 80, $suffix = "") { function shorten_utf8(string $string, int $length = 80, string $suffix = "") {
if (!preg_match("(^(" . repeat_pattern("[\t\r\n -\x{10FFFF}]", $length) . ")($)?)u", $string, $match)) { // ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow if (!preg_match("(^(" . repeat_pattern("[\t\r\n -\x{10FFFF}]", $length) . ")($)?)u", $string, $match)) { // ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow
preg_match("(^(" . repeat_pattern("[\t\r\n -~]", $length) . ")($)?)", $string, $match); preg_match("(^(" . repeat_pattern("[\t\r\n -~]", $length) . ")($)?)", $string, $match);
} }
@@ -702,29 +642,25 @@ function format_number($val) {
} }
/** Generate friendly URL /** Generate friendly URL
* @param string $val
* @return string * @return string
*/ */
function friendly_url($val) { function friendly_url(string $val) {
// used for blobs and export // used for blobs and export
return preg_replace('~\W~i', '-', $val); return preg_replace('~\W~i', '-', $val);
} }
/** Get status of a single table and fall back to name on error /** Get status of a single table and fall back to name on error
* @param string $table
* @param bool $fast
* @return TableStatus one element from table_status() * @return TableStatus one element from table_status()
*/ */
function table_status1($table, $fast = false) { function table_status1(string $table, bool $fast = false) {
$return = table_status($table, $fast); $return = table_status($table, $fast);
return ($return ? reset($return) : array("Name" => $table)); return ($return ? reset($return) : array("Name" => $table));
} }
/** Find out foreign keys for each column /** Find out foreign keys for each column
* @param string $table
* @return list<ForeignKey>[] [$col => []] * @return list<ForeignKey>[] [$col => []]
*/ */
function column_foreign_keys($table) { function column_foreign_keys(string $table) {
global $adminer; global $adminer;
$return = array(); $return = array();
foreach ($adminer->foreignKeys($table) as $foreign_key) { foreach ($adminer->foreignKeys($table) as $foreign_key) {
@@ -761,11 +697,9 @@ function fields_from_edit() { // used by Mongo and SimpleDB
} }
/** Send headers for export /** Send headers for export
* @param string $identifier
* @param bool $multi_table
* @return string extension * @return string extension
*/ */
function dump_headers($identifier, $multi_table = false) { function dump_headers(string $identifier, bool $multi_table = false) {
global $adminer; global $adminer;
$return = $adminer->dumpHeaders($identifier, $multi_table); $return = $adminer->dumpHeaders($identifier, $multi_table);
$output = $_POST["output"]; $output = $_POST["output"];
@@ -785,7 +719,7 @@ function dump_headers($identifier, $multi_table = false) {
* @param string[] $row * @param string[] $row
* @return void * @return void
*/ */
function dump_csv($row) { function dump_csv(array $row) {
foreach ($row as $key => $val) { foreach ($row as $key => $val) {
if (preg_match('~["\n,;\t]|^0|\.\d*0$~', $val) || $val === "") { if (preg_match('~["\n,;\t]|^0|\.\d*0$~', $val) || $val === "") {
$row[$key] = '"' . str_replace('"', '""', $val) . '"'; $row[$key] = '"' . str_replace('"', '""', $val) . '"';
@@ -795,11 +729,10 @@ function dump_csv($row) {
} }
/** Apply SQL function /** Apply SQL function
* @param string $function
* @param string $column escaped column identifier * @param string $column escaped column identifier
* @return string * @return string
*/ */
function apply_sql_function($function, $column) { function apply_sql_function(string $function, string $column) {
return ($function ? ($function == "unixepoch" ? "DATETIME($column, '$function')" : ($function == "count distinct" ? "COUNT(DISTINCT " : strtoupper("$function(")) . "$column)") : $column); return ($function ? ($function == "unixepoch" ? "DATETIME($column, '$function')" : ($function == "count distinct" ? "COUNT(DISTINCT " : strtoupper("$function(")) . "$column)") : $column);
} }
@@ -824,10 +757,9 @@ function get_temp_dir() {
} }
/** Open and exclusively lock a file /** Open and exclusively lock a file
* @param string $filename
* @return resource|void null for error * @return resource|void null for error
*/ */
function file_open_lock($filename) { function file_open_lock(string $filename) {
if (is_link($filename)) { if (is_link($filename)) {
return; // https://cwe.mitre.org/data/definitions/61.html return; // https://cwe.mitre.org/data/definitions/61.html
} }
@@ -844,11 +776,9 @@ function file_open_lock($filename) {
} }
/** Write and unlock a file /** Write and unlock a file
* @param resource $fp
* @param string $data
* @return void * @return void
*/ */
function file_write_unlock($fp, $data) { function file_write_unlock(resource $fp, string $data) {
rewind($fp); rewind($fp);
fwrite($fp, $data); fwrite($fp, $data);
ftruncate($fp, strlen($data)); ftruncate($fp, strlen($data));
@@ -856,10 +786,9 @@ function file_write_unlock($fp, $data) {
} }
/** Unlock and close a file /** Unlock and close a file
* @param resource $fp
* @return void * @return void
*/ */
function file_unlock($fp) { function file_unlock(resource $fp) {
flock($fp, LOCK_UN); flock($fp, LOCK_UN);
fclose($fp); fclose($fp);
} }
@@ -868,16 +797,15 @@ function file_unlock($fp) {
* @param mixed[] $array * @param mixed[] $array
* @return mixed if not found * @return mixed if not found
*/ */
function first($array) { function first(array $array) {
// reset(f()) triggers a notice // reset(f()) triggers a notice
return reset($array); return reset($array);
} }
/** Read password from file adminer.key in temporary directory or create one /** Read password from file adminer.key in temporary directory or create one
* @param bool $create
* @return string|false false if the file can not be created * @return string|false false if the file can not be created
*/ */
function password_file($create) { function password_file(bool $create) {
$filename = get_temp_dir() . "/adminer.key"; $filename = get_temp_dir() . "/adminer.key";
if (!$create && !file_exists($filename)) { if (!$create && !file_exists($filename)) {
return false; return false;
@@ -905,12 +833,10 @@ function rand_string() {
/** Format value to use in select /** Format value to use in select
* @param string|string[] $val * @param string|string[] $val
* @param string $link
* @param Field $field * @param Field $field
* @param int $text_length
* @return string HTML * @return string HTML
*/ */
function select_value($val, $link, $field, $text_length) { function select_value($val, string $link, array $field, int $text_length) {
global $adminer; global $adminer;
if (is_array($val)) { if (is_array($val)) {
$return = ""; $return = "";
@@ -947,10 +873,9 @@ function select_value($val, $link, $field, $text_length) {
} }
/** Check whether the string is e-mail address /** Check whether the string is e-mail address
* @param ?string $email
* @return bool * @return bool
*/ */
function is_mail($email) { function is_mail(?string $email) {
$atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // characters of local-name $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // characters of local-name
$domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component
$pattern = "$atom+(\\.$atom+)*@($domain?\\.)+$domain"; $pattern = "$atom+(\\.$atom+)*@($domain?\\.)+$domain";
@@ -958,10 +883,9 @@ function is_mail($email) {
} }
/** Check whether the string is URL address /** Check whether the string is URL address
* @param string $string
* @return bool * @return bool
*/ */
function is_url($string) { function is_url(string $string) {
$domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component //! IDN $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); //! restrict path, query and fragment characters return preg_match("~^(https?)://($domain?\\.)+$domain(:\\d+)?(/.*)?(\\?.*)?(#.*)?\$~i", $string); //! restrict path, query and fragment characters
} }
@@ -970,18 +894,16 @@ function is_url($string) {
* @param Field $field * @param Field $field
* @return bool * @return bool
*/ */
function is_shortable($field) { function is_shortable(array $field) {
return preg_match('~char|text|json|lob|geometry|point|linestring|polygon|string|bytea~', $field["type"]); return preg_match('~char|text|json|lob|geometry|point|linestring|polygon|string|bytea~', $field["type"]);
} }
/** Get query to compute number of found rows /** Get query to compute number of found rows
* @param string $table
* @param list<string> $where * @param list<string> $where
* @param bool $is_group
* @param list<string> $group * @param list<string> $group
* @return string * @return string
*/ */
function count_rows($table, $where, $is_group, $group) { function count_rows(string $table, array $where, bool $is_group, array $group) {
$query = " FROM " . table($table) . ($where ? " WHERE " . implode(" AND ", $where) : ""); $query = " FROM " . table($table) . ($where ? " WHERE " . implode(" AND ", $where) : "");
return ($is_group && (JUSH == "sql" || count($group) == 1) return ($is_group && (JUSH == "sql" || count($group) == 1)
? "SELECT COUNT(DISTINCT " . implode(", ", $group) . ")$query" ? "SELECT COUNT(DISTINCT " . implode(", ", $group) . ")$query"
@@ -990,10 +912,9 @@ function count_rows($table, $where, $is_group, $group) {
} }
/** Run query which can be killed by AJAX call after timing out /** Run query which can be killed by AJAX call after timing out
* @param string $query
* @return string[] * @return string[]
*/ */
function slow_query($query) { function slow_query(string $query) {
global $adminer, $token, $driver; global $adminer, $token, $driver;
$db = $adminer->database(); $db = $adminer->database();
$timeout = $adminer->queryTimeout(); $timeout = $adminer->queryTimeout();
@@ -1035,10 +956,9 @@ function verify_token() {
// used in compiled version // used in compiled version
/** /**
* @param string $binary
* @return string * @return string
*/ */
function lzw_decompress($binary) { function lzw_decompress(string $binary) {
// convert binary string to codes // convert binary string to codes
$dictionary_count = 256; $dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2)) $bits = 8; // ceil(log($dictionary_count, 2))

View File

@@ -2,19 +2,16 @@
namespace Adminer; namespace Adminer;
/** Return <script> element /** Return <script> element
* @param string $source
* @param string $trailing
* @return string * @return string
*/ */
function script($source, $trailing = "\n") { function script(string $source, string $trailing = "\n") {
return "<script" . nonce() . ">$source</script>$trailing"; return "<script" . nonce() . ">$source</script>$trailing";
} }
/** Return <script src> element /** Return <script src> element
* @param string $url
* @return string * @return string
*/ */
function script_src($url) { function script_src(string $url) {
return "<script src='" . h($url) . "'" . nonce() . "></script>\n"; return "<script src='" . h($url) . "'" . nonce() . "></script>\n";
} }
@@ -26,11 +23,10 @@ function nonce() {
} }
/** Get <input type="hidden"> /** Get <input type="hidden">
* @param string $name
* @param string|int $value * @param string|int $value
* @return string HTML * @return string HTML
*/ */
function input_hidden($name, $value = "") { function input_hidden(string $name, $value = "") {
return "<input type='hidden' name='" . h($name) . "' value='" . h($value) . "'>\n"; return "<input type='hidden' name='" . h($name) . "' value='" . h($value) . "'>\n";
} }
@@ -38,7 +34,7 @@ function input_hidden($name, $value = "") {
* @param string $special token to use instead of global $token * @param string $special token to use instead of global $token
* @return string HTML * @return string HTML
*/ */
function input_token($special = "") { function input_token(string $special = "") {
global $token; global $token;
return input_hidden("token", ($special ?: $token)); return input_hidden("token", ($special ?: $token));
} }
@@ -51,32 +47,24 @@ function target_blank() {
} }
/** Escape for HTML /** Escape for HTML
* @param string $string
* @return string * @return string
*/ */
function h($string) { function h(string $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> /** Convert \n to <br>
* @param string $string
* @return string * @return string
*/ */
function nl_br($string) { function nl_br(string $string) {
return str_replace("\n", "<br>", $string); // nl2br() uses XHTML before PHP 5.3 return str_replace("\n", "<br>", $string); // nl2br() uses XHTML before PHP 5.3
} }
/** Generate HTML checkbox /** Generate HTML checkbox
* @param string $name
* @param string|int $value * @param string|int $value
* @param bool $checked
* @param string $label
* @param string $onclick
* @param string $class
* @param string $labelled_by
* @return string * @return string
*/ */
function checkbox($name, $value, $checked, $label = "", $onclick = "", $class = "", $labelled_by = "") { function checkbox(string $name, $value, bool $checked, string $label = "", string $onclick = "", string $class = "", string $labelled_by = "") {
$return = "<input type='checkbox' name='$name' value='" . h($value) . "'" $return = "<input type='checkbox' name='$name' value='" . h($value) . "'"
. ($checked ? " checked" : "") . ($checked ? " checked" : "")
. ($labelled_by ? " aria-labelledby='$labelled_by'" : "") . ($labelled_by ? " aria-labelledby='$labelled_by'" : "")
@@ -92,7 +80,7 @@ function checkbox($name, $value, $checked, $label = "", $onclick = "", $class =
* @param bool $use_keys always use array keys for value="", otherwise only string keys are used * @param bool $use_keys always use array keys for value="", otherwise only string keys are used
* @return string * @return string
*/ */
function optionlist($options, $selected = null, $use_keys = false) { function optionlist($options, $selected = null, bool $use_keys = false) {
$return = ""; $return = "";
foreach ($options as $k => $v) { foreach ($options as $k => $v) {
$opts = array($k => $v); $opts = array($k => $v);
@@ -115,14 +103,10 @@ function optionlist($options, $selected = null, $use_keys = false) {
} }
/** Generate HTML <select> /** Generate HTML <select>
* @param string $name
* @param string[] $options * @param string[] $options
* @param string $value
* @param string $onchange
* @param string $labelled_by
* @return string * @return string
*/ */
function html_select($name, $options, $value = "", $onchange = "", $labelled_by = "") { function html_select(string $name, array $options, string $value = "", string $onchange = "", string $labelled_by = "") {
return "<select name='" . h($name) . "'" return "<select name='" . h($name) . "'"
. ($labelled_by ? " aria-labelledby='$labelled_by'" : "") . ($labelled_by ? " aria-labelledby='$labelled_by'" : "")
. ">" . optionlist($options, $value) . "</select>" . ">" . optionlist($options, $value) . "</select>"
@@ -131,12 +115,10 @@ function html_select($name, $options, $value = "", $onchange = "", $labelled_by
} }
/** Generate HTML radio list /** Generate HTML radio list
* @param string $name
* @param string[] $options * @param string[] $options
* @param string $value
* @return string * @return string
*/ */
function html_radios($name, $options, $value = "") { function html_radios(string $name, array $options, string $value = "") {
$return = ""; $return = "";
foreach ($options as $key => $val) { foreach ($options as $key => $val) {
$return .= "<label><input type='radio' name='" . h($name) . "' value='" . h($key) . "'" . ($key == $value ? " checked" : "") . ">" . h($val) . "</label>"; $return .= "<label><input type='radio' name='" . h($name) . "' value='" . h($key) . "'" . ($key == $value ? " checked" : "") . ">" . h($val) . "</label>";
@@ -145,21 +127,16 @@ function html_radios($name, $options, $value = "") {
} }
/** Get onclick confirmation /** Get onclick confirmation
* @param string $message
* @param string $selector
* @return string * @return string
*/ */
function confirm($message = "", $selector = "qsl('input')") { function confirm(string $message = "", string $selector = "qsl('input')") {
return script("$selector.onclick = () => confirm('" . ($message ? js_escape($message) : lang('Are you sure?')) . "');", ""); return script("$selector.onclick = () => confirm('" . ($message ? js_escape($message) : lang('Are you sure?')) . "');", "");
} }
/** Print header for hidden fieldset (close by </div></fieldset>) /** Print header for hidden fieldset (close by </div></fieldset>)
* @param string $id
* @param string $legend
* @param bool $visible
* @return void * @return void
*/ */
function print_fieldset($id, $legend, $visible = false) { function print_fieldset(string $id, string $legend, bool $visible = false) {
echo "<fieldset><legend>"; echo "<fieldset><legend>";
echo "<a href='#fieldset-$id'>$legend</a>"; echo "<a href='#fieldset-$id'>$legend</a>";
echo script("qsl('a').onclick = partial(toggle, 'fieldset-$id');", ""); echo script("qsl('a').onclick = partial(toggle, 'fieldset-$id');", "");
@@ -168,28 +145,23 @@ function print_fieldset($id, $legend, $visible = false) {
} }
/** Return class='active' if $bold is true /** Return class='active' if $bold is true
* @param bool $bold
* @param string $class
* @return string * @return string
*/ */
function bold($bold, $class = "") { function bold(bool $bold, string $class = "") {
return ($bold ? " class='active $class'" : ($class ? " class='$class'" : "")); return ($bold ? " class='active $class'" : ($class ? " class='$class'" : ""));
} }
/** Escape string for JavaScript apostrophes /** Escape string for JavaScript apostrophes
* @param string $string
* @return string * @return string
*/ */
function js_escape($string) { function js_escape(string $string) {
return addcslashes($string, "\r\n'\\/"); // slash for <script> return addcslashes($string, "\r\n'\\/"); // slash for <script>
} }
/** Generate page number for pagination /** Generate page number for pagination
* @param int $page
* @param int $current
* @return string * @return string
*/ */
function pagination($page, $current) { function pagination(int $page, int $current) {
return " " . ($page == $current return " " . ($page == $current
? $page + 1 ? $page + 1
: '<a href="' . h(remove_from_uri("page") . ($page ? "&page=$page" . ($_GET["next"] ? "&next=" . urlencode($_GET["next"]) : "") : "")) . '">' . ($page + 1) . "</a>" : '<a href="' . h(remove_from_uri("page") . ($page ? "&page=$page" . ($_GET["next"] ? "&next=" . urlencode($_GET["next"]) : "") : "")) . '">' . ($page + 1) . "</a>"
@@ -199,10 +171,9 @@ function pagination($page, $current) {
/** Print hidden fields /** Print hidden fields
* @param mixed[] $process * @param mixed[] $process
* @param list<string> $ignore * @param list<string> $ignore
* @param string $prefix
* @return bool * @return bool
*/ */
function hidden_fields($process, $ignore = array(), $prefix = '') { function hidden_fields(array $process, array $ignore = array(), string $prefix = '') {
$return = false; $return = false;
foreach ($process as $key => $val) { foreach ($process as $key => $val) {
if (!in_array($key, $ignore)) { if (!in_array($key, $ignore)) {
@@ -228,13 +199,11 @@ function hidden_fields_get() {
/** Print enum or set input field /** Print enum or set input field
* @param string $type "radio"|"checkbox" * @param string $type "radio"|"checkbox"
* @param string $attrs
* @param Field $field * @param Field $field
* @param mixed $value string|array * @param mixed $value string|array
* @param string $empty
* @return string * @return string
*/ */
function enum_input($type, $attrs, $field, $value, $empty = null) { function enum_input(string $type, string $attrs, array $field, $value, string $empty = null) {
global $adminer; global $adminer;
preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches); preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
$return = ($empty !== null ? "<label><input type='$type'$attrs value='$empty'" . ((is_array($value) ? in_array($empty, $value) : $value === $empty) ? " checked" : "") . "><i>" . lang('empty') . "</i></label>" : ""); $return = ($empty !== null ? "<label><input type='$type'$attrs value='$empty'" . ((is_array($value) ? in_array($empty, $value) : $value === $empty) ? " checked" : "") . "><i>" . lang('empty') . "</i></label>" : "");
@@ -249,11 +218,9 @@ function enum_input($type, $attrs, $field, $value, $empty = null) {
/** Print edit input field /** Print edit input field
* @param Field|RoutineField $field one field from fields() * @param Field|RoutineField $field one field from fields()
* @param mixed $value * @param mixed $value
* @param string $function
* @param bool $autofocus
* @return void * @return void
*/ */
function input($field, $value, $function, $autofocus = false) { function input(array $field, $value, string $function, bool $autofocus = false) {
global $driver, $adminer; global $driver, $adminer;
$name = h(bracket_escape($field["field"])); $name = h(bracket_escape($field["field"]));
echo "<td class='function'>"; echo "<td class='function'>";
@@ -346,7 +313,7 @@ function input($field, $value, $function, $autofocus = false) {
* @param Field|RoutineField $field one field from fields() * @param Field|RoutineField $field one field from fields()
* @return mixed false to leave the original value * @return mixed false to leave the original value
*/ */
function process_input($field) { function process_input(array $field) {
global $adminer, $driver; global $adminer, $driver;
if (stripos($field["default"], "GENERATED ALWAYS AS ") === 0) { if (stripos($field["default"], "GENERATED ALWAYS AS ") === 0) {
return; return;
@@ -420,18 +387,16 @@ function search_tables() {
* @param int $side JS expression * @param int $side JS expression
* @return string * @return string
*/ */
function on_help($command, $side = 0) { function on_help(string $command, int $side = 0) {
return script("mixin(qsl('select, input'), {onmouseover: function (event) { helpMouseover.call(this, event, $command, $side) }, onmouseout: helpMouseout});", ""); return script("mixin(qsl('select, input'), {onmouseover: function (event) { helpMouseover.call(this, event, $command, $side) }, onmouseout: helpMouseout});", "");
} }
/** Print edit data form /** Print edit data form
* @param string $table
* @param Field[] $fields * @param Field[] $fields
* @param mixed $row * @param mixed $row
* @param bool $update
* @return void * @return void
*/ */
function edit_form($table, $fields, $row, $update) { function edit_form(string $table, array $fields, $row, bool $update) {
global $adminer, $error; global $adminer, $error;
$table_name = $adminer->tableName(table_status1($table, true)); $table_name = $adminer->tableName(table_status1($table, true));
page_header( page_header(
@@ -536,12 +501,8 @@ function edit_form($table, $fields, $row, $update) {
} }
/** Get button with icon /** Get button with icon
* @param string $icon
* @param string $name
* @param string $html
* @param string $title
* @return string * @return string
*/ */
function icon($icon, $name, $html, $title) { function icon(string $icon, string $name, string $html, string $title) {
return "<button type='submit' name='$name' title='" . h($title) . "' class='icon icon-$icon'><span>$html</span></button>"; return "<button type='submit' name='$name' title='" . h($title) . "' class='icon icon-$icon'><span>$html</span></button>";
} }

View File

@@ -64,7 +64,7 @@ function get_lang() {
* @param float|string $number * @param float|string $number
* @return string * @return string
*/ */
function lang($idf, $number = null) { function lang(string $idf, $number = null) {
// this is matched by compile.php // this is matched by compile.php
global $LANG, $translations; global $LANG, $translations;
$translation = ($translations[$idf] ?: $idf); $translation = ($translations[$idf] ?: $idf);

View File

@@ -7,13 +7,10 @@ if (extension_loaded('pdo')) {
/** @var \PDO */ protected $pdo; /** @var \PDO */ protected $pdo;
/** Connect to server using DSN /** Connect to server using DSN
* @param string $dsn
* @param string $username
* @param string $password
* @param mixed[] $options * @param mixed[] $options
* @return void * @return void
*/ */
function dsn($dsn, $username, $password, $options = array()) { function dsn(string $dsn, string $username, string $password, array $options = array()) {
$options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_SILENT; $options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_SILENT;
$options[\PDO::ATTR_STATEMENT_CLASS] = array('Adminer\PdoResult'); $options[\PDO::ATTR_STATEMENT_CLASS] = array('Adminer\PdoResult');
try { try {

View File

@@ -7,7 +7,7 @@ class Plugins extends Adminer {
/** Register plugins /** Register plugins
* @param ?list<object> $plugins object instances or null to autoload plugins from adminer-plugins/ * @param ?list<object> $plugins object instances or null to autoload plugins from adminer-plugins/
*/ */
function __construct($plugins) { function __construct(?array $plugins) {
if ($plugins === null) { if ($plugins === null) {
$plugins = array(); $plugins = array();
$basename = "adminer-plugins"; $basename = "adminer-plugins";
@@ -47,7 +47,7 @@ class Plugins extends Adminer {
* @param mixed[] $args * @param mixed[] $args
* @return mixed * @return mixed
*/ */
private function callParent($function, $args) { private function callParent(string $function, array $args) {
return call_user_func_array(array('parent', $function), $args); return call_user_func_array(array('parent', $function), $args);
} }
@@ -56,7 +56,7 @@ class Plugins extends Adminer {
* @param mixed[] $params * @param mixed[] $params
* @return mixed * @return mixed
*/ */
private function applyPlugin($function, $params) { private function applyPlugin(string $function, array $params) {
$args = array(); $args = array();
foreach ($params as $key => $val) { foreach ($params as $key => $val) {
// some plugins accept params by reference - we don't need to propage it outside, just to the other plugins // some plugins accept params by reference - we don't need to propage it outside, just to the other plugins
@@ -78,7 +78,7 @@ class Plugins extends Adminer {
* @param mixed[] $args * @param mixed[] $args
* @return mixed * @return mixed
*/ */
private function appendPlugin($function, $args) { private function appendPlugin(string $function, array $args) {
$return = $this->callParent($function, $args); $return = $this->callParent($function, $args);
foreach ($this->plugins as $plugin) { foreach ($this->plugins as $plugin) {
if (method_exists($plugin, $function)) { if (method_exists($plugin, $function)) {

View File

@@ -10,10 +10,9 @@ class TmpFile {
} }
/** /**
* @param string $contents
* @return void * @return void
*/ */
function write($contents) { function write(string $contents) {
$this->size += strlen($contents); $this->size += strlen($contents);
fwrite($this->handler, $contents); fwrite($this->handler, $contents);
} }

View File

@@ -7,10 +7,9 @@ namespace Adminer;
*/ */
/** /**
* @param int $n
* @return int * @return int
*/ */
function int32($n) { function int32(int $n) {
while ($n >= 2147483648) { while ($n >= 2147483648) {
$n -= 4294967296; $n -= 4294967296;
} }
@@ -22,10 +21,9 @@ function int32($n) {
/** /**
* @param int[] $v * @param int[] $v
* @param bool $w
* @return string * @return string
*/ */
function long2str($v, $w) { function long2str(array $v, bool $w) {
$s = ''; $s = '';
foreach ($v as $val) { foreach ($v as $val) {
$s .= pack('V', $val); $s .= pack('V', $val);
@@ -37,11 +35,9 @@ function long2str($v, $w) {
} }
/** /**
* @param string $s
* @param bool $w
* @return int[] * @return int[]
*/ */
function str2long($s, $w) { function str2long(string $s, bool $w) {
$v = array_values(unpack('V*', str_pad($s, 4 * ceil(strlen($s) / 4), "\0"))); $v = array_values(unpack('V*', str_pad($s, 4 * ceil(strlen($s) / 4), "\0")));
if ($w) { if ($w) {
$v[] = strlen($s); $v[] = strlen($s);
@@ -50,22 +46,17 @@ function str2long($s, $w) {
} }
/** /**
* @param int $z
* @param int $y
* @param int $sum
* @param int $k
* @return int * @return int
*/ */
function xxtea_mx($z, $y, $sum, $k) { function xxtea_mx(int $z, int $y, int $sum, int $k) {
return int32((($z >> 5 & 0x7FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k ^ $z)); return int32((($z >> 5 & 0x7FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k ^ $z));
} }
/** Cipher /** Cipher
* @param string $str plain-text password * @param string $str plain-text password
* @param string $key
* @return string binary cipher * @return string binary cipher
*/ */
function encrypt_string($str, $key) { function encrypt_string(string $str, string $key) {
if ($str == "") { if ($str == "") {
return ""; return "";
} }
@@ -95,10 +86,9 @@ function encrypt_string($str, $key) {
/** Decipher /** Decipher
* @param string $str binary cipher * @param string $str binary cipher
* @param string $key
* @return string|false plain-text password * @return string|false plain-text password
*/ */
function decrypt_string($str, $key) { function decrypt_string(string $str, string $key) {
if ($str == "") { if ($str == "") {
return ""; return "";
} }

View File

@@ -87,7 +87,7 @@ function put_file($match) {
} }
if (basename($match[2]) != "lang.inc.php" || !$_SESSION["lang"]) { if (basename($match[2]) != "lang.inc.php" || !$_SESSION["lang"]) {
if (basename($match[2]) == "lang.inc.php") { if (basename($match[2]) == "lang.inc.php") {
$return = str_replace('function lang($idf, $number = null) {', 'function lang($idf, $number = null) { $return = str_replace('function lang(string $idf, $number = null) {', 'function lang($idf, $number = null) {
if (is_string($idf)) { // compiled version uses numbers, string comes from a plugin if (is_string($idf)) { // compiled version uses numbers, string comes from a plugin
// English translation is closest to the original identifiers //! pluralized translations are not found // English translation is closest to the original identifiers //! pluralized translations are not found
$pos = array_search($idf, get_translations("en")); //! this should be cached $pos = array_search($idf, get_translations("en")); //! this should be cached

View File

@@ -2,23 +2,18 @@
namespace Adminer; namespace Adminer;
/** Encode e-mail header in UTF-8 /** Encode e-mail header in UTF-8
* @param string $header
* @return string * @return string
*/ */
function email_header($header) { function email_header(string $header) {
// iconv_mime_encode requires iconv, imap_8bit requires IMAP extension // iconv_mime_encode requires iconv, imap_8bit requires IMAP extension
return "=?UTF-8?B?" . base64_encode($header) . "?="; //! split long lines return "=?UTF-8?B?" . base64_encode($header) . "?="; //! split long lines
} }
/** Send e-mail in UTF-8 /** Send e-mail in UTF-8
* @param string $email
* @param string $subject
* @param string $message
* @param string $from
* @param array{error?:list<int>, type?:list<string>, name?:list<string>, tmp_name?:list<string>} $files * @param array{error?:list<int>, type?:list<string>, name?:list<string>, tmp_name?:list<string>} $files
* @return bool * @return bool
*/ */
function send_mail($email, $subject, $message, $from = "", $files = array()) { function send_mail(string $email, string $subject, string $message, string $from = "", array $files = array()) {
$eol = PHP_EOL; $eol = PHP_EOL;
$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");
@@ -50,6 +45,6 @@ function send_mail($email, $subject, $message, $from = "", $files = array()) {
* @param Field $field single field returned from fields() * @param Field $field single field returned from fields()
* @return bool * @return bool
*/ */
function like_bool($field) { function like_bool(array $field) {
return preg_match("~bool|(tinyint|bit)\\(1\\)~", $field["full_type"]); return preg_match("~bool|(tinyint|bit)\\(1\\)~", $field["full_type"]);
} }

View File

@@ -12,7 +12,7 @@ class AdminerDatabaseHide {
/** /**
* @param list<string> $disabled case insensitive database names in values * @param list<string> $disabled case insensitive database names in values
*/ */
function __construct($disabled) { function __construct(array $disabled) {
$this->disabled = array_map('strtolower', $disabled); $this->disabled = array_map('strtolower', $disabled);
} }

View File

@@ -12,7 +12,7 @@ class AdminerDesigns {
/** /**
* @param list<string> $designs URL in key, name in value * @param list<string> $designs URL in key, name in value
*/ */
function __construct($designs) { function __construct(array $designs) {
$this->designs = $designs; $this->designs = $designs;
} }

View File

@@ -13,12 +13,9 @@ if (isset($_GET["elastic"])) {
private $url; private $url;
/** /**
* @param string $path
* @param ?array $content
* @param string $method
* @return array|false * @return array|false
*/ */
function rootQuery($path, array $content = null, $method = 'GET') { function rootQuery(string $path, ?array $content = null, string $method = 'GET') {
$file = @file_get_contents("$this->url/" . ltrim($path, '/'), false, stream_context_create(array('http' => array( $file = @file_get_contents("$this->url/" . ltrim($path, '/'), false, stream_context_create(array('http' => array(
'method' => $method, 'method' => $method,
'content' => $content !== null ? json_encode($content) : null, 'content' => $content !== null ? json_encode($content) : null,
@@ -53,12 +50,9 @@ if (isset($_GET["elastic"])) {
} }
/** Perform query relative to actual selected DB /** Perform query relative to actual selected DB
* @param string $path
* @param ?array $content
* @param string $method
* @return array|false * @return array|false
*/ */
function query($path, array $content = null, $method = 'GET') { function query(string $path, ?array $content = null, string $method = 'GET') {
// Support for global search through all tables // Support for global search through all tables
if ($path != "" && $path[0] == "S" && preg_match('/SELECT 1 FROM ([^ ]+) WHERE (.+) LIMIT ([0-9]+)/', $path, $matches)) { if ($path != "" && $path[0] == "S" && preg_match('/SELECT 1 FROM ([^ ]+) WHERE (.+) LIMIT ([0-9]+)/', $path, $matches)) {
$driver = driver(); $driver = driver();
@@ -72,12 +66,9 @@ if (isset($_GET["elastic"])) {
} }
/** /**
* @param string $server
* @param string $username
* @param string $password
* @return bool * @return bool
*/ */
function connect($server, $username, $password) { function connect(string $server, string $username, string $password) {
preg_match('~^(https?://)?(.*)~', $server, $match); preg_match('~^(https?://)?(.*)~', $server, $match);
$this->url = ($match[1] ?: "http://") . urlencode($username) . ":" . urlencode($password) . "@$match[2]"; $this->url = ($match[1] ?: "http://") . urlencode($username) . ":" . urlencode($password) . "@$match[2]";
$return = $this->query(''); $return = $this->query('');
@@ -531,10 +522,9 @@ if (isset($_GET["elastic"])) {
} }
/** Alter type /** Alter type
* @param array $table
* @return mixed * @return mixed
*/ */
function alter_table($table, $name, $fields, $foreign, $comment, $engine, $collation, $auto_increment, $partitioning) { function alter_table(array $table, $name, $fields, $foreign, $comment, $engine, $collation, $auto_increment, $partitioning) {
$properties = array(); $properties = array();
foreach ($fields as $f) { foreach ($fields as $f) {
$field_name = trim($f[1][0]); $field_name = trim($f[1][0]);
@@ -555,7 +545,7 @@ if (isset($_GET["elastic"])) {
* @param list<string> $tables * @param list<string> $tables
* @return bool * @return bool
*/ */
function drop_tables($tables) { function drop_tables(array $tables) {
$return = true; $return = true;
foreach ($tables as $table) { //! convert to bulk api foreach ($tables as $table) { //! convert to bulk api
$return = $return && connection()->query(urlencode($table), null, 'DELETE'); $return = $return && connection()->query(urlencode($table), null, 'DELETE');

View File

@@ -15,7 +15,7 @@ class AdminerEditCalendar {
* @param string $prepend text to append before first calendar usage * @param string $prepend text to append before first calendar usage
* @param string $langPath path to language file, %s stands for language code * @param string $langPath path to language file, %s stands for language code
*/ */
function __construct($prepend = null, $langPath = "jquery-ui/i18n/jquery.ui.datepicker-%s.js") { function __construct(string $prepend = null, string $langPath = "jquery-ui/i18n/jquery.ui.datepicker-%s.js") {
$this->prepend = $prepend; $this->prepend = $prepend;
$this->langPath = $langPath; $this->langPath = $langPath;
} }

View File

@@ -16,7 +16,7 @@ class AdminerEmailTable {
* @param string $subject quoted column name * @param string $subject quoted column name
* @param string $message quoted column name * @param string $message quoted column name
*/ */
function __construct($table = "email", $id = "id", $title = "subject", $subject = "subject", $message = "message") { function __construct(string $table = "email", string $id = "id", string $title = "subject", string $subject = "subject", string $message = "message") {
$this->table = $table; $this->table = $table;
$this->id = $id; $this->id = $id;
$this->title = $title; $this->title = $title;

View File

@@ -15,7 +15,7 @@ class AdminerFileUpload {
* @param string $displayPath prefix for displaying data, null stands for $uploadPath * @param string $displayPath prefix for displaying data, null stands for $uploadPath
* @param string $extensions regular expression with allowed file extensions * @param string $extensions regular expression with allowed file extensions
*/ */
function __construct($uploadPath = "../static/data/", $displayPath = null, $extensions = "[a-zA-Z0-9]+") { function __construct(string $uploadPath = "../static/data/", string $displayPath = null, string $extensions = "[a-zA-Z0-9]+") {
$this->uploadPath = $uploadPath; $this->uploadPath = $uploadPath;
$this->displayPath = ($displayPath !== null ? $displayPath : $uploadPath); $this->displayPath = ($displayPath !== null ? $displayPath : $uploadPath);
$this->extensions = $extensions; $this->extensions = $extensions;

View File

@@ -12,7 +12,7 @@ class AdminerFrames {
/** /**
* @param bool $sameOrigin allow running from the same origin only * @param bool $sameOrigin allow running from the same origin only
*/ */
function __construct($sameOrigin = false) { function __construct(bool $sameOrigin = false) {
$this->sameOrigin = $sameOrigin; $this->sameOrigin = $sameOrigin;
} }

View File

@@ -13,7 +13,7 @@ class AdminerLoginIp {
* @param list<string> $ips IP address prefixes * @param list<string> $ips IP address prefixes
* @param list<string> $forwarded_for X-Forwarded-For prefixes if IP address matches, empty array means anything * @param list<string> $forwarded_for X-Forwarded-For prefixes if IP address matches, empty array means anything
*/ */
function __construct($ips, $forwarded_for = array()) { function __construct(array $ips, array $forwarded_for = array()) {
$this->ips = $ips; $this->ips = $ips;
$this->forwarded_for= $forwarded_for; $this->forwarded_for= $forwarded_for;
} }

View File

@@ -12,7 +12,7 @@ class AdminerLoginOtp {
/** /**
* @param string $secret decoded secret, e.g. base64_decode("SECRET") * @param string $secret decoded secret, e.g. base64_decode("SECRET")
*/ */
function __construct($secret) { function __construct(string $secret) {
$this->secret = $secret; $this->secret = $secret;
if ($_POST["auth"]) { if ($_POST["auth"]) {
$_SESSION["otp"] = (string) $_POST["auth"]["otp"]; $_SESSION["otp"] = (string) $_POST["auth"]["otp"];

View File

@@ -12,7 +12,7 @@ class AdminerLoginPasswordLess {
/** Set allowed password /** Set allowed password
* @param string $password_hash result of password_hash * @param string $password_hash result of password_hash
*/ */
function __construct($password_hash) { function __construct(string $password_hash) {
$this->password_hash = $password_hash; $this->password_hash = $password_hash;
} }

View File

@@ -12,7 +12,7 @@ class AdminerLoginServers {
/** Set supported servers /** Set supported servers
* @param array{server:string, driver:string}[] $servers [$description => ["server" => , "driver" => "server|pgsql|sqlite|..."]] * @param array{server:string, driver:string}[] $servers [$description => ["server" => , "driver" => "server|pgsql|sqlite|..."]]
*/ */
function __construct($servers) { function __construct(array $servers) {
$this->servers = $servers; $this->servers = $servers;
if ($_POST["auth"]) { if ($_POST["auth"]) {
$key = $_POST["auth"]["server"]; $key = $_POST["auth"]["server"];

View File

@@ -10,12 +10,11 @@ class AdminerLoginSsl {
protected $ssl; protected $ssl;
/** /**
* @param array{ssl?:string, cert?:string, verify?:bool, mode?:string, Encrypt?:bool, TrustServerCertificate?:bool} $ssl
* MySQL: ["key" => filename, "cert" => filename, "ca" => filename, "verify" => bool] * MySQL: ["key" => filename, "cert" => filename, "ca" => filename, "verify" => bool]
* PostgresSQL: ["mode" => sslmode] (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE) * PostgresSQL: ["mode" => sslmode] (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE)
* MSSQL: ["Encrypt" => true, "TrustServerCertificate" => true] (https://learn.microsoft.com/en-us/sql/connect/php/connection-options) * MSSQL: ["Encrypt" => true, "TrustServerCertificate" => true] (https://learn.microsoft.com/en-us/sql/connect/php/connection-options)
*/ */
function __construct($ssl) { function __construct(array $ssl) {
$this->ssl = $ssl; $this->ssl = $ssl;
} }

View File

@@ -19,9 +19,8 @@ class AdminerLoginTable {
protected $database; protected $database;
/** Set database of login table /** Set database of login table
* @param string $database
*/ */
function __construct($database) { function __construct(string $database) {
$this->database = $database; $this->database = $database;
} }

View File

@@ -12,7 +12,7 @@ class AdminerMasterSlave {
/** /**
* @param string[] $masters [$slave => $master] * @param string[] $masters [$slave => $master]
*/ */
function __construct($masters) { function __construct(array $masters) {
$this->masters = $masters; $this->masters = $masters;
} }

View File

@@ -13,7 +13,7 @@ class AdminerSlugify {
* @param string $from find these characters ... * @param string $from find these characters ...
* @param string $to ... and replace them by these * @param string $to ... and replace them by these
*/ */
function __construct($from = 'áčďéěíňóřšťúůýž', $to = 'acdeeinorstuuyz') { function __construct(string $from = 'áčďéěíňóřšťúůýž', string $to = 'acdeeinorstuuyz') {
$this->from = $from; $this->from = $from;
$this->to = $to; $this->to = $to;
} }

View File

@@ -17,7 +17,7 @@ class AdminerSqlGemini {
* @param string $apiKey Get API key at: https://aistudio.google.com/apikey * @param string $apiKey Get API key at: https://aistudio.google.com/apikey
* @param string $model Available models: https://ai.google.dev/gemini-api/docs/models#available-models * @param string $model Available models: https://ai.google.dev/gemini-api/docs/models#available-models
*/ */
function __construct($apiKey, $model = "gemini-2.0-flash") { function __construct(string $apiKey, string $model = "gemini-2.0-flash") {
$this->apiKey = $apiKey; $this->apiKey = $apiKey;
$this->model = $model; $this->model = $model;
} }

View File

@@ -12,7 +12,7 @@ class AdminerSqlLog {
/** /**
* @param string $filename defaults to "$database.sql" * @param string $filename defaults to "$database.sql"
*/ */
function __construct($filename = "") { function __construct(string $filename = "") {
$this->filename = $filename; $this->filename = $filename;
} }

View File

@@ -12,7 +12,7 @@ class AdminerTableIndexesStructure {
* @param Index[] $indexes data about all indexes on a table * @param Index[] $indexes data about all indexes on a table
* @return bool * @return bool
*/ */
function tableIndexesPrint($indexes) { function tableIndexesPrint(array $indexes) {
echo "<table>\n"; echo "<table>\n";
echo "<thead><tr><th>" . Adminer\lang('Name') . "<th>" . Adminer\lang('Type') . "<th>" . Adminer\lang('Columns') . "</thead>\n"; echo "<thead><tr><th>" . Adminer\lang('Name') . "<th>" . Adminer\lang('Type') . "<th>" . Adminer\lang('Columns') . "</thead>\n";
foreach ($indexes as $name => $index) { foreach ($indexes as $name => $index) {

View File

@@ -12,7 +12,7 @@ class AdminerTableStructure {
* @param Field[] $fields data about individual fields * @param Field[] $fields data about individual fields
* @return bool * @return bool
*/ */
function tableStructurePrint($fields, $tableStatus = null) { function tableStructurePrint(array $fields, $tableStatus = null) {
echo "<div class='scrollable'>\n"; echo "<div class='scrollable'>\n";
echo "<table class='nowrap odds'>\n"; echo "<table class='nowrap odds'>\n";
echo "<thead><tr>" echo "<thead><tr>"

View File

@@ -11,9 +11,8 @@ class AdminerTinymce {
protected $path; protected $path;
/** /**
* @param string $path
*/ */
function __construct($path = "tiny_mce/tiny_mce.js") { function __construct(string $path = "tiny_mce/tiny_mce.js") {
$this->path = $path; $this->path = $path;
} }