class Util

Misc functions used all over the scripts.

Methods

static bool
showIcons(string $value)

Checks whether configuration value tells to show icons.

static bool
showText(string $value)

Checks whether configuration value tells to show text.

static string
getFormattedMaximumUploadSize(int $max_upload_size)

Returns the formatted maximum size for an upload

static string
escapeMysqlWildcards(string $name)

Add slashes before "_" and "%" characters for using them in MySQL database, table and field names.

static string
unescapeMysqlWildcards(string $name)

removes slashes before "_" and "%" characters Note: This function does not unescape backslashes!

static string
unQuote(string $quoted_string, string $quote = null)

removes quotes (',",`) from a quoted string

static string
getMySQLDocuURL(string $link, string $anchor = '')

Get a URL link to the official MySQL documentation

static string
getDocuURL(bool $isMariaDB = false)

Get a URL link to the official documentation page of either MySQL or MariaDB depending on the databse server of the user.

static array
getTableList(string $db, string $tables = null, int $limit_offset = 0, int|bool $limit_count = false)

returns array with tables of given db with extended information and grouped

static mixed
backquote(array|string $a_name, bool|null $do_it = true)

Adds backquotes on both sides of a database, table or field name.

static mixed
backquoteCompat(array|string $a_name, string $compatibility = 'MSSQL', bool|null $do_it = true)

Adds backquotes on both sides of a database, table or field name.

static bool
profilingSupported()

Verifies if current MySQL server supports profiling

static array|null
formatByteDown(double|int $value, int $limes = 6, int $comma = 0)

Formats $value to byte view

static string
formatNumber(double $value, int $digits_left = 3, int $digits_right = 0, bool $only_down = false, bool $noTrailingZero = true)

Formats $value to the given length and appends SI prefixes with a $length of 0 no truncation occurs, number is only formatted to the current locale

static int
extractValueFromFormattedSize(string $formatted_size)

Returns the number of bytes when a formatted size is given

static string
localisedDate(int $timestamp = -1, string $format = '')

Writes localised date

static array
splitURLQuery(string $url)

Splits a URL string by parameter

static string
timespanFormat(int $seconds)

Returns a given timespan value in a readable format.

static void
checkParameters(string[] $params, bool $request = false)

Function added to avoid path disclosures.

static array
getUniqueCondition(resource $handle, int $fields_cnt, array $fields_meta, array $row, bool $force_unique = false, string|bool $restrict_to_table = false, array|null $analyzed_sql_results = null)

Function to generate unique condition for specified row.

static string
getCharsetQueryPart(string $collation, bool $override = false)

Generate the charset query part

static string
pageselector(string $name, int $rows, int $pageNow = 1, int $nbTotalPage = 1, int $showAll = 200, int $sliceStart = 5, int $sliceEnd = 5, int $percent = 20, int $range = 10, string $prompt = '')

Generate a pagination selector for browsing resultsets

static int
getPageFromPosition(int $pos, int $max_count)

Calculate page number through position

static string
userDir(string $dir)

replaces %u in given path with current user name

static void
clearUserCache()

Clears cache content which needs to be refreshed on user change.

static string
cacheKey()

Calculates session cache key

static bool
cacheExists(string $var)

Verifies if something is cached in the session

static mixed
cacheGet(string $var, Closure $callback = null)

Gets cached information from the session

static void
cacheSet(string $var, mixed $val = null)

Caches information in the session

static void
cacheUnset(string $var)

Removes cached information from the session

static string
printableBitValue(int $value, int $length)

Converts a bit value to printable format; in MySQL a BIT field can be from 1 to 64 bits so we need this function because in PHP, decbin() supports only 32 bits on 32-bit servers

static string
convertBitDefaultValue(string $bit_default_value)

Converts a BIT type default value for example, b'010' becomes 010

static array
extractColumnSpec(string $columnspec)

Extracts the various parts from a column spec

static bool
isForeignKeySupported(string $engine)

Verifies if this table's engine supports foreign keys

static bool
isForeignKeyCheck()

Is Foreign key check enabled?

static bool
handleDisableFKCheckInit()

Handle foreign key check request

static void
handleDisableFKCheckCleanup(bool $default_fk_check_value)

Cleanup changes done for foreign key check

static string
asWKT(string $data, bool $includeSRID = false)

Converts GIS data to Well Known Text format

static string
duplicateFirstNewline(string $string)

If the string starts with a \r\n pair (0x0d0a) add an extra \n

static string|bool
getTitleForTarget(string $target)

Get the action word corresponding to a script name in order to display it as a title in navigation panel

static string
getScriptNameForOption(string $target, string $location)

Get the script name corresponding to a plain English config word in order to append in links on navigation and main panel

static string
expandUserString(string $string, array|string $escape = null, array $updates = [])

Formats user string, expanding @VARIABLES@, accepting strftime format string.

static mixed
getSupportedDatatypes(bool $html = false, string $selected = '')

This function processes the datatypes supported by the DB, as specified in Types->getColumns() and either returns an array (useful for quickly checking if a datatype is supported) or an HTML snippet that creates a drop-down list.

static array
unsupportedDatatypes()

Returns a list of datatypes that are not (yet) handled by PMA.

static string[]
getGISDatatypes(bool $upper_case = false)

Return GIS data types

static string
createGISData(string $gis_string, int $mysqlVersion)

Generates GIS data based on the string passed.

static array
getGISFunctions(string $geom_type = null, bool $binary = true, bool $display = false)

Returns the names and details of the functions that can be applied on geometry data types.

static bool
currentUserHasPrivilege(string $priv, mixed $db = null, mixed $tbl = null)

Checks if the current user has a specific privilege and returns true if the user indeed has that privilege or false if they don't. This function must only be used for features that are available since MySQL 5, because it relies on the INFORMATION_SCHEMA database to be present.

static string
getServerType()

Returns server type for current connection

static array
parseEnumSetValues(string $definition, bool $escapeHtml = true)

Parses ENUM/SET values

static string
getFirstOccurringRegularExpression(array $regex_array, string $query)

Get regular expression which occur first inside the given sql query.

static array|null
getMenuTabList(string $level = null)

Return the list of tabs for the menu with corresponding names

static string
addMicroseconds(string $value)

Add fractional seconds to time, datetime and timestamp strings.

static string
getCompressionMimeType(resource $file)

Reads the file, detects the compression MIME type, closes the file and returns the MIME type

static string
getCollateForIS()

Provide COLLATE clause, if required, to perform case sensitive comparisons for queries on information_schema.

static array
processIndexData(array $indexes)

Process the index data.

static bool
isVirtualColumnsSupported()

Returns whether the database server supports virtual columns

static array
getDbInfo(string $db, string|null $sub_part)

Gets the list of tables in the current db and information about these tables if possible

static array
getTablesWhenOpen(string $db, object $db_info_result)

Gets the list of tables in the current db, taking into account that they might be "in use"

static array
listPHPExtensions()

Returs list of used PHP extensions.

static string
requestString(mixed $value)

Converts given (request) paramter to string

static string
generateRandom(int $length, bool $asHex = false)

Generates random string consisting of ASCII chars

static string
date(string $format)

Wraper around PHP date function

static void
setTimeLimit()

Wrapper around php's set_time_limit

static mixed
getValueByKey(array $array, string|array $path, mixed $default = null)

Access to a multidimensional array by dot notation

static string
sortableTableHeader(string $title, string $sort, string $initialSortOrder = 'ASC')

Creates a clickable column header for table information

static bool
isInteger(mixed $input)

Check that input is an int or an int in a string

static array
buildActionTitles()

Build titles and icons for action links

static string
getProtoFromForwardedHeader(string $headerContents)

Get the protocol from the RFC 7239 Forwarded header

Details

at line 104
static bool showIcons(string $value)

Checks whether configuration value tells to show icons.

Parameters

string $value Configuration option name

Return Value

bool Whether to show icons.

at line 116
static bool showText(string $value)

Checks whether configuration value tells to show text.

Parameters

string $value Configuration option name

Return Value

bool Whether to show text.

at line 130
static string getFormattedMaximumUploadSize(int $max_upload_size)

Returns the formatted maximum size for an upload

Parameters

int $max_upload_size the size

Return Value

string the message

at line 149
static string escapeMysqlWildcards(string $name)

Add slashes before "_" and "%" characters for using them in MySQL database, table and field names.

Note: This function does not escape backslashes!

Parameters

string $name the string to escape

Return Value

string the escaped string

at line 164
static string unescapeMysqlWildcards(string $name)

removes slashes before "_" and "%" characters Note: This function does not unescape backslashes!

Parameters

string $name the string to escape

Return Value

string the escaped string

at line 179
static string unQuote(string $quoted_string, string $quote = null)

removes quotes (',",`) from a quoted string

checks if the string is quoted and removes this quotes

Parameters

string $quoted_string string to remove quotes from
string $quote type of quote to remove

Return Value

string unqoted string

at line 219
static string getMySQLDocuURL(string $link, string $anchor = '')

Get a URL link to the official MySQL documentation

Parameters

string $link contains name of page/anchor that is being linked
string $anchor anchor to page part

Return Value

string the URL link

at line 258
static string getDocuURL(bool $isMariaDB = false)

Get a URL link to the official documentation page of either MySQL or MariaDB depending on the databse server of the user.

Parameters

bool $isMariaDB if the database server is MariaDB

Return Value

string The URL link

at line 310
static array getTableList(string $db, string $tables = null, int $limit_offset = 0, int|bool $limit_count = false)

returns array with tables of given db with extended information and grouped

Parameters

string $db name of db
string $tables name of tables
int $limit_offset list offset
int|bool $limit_count max tables to return

Return Value

array (recursive) grouped table list

at line 421
static mixed backquote(array|string $a_name, bool|null $do_it = true)

Adds backquotes on both sides of a database, table or field name.

and escapes backquotes inside the name with another backquote

example: echo backquote('owners db'); //owner``s db`

Parameters

array|string $a_name the database, table or field name to "backquote" or array of it
bool|null $do_it a flag to bypass this function (used by dump functions)

Return Value

mixed the "backquoted" database, table or field name

at line 447
static mixed backquoteCompat(array|string $a_name, string $compatibility = 'MSSQL', bool|null $do_it = true)

Adds backquotes on both sides of a database, table or field name.

in compatibility mode

example: echo backquoteCompat('owners db'); //owner``s db`

Parameters

array|string $a_name the database, table or field name to "backquote" or array of it
string $compatibility string compatibility mode (used by dump functions)
bool|null $do_it a flag to bypass this function (used by dump functions)

Return Value

mixed the "backquoted" database, table or field name

at line 492
static bool profilingSupported()

Verifies if current MySQL server supports profiling

Return Value

bool whether profiling is supported

at line 520
static array|null formatByteDown(double|int $value, int $limes = 6, int $comma = 0)

Formats $value to byte view

Parameters

double|int $value the value to format
int $limes the sensitiveness
int $comma the number of decimals to retain

Return Value

array|null the formatted value and its unit

at line 599
static string formatNumber(double $value, int $digits_left = 3, int $digits_right = 0, bool $only_down = false, bool $noTrailingZero = true)

Formats $value to the given length and appends SI prefixes with a $length of 0 no truncation occurs, number is only formatted to the current locale

examples: echo formatNumber(123456789, 6); // 123,457 k echo formatNumber(-123456789, 4, 2); // -123.46 M echo formatNumber(-0.003, 6); // -3 m echo formatNumber(0.003, 3, 3); // 0.003 echo formatNumber(0.00003, 3, 2); // 0.03 m echo formatNumber(0, 6); // 0

Parameters

double $value the value to format
int $digits_left number of digits left of the comma
int $digits_right number of digits right of the comma
bool $only_down do not reformat numbers below 1
bool $noTrailingZero removes trailing zeros right of the comma (default: true)

Return Value

string the formatted value and its unit

at line 716
static int extractValueFromFormattedSize(string $formatted_size)

Returns the number of bytes when a formatted size is given

Parameters

string $formatted_size the size expression (for example 8MB)

Return Value

int The numerical part of the expression (for example 8)

at line 754
static string localisedDate(int $timestamp = -1, string $format = '')

Writes localised date

Parameters

int $timestamp the current timestamp
string $format format

Return Value

string the formatted date

at line 847
static array splitURLQuery(string $url)

Splits a URL string by parameter

Parameters

string $url the URL

Return Value

array the parameter/value pairs, for example [0] db=sakila

at line 876
static string timespanFormat(int $seconds)

Returns a given timespan value in a readable format.

Parameters

int $seconds the timespan

Return Value

string the formatted value

at line 915
static void checkParameters(string[] $params, bool $request = false)

Function added to avoid path disclosures.

Called by each script that needs parameters, it displays an error message and, by default, stops the execution.

Parameters

string[] $params The names of the parameters needed by the calling script
bool $request Check parameters in request

Return Value

void

at line 959
static array getUniqueCondition(resource $handle, int $fields_cnt, array $fields_meta, array $row, bool $force_unique = false, string|bool $restrict_to_table = false, array|null $analyzed_sql_results = null)

Function to generate unique condition for specified row.

Parameters

resource $handle current query result
int $fields_cnt number of fields
array $fields_meta meta information about fields
array $row current row
bool $force_unique generate condition only on pk or unique
string|bool $restrict_to_table restrict the unique condition to this table or false if none
array|null $analyzed_sql_results the analyzed query

Return Value

array the calculated condition and whether condition is unique

at line 1134
static string getCharsetQueryPart(string $collation, bool $override = false)

Generate the charset query part

Parameters

string $collation Collation
bool $override (optional) force 'CHARACTER SET' keyword

Return Value

string

at line 1168
static string pageselector(string $name, int $rows, int $pageNow = 1, int $nbTotalPage = 1, int $showAll = 200, int $sliceStart = 5, int $sliceEnd = 5, int $percent = 20, int $range = 10, string $prompt = '')

Generate a pagination selector for browsing resultsets

Parameters

string $name The name for the request parameter
int $rows Number of rows in the pagination set
int $pageNow current page number
int $nbTotalPage number of total pages
int $showAll If the number of pages is lower than this variable, no pages will be omitted in pagination
int $sliceStart How many rows at the beginning should always be shown?
int $sliceEnd How many rows at the end should always be shown?
int $percent Percentage of calculation page offsets to hop to a next page
int $range Near the current page, how many pages should be considered "nearby" and displayed as well?
string $prompt The prompt to display (sometimes empty)

Return Value

string

at line 1299
static int getPageFromPosition(int $pos, int $max_count)

Calculate page number through position

Parameters

int $pos position of first item
int $max_count number of items per page

Return Value

int $page_num

at line 1317
static string userDir(string $dir)

replaces %u in given path with current user name

example: $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'

Parameters

string $dir with wildcard for user

Return Value

string per user directory

at line 1332
static void clearUserCache()

Clears cache content which needs to be refreshed on user change.

Return Value

void

at line 1344
static string cacheKey()

Calculates session cache key

Return Value

string

at line 1360
static bool cacheExists(string $var)

Verifies if something is cached in the session

Parameters

string $var variable name

Return Value

bool

at line 1373
static mixed cacheGet(string $var, Closure $callback = null)

Gets cached information from the session

Parameters

string $var variable name
Closure $callback callback to fetch the value

Return Value

mixed

at line 1395
static void cacheSet(string $var, mixed $val = null)

Caches information in the session

Parameters

string $var variable name
mixed $val value

Return Value

void

at line 1407
static void cacheUnset(string $var)

Removes cached information from the session

Parameters

string $var variable name

Return Value

void

at line 1423
static string printableBitValue(int $value, int $length)

Converts a bit value to printable format; in MySQL a BIT field can be from 1 to 64 bits so we need this function because in PHP, decbin() supports only 32 bits on 32-bit servers

Parameters

int $value coming from a BIT field
int $length length

Return Value

string the printable value

at line 1462
static string convertBitDefaultValue(string $bit_default_value)

Converts a BIT type default value for example, b'010' becomes 010

Parameters

string $bit_default_value value

Return Value

string the converted value

at line 1475
static array extractColumnSpec(string $columnspec)

Extracts the various parts from a column spec

Parameters

string $columnspec Column specification

Return Value

array associative array containing type, spec_in_brackets and possibly enum_set_values (another array)

at line 1600
static bool isForeignKeySupported(string $engine)

Verifies if this table's engine supports foreign keys

Parameters

string $engine engine

Return Value

bool

at line 1623
static bool isForeignKeyCheck()

Is Foreign key check enabled?

Return Value

bool

at line 1638
static bool handleDisableFKCheckInit()

Handle foreign key check request

Return Value

bool Default foreign key checks value

at line 1661
static void handleDisableFKCheckCleanup(bool $default_fk_check_value)

Cleanup changes done for foreign key check

Parameters

bool $default_fk_check_value original value for 'FOREIGN_KEY_CHECKS'

Return Value

void

at line 1677
static string asWKT(string $data, bool $includeSRID = false)

Converts GIS data to Well Known Text format

Parameters

string $data GIS data
bool $includeSRID Add SRID to the WKT

Return Value

string GIS data in Well Know Text format

at line 1714
static string duplicateFirstNewline(string $string)

If the string starts with a \r\n pair (0x0d0a) add an extra \n

Parameters

string $string string

Return Value

string with the chars replaced

at line 1733
static string|bool getTitleForTarget(string $target)

Get the action word corresponding to a script name in order to display it as a title in navigation panel

Parameters

string $target a valid value for $cfg['NavigationTreeDefaultTabTable'], $cfg['NavigationTreeDefaultTabTable2'], $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']

Return Value

string|bool Title for the $cfg value

at line 1759
static string getScriptNameForOption(string $target, string $location)

Get the script name corresponding to a plain English config word in order to append in links on navigation and main panel

Parameters

string $target a valid value for $cfg['NavigationTreeDefaultTabTable'], $cfg['NavigationTreeDefaultTabTable2'], $cfg['DefaultTabTable'], $cfg['DefaultTabDatabase'] or $cfg['DefaultTabServer']
string $location one out of 'server', 'table', 'database'

Return Value

string script name corresponding to the config word

at line 1823
static string expandUserString(string $string, array|string $escape = null, array $updates = [])

Formats user string, expanding @VARIABLES@, accepting strftime format string.

Parameters

string $string Text where to do expansion.
array|string $escape Function to call for escaping variable values. Can also be an array of: - the escape method name - the class that contains the method - location of the class (for inclusion)
array $updates Array with overrides for default parameters (obtained from GLOBALS).

Return Value

string

at line 1927
static mixed getSupportedDatatypes(bool $html = false, string $selected = '')

This function processes the datatypes supported by the DB, as specified in Types->getColumns() and either returns an array (useful for quickly checking if a datatype is supported) or an HTML snippet that creates a drop-down list.

Parameters

bool $html Whether to generate an html snippet or an array
string $selected The value to mark as selected in HTML mode

Return Value

mixed An HTML snippet or an array of datatypes.

at line 1957
static array unsupportedDatatypes()

Returns a list of datatypes that are not (yet) handled by PMA.

Used by: /table/change and libraries/db_routines.inc.php

Return Value

array list of datatypes

at line 1969
static string[] getGISDatatypes(bool $upper_case = false)

Return GIS data types

Parameters

bool $upper_case whether to return values in upper case

Return Value

string[] GIS data types

at line 1995
static string createGISData(string $gis_string, int $mysqlVersion)

Generates GIS data based on the string passed.

Parameters

string $gis_string GIS string
int $mysqlVersion The mysql version as int

Return Value

string GIS data enclosed in 'ST_GeomFromText' or 'GeomFromText' function

at line 2024
static array getGISFunctions(string $geom_type = null, bool $binary = true, bool $display = false)

Returns the names and details of the functions that can be applied on geometry data types.

Parameters

string $geom_type if provided the output is limited to the functions that are applicable to the provided geometry type.
bool $binary if set to false functions that take two geometries as arguments will not be included.
bool $display if set to true separators will be added to the output array.

Return Value

array names and details of the functions that can be applied on geometry data types.

at line 2268
static bool currentUserHasPrivilege(string $priv, mixed $db = null, mixed $tbl = null)

Checks if the current user has a specific privilege and returns true if the user indeed has that privilege or false if they don't. This function must only be used for features that are available since MySQL 5, because it relies on the INFORMATION_SCHEMA database to be present.

Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb'); // Checks if the currently logged in user has the global // 'CREATE ROUTINE' privilege or, if not, checks if the // user has this privilege on database 'mydb'.

Parameters

string $priv The privilege to check
mixed $db null, to only check global privileges string, db name where to also check for privileges
mixed $tbl null, to only check global/db privileges string, table name where to also check for privileges

Return Value

bool

at line 2353
static string getServerType()

Returns server type for current connection

Known types are: MariaDB, Percona and MySQL (default)

Return Value

string

at line 2375
static array parseEnumSetValues(string $definition, bool $escapeHtml = true)

Parses ENUM/SET values

Parameters

string $definition The definition of the column for which to parse the values
bool $escapeHtml Whether to escape html entities

Return Value

array

at line 2432
static string getFirstOccurringRegularExpression(array $regex_array, string $query)

Get regular expression which occur first inside the given sql query.

Parameters

array $regex_array Comparing regular expressions.
string $query SQL query to be checked.

Return Value

string Matching regular expression.

at line 2457
static array|null getMenuTabList(string $level = null)

Return the list of tabs for the menu with corresponding names

Parameters

string $level 'server', 'db' or 'table' level

Return Value

array|null list of tabs for the menu

at line 2524
static string addMicroseconds(string $value)

Add fractional seconds to time, datetime and timestamp strings.

If the string contains fractional seconds, pads it with 0s up to 6 decimal places.

Parameters

string $value time, datetime or timestamp strings

Return Value

string time, datetime or timestamp strings with fractional seconds

at line 2551
static string getCompressionMimeType(resource $file)

Reads the file, detects the compression MIME type, closes the file and returns the MIME type

Parameters

resource $file the file handle

Return Value

string the MIME type for compression, or 'none'

at line 2574
static string getCollateForIS()

Provide COLLATE clause, if required, to perform case sensitive comparisons for queries on information_schema.

Return Value

string COLLATE clause if needed or empty string.

at line 2592
static array processIndexData(array $indexes)

Process the index data.

Parameters

array $indexes index data

Return Value

array processes index data

at line 2644
static bool isVirtualColumnsSupported()

Returns whether the database server supports virtual columns

Return Value

bool

at line 2661
static array getDbInfo(string $db, string|null $sub_part)

Gets the list of tables in the current db and information about these tables if possible

Parameters

string $db database name
string|null $sub_part part of script name

Return Value

array

at line 2836
static array getTablesWhenOpen(string $db, object $db_info_result)

Gets the list of tables in the current db, taking into account that they might be "in use"

Parameters

string $db database name
object $db_info_result result set

Return Value

array list of tables

at line 2916
static array listPHPExtensions()

Returs list of used PHP extensions.

Return Value

array of strings

at line 2943
static string requestString(mixed $value)

Converts given (request) paramter to string

Parameters

mixed $value Value to convert

Return Value

string

at line 2957
static string generateRandom(int $length, bool $asHex = false)

Generates random string consisting of ASCII chars

Parameters

int $length Length of string
bool $asHex (optional) Send the result as hex

Return Value

string

at line 2987
static string date(string $format)

Wraper around PHP date function

Parameters

string $format Date format string

Return Value

string

at line 3000
static void setTimeLimit()

Wrapper around php's set_time_limit

Return Value

void

at line 3017
static mixed getValueByKey(array $array, string|array $path, mixed $default = null)

Access to a multidimensional array by dot notation

Parameters

array $array List of values
string|array $path Path to searched value
mixed $default Default value

Return Value

mixed Searched value

at line 3043
static string sortableTableHeader(string $title, string $sort, string $initialSortOrder = 'ASC')

Creates a clickable column header for table information

Parameters

string $title Title to use for the link
string $sort Corresponds to sortable data name mapped in Util::getDbInfo
string $initialSortOrder Initial sort order

Return Value

string Link to be displayed in the table header

at line 3131
static bool isInteger(mixed $input)

Check that input is an int or an int in a string

Parameters

mixed $input input to check

Return Value

bool

at line 3141
static array buildActionTitles()

Build titles and icons for action links

Return Value

array the action titles

at line 3174
static string getProtoFromForwardedHeader(string $headerContents)

Get the protocol from the RFC 7239 Forwarded header

Parameters

string $headerContents The Forwarded header contents

Return Value

string the protocol http/https