/phpmyadmin/libraries/Util.class.php
PHP | 4915 lines | 3062 code | 447 blank | 1406 comment | 625 complexity | 8229ea6ed76de49e94c4c89cee92b5fe MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- /* vim: set expandtab sw=4 ts=4 sts=4: */
- /**
- * Hold the PMA_Util class
- *
- * @package PhpMyAdmin
- */
- if (! defined('PHPMYADMIN')) {
- exit;
- }
- require_once 'libraries/Template.class.php';
- use PMA\Template;
- /**
- * Misc functions used all over the scripts.
- *
- * @package PhpMyAdmin
- */
- class PMA_Util
- {
- /**
- * Detects which function to use for pow.
- *
- * @return string Function name.
- */
- public static function detectPow()
- {
- if (function_exists('bcpow')) {
- // BCMath Arbitrary Precision Mathematics Function
- return 'bcpow';
- } elseif (function_exists('gmp_pow')) {
- // GMP Function
- return 'gmp_pow';
- } else {
- // PHP function
- return 'pow';
- }
- }
- /**
- * Exponential expression / raise number into power
- *
- * @param string $base base to raise
- * @param string $exp exponent to use
- * @param string $use_function pow function to use, or false for auto-detect
- *
- * @return mixed string or float
- */
- public static function pow($base, $exp, $use_function = '')
- {
- static $pow_function = null;
- if ($pow_function == null) {
- $pow_function = self::detectPow();
- }
- if (! $use_function) {
- if ($exp < 0) {
- $use_function = 'pow';
- } else {
- $use_function = $pow_function;
- }
- }
- if (($exp < 0) && ($use_function != 'pow')) {
- return false;
- }
- switch ($use_function) {
- case 'bcpow' :
- // bcscale() needed for testing pow() with base values < 1
- bcscale(10);
- $pow = bcpow($base, $exp);
- break;
- case 'gmp_pow' :
- $pow = gmp_strval(gmp_pow($base, $exp));
- break;
- case 'pow' :
- $base = (float) $base;
- $exp = (int) $exp;
- $pow = pow($base, $exp);
- break;
- default:
- $pow = $use_function($base, $exp);
- }
- return $pow;
- }
- /**
- * Checks whether configuration value tells to show icons.
- *
- * @param string $value Configuration option name
- *
- * @return boolean Whether to show icons.
- */
- public static function showIcons($value)
- {
- return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
- }
- /**
- * Checks whether configuration value tells to show text.
- *
- * @param string $value Configuration option name
- *
- * @return boolean Whether to show text.
- */
- public static function showText($value)
- {
- return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
- }
- /**
- * Returns an HTML IMG tag for a particular icon from a theme,
- * which may be an actual file or an icon from a sprite.
- * This function takes into account the ActionLinksMode
- * configuration setting and wraps the image tag in a span tag.
- *
- * @param string $icon name of icon file
- * @param string $alternate alternate text
- * @param boolean $force_text whether to force alternate text to be displayed
- * @param boolean $menu_icon whether this icon is for the menu bar or not
- * @param string $control_param which directive controls the display
- *
- * @return string an html snippet
- */
- public static function getIcon(
- $icon, $alternate = '', $force_text = false,
- $menu_icon = false, $control_param = 'ActionLinksMode'
- ) {
- $include_icon = $include_text = false;
- if (self::showIcons($control_param)) {
- $include_icon = true;
- }
- if ($force_text
- || self::showText($control_param)
- ) {
- $include_text = true;
- }
- // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
- // we don't need a span
- $button = $menu_icon ? '' : '<span class="nowrap">';
- if ($include_icon) {
- $button .= self::getImage($icon, $alternate);
- }
- if ($include_icon && $include_text) {
- $button .= ' ';
- }
- if ($include_text) {
- $button .= $alternate;
- }
- $button .= $menu_icon ? '' : '</span>';
- return $button;
- }
- /**
- * Returns an HTML IMG tag for a particular image from a theme,
- * which may be an actual file or an icon from a sprite
- *
- * @param string $image The name of the file to get
- * @param string $alternate Used to set 'alt' and 'title' attributes
- * of the image
- * @param array $attributes An associative array of other attributes
- *
- * @return string an html IMG tag
- */
- public static function getImage($image, $alternate = '', $attributes = array())
- {
- static $sprites; // cached list of available sprites (if any)
- if (defined('TESTSUITE')) {
- // prevent caching in testsuite
- unset($sprites);
- }
- $is_sprite = false;
- $alternate = htmlspecialchars($alternate);
- // If it's the first time this function is called
- if (! isset($sprites)) {
- // Try to load the list of sprites
- $sprite_file = $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
- if (is_readable($sprite_file)) {
- include_once $sprite_file;
- $sprites = PMA_sprites();
- } else {
- // No sprites are available for this theme
- $sprites = array();
- }
- }
- // Check if we have the requested image as a sprite
- // and set $url accordingly
- $class = str_replace(array('.gif','.png'), '', $image);
- if (array_key_exists($class, $sprites)) {
- $is_sprite = true;
- $url = (defined('PMA_TEST_THEME') ? '../' : '') . 'themes/dot.gif';
- } else {
- $url = $GLOBALS['pmaThemeImage'] . $image;
- }
- // set class attribute
- if ($is_sprite) {
- if (isset($attributes['class'])) {
- $attributes['class'] = "icon ic_$class " . $attributes['class'];
- } else {
- $attributes['class'] = "icon ic_$class";
- }
- }
- // set all other attributes
- $attr_str = '';
- foreach ($attributes as $key => $value) {
- if (! in_array($key, array('alt', 'title'))) {
- $attr_str .= " $key=\"$value\"";
- }
- }
- // override the alt attribute
- if (isset($attributes['alt'])) {
- $alt = $attributes['alt'];
- } else {
- $alt = $alternate;
- }
- // override the title attribute
- if (isset($attributes['title'])) {
- $title = $attributes['title'];
- } else {
- $title = $alternate;
- }
- // generate the IMG tag
- $template = '<img src="%s" title="%s" alt="%s"%s />';
- $retval = sprintf($template, $url, $title, $alt, $attr_str);
- return $retval;
- }
- /**
- * Returns the formatted maximum size for an upload
- *
- * @param integer $max_upload_size the size
- *
- * @return string the message
- *
- * @access public
- */
- public static function getFormattedMaximumUploadSize($max_upload_size)
- {
- // I have to reduce the second parameter (sensitiveness) from 6 to 4
- // to avoid weird results like 512 kKib
- list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
- return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
- }
- /**
- * Generates a hidden field which should indicate to the browser
- * the maximum size for upload
- *
- * @param integer $max_size the size
- *
- * @return string the INPUT field
- *
- * @access public
- */
- public static function generateHiddenMaxFileSize($max_size)
- {
- return '<input type="hidden" name="MAX_FILE_SIZE" value="'
- . $max_size . '" />';
- }
- /**
- * Add slashes before "'" and "\" characters so a value containing them can
- * be used in a sql comparison.
- *
- * @param string $a_string the string to slash
- * @param bool $is_like whether the string will be used in a 'LIKE' clause
- * (it then requires two more escaped sequences) or not
- * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
- * (converts \n to \\n, \r to \\r)
- * @param bool $php_code whether this function is used as part of the
- * "Create PHP code" dialog
- *
- * @return string the slashed string
- *
- * @access public
- */
- public static function sqlAddSlashes(
- $a_string = '', $is_like = false, $crlf = false, $php_code = false
- ) {
- if ($is_like) {
- $a_string = str_replace('\\', '\\\\\\\\', $a_string);
- } else {
- $a_string = str_replace('\\', '\\\\', $a_string);
- }
- if ($crlf) {
- $a_string = strtr(
- $a_string,
- array("\n" => '\n', "\r" => '\r', "\t" => '\t')
- );
- }
- if ($php_code) {
- $a_string = str_replace('\'', '\\\'', $a_string);
- } else {
- $a_string = str_replace('\'', '\\\'', $a_string);
- }
- return $a_string;
- } // end of the 'sqlAddSlashes()' function
- /**
- * Add slashes before "_" and "%" characters for using them in MySQL
- * database, table and field names.
- * Note: This function does not escape backslashes!
- *
- * @param string $name the string to escape
- *
- * @return string the escaped string
- *
- * @access public
- */
- public static function escapeMysqlWildcards($name)
- {
- return strtr($name, array('_' => '\\_', '%' => '\\%'));
- } // end of the 'escapeMysqlWildcards()' function
- /**
- * removes slashes before "_" and "%" characters
- * Note: This function does not unescape backslashes!
- *
- * @param string $name the string to escape
- *
- * @return string the escaped string
- *
- * @access public
- */
- public static function unescapeMysqlWildcards($name)
- {
- return strtr($name, array('\\_' => '_', '\\%' => '%'));
- } // end of the 'unescapeMysqlWildcards()' function
- /**
- * removes quotes (',",`) from a quoted string
- *
- * checks if the string is quoted and removes this quotes
- *
- * @param string $quoted_string string to remove quotes from
- * @param string $quote type of quote to remove
- *
- * @return string unqoted string
- */
- public static function unQuote($quoted_string, $quote = null)
- {
- $quotes = array();
- if ($quote === null) {
- $quotes[] = '`';
- $quotes[] = '"';
- $quotes[] = "'";
- } else {
- $quotes[] = $quote;
- }
- foreach ($quotes as $quote) {
- if (/*overload*/mb_substr($quoted_string, 0, 1) === $quote
- && /*overload*/mb_substr($quoted_string, -1, 1) === $quote
- ) {
- $unquoted_string = /*overload*/mb_substr($quoted_string, 1, -1);
- // replace escaped quotes
- $unquoted_string = str_replace(
- $quote . $quote,
- $quote,
- $unquoted_string
- );
- return $unquoted_string;
- }
- }
- return $quoted_string;
- }
- /**
- * format sql strings
- *
- * @param string $sqlQuery raw SQL string
- * @param boolean $truncate truncate the query if it is too long
- *
- * @return string the formatted sql
- *
- * @global array $cfg the configuration array
- *
- * @access public
- * @todo move into PMA_Sql
- */
- public static function formatSql($sqlQuery, $truncate = false)
- {
- global $cfg;
- if ($truncate
- && /*overload*/mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
- ) {
- $sqlQuery = /*overload*/mb_substr(
- $sqlQuery,
- 0,
- $cfg['MaxCharactersInDisplayedSQL']
- ) . '[...]';
- }
- return '<code class="sql"><pre>' . "\n"
- . htmlspecialchars($sqlQuery) . "\n"
- . '</pre></code>';
- } // end of the "formatSql()" function
- /**
- * Displays a link to the documentation as an icon
- *
- * @param string $link documentation link
- * @param string $target optional link target
- *
- * @return string the html link
- *
- * @access public
- */
- public static function showDocLink($link, $target = 'documentation')
- {
- return '<a href="' . $link . '" target="' . $target . '">'
- . self::getImage('b_help.png', __('Documentation'))
- . '</a>';
- } // end of the 'showDocLink()' function
- /**
- * Get a URL link to the official MySQL documentation
- *
- * @param string $link contains name of page/anchor that is being linked
- * @param string $anchor anchor to page part
- *
- * @return string the URL link
- *
- * @access public
- */
- public static function getMySQLDocuURL($link, $anchor = '')
- {
- // Fixup for newly used names:
- $link = str_replace('_', '-', /*overload*/mb_strtolower($link));
- if (empty($link)) {
- $link = 'index';
- }
- $mysql = '5.5';
- $lang = 'en';
- if (defined('PMA_MYSQL_INT_VERSION')) {
- if (PMA_MYSQL_INT_VERSION >= 50700) {
- $mysql = '5.7';
- } else if (PMA_MYSQL_INT_VERSION >= 50600) {
- $mysql = '5.6';
- } else if (PMA_MYSQL_INT_VERSION >= 50500) {
- $mysql = '5.5';
- }
- }
- $url = 'http://dev.mysql.com/doc/refman/'
- . $mysql . '/' . $lang . '/' . $link . '.html';
- if (! empty($anchor)) {
- $url .= '#' . $anchor;
- }
- return PMA_linkURL($url);
- }
- /**
- * Displays a link to the official MySQL documentation
- *
- * @param string $link contains name of page/anchor that is being linked
- * @param bool $big_icon whether to use big icon (like in left frame)
- * @param string $anchor anchor to page part
- * @param bool $just_open whether only the opening <a> tag should be returned
- *
- * @return string the html link
- *
- * @access public
- */
- public static function showMySQLDocu(
- $link, $big_icon = false, $anchor = '', $just_open = false
- ) {
- $url = self::getMySQLDocuURL($link, $anchor);
- $open_link = '<a href="' . $url . '" target="mysql_doc">';
- if ($just_open) {
- return $open_link;
- } elseif ($big_icon) {
- return $open_link
- . self::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
- } else {
- return self::showDocLink($url, 'mysql_doc');
- }
- } // end of the 'showMySQLDocu()' function
- /**
- * Returns link to documentation.
- *
- * @param string $page Page in documentation
- * @param string $anchor Optional anchor in page
- *
- * @return string URL
- */
- public static function getDocuLink($page, $anchor = '')
- {
- /* Construct base URL */
- $url = $page . '.html';
- if (!empty($anchor)) {
- $url .= '#' . $anchor;
- }
- /* Check if we have built local documentation */
- if (defined('TESTSUITE')) {
- /* Provide consistent URL for testsuite */
- return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
- } else if (file_exists('doc/html/index.html')) {
- if (defined('PMA_SETUP')) {
- return '../doc/html/' . $url;
- } else {
- return './doc/html/' . $url;
- }
- } else {
- /* TODO: Should link to correct branch for released versions */
- return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
- }
- }
- /**
- * Displays a link to the phpMyAdmin documentation
- *
- * @param string $page Page in documentation
- * @param string $anchor Optional anchor in page
- *
- * @return string the html link
- *
- * @access public
- */
- public static function showDocu($page, $anchor = '')
- {
- return self::showDocLink(self::getDocuLink($page, $anchor));
- } // end of the 'showDocu()' function
- /**
- * Displays a link to the PHP documentation
- *
- * @param string $target anchor in documentation
- *
- * @return string the html link
- *
- * @access public
- */
- public static function showPHPDocu($target)
- {
- $url = PMA_getPHPDocLink($target);
- return self::showDocLink($url);
- } // end of the 'showPHPDocu()' function
- /**
- * Returns HTML code for a tooltip
- *
- * @param string $message the message for the tooltip
- *
- * @return string
- *
- * @access public
- */
- public static function showHint($message)
- {
- if ($GLOBALS['cfg']['ShowHint']) {
- $classClause = ' class="pma_hint"';
- } else {
- $classClause = '';
- }
- return '<span' . $classClause . '>'
- . self::getImage('b_help.png')
- . '<span class="hide">' . $message . '</span>'
- . '</span>';
- }
- /**
- * Displays a MySQL error message in the main panel when $exit is true.
- * Returns the error message otherwise.
- *
- * @param string|bool $server_msg Server's error message.
- * @param string $sql_query The SQL query that failed.
- * @param bool $is_modify_link Whether to show a "modify" link or not.
- * @param string $back_url URL for the "back" link (full path is
- * not required).
- * @param bool $exit Whether execution should be stopped or
- * the error message should be returned.
- *
- * @return string
- *
- * @global string $table The current table.
- * @global string $db The current database.
- *
- * @access public
- */
- public static function mysqlDie(
- $server_msg = '', $sql_query = '',
- $is_modify_link = true, $back_url = '', $exit = true
- ) {
- global $table, $db;
- /**
- * Error message to be built.
- * @var string $error_msg
- */
- $error_msg = '';
- // Checking for any server errors.
- if (empty($server_msg)) {
- $server_msg = $GLOBALS['dbi']->getError();
- }
- // Finding the query that failed, if not specified.
- if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
- $sql_query = $GLOBALS['sql_query'];
- }
- $sql_query = trim($sql_query);
- $errors = array();
- if (! empty($sql_query)) {
- /**
- * The lexer used for analysis.
- * @var SqlParser\Lexer $lexer
- */
- $lexer = new SqlParser\Lexer($sql_query);
- /**
- * The parser used for analysis.
- * @var SqlParser\Parser $parser
- */
- $parser = new SqlParser\Parser($lexer->list);
- /**
- * The errors found by the lexer and the parser.
- * @var array $errors
- */
- $errors = SqlParser\Utils\Error::get(array($lexer, $parser));
- }
- if (empty($sql_query)) {
- $formatted_sql = '';
- } elseif (count($errors)) {
- $formatted_sql = htmlspecialchars($sql_query);
- } else {
- $formatted_sql = self::formatSql($sql_query, true);
- }
- $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
- // For security reasons, if the MySQL refuses the connection, the query
- // is hidden so no details are revealed.
- if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
- // Static analysis errors.
- if (!empty($errors)) {
- $error_msg .= '<p><strong>' . __('Static analysis:')
- . '</strong></p>';
- $error_msg .= '<p>' . sprintf(
- __('%d errors were found during analysis.'), count($errors)
- ) . '</p>';
- $error_msg .= '<p><ol>';
- $error_msg .= implode(
- SqlParser\Utils\Error::format(
- $errors,
- '<li>%2$s (near "%4$s" at position %5$d)</li>'
- )
- );
- $error_msg .= '</ol></p>';
- }
- // Display the SQL query and link to MySQL documentation.
- $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
- $formattedSqlToLower = /*overload*/mb_strtolower($formatted_sql);
- // TODO: Show documentation for all statement types.
- if (/*overload*/mb_strstr($formattedSqlToLower, 'select')) {
- // please show me help to the error on select
- $error_msg .= self::showMySQLDocu('SELECT');
- }
- if ($is_modify_link) {
- $_url_params = array(
- 'sql_query' => $sql_query,
- 'show_query' => 1,
- );
- if (/*overload*/mb_strlen($table)) {
- $_url_params['db'] = $db;
- $_url_params['table'] = $table;
- $doedit_goto = '<a href="tbl_sql.php'
- . PMA_URL_getCommon($_url_params) . '">';
- } elseif (/*overload*/mb_strlen($db)) {
- $_url_params['db'] = $db;
- $doedit_goto = '<a href="db_sql.php'
- . PMA_URL_getCommon($_url_params) . '">';
- } else {
- $doedit_goto = '<a href="server_sql.php'
- . PMA_URL_getCommon($_url_params) . '">';
- }
- $error_msg .= $doedit_goto
- . self::getIcon('b_edit.png', __('Edit'))
- . '</a>';
- }
- $error_msg .= ' </p>' . "\n"
- . '<p>' . "\n"
- . $formatted_sql . "\n"
- . '</p>' . "\n";
- }
- // Display server's error.
- if (!empty($server_msg)) {
- $server_msg = preg_replace(
- "@((\015\012)|(\015)|(\012)){3,}@",
- "\n\n",
- $server_msg
- );
- // Adds a link to MySQL documentation.
- $error_msg .= '<p>' . "\n"
- . ' <strong>' . __('MySQL said: ') . '</strong>'
- . self::showMySQLDocu('Error-messages-server')
- . "\n"
- . '</p>' . "\n";
- // The error message will be displayed within a CODE segment.
- // To preserve original formatting, but allow word-wrapping,
- // a couple of replacements are done.
- // All non-single blanks and TAB-characters are replaced with their
- // HTML-counterpart
- $server_msg = str_replace(
- array(' ', "\t"),
- array(' ', ' '),
- $server_msg
- );
- // Replace line breaks
- $server_msg = nl2br($server_msg);
- $error_msg .= '<code>' . $server_msg . '</code><br/>';
- }
- $error_msg .= '</div>';
- $_SESSION['Import_message']['message'] = $error_msg;
- if (!$exit) {
- return $error_msg;
- }
- /**
- * If this is an AJAX request, there is no "Back" link and
- * `PMA_Response()` is used to send the response.
- */
- if (!empty($GLOBALS['is_ajax_request'])) {
- $response = PMA_Response::getInstance();
- $response->isSuccess(false);
- $response->addJSON('message', $error_msg);
- exit;
- }
- if (!empty($back_url)) {
- if (/*overload*/mb_strstr($back_url, '?')) {
- $back_url .= '&no_history=true';
- } else {
- $back_url .= '?no_history=true';
- }
- $_SESSION['Import_message']['go_back_url'] = $back_url;
- $error_msg .= '<fieldset class="tblFooters">'
- . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
- . '</fieldset>' . "\n\n";
- }
- exit($error_msg);
- }
- /**
- * Check the correct row count
- *
- * @param string $db the db name
- * @param array $table the table infos
- *
- * @return int $rowCount the possibly modified row count
- *
- */
- private static function _checkRowCount($db, $table)
- {
- $rowCount = 0;
- if ($table['Rows'] === null) {
- // Do not check exact row count here,
- // if row count is invalid possibly the table is defect
- // and this would break the navigation panel;
- // but we can check row count if this is a view or the
- // information_schema database
- // since PMA_Table::countRecords() returns a limited row count
- // in this case.
- // set this because PMA_Table::countRecords() can use it
- $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
- if ($tbl_is_view || $GLOBALS['dbi']->isSystemSchema($db)) {
- $rowCount = $GLOBALS['dbi']
- ->getTable($db, $table['Name'])
- ->countRecords();
- }
- }
- return $rowCount;
- }
- /**
- * returns array with tables of given db with extended information and grouped
- *
- * @param string $db name of db
- * @param string $tables name of tables
- * @param integer $limit_offset list offset
- * @param int|bool $limit_count max tables to return
- *
- * @return array (recursive) grouped table list
- */
- public static function getTableList(
- $db, $tables = null, $limit_offset = 0, $limit_count = false
- ) {
- $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
- if ($tables === null) {
- $tables = $GLOBALS['dbi']->getTablesFull(
- $db, '', false, null, $limit_offset, $limit_count
- );
- if ($GLOBALS['cfg']['NaturalOrder']) {
- uksort($tables, 'strnatcasecmp');
- }
- }
- if (count($tables) < 1) {
- return $tables;
- }
- $default = array(
- 'Name' => '',
- 'Rows' => 0,
- 'Comment' => '',
- 'disp_name' => '',
- );
- $table_groups = array();
- foreach ($tables as $table_name => $table) {
- $table['Rows'] = self::_checkRowCount($db, $table);
- // in $group we save the reference to the place in $table_groups
- // where to store the table info
- if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
- && $sep && /*overload*/mb_strstr($table_name, $sep)
- ) {
- $parts = explode($sep, $table_name);
- $group =& $table_groups;
- $i = 0;
- $group_name_full = '';
- $parts_cnt = count($parts) - 1;
- while (($i < $parts_cnt)
- && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
- ) {
- $group_name = $parts[$i] . $sep;
- $group_name_full .= $group_name;
- if (! isset($group[$group_name])) {
- $group[$group_name] = array();
- $group[$group_name]['is' . $sep . 'group'] = true;
- $group[$group_name]['tab' . $sep . 'count'] = 1;
- $group[$group_name]['tab' . $sep . 'group']
- = $group_name_full;
- } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
- $table = $group[$group_name];
- $group[$group_name] = array();
- $group[$group_name][$group_name] = $table;
- unset($table);
- $group[$group_name]['is' . $sep . 'group'] = true;
- $group[$group_name]['tab' . $sep . 'count'] = 1;
- $group[$group_name]['tab' . $sep . 'group']
- = $group_name_full;
- } else {
- $group[$group_name]['tab' . $sep . 'count']++;
- }
- $group =& $group[$group_name];
- $i++;
- }
- } else {
- if (! isset($table_groups[$table_name])) {
- $table_groups[$table_name] = array();
- }
- $group =& $table_groups;
- }
- $table['disp_name'] = $table['Name'];
- $group[$table_name] = array_merge($default, $table);
- }
- return $table_groups;
- }
- /* ----------------------- Set of misc functions ----------------------- */
- /**
- * Adds backquotes on both sides of a database, table or field name.
- * and escapes backquotes inside the name with another backquote
- *
- * example:
- * <code>
- * echo backquote('owner`s db'); // `owner``s db`
- *
- * </code>
- *
- * @param mixed $a_name the database, table or field name to "backquote"
- * or array of it
- * @param boolean $do_it a flag to bypass this function (used by dump
- * functions)
- *
- * @return mixed the "backquoted" database, table or field name
- *
- * @access public
- */
- public static function backquote($a_name, $do_it = true)
- {
- if (is_array($a_name)) {
- foreach ($a_name as &$data) {
- $data = self::backquote($data, $do_it);
- }
- return $a_name;
- }
- if (! $do_it) {
- if (!(SqlParser\Context::isKeyword($a_name) & SqlParser\Token::FLAG_KEYWORD_RESERVED)
- ) {
- return $a_name;
- }
- }
- // '0' is also empty for php :-(
- if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
- return '`' . str_replace('`', '``', $a_name) . '`';
- } else {
- return $a_name;
- }
- } // end of the 'backquote()' function
- /**
- * Adds backquotes on both sides of a database, table or field name.
- * in compatibility mode
- *
- * example:
- * <code>
- * echo backquoteCompat('owner`s db'); // `owner``s db`
- *
- * </code>
- *
- * @param mixed $a_name the database, table or field name to
- * "backquote" or array of it
- * @param string $compatibility string compatibility mode (used by dump
- * functions)
- * @param boolean $do_it a flag to bypass this function (used by dump
- * functions)
- *
- * @return mixed the "backquoted" database, table or field name
- *
- * @access public
- */
- public static function backquoteCompat(
- $a_name, $compatibility = 'MSSQL', $do_it = true
- ) {
- if (is_array($a_name)) {
- foreach ($a_name as &$data) {
- $data = self::backquoteCompat($data, $compatibility, $do_it);
- }
- return $a_name;
- }
- if (! $do_it) {
- if (!SqlParser\Context::isKeyword($a_name)) {
- return $a_name;
- }
- }
- // @todo add more compatibility cases (ORACLE for example)
- switch ($compatibility) {
- case 'MSSQL':
- $quote = '"';
- break;
- default:
- $quote = "`";
- break;
- }
- // '0' is also empty for php :-(
- if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
- return $quote . $a_name . $quote;
- } else {
- return $a_name;
- }
- } // end of the 'backquoteCompat()' function
- /**
- * Defines the <CR><LF> value depending on the user OS.
- *
- * @return string the <CR><LF> value to use
- *
- * @access public
- */
- public static function whichCrlf()
- {
- // The 'PMA_USR_OS' constant is defined in "libraries/Config.class.php"
- // Win case
- if (PMA_USR_OS == 'Win') {
- $the_crlf = "\r\n";
- } else {
- // Others
- $the_crlf = "\n";
- }
- return $the_crlf;
- } // end of the 'whichCrlf()' function
- /**
- * Prepare the message and the query
- * usually the message is the result of the query executed
- *
- * @param PMA_Message|string $message the message to display
- * @param string $sql_query the query to display
- * @param string $type the type (level) of the message
- *
- * @return string
- *
- * @access public
- */
- public static function getMessage(
- $message, $sql_query = null, $type = 'notice'
- ) {
- global $cfg;
- $retval = '';
- if (null === $sql_query) {
- if (! empty($GLOBALS['display_query'])) {
- $sql_query = $GLOBALS['display_query'];
- } elseif (! empty($GLOBALS['unparsed_sql'])) {
- $sql_query = $GLOBALS['unparsed_sql'];
- } elseif (! empty($GLOBALS['sql_query'])) {
- $sql_query = $GLOBALS['sql_query'];
- } else {
- $sql_query = '';
- }
- }
- if (isset($GLOBALS['using_bookmark_message'])) {
- $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
- unset($GLOBALS['using_bookmark_message']);
- }
- // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
- // check for it's presence before using it
- $retval .= '<div class="result_query"'
- . ( isset($GLOBALS['cell_align_left'])
- ? ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
- : '' )
- . '>' . "\n";
- if ($message instanceof PMA_Message) {
- if (isset($GLOBALS['special_message'])) {
- $message->addMessage($GLOBALS['special_message']);
- unset($GLOBALS['special_message']);
- }
- $retval .= $message->getDisplay();
- } else {
- $retval .= '<div class="' . $type . '">';
- $retval .= PMA_sanitize($message);
- if (isset($GLOBALS['special_message'])) {
- $retval .= PMA_sanitize($GLOBALS['special_message']);
- unset($GLOBALS['special_message']);
- }
- $retval .= '</div>';
- }
- if ($cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';') {
- // Html format the query to be displayed
- // If we want to show some sql code it is easiest to create it here
- /* SQL-Parser-Analyzer */
- if (! empty($GLOBALS['show_as_php'])) {
- $new_line = '\\n"<br />' . "\n"
- . ' . "';
- $query_base = htmlspecialchars(addslashes($sql_query));
- $query_base = preg_replace(
- '/((\015\012)|(\015)|(\012))/', $new_line, $query_base
- );
- } else {
- $query_base = $sql_query;
- }
- $query_too_big = false;
- $queryLength = /*overload*/mb_strlen($query_base);
- if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
- // when the query is large (for example an INSERT of binary
- // data), the parser chokes; so avoid parsing the query
- $query_too_big = true;
- $shortened_query_base = nl2br(
- htmlspecialchars(
- /*overload*/mb_substr(
- $sql_query,
- 0,
- $cfg['MaxCharactersInDisplayedSQL']
- ) . '[...]'
- )
- );
- }
- if (! empty($GLOBALS['show_as_php'])) {
- $query_base = '$sql = "' . $query_base;
- } elseif (isset($query_base)) {
- $query_base = self::formatSql($query_base);
- }
- // Prepares links that may be displayed to edit/explain the query
- // (don't go to default pages, we must go to the page
- // where the query box is available)
- // Basic url query part
- $url_params = array();
- if (! isset($GLOBALS['db'])) {
- $GLOBALS['db'] = '';
- }
- if (/*overload*/mb_strlen($GLOBALS['db'])) {
- $url_params['db'] = $GLOBALS['db'];
- if (/*overload*/mb_strlen($GLOBALS['table'])) {
- $url_params['table'] = $GLOBALS['table'];
- $edit_link = 'tbl_sql.php';
- } else {
- $edit_link = 'db_sql.php';
- }
- } else {
- $edit_link = 'server_sql.php';
- }
- // Want to have the query explained
- // but only explain a SELECT (that has not been explained)
- /* SQL-Parser-Analyzer */
- $explain_link = '';
- $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
- if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
- $explain_params = $url_params;
- if ($is_select) {
- $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
- $explain_link = ' ['
- . self::linkOrButton(
- 'import.php' . PMA_URL_getCommon($explain_params),
- __('Explain SQL')
- ) . ']';
- } elseif (preg_match(
- '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query
- )) {
- $explain_params['sql_query']
- = /*overload*/mb_substr($sql_query, 8);
- $explain_link = ' ['
- . self::linkOrButton(
- 'import.php' . PMA_URL_getCommon($explain_params),
- __('Skip Explain SQL')
- ) . ']';
- $url = 'https://mariadb.org/explain_analyzer/analyze/'
- . '?client=phpMyAdmin&raw_explain='
- . urlencode(self::_generateRowQueryOutput($sql_query));
- $explain_link .= ' ['
- . self::linkOrButton(
- 'url.php?url=' . urlencode($url),
- sprintf(__('Analyze Explain at %s'), 'mariadb.org'),
- array(),
- true,
- false,
- '_blank'
- ) . ']';
- }
- } //show explain
- $url_params['sql_query'] = $sql_query;
- $url_params['show_query'] = 1;
- // even if the query is big and was truncated, offer the chance
- // to edit it (unless it's enormous, see linkOrButton() )
- if (! empty($cfg['SQLQuery']['Edit'])) {
- $edit_link .= PMA_URL_getCommon($url_params) . '#querybox';
- $edit_link = ' ['
- . self::linkOrButton(
- $edit_link, __('Edit')
- )
- . ']';
- } else {
- $edit_link = '';
- }
- // Also we would like to get the SQL formed in some nice
- // php-code
- if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
- $php_params = $url_params;
- if (! empty($GLOBALS['show_as_php'])) {
- $_message = __('Without PHP Code');
- } else {
- $php_params['show_as_php'] = 1;
- $_message = __('Create PHP code');
- }
- $php_link = 'import.php' . PMA_URL_getCommon($php_params);
- $php_link = ' [' . self::linkOrButton($php_link, $_message) . ']';
- if (isset($GLOBALS['show_as_php'])) {
- $runquery_link = 'import.php'
- . PMA_URL_getCommon($url_params);
- $php_link .= ' ['
- . self::linkOrButton($runquery_link, __('Submit Query'))
- . ']';
- }
- } else {
- $php_link = '';
- } //show as php
- // Refresh query
- if (! empty($cfg['SQLQuery']['Refresh'])
- && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
- && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
- ) {
- $refresh_link = 'import.php' . PMA_URL_getCommon($url_params);
- $refresh_link = ' ['
- . self::linkOrButton($refresh_link, __('Refresh')) . ']';
- } else {
- $refresh_link = '';
- } //refresh
- $retval .= '<div class="sqlOuter">';
- if ($query_too_big) {
- $retval .= $shortened_query_base;
- } else {
- $retval .= $query_base;
- }
- //Clean up the end of the PHP
- if (! empty($GLOBALS['show_as_php'])) {
- $retval .= '";';
- }
- $retval .= '</div>';
- $retval .= '<div class="tools print_ignore">';
- $retval .= '<form action="sql.php" method="post">';
- $retval .= PMA_URL_getHiddenInputs(
- $GLOBALS['db'], $GLOBALS['table']
- );
- $retval .= '<input type="hidden" name="sql_query" value="'
- . htmlspecialchars($sql_query) . '" />';
- // avoid displaying a Profiling checkbox that could
- // be checked, which would reexecute an INSERT, for example
- if (! empty($refresh_link) && self::profilingSupported()) {
- $retval .= '<input type="hidden" name="profiling_form" value="1" />';
- $retval .= self::getCheckbox(
- 'profiling', __('Profiling'), isset($_SESSION['profiling']), true
- );
- }
- $retval .= '</form>';
- /**
- * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
- */
- if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
- $inline_edit_link = ' ['
- . self::linkOrButton(
- '#',
- _pgettext('Inline edit query', 'Edit inline'),
- array('class' => 'inline_edit_sql')
- )
- . ']';
- } else {
- $inline_edit_link = '';
- }
- $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
- . $refresh_link;
- $retval .= '</div>';
- }
- $retval .= '</div>';
- if ($GLOBALS['is_ajax_request'] === false) {
- $retval .= '<br class="clearfloat" />';
- }
- return $retval;
- } // end of the 'getMessage()' function
- /**
- * Execute an EXPLAIN query and formats results similar to MySQL command line
- * utility.
- *
- * @param string $sqlQuery EXPLAIN query
- *
- * @return string query resuls
- */
- private static function _generateRowQueryOutput($sqlQuery)
- {
- $ret = '';
- $result = $GLOBALS['dbi']->query($sqlQuery);
- if ($result) {
- $devider = '+';
- $columnNames = '|';
- $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result);
- foreach ($fieldsMeta as $meta) {
- $devider .= '---+';
- $columnNames .= ' ' . $meta->name . ' |';
- }
- $devider .= "\n";
- $ret .= $devider . $columnNames . "\n" . $devider;
- while ($row = $GLOBALS['dbi']->fetchRow($result)) {
- $values = '|';
- foreach ($row as $value) {
- if (is_null($value)) {
- $value = 'NULL';
- }
- $values .= ' ' . $value . ' |';
- }
- $ret .= $values . "\n";
- }
- $ret .= $devider;
- }
- return $ret;
- }
- /**
- * Verifies if current MySQL server supports profiling
- *
- * @access public
- *
- * @return boolean whether profiling is supported
- */
- public static function profilingSupported()
- {
- if (!self::cacheExists('profiling_supported')) {
- // 5.0.37 has profiling but for example, 5.1.20 does not
- // (avoid a trip to the server for MySQL before 5.0.37)
- // and do not set a constant as we might be switching servers
- if (defined('PMA_MYSQL_INT_VERSION')
- && $GLOBALS['dbi']->fetchValue("SELECT @@have_profiling")
- ) {
- self::cacheSet('profiling_supported', true);
- } else {
- self::cacheSet('profiling_supported', false);
- }
- }
- return self::cacheGet('profiling_supported');
- }
- /**
- * Formats $value to byte view
- *
- * @param double|int $value the value to format
- * @param int $limes the sensitiveness
- * @param int $comma the number of decimals to retain
- *
- * @return array the formatted value and its unit
- *
- * @access public
- */
- public static function formatByteDown($value, $limes = 6, $comma = 0)
- {
- if ($value === null) {
- return null;
- }
- $byteUnits = array(
- /* l10n: shortcuts for Byte */
- __('B'),
- /* l10n: shortcuts for Kilobyte */
- __('KiB'),
- /* l10n: shortcuts for Megabyte */
- __('MiB'),
- /* l10n: shortcuts for Gigabyte */
- __('GiB'),
- /* l10n: shortcuts for Terabyte */
- __('TiB'),
- /* l10n: shortcuts for Petabyte */
- __('PiB'),
- /* l10n: shortcuts for Exabyte */
- __('EiB')
- );
- $dh = self::pow(10, $comma);
- $li = self::pow(10, $limes);
- $unit = $byteUnits[0];
- for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
- // cast to float to avoid overflow
- $unitSize = (float) $li * self::pow(10, $ex);
- if (isset($byteUnits[$d]) && $value >= $unitSize) {
- // use 1024.0 to avoid integer overflow on 64-bit machines
- $value = round($value / (self::pow(1024, $d) / $dh)) /$dh;
- $unit = $byteUnits[$d];
- break 1;
- } // end if
- } // end for
- if ($unit != $byteUnits[0]) {
- // if the unit is not bytes (as represented in current language)
- // reformat with max length of 5
- // 4th parameter=true means do not reformat if value < 1
- $return_value = self::formatNumber($value, 5, $comma, true);
- } else {
- // do not reformat, just handle the locale
- $return_value = self::formatNumber($value, 0);
- }
- return array(trim($return_value), $unit);
- } // end of the 'formatByteDown' function
- /**
- * Changes thousands and decimal separators to locale specific values.
- *
- * @param string $value the value
- *
- * @return string
- */
- public static function localizeNumber($value)
- {
- return str_replace(
- array(',', '.'),
- array(
- /* l10n: Thousands separator */
- __(','),
- /* l10n: Decimal separator */
- __('.'),
- ),
- $value
- );
- }
- /**
- * 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:
- * <code>
- * 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
- * </code>
- *
- * @param double $value the value to format
- * @param integer $digits_left number of digits left of the comma
- * @param integer $digits_right number of digits right of the comma
- * @param boolean $only_down do not reformat numbers below 1
- * @param boolean $noTrailingZero removes trailing zeros right of the comma
- * (default: true)
- *
- * @return string the formatted value and its unit
- *
- * @access public
- */
- public static function formatNumber(
- $value, $digits_left = 3, $digits_right = 0,
- $only_down = false, $noTrailingZero = true
- …
Large files files are truncated, but you can click here to view the full file