class Util (View source)

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|float|string $maxUploadSize)

Returns the formatted maximum size for an upload

static string
unQuote(string $quotedString, string|null $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 database server of the user.

static string
backquote(Stringable|string|null $identifier)

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

static string
backquoteCompat(Stringable|string|null $identifier, string $compatibility = 'MSSQL', bool $doIt = true)

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

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

Formats $value to byte view

static string
formatNumber(float|int|string $value, int $digitsLeft = 3, int $digitsRight = 0, bool $onlyDown = 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|float
extractValueFromFormattedSize(string|int $formattedSize)

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 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 $maxCount)

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
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|null $bitDefaultValue)

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

static array
extractColumnSpec(string $columnSpecification)

Extracts the various parts from a column spec

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
getUrlForOption(string $target, string $location)

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

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

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

static array
getSupportedDatatypes()

This function processes the datatypes supported by the DB, as specified in Types->getColumns() and returns an array (useful for quickly checking if a datatype is supported).

static array
unsupportedDatatypes()

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

static bool
isUUIDSupported()

This function is to check whether database support UUID

static bool
currentUserHasPrivilege(string $priv, string|null $db = null, string|null $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 array
getMenuTabList(UserGroupLevel $level)

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 array
getDbInfo(ServerRequest $request, string $db, bool $isResultLimited = true)

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

static array
listPHPExtensions()

Returns list of used PHP extensions.

static string
requestString(mixed $value)

Converts given (request) parameter to string

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

Generates random string consisting of ASCII chars

static string
date(string $format)

Wrapper around PHP date function

static void
setTimeLimit()

Wrapper around php's set_time_limit

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

Access to a multidimensional array recursively by the keys specified in $path

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 string
getProtoFromForwardedHeader(string $headerContents)

Get the protocol from the RFC 7239 Forwarded header

static int
getTableListPosition(ServerRequest $request, string $db)

No description

Details

static bool showIcons(string $value)

Checks whether configuration value tells to show icons.

Parameters

string $value

Configuration option name

Return Value

bool

static bool showText(string $value)

Checks whether configuration value tells to show text.

Parameters

string $value

Configuration option name

Return Value

bool

static string getFormattedMaximumUploadSize(int|float|string $maxUploadSize)

Returns the formatted maximum size for an upload

Parameters

int|float|string $maxUploadSize

the size

Return Value

string

the message

static string unQuote(string $quotedString, string|null $quote = null)

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

checks if the string is quoted and removes this quotes

Parameters

string $quotedString

string to remove quotes from

string|null $quote

type of quote to remove

Return Value

string

unquoted string

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

static string getDocuURL(bool $isMariaDB = false)

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

Parameters

bool $isMariaDB

if the database server is MariaDB

Return Value

string

The URL link

static string backquote(Stringable|string|null $identifier)

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

and escapes backquotes inside the name with another backquote

example:

echo backquote('owner`s db'); // `owner``s db`

Parameters

Stringable|string|null $identifier

the database, table or field name to "backquote"

Return Value

string

static string backquoteCompat(Stringable|string|null $identifier, string $compatibility = 'MSSQL', bool $doIt = true)

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

in compatibility mode

example:

echo backquoteCompat('owner`s db'); // `owner``s db`

Parameters

Stringable|string|null $identifier

the database, table or field name to "backquote"

string $compatibility

string compatibility mode (used by dump functions)

bool $doIt

a flag to bypass this function (used by dump functions)

Return Value

string

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

Formats $value to byte view

Parameters

float|int|string|null $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

static string formatNumber(float|int|string $value, int $digitsLeft = 3, int $digitsRight = 0, bool $onlyDown = 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

float|int|string $value

the value to format

int $digitsLeft

number of digits left of the comma

int $digitsRight

number of digits right of the comma

bool $onlyDown

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

static int|float extractValueFromFormattedSize(string|int $formattedSize)

Returns the number of bytes when a formatted size is given

Parameters

string|int $formattedSize

the size expression (for example 8MB)

Return Value

int|float

The numerical part of the expression (for example 8)

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

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

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

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

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

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

Calculate page number through position

Parameters

int $pos

position of first item

int $maxCount

number of items per page

Return Value

int $page_num

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

static void clearUserCache()

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

Return Value

void

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

static string convertBitDefaultValue(string|null $bitDefaultValue)

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

Parameters

string|null $bitDefaultValue value

Return Value

string

the converted value

static array extractColumnSpec(string $columnSpecification)

Extracts the various parts from a column spec

Parameters

string $columnSpecification

Column specification

Return Value

array

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

static string duplicateFirstNewline(string $string)

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

Parameters

string $string

Return Value

string

with the chars replaced

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

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

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

Get the URL 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

The URL corresponding to the config word

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

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

Parameters

string $string

Text where to do expansion.

callable|null $escape

Function to call for escaping variable values.

array $updates

Array with overrides for default parameters (obtained from GLOBALS).

Return Value

string

static array getSupportedDatatypes()

This function processes the datatypes supported by the DB, as specified in Types->getColumns() and returns an array (useful for quickly checking if a datatype is supported).

Return Value

array

An array of datatypes.

static array unsupportedDatatypes()

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

Used by: /table/change and libraries/Routines.php

Return Value

array

list of datatypes

static bool isUUIDSupported()

This function is to check whether database support UUID

Return Value

bool

static bool currentUserHasPrivilege(string $priv, string|null $db = null, string|null $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

string|null $db

null, to only check global privileges string, db name where to also check for privileges

string|null $tbl

null, to only check global/db privileges string, table name where to also check for privileges

Return Value

bool

static string getServerType()

Returns server type for current connection

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

Return Value

string

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

static array getMenuTabList(UserGroupLevel $level)

Return the list of tabs for the menu with corresponding names

Parameters

UserGroupLevel $level

Return Value

array

list of tabs for the menu

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

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'

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.

static array processIndexData(array $indexes)

Process the index data.

Parameters

array $indexes

index data

Return Value

array

processes index data

static array getDbInfo(ServerRequest $request, string $db, bool $isResultLimited = true)

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

Parameters

ServerRequest $request
string $db
bool $isResultLimited

Return Value

array

static array listPHPExtensions()

Returns list of used PHP extensions.

Return Value

array

static string requestString(mixed $value)

Converts given (request) parameter to string

Parameters

mixed $value

Value to convert

Return Value

string

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

static string date(string $format)

Wrapper around PHP date function

Parameters

string $format

Date format string

Return Value

string

static void setTimeLimit()

Wrapper around php's set_time_limit

Return Value

void

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

Access to a multidimensional array recursively by the keys specified in $path

Parameters

array $array

List of values

array $path

Path to searched value

mixed $default

Default value

Return Value

mixed

Searched value

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

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

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

static int getTableListPosition(ServerRequest $request, string $db)

No description

Parameters

ServerRequest $request
string $db

Return Value

int