2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Hold the PMA\libraries\Util class
8 namespace PMA\libraries
;
10 use PMA\libraries\plugins\ImportPlugin
;
11 use SqlParser\Context
;
16 use SqlParser\Utils\Error
as ParserError
;
17 use PMA\libraries\URL
;
18 use PMA\libraries\Sanitize
;
19 use PMA\libraries\Template
;
21 if (! defined('PHPMYADMIN')) {
26 * Misc functions used all over the scripts.
33 * Checks whether configuration value tells to show icons.
35 * @param string $value Configuration option name
37 * @return boolean Whether to show icons.
39 public static function showIcons($value)
41 return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
45 * Checks whether configuration value tells to show text.
47 * @param string $value Configuration option name
49 * @return boolean Whether to show text.
51 public static function showText($value)
53 return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
57 * Returns an HTML IMG tag for a particular icon from a theme,
58 * which may be an actual file or an icon from a sprite.
59 * This function takes into account the ActionLinksMode
60 * configuration setting and wraps the image tag in a span tag.
62 * @param string $icon name of icon file
63 * @param string $alternate alternate text
64 * @param boolean $force_text whether to force alternate text to be displayed
65 * @param boolean $menu_icon whether this icon is for the menu bar or not
66 * @param string $control_param which directive controls the display
68 * @return string an html snippet
70 public static function getIcon(
75 $control_param = 'ActionLinksMode'
77 $include_icon = $include_text = false;
78 if (self
::showIcons($control_param)) {
82 || self
::showText($control_param)
86 // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
87 // we don't need a span
88 $button = $menu_icon ?
'' : '<span class="nowrap">';
90 $button .= self
::getImage($icon, $alternate);
92 if ($include_icon && $include_text) {
96 $button .= $alternate;
98 $button .= $menu_icon ?
'' : '</span>';
104 * Returns an HTML IMG tag for a particular image from a theme,
105 * which may be an actual file or an icon from a sprite
107 * @param string $image The name of the file to get
108 * @param string $alternate Used to set 'alt' and 'title' attributes
110 * @param array $attributes An associative array of other attributes
112 * @return string an html IMG tag
114 public static function getImage($image, $alternate = '', $attributes = array())
116 static $sprites; // cached list of available sprites (if any)
117 if (defined('TESTSUITE')) {
118 // prevent caching in testsuite
123 $alternate = htmlspecialchars($alternate);
125 // If it's the first time this function is called
126 if (! isset($sprites)) {
128 // Try to load the list of sprites
129 if (isset($_SESSION['PMA_Theme'])) {
130 $sprites = $_SESSION['PMA_Theme']->getSpriteData();
134 // Check if we have the requested image as a sprite
135 // and set $url accordingly
136 $class = str_replace(array('.gif','.png'), '', $image);
137 if (array_key_exists($class, $sprites)) {
139 $url = (defined('PMA_TEST_THEME') ?
'../' : '') . 'themes/dot.gif';
140 } elseif (isset($GLOBALS['pmaThemeImage'])) {
141 $url = $GLOBALS['pmaThemeImage'] . $image;
143 $url = './themes/pmahomme/' . $image;
146 // set class attribute
148 if (isset($attributes['class'])) {
149 $attributes['class'] = "icon ic_$class " . $attributes['class'];
151 $attributes['class'] = "icon ic_$class";
155 // set all other attributes
157 foreach ($attributes as $key => $value) {
158 if (! in_array($key, array('alt', 'title'))) {
159 $attr_str .= " $key=\"$value\"";
163 // override the alt attribute
164 if (isset($attributes['alt'])) {
165 $alt = $attributes['alt'];
170 // override the title attribute
171 if (isset($attributes['title'])) {
172 $title = $attributes['title'];
177 // generate the IMG tag
178 $template = '<img src="%s" title="%s" alt="%s"%s />';
179 $retval = sprintf($template, $url, $title, $alt, $attr_str);
185 * Returns the formatted maximum size for an upload
187 * @param integer $max_upload_size the size
189 * @return string the message
193 public static function getFormattedMaximumUploadSize($max_upload_size)
195 // I have to reduce the second parameter (sensitiveness) from 6 to 4
196 // to avoid weird results like 512 kKib
197 list($max_size, $max_unit) = self
::formatByteDown($max_upload_size, 4);
198 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
202 * Generates a hidden field which should indicate to the browser
203 * the maximum size for upload
205 * @param integer $max_size the size
207 * @return string the INPUT field
211 public static function generateHiddenMaxFileSize($max_size)
213 return '<input type="hidden" name="MAX_FILE_SIZE" value="'
214 . $max_size . '" />';
218 * Add slashes before "_" and "%" characters for using them in MySQL
219 * database, table and field names.
220 * Note: This function does not escape backslashes!
222 * @param string $name the string to escape
224 * @return string the escaped string
228 public static function escapeMysqlWildcards($name)
230 return strtr($name, array('_' => '\\_', '%' => '\\%'));
231 } // end of the 'escapeMysqlWildcards()' function
234 * removes slashes before "_" and "%" characters
235 * Note: This function does not unescape backslashes!
237 * @param string $name the string to escape
239 * @return string the escaped string
243 public static function unescapeMysqlWildcards($name)
245 return strtr($name, array('\\_' => '_', '\\%' => '%'));
246 } // end of the 'unescapeMysqlWildcards()' function
249 * removes quotes (',",`) from a quoted string
251 * checks if the string is quoted and removes this quotes
253 * @param string $quoted_string string to remove quotes from
254 * @param string $quote type of quote to remove
256 * @return string unqoted string
258 public static function unQuote($quoted_string, $quote = null)
262 if ($quote === null) {
270 foreach ($quotes as $quote) {
271 if (mb_substr($quoted_string, 0, 1) === $quote
272 && mb_substr($quoted_string, -1, 1) === $quote
274 $unquoted_string = mb_substr($quoted_string, 1, -1);
275 // replace escaped quotes
276 $unquoted_string = str_replace(
281 return $unquoted_string;
285 return $quoted_string;
291 * @param string $sqlQuery raw SQL string
292 * @param boolean $truncate truncate the query if it is too long
294 * @return string the formatted sql
296 * @global array $cfg the configuration array
299 * @todo move into PMA_Sql
301 public static function formatSql($sqlQuery, $truncate = false)
306 && mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
308 $sqlQuery = mb_substr(
311 $cfg['MaxCharactersInDisplayedSQL']
314 return '<code class="sql"><pre>' . "\n"
315 . htmlspecialchars($sqlQuery) . "\n"
317 } // end of the "formatSql()" function
320 * Displays a link to the documentation as an icon
322 * @param string $link documentation link
323 * @param string $target optional link target
324 * @param boolean $bbcode optional flag indicating whether to output bbcode
326 * @return string the html link
330 public static function showDocLink($link, $target = 'documentation', $bbcode = false)
333 return "[a@$link@$target][dochelpicon][/a]";
335 return '<a href="' . $link . '" target="' . $target . '">'
336 . self
::getImage('b_help.png', __('Documentation'))
339 } // end of the 'showDocLink()' function
342 * Get a URL link to the official MySQL documentation
344 * @param string $link contains name of page/anchor that is being linked
345 * @param string $anchor anchor to page part
347 * @return string the URL link
351 public static function getMySQLDocuURL($link, $anchor = '')
353 // Fixup for newly used names:
354 $link = str_replace('_', '-', mb_strtolower($link));
361 if (defined('PMA_MYSQL_INT_VERSION')) {
362 if (PMA_MYSQL_INT_VERSION
>= 50700) {
364 } elseif (PMA_MYSQL_INT_VERSION
>= 50600) {
366 } elseif (PMA_MYSQL_INT_VERSION
>= 50500) {
370 $url = 'https://dev.mysql.com/doc/refman/'
371 . $mysql . '/' . $lang . '/' . $link . '.html';
372 if (! empty($anchor)) {
373 $url .= '#' . $anchor;
376 return PMA_linkURL($url);
380 * Displays a link to the official MySQL documentation
382 * @param string $link contains name of page/anchor that is being linked
383 * @param bool $big_icon whether to use big icon (like in left frame)
384 * @param string $anchor anchor to page part
385 * @param bool $just_open whether only the opening <a> tag should be returned
387 * @return string the html link
391 public static function showMySQLDocu(
397 $url = self
::getMySQLDocuURL($link, $anchor);
398 $open_link = '<a href="' . $url . '" target="mysql_doc">';
401 } elseif ($big_icon) {
403 . self
::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
405 return self
::showDocLink($url, 'mysql_doc');
407 } // end of the 'showMySQLDocu()' function
410 * Returns link to documentation.
412 * @param string $page Page in documentation
413 * @param string $anchor Optional anchor in page
417 public static function getDocuLink($page, $anchor = '')
419 /* Construct base URL */
420 $url = $page . '.html';
421 if (!empty($anchor)) {
422 $url .= '#' . $anchor;
425 /* Check if we have built local documentation */
426 if (defined('TESTSUITE')) {
427 /* Provide consistent URL for testsuite */
428 return PMA_linkURL('https://docs.phpmyadmin.net/en/latest/' . $url);
429 } elseif (@file_exists
('doc/html/index.html')) {
430 if (defined('PMA_SETUP')) {
431 return '../doc/html/' . $url;
433 return './doc/html/' . $url;
436 /* TODO: Should link to correct branch for released versions */
437 return PMA_linkURL('https://docs.phpmyadmin.net/en/latest/' . $url);
442 * Displays a link to the phpMyAdmin documentation
444 * @param string $page Page in documentation
445 * @param string $anchor Optional anchor in page
446 * @param boolean $bbcode Optional flag indicating whether to output bbcode
448 * @return string the html link
452 public static function showDocu($page, $anchor = '', $bbcode = false)
454 return self
::showDocLink(self
::getDocuLink($page, $anchor), 'documentation', $bbcode);
455 } // end of the 'showDocu()' function
458 * Displays a link to the PHP documentation
460 * @param string $target anchor in documentation
462 * @return string the html link
466 public static function showPHPDocu($target)
468 $url = PMA_getPHPDocLink($target);
470 return self
::showDocLink($url);
471 } // end of the 'showPHPDocu()' function
474 * Returns HTML code for a tooltip
476 * @param string $message the message for the tooltip
482 public static function showHint($message)
484 if ($GLOBALS['cfg']['ShowHint']) {
485 $classClause = ' class="pma_hint"';
489 return '<span' . $classClause . '>'
490 . self
::getImage('b_help.png')
491 . '<span class="hide">' . $message . '</span>'
496 * Displays a MySQL error message in the main panel when $exit is true.
497 * Returns the error message otherwise.
499 * @param string|bool $server_msg Server's error message.
500 * @param string $sql_query The SQL query that failed.
501 * @param bool $is_modify_link Whether to show a "modify" link or not.
502 * @param string $back_url URL for the "back" link (full path is
504 * @param bool $exit Whether execution should be stopped or
505 * the error message should be returned.
509 * @global string $table The current table.
510 * @global string $db The current database.
514 public static function mysqlDie(
517 $is_modify_link = true,
524 * Error message to be built.
525 * @var string $error_msg
529 // Checking for any server errors.
530 if (empty($server_msg)) {
531 $server_msg = $GLOBALS['dbi']->getError();
534 // Finding the query that failed, if not specified.
535 if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
536 $sql_query = $GLOBALS['sql_query'];
538 $sql_query = trim($sql_query);
541 * The lexer used for analysis.
544 $lexer = new Lexer($sql_query);
547 * The parser used for analysis.
548 * @var Parser $parser
550 $parser = new Parser($lexer->list);
553 * The errors found by the lexer and the parser.
556 $errors = ParserError
::get(array($lexer, $parser));
558 if (empty($sql_query)) {
560 } elseif (count($errors)) {
561 $formatted_sql = htmlspecialchars($sql_query);
563 $formatted_sql = self
::formatSql($sql_query, true);
566 $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
568 // For security reasons, if the MySQL refuses the connection, the query
569 // is hidden so no details are revealed.
570 if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
571 // Static analysis errors.
572 if (!empty($errors)) {
573 $error_msg .= '<p><strong>' . __('Static analysis:')
575 $error_msg .= '<p>' . sprintf(
576 __('%d errors were found during analysis.'),
579 $error_msg .= '<p><ol>';
580 $error_msg .= implode(
583 '<li>%2$s (near "%4$s" at position %5$d)</li>'
586 $error_msg .= '</ol></p>';
589 // Display the SQL query and link to MySQL documentation.
590 $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
591 $formattedSqlToLower = mb_strtolower($formatted_sql);
593 // TODO: Show documentation for all statement types.
594 if (mb_strstr($formattedSqlToLower, 'select')) {
595 // please show me help to the error on select
596 $error_msg .= self
::showMySQLDocu('SELECT');
599 if ($is_modify_link) {
600 $_url_params = array(
601 'sql_query' => $sql_query,
604 if (strlen($table) > 0) {
605 $_url_params['db'] = $db;
606 $_url_params['table'] = $table;
607 $doedit_goto = '<a href="tbl_sql.php'
608 . URL
::getCommon($_url_params) . '">';
609 } elseif (strlen($db) > 0) {
610 $_url_params['db'] = $db;
611 $doedit_goto = '<a href="db_sql.php'
612 . URL
::getCommon($_url_params) . '">';
614 $doedit_goto = '<a href="server_sql.php'
615 . URL
::getCommon($_url_params) . '">';
618 $error_msg .= $doedit_goto
619 . self
::getIcon('b_edit.png', __('Edit'))
623 $error_msg .= ' </p>' . "\n"
625 . $formatted_sql . "\n"
629 // Display server's error.
630 if (!empty($server_msg)) {
631 $server_msg = preg_replace(
632 "@((\015\012)|(\015)|(\012)){3,}@",
637 // Adds a link to MySQL documentation.
638 $error_msg .= '<p>' . "\n"
639 . ' <strong>' . __('MySQL said: ') . '</strong>'
640 . self
::showMySQLDocu('Error-messages-server')
644 // The error message will be displayed within a CODE segment.
645 // To preserve original formatting, but allow word-wrapping,
646 // a couple of replacements are done.
647 // All non-single blanks and TAB-characters are replaced with their
649 $server_msg = str_replace(
651 array(' ', ' '),
655 // Replace line breaks
656 $server_msg = nl2br($server_msg);
658 $error_msg .= '<code>' . $server_msg . '</code><br/>';
661 $error_msg .= '</div>';
662 $_SESSION['Import_message']['message'] = $error_msg;
669 * If this is an AJAX request, there is no "Back" link and
670 * `Response()` is used to send the response.
672 $response = Response
::getInstance();
673 if ($response->isAjax()) {
674 $response->setRequestStatus(false);
675 $response->addJSON('message', $error_msg);
679 if (!empty($back_url)) {
680 if (mb_strstr($back_url, '?')) {
681 $back_url .= '&no_history=true';
683 $back_url .= '?no_history=true';
686 $_SESSION['Import_message']['go_back_url'] = $back_url;
688 $error_msg .= '<fieldset class="tblFooters">'
689 . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
690 . '</fieldset>' . "\n\n";
697 * Check the correct row count
699 * @param string $db the db name
700 * @param array $table the table infos
702 * @return int $rowCount the possibly modified row count
705 private static function _checkRowCount($db, $table)
709 if ($table['Rows'] === null) {
710 // Do not check exact row count here,
711 // if row count is invalid possibly the table is defect
712 // and this would break the navigation panel;
713 // but we can check row count if this is a view or the
714 // information_schema database
715 // since Table::countRecords() returns a limited row count
718 // set this because Table::countRecords() can use it
719 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
721 if ($tbl_is_view ||
$GLOBALS['dbi']->isSystemSchema($db)) {
722 $rowCount = $GLOBALS['dbi']
723 ->getTable($db, $table['Name'])
731 * returns array with tables of given db with extended information and grouped
733 * @param string $db name of db
734 * @param string $tables name of tables
735 * @param integer $limit_offset list offset
736 * @param int|bool $limit_count max tables to return
738 * @return array (recursive) grouped table list
740 public static function getTableList(
746 $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
748 if ($tables === null) {
749 $tables = $GLOBALS['dbi']->getTablesFull(
757 if ($GLOBALS['cfg']['NaturalOrder']) {
758 uksort($tables, 'strnatcasecmp');
762 if (count($tables) < 1) {
773 $table_groups = array();
775 foreach ($tables as $table_name => $table) {
776 $table['Rows'] = self
::_checkRowCount($db, $table);
778 // in $group we save the reference to the place in $table_groups
779 // where to store the table info
780 if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
781 && $sep && mb_strstr($table_name, $sep)
783 $parts = explode($sep, $table_name);
785 $group =& $table_groups;
787 $group_name_full = '';
788 $parts_cnt = count($parts) - 1;
790 while (($i < $parts_cnt)
791 && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
793 $group_name = $parts[$i] . $sep;
794 $group_name_full .= $group_name;
796 if (! isset($group[$group_name])) {
797 $group[$group_name] = array();
798 $group[$group_name]['is' . $sep . 'group'] = true;
799 $group[$group_name]['tab' . $sep . 'count'] = 1;
800 $group[$group_name]['tab' . $sep . 'group']
803 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
804 $table = $group[$group_name];
805 $group[$group_name] = array();
806 $group[$group_name][$group_name] = $table;
807 $group[$group_name]['is' . $sep . 'group'] = true;
808 $group[$group_name]['tab' . $sep . 'count'] = 1;
809 $group[$group_name]['tab' . $sep . 'group']
813 $group[$group_name]['tab' . $sep . 'count']++
;
816 $group =& $group[$group_name];
821 if (! isset($table_groups[$table_name])) {
822 $table_groups[$table_name] = array();
824 $group =& $table_groups;
827 $table['disp_name'] = $table['Name'];
828 $group[$table_name] = array_merge($default, $table);
831 return $table_groups;
834 /* ----------------------- Set of misc functions ----------------------- */
837 * Adds backquotes on both sides of a database, table or field name.
838 * and escapes backquotes inside the name with another backquote
842 * echo backquote('owner`s db'); // `owner``s db`
846 * @param mixed $a_name the database, table or field name to "backquote"
848 * @param boolean $do_it a flag to bypass this function (used by dump
851 * @return mixed the "backquoted" database, table or field name
855 public static function backquote($a_name, $do_it = true)
857 if (is_array($a_name)) {
858 foreach ($a_name as &$data) {
859 $data = self
::backquote($data, $do_it);
865 if (!(Context
::isKeyword($a_name) & Token
::FLAG_KEYWORD_RESERVED
)
871 // '0' is also empty for php :-(
872 if (strlen($a_name) > 0 && $a_name !== '*') {
873 return '`' . str_replace('`', '``', $a_name) . '`';
877 } // end of the 'backquote()' function
880 * Adds backquotes on both sides of a database, table or field name.
881 * in compatibility mode
885 * echo backquoteCompat('owner`s db'); // `owner``s db`
889 * @param mixed $a_name the database, table or field name to
890 * "backquote" or array of it
891 * @param string $compatibility string compatibility mode (used by dump
893 * @param boolean $do_it a flag to bypass this function (used by dump
896 * @return mixed the "backquoted" database, table or field name
900 public static function backquoteCompat(
902 $compatibility = 'MSSQL',
905 if (is_array($a_name)) {
906 foreach ($a_name as &$data) {
907 $data = self
::backquoteCompat($data, $compatibility, $do_it);
913 if (!Context
::isKeyword($a_name)) {
918 // @todo add more compatibility cases (ORACLE for example)
919 switch ($compatibility) {
928 // '0' is also empty for php :-(
929 if (strlen($a_name) > 0 && $a_name !== '*') {
930 return $quote . $a_name . $quote;
934 } // end of the 'backquoteCompat()' function
937 * Defines the <CR><LF> value depending on the user OS.
939 * @return string the <CR><LF> value to use
943 public static function whichCrlf()
945 // The 'PMA_USR_OS' constant is defined in "libraries/Config.php"
947 if (PMA_USR_OS
== 'Win') {
955 } // end of the 'whichCrlf()' function
958 * Prepare the message and the query
959 * usually the message is the result of the query executed
961 * @param Message|string $message the message to display
962 * @param string $sql_query the query to display
963 * @param string $type the type (level) of the message
969 public static function getMessage(
977 if (null === $sql_query) {
978 if (! empty($GLOBALS['display_query'])) {
979 $sql_query = $GLOBALS['display_query'];
980 } elseif (! empty($GLOBALS['unparsed_sql'])) {
981 $sql_query = $GLOBALS['unparsed_sql'];
982 } elseif (! empty($GLOBALS['sql_query'])) {
983 $sql_query = $GLOBALS['sql_query'];
989 $render_sql = $cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';';
991 if (isset($GLOBALS['using_bookmark_message'])) {
992 $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
993 unset($GLOBALS['using_bookmark_message']);
997 $retval .= '<div class="result_query"'
998 . ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
1002 if ($message instanceof Message
) {
1003 if (isset($GLOBALS['special_message'])) {
1004 $message->addText($GLOBALS['special_message']);
1005 unset($GLOBALS['special_message']);
1007 $retval .= $message->getDisplay();
1009 $retval .= '<div class="' . $type . '">';
1010 $retval .= Sanitize
::sanitize($message);
1011 if (isset($GLOBALS['special_message'])) {
1012 $retval .= Sanitize
::sanitize($GLOBALS['special_message']);
1013 unset($GLOBALS['special_message']);
1015 $retval .= '</div>';
1019 $query_too_big = false;
1021 $queryLength = mb_strlen($sql_query);
1022 if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
1023 // when the query is large (for example an INSERT of binary
1024 // data), the parser chokes; so avoid parsing the query
1025 $query_too_big = true;
1026 $query_base = mb_substr(
1029 $cfg['MaxCharactersInDisplayedSQL']
1032 $query_base = $sql_query;
1035 // Html format the query to be displayed
1036 // If we want to show some sql code it is easiest to create it here
1037 /* SQL-Parser-Analyzer */
1039 if (! empty($GLOBALS['show_as_php'])) {
1040 $new_line = '\\n"<br />' . "\n" . ' . "';
1041 $query_base = '$sql = \'' . $query_base;
1042 $query_base = '<code class="php"><pre>' . "\n"
1043 . htmlspecialchars(addslashes($query_base));
1044 $query_base = preg_replace(
1045 '/((\015\012)|(\015)|(\012))/',
1049 $query_base = '$sql = \'' . $query_base . '"';
1050 } elseif ($query_too_big) {
1051 $query_base = htmlspecialchars($query_base);
1053 $query_base = self
::formatSql($query_base);
1056 // Prepares links that may be displayed to edit/explain the query
1057 // (don't go to default pages, we must go to the page
1058 // where the query box is available)
1060 // Basic url query part
1061 $url_params = array();
1062 if (! isset($GLOBALS['db'])) {
1063 $GLOBALS['db'] = '';
1065 if (strlen($GLOBALS['db']) > 0) {
1066 $url_params['db'] = $GLOBALS['db'];
1067 if (strlen($GLOBALS['table']) > 0) {
1068 $url_params['table'] = $GLOBALS['table'];
1069 $edit_link = 'tbl_sql.php';
1071 $edit_link = 'db_sql.php';
1074 $edit_link = 'server_sql.php';
1077 // Want to have the query explained
1078 // but only explain a SELECT (that has not been explained)
1079 /* SQL-Parser-Analyzer */
1081 $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
1082 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1083 $explain_params = $url_params;
1085 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1086 $explain_link = ' ['
1087 . self
::linkOrButton(
1088 'import.php' . URL
::getCommon($explain_params),
1091 } elseif (preg_match(
1092 '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i',
1095 $explain_params['sql_query']
1096 = mb_substr($sql_query, 8);
1097 $explain_link = ' ['
1098 . self
::linkOrButton(
1099 'import.php' . URL
::getCommon($explain_params),
1100 __('Skip Explain SQL')
1102 $url = 'https://mariadb.org/explain_analyzer/analyze/'
1103 . '?client=phpMyAdmin&raw_explain='
1104 . urlencode(self
::_generateRowQueryOutput($sql_query));
1105 $explain_link .= ' ['
1106 . self
::linkOrButton(
1107 htmlspecialchars('url.php?url=' . urlencode($url)),
1108 sprintf(__('Analyze Explain at %s'), 'mariadb.org'),
1117 $url_params['sql_query'] = $sql_query;
1118 $url_params['show_query'] = 1;
1120 // even if the query is big and was truncated, offer the chance
1121 // to edit it (unless it's enormous, see linkOrButton() )
1122 if (! empty($cfg['SQLQuery']['Edit'])
1123 && empty($GLOBALS['show_as_php'])
1125 $edit_link .= URL
::getCommon($url_params) . '#querybox';
1127 . self
::linkOrButton($edit_link, __('Edit'))
1133 // Also we would like to get the SQL formed in some nice
1135 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1137 if (! empty($GLOBALS['show_as_php'])) {
1139 . self
::linkOrButton(
1140 'import.php' . URL
::getCommon($url_params),
1141 __('Without PHP code'),
1151 . self
::linkOrButton(
1152 'import.php' . URL
::getCommon($url_params),
1162 $php_params = $url_params;
1163 $php_params['show_as_php'] = 1;
1164 $_message = __('Create PHP code');
1166 . self
::linkOrButton(
1167 'import.php' . URL
::getCommon($php_params),
1177 if (! empty($cfg['SQLQuery']['Refresh'])
1178 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1179 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1181 $refresh_link = 'import.php' . URL
::getCommon($url_params);
1182 $refresh_link = ' ['
1183 . self
::linkOrButton($refresh_link, __('Refresh')) . ']';
1188 $retval .= '<div class="sqlOuter">';
1189 $retval .= $query_base;
1191 //Clean up the end of the PHP
1192 if (! empty($GLOBALS['show_as_php'])) {
1193 $retval .= '\';' . "\n"
1196 $retval .= '</div>';
1198 $retval .= '<div class="tools print_ignore">';
1199 $retval .= '<form action="sql.php" method="post">';
1200 $retval .= URL
::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']);
1201 $retval .= '<input type="hidden" name="sql_query" value="'
1202 . htmlspecialchars($sql_query) . '" />';
1204 // avoid displaying a Profiling checkbox that could
1205 // be checked, which would reexecute an INSERT, for example
1206 if (! empty($refresh_link) && self
::profilingSupported()) {
1207 $retval .= '<input type="hidden" name="profiling_form" value="1" />';
1208 $retval .= Template
::get('checkbox')
1211 'html_field_name' => 'profiling',
1212 'label' => __('Profiling'),
1213 'checked' => isset($_SESSION['profiling']),
1215 'html_field_id' => '',
1219 $retval .= '</form>';
1222 * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
1224 if (! empty($cfg['SQLQuery']['Edit'])
1226 && empty($GLOBALS['show_as_php'])
1228 $inline_edit_link = ' ['
1229 . self
::linkOrButton(
1231 _pgettext('Inline edit query', 'Edit inline'),
1232 array('class' => 'inline_edit_sql')
1236 $inline_edit_link = '';
1238 $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
1240 $retval .= '</div>';
1242 $retval .= '</div>';
1246 } // end of the 'getMessage()' function
1249 * Execute an EXPLAIN query and formats results similar to MySQL command line
1252 * @param string $sqlQuery EXPLAIN query
1254 * @return string query resuls
1256 private static function _generateRowQueryOutput($sqlQuery)
1259 $result = $GLOBALS['dbi']->query($sqlQuery);
1263 $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result);
1264 foreach ($fieldsMeta as $meta) {
1266 $columnNames .= ' ' . $meta->name
. ' |';
1270 $ret .= $devider . $columnNames . "\n" . $devider;
1271 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
1273 foreach ($row as $value) {
1274 if (is_null($value)) {
1277 $values .= ' ' . $value . ' |';
1279 $ret .= $values . "\n";
1287 * Verifies if current MySQL server supports profiling
1291 * @return boolean whether profiling is supported
1293 public static function profilingSupported()
1295 if (!self
::cacheExists('profiling_supported')) {
1296 // 5.0.37 has profiling but for example, 5.1.20 does not
1297 // (avoid a trip to the server for MySQL before 5.0.37)
1298 // and do not set a constant as we might be switching servers
1299 if (defined('PMA_MYSQL_INT_VERSION')
1300 && $GLOBALS['dbi']->fetchValue("SELECT @@have_profiling")
1302 self
::cacheSet('profiling_supported', true);
1304 self
::cacheSet('profiling_supported', false);
1308 return self
::cacheGet('profiling_supported');
1312 * Formats $value to byte view
1314 * @param double|int $value the value to format
1315 * @param int $limes the sensitiveness
1316 * @param int $comma the number of decimals to retain
1318 * @return array the formatted value and its unit
1322 public static function formatByteDown($value, $limes = 6, $comma = 0)
1324 if ($value === null) {
1329 /* l10n: shortcuts for Byte */
1331 /* l10n: shortcuts for Kilobyte */
1333 /* l10n: shortcuts for Megabyte */
1335 /* l10n: shortcuts for Gigabyte */
1337 /* l10n: shortcuts for Terabyte */
1339 /* l10n: shortcuts for Petabyte */
1341 /* l10n: shortcuts for Exabyte */
1345 $dh = pow(10, $comma);
1346 $li = pow(10, $limes);
1347 $unit = $byteUnits[0];
1349 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1350 $unitSize = $li * pow(10, $ex);
1351 if (isset($byteUnits[$d]) && $value >= $unitSize) {
1352 // use 1024.0 to avoid integer overflow on 64-bit machines
1353 $value = round($value / (pow(1024, $d) / $dh)) /$dh;
1354 $unit = $byteUnits[$d];
1359 if ($unit != $byteUnits[0]) {
1360 // if the unit is not bytes (as represented in current language)
1361 // reformat with max length of 5
1362 // 4th parameter=true means do not reformat if value < 1
1363 $return_value = self
::formatNumber($value, 5, $comma, true);
1365 // do not reformat, just handle the locale
1366 $return_value = self
::formatNumber($value, 0);
1369 return array(trim($return_value), $unit);
1370 } // end of the 'formatByteDown' function
1374 * Formats $value to the given length and appends SI prefixes
1375 * with a $length of 0 no truncation occurs, number is only formatted
1376 * to the current locale
1380 * echo formatNumber(123456789, 6); // 123,457 k
1381 * echo formatNumber(-123456789, 4, 2); // -123.46 M
1382 * echo formatNumber(-0.003, 6); // -3 m
1383 * echo formatNumber(0.003, 3, 3); // 0.003
1384 * echo formatNumber(0.00003, 3, 2); // 0.03 m
1385 * echo formatNumber(0, 6); // 0
1388 * @param double $value the value to format
1389 * @param integer $digits_left number of digits left of the comma
1390 * @param integer $digits_right number of digits right of the comma
1391 * @param boolean $only_down do not reformat numbers below 1
1392 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1395 * @return string the formatted value and its unit
1399 public static function formatNumber(
1404 $noTrailingZero = true
1410 $originalValue = $value;
1411 //number_format is not multibyte safe, str_replace is safe
1412 if ($digits_left === 0) {
1413 $value = number_format(
1416 /* l10n: Decimal separator */
1418 /* l10n: Thousands separator */
1421 if (($originalValue != 0) && (floatval($value) == 0)) {
1422 $value = ' <' . (1 / pow(10, $digits_right));
1427 // this units needs no translation, ISO
1448 // check for negative value to retain sign
1451 $value = abs($value);
1456 $dh = pow(10, $digits_right);
1459 * This gives us the right SI prefix already,
1460 * but $digits_left parameter not incorporated
1462 $d = floor(log10($value) / 3);
1464 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1465 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1466 * to use, then lower the SI prefix
1468 $cur_digits = floor(log10($value / pow(1000, $d))+
1);
1469 if ($digits_left > $cur_digits) {
1470 $d -= floor(($digits_left - $cur_digits)/3);
1473 if ($d < 0 && $only_down) {
1477 $value = round($value / (pow(1000, $d) / $dh)) /$dh;
1480 // number_format is not multibyte safe, str_replace is safe
1481 $formattedValue = number_format(
1484 /* l10n: Decimal separator */
1486 /* l10n: Thousands separator */
1489 // If we don't want any zeros, remove them now
1490 if ($noTrailingZero && strpos($formattedValue, '.') !== false) {
1491 $formattedValue = preg_replace('/\.?0+$/', '', $formattedValue);
1494 if ($originalValue != 0 && floatval($value) == 0) {
1495 return ' <' . number_format(
1496 (1 / pow(10, $digits_right)),
1498 /* l10n: Decimal separator */
1500 /* l10n: Thousands separator */
1506 return $sign . $formattedValue . ' ' . $unit;
1507 } // end of the 'formatNumber' function
1510 * Returns the number of bytes when a formatted size is given
1512 * @param string $formatted_size the size expression (for example 8MB)
1514 * @return integer The numerical part of the expression (for example 8)
1516 public static function extractValueFromFormattedSize($formatted_size)
1520 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1521 $return_value = mb_substr($formatted_size, 0, -2)
1523 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1524 $return_value = mb_substr($formatted_size, 0, -2)
1526 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1527 $return_value = mb_substr($formatted_size, 0, -1)
1530 return $return_value;
1531 }// end of the 'extractValueFromFormattedSize' function
1534 * Writes localised date
1536 * @param integer $timestamp the current timestamp
1537 * @param string $format format
1539 * @return string the formatted date
1543 public static function localisedDate($timestamp = -1, $format = '')
1546 /* l10n: Short month name */
1548 /* l10n: Short month name */
1550 /* l10n: Short month name */
1552 /* l10n: Short month name */
1554 /* l10n: Short month name */
1555 _pgettext('Short month name', 'May'),
1556 /* l10n: Short month name */
1558 /* l10n: Short month name */
1560 /* l10n: Short month name */
1562 /* l10n: Short month name */
1564 /* l10n: Short month name */
1566 /* l10n: Short month name */
1568 /* l10n: Short month name */
1570 $day_of_week = array(
1571 /* l10n: Short week day name */
1572 _pgettext('Short week day name', 'Sun'),
1573 /* l10n: Short week day name */
1575 /* l10n: Short week day name */
1577 /* l10n: Short week day name */
1579 /* l10n: Short week day name */
1581 /* l10n: Short week day name */
1583 /* l10n: Short week day name */
1586 if ($format == '') {
1587 /* l10n: See https://secure.php.net/manual/en/function.strftime.php */
1588 $format = __('%B %d, %Y at %I:%M %p');
1591 if ($timestamp == -1) {
1592 $timestamp = time();
1595 $date = preg_replace(
1597 $day_of_week[(int)strftime('%w', $timestamp)],
1600 $date = preg_replace(
1602 $month[(int)strftime('%m', $timestamp)-1],
1606 $ret = strftime($date, $timestamp);
1607 // Some OSes such as Win8.1 Traditional Chinese version did not produce UTF-8
1608 // output here. See https://sourceforge.net/p/phpmyadmin/bugs/4207/
1609 if (mb_detect_encoding($ret, 'UTF-8', true) != 'UTF-8') {
1610 $ret = date('Y-m-d H:i:s', $timestamp);
1614 } // end of the 'localisedDate()' function
1617 * returns a tab for tabbed navigation.
1618 * If the variables $link and $args ar left empty, an inactive tab is created
1620 * @param array $tab array with all options
1621 * @param array $url_params tab specific URL parameters
1623 * @return string html code for one tab, a link if valid otherwise a span
1627 public static function getHtmlTab($tab, $url_params = array())
1643 $tab = array_merge($defaults, $tab);
1645 // determine additional style-class
1646 if (empty($tab['class'])) {
1647 if (! empty($tab['active'])
1648 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1650 $tab['class'] = 'active';
1651 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1652 && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])
1654 $tab['class'] = 'active';
1658 // If there are any tab specific URL parameters, merge those with
1659 // the general URL parameters
1660 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1661 $url_params = array_merge($url_params, $tab['url_params']);
1665 if (! empty($tab['link'])) {
1666 $tab['link'] = htmlentities($tab['link']);
1667 $tab['link'] = $tab['link'] . URL
::getCommon($url_params);
1668 if (! empty($tab['args'])) {
1669 foreach ($tab['args'] as $param => $value) {
1670 $tab['link'] .= URL
::getArgSeparator('html')
1671 . urlencode($param) . '=' . urlencode($value);
1676 if (! empty($tab['fragment'])) {
1677 $tab['link'] .= $tab['fragment'];
1681 if (isset($tab['icon'])) {
1682 // avoid generating an alt tag, because it only illustrates
1683 // the text that follows and if browser does not display
1684 // images, the text is duplicated
1685 $tab['text'] = self
::getIcon(
1693 } elseif (empty($tab['text'])) {
1694 // check to not display an empty link-text
1697 'empty linktext in function ' . __FUNCTION__
. '()',
1702 //Set the id for the tab, if set in the params
1703 $tabId = (empty($tab['id']) ?
null : $tab['id']);
1706 if (!empty($tab['link'])) {
1708 'content' => $tab['text'],
1710 'href' => empty($tab['link']) ?
null : $tab['link'],
1712 'class' => 'tab' . htmlentities($tab['class']),
1716 $item['content'] = '<span class="tab' . htmlentities($tab['class']) . '"'
1717 . $tabId . '>' . $tab['text'] . '</span>';
1720 $item['class'] = $tab['class'] == 'active' ?
'active' : '';
1722 return Template
::get('list/item')
1724 } // end of the 'getHtmlTab()' function
1727 * returns html-code for a tab navigation
1729 * @param array $tabs one element per tab
1730 * @param array $url_params additional URL parameters
1731 * @param string $menu_id HTML id attribute for the menu container
1732 * @param bool $resizable whether to add a "resizable" class
1734 * @return string html-code for tab-navigation
1736 public static function getHtmlTabs(
1744 $class = ' class="resizable-menu"';
1747 $tab_navigation = '<div id="' . htmlentities($menu_id)
1748 . 'container" class="menucontainer">'
1749 . '<ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
1751 foreach ($tabs as $tab) {
1752 $tab_navigation .= self
::getHtmlTab($tab, $url_params);
1756 '<div class="clearfloat"></div>'
1760 return $tab_navigation;
1764 * Displays a link, or a button if the link's URL is too large, to
1765 * accommodate some browsers' limitations
1767 * @param string $url the URL
1768 * @param string $message the link message
1769 * @param mixed $tag_params string: js confirmation
1770 * array: additional tag params (f.e. style="")
1771 * @param boolean $new_form we set this to false when we are already in
1772 * a form, to avoid generating nested forms
1773 * @param boolean $strip_img whether to strip the image
1774 * @param string $target target
1775 * @param boolean $force_button use a button even when the URL is not too long
1777 * @return string the results to be echoed or saved in an array
1779 public static function linkOrButton(
1780 $url, $message, $tag_params = array(),
1781 $new_form = true, $strip_img = false, $target = '', $force_button = false
1783 $url_length = mb_strlen($url);
1784 // with this we should be able to catch case of image upload
1785 // into a (MEDIUM) BLOB; not worth generating even a form for these
1786 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1790 if (! is_array($tag_params)) {
1792 $tag_params = array();
1793 if (! empty($tmp)) {
1794 $tag_params['onclick'] = 'return confirmLink(this, \''
1795 . Sanitize
::escapeJsString($tmp) . '\')';
1799 if (! empty($target)) {
1800 $tag_params['target'] = htmlentities($target);
1801 if ($target === '_blank' && strncmp($url, 'url.php?', 8) == 0) {
1802 $tag_params['rel'] = 'noopener noreferrer';
1806 $displayed_message = '';
1807 // Add text if not already added
1808 if (stristr($message, '<img')
1809 && (! $strip_img ||
($GLOBALS['cfg']['ActionLinksMode'] == 'icons'))
1810 && (strip_tags($message) == $message)
1812 $displayed_message = '<span>'
1814 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1819 // Suhosin: Check that each query parameter is not above maximum
1820 $in_suhosin_limits = true;
1821 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1822 $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
1823 if ($suhosin_get_MaxValueLength) {
1824 $query_parts = self
::splitURLQuery($url);
1825 foreach ($query_parts as $query_pair) {
1826 if (strpos($query_pair, '=') === false) {
1830 list(, $eachval) = explode('=', $query_pair);
1831 if (mb_strlen($eachval) > $suhosin_get_MaxValueLength
1833 $in_suhosin_limits = false;
1840 if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
1841 && $in_suhosin_limits
1844 $tag_params_strings = array();
1845 foreach ($tag_params as $par_name => $par_value) {
1846 // htmlspecialchars() only on non javascript
1847 $par_value = mb_substr($par_name, 0, 2) == 'on'
1849 : htmlspecialchars($par_value);
1850 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1853 // no whitespace within an <a> else Safari will make it part of the link
1854 $ret = "\n" . '<a href="' . $url . '" '
1855 . implode(' ', $tag_params_strings) . '>'
1856 . $message . $displayed_message . '</a>' . "\n";
1858 // no spaces (line breaks) at all
1859 // or after the hidden fields
1860 // IE will display them all
1862 if (! isset($query_parts)) {
1863 $query_parts = self
::splitURLQuery($url);
1865 $url_parts = parse_url($url);
1869 $target = ' target="' . $target . '"';
1871 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1872 . ' method="post"' . $target . ' style="display: inline;">';
1874 $subname_close = '';
1877 $query_parts[] = 'redirect=' . $url_parts['path'];
1878 if (empty($GLOBALS['subform_counter'])) {
1879 $GLOBALS['subform_counter'] = 0;
1881 $GLOBALS['subform_counter']++
;
1883 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1884 $subname_close = ']';
1885 $submit_link = '#usesubform[' . $GLOBALS['subform_counter']
1889 foreach ($query_parts as $query_pair) {
1890 list($eachvar, $eachval) = explode('=', $query_pair);
1891 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1892 . $subname_close . '" value="'
1893 . htmlspecialchars(urldecode($eachval)) . '" />';
1896 if (empty($tag_params['class'])) {
1897 $tag_params['class'] = 'formLinkSubmit';
1899 $tag_params['class'] .= ' formLinkSubmit';
1902 $tag_params_strings = array();
1903 foreach ($tag_params as $par_name => $par_value) {
1904 // htmlspecialchars() only on non javascript
1905 $par_value = mb_substr($par_name, 0, 2) == 'on'
1907 : htmlspecialchars($par_value);
1908 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1911 $ret .= "\n" . '<a href="' . $submit_link . '" '
1912 . implode(' ', $tag_params_strings) . '>'
1913 . $message . ' ' . $displayed_message . '</a>' . "\n";
1918 } // end if... else...
1921 } // end of the 'linkOrButton()' function
1924 * Splits a URL string by parameter
1926 * @param string $url the URL
1928 * @return array the parameter/value pairs, for example [0] db=sakila
1930 public static function splitURLQuery($url)
1932 // decode encoded url separators
1933 $separator = URL
::getArgSeparator();
1934 // on most places separator is still hard coded ...
1935 if ($separator !== '&') {
1936 // ... so always replace & with $separator
1937 $url = str_replace(htmlentities('&'), $separator, $url);
1938 $url = str_replace('&', $separator, $url);
1941 $url = str_replace(htmlentities($separator), $separator, $url);
1944 $url_parts = parse_url($url);
1946 if (! empty($url_parts['query'])) {
1947 return explode($separator, $url_parts['query']);
1954 * Returns a given timespan value in a readable format.
1956 * @param int $seconds the timespan
1958 * @return string the formatted value
1960 public static function timespanFormat($seconds)
1962 $days = floor($seconds / 86400);
1964 $seconds -= $days * 86400;
1967 $hours = floor($seconds / 3600);
1968 if ($days > 0 ||
$hours > 0) {
1969 $seconds -= $hours * 3600;
1972 $minutes = floor($seconds / 60);
1973 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1974 $seconds -= $minutes * 60;
1978 __('%s days, %s hours, %s minutes and %s seconds'),
1987 * Function added to avoid path disclosures.
1988 * Called by each script that needs parameters, it displays
1989 * an error message and, by default, stops the execution.
1991 * Not sure we could use a strMissingParameter message here,
1992 * would have to check if the error message file is always available
1994 * @param string[] $params The names of the parameters needed by the calling
1996 * @param bool $request Whether to include this list in checking for
2001 * @global boolean $checked_special flag whether any special variable
2006 public static function checkParameters($params, $request = true)
2008 global $checked_special;
2010 if (! isset($checked_special)) {
2011 $checked_special = false;
2014 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2015 $found_error = false;
2016 $error_message = '';
2018 foreach ($params as $param) {
2019 if ($request && ($param != 'db') && ($param != 'table')) {
2020 $checked_special = true;
2023 if (! isset($GLOBALS[$param])) {
2024 $error_message .= $reported_script_name
2025 . ': ' . __('Missing parameter:') . ' '
2027 . self
::showDocu('faq', 'faqmissingparameters',true)
2029 $found_error = true;
2033 PMA_fatalError($error_message);
2038 * Function to generate unique condition for specified row.
2040 * @param resource $handle current query result
2041 * @param integer $fields_cnt number of fields
2042 * @param array $fields_meta meta information about fields
2043 * @param array $row current row
2044 * @param boolean $force_unique generate condition only on pk
2046 * @param string|boolean $restrict_to_table restrict the unique condition
2047 * to this table or false if
2049 * @param array $analyzed_sql_results the analyzed query
2053 * @return array the calculated condition and whether condition is unique
2055 public static function getUniqueCondition(
2056 $handle, $fields_cnt, $fields_meta, $row, $force_unique = false,
2057 $restrict_to_table = false, $analyzed_sql_results = null
2061 $nonprimary_condition = '';
2062 $preferred_condition = '';
2063 $primary_key_array = array();
2064 $unique_key_array = array();
2065 $nonprimary_condition_array = array();
2066 $condition_array = array();
2068 for ($i = 0; $i < $fields_cnt; ++
$i) {
2071 $field_flags = $GLOBALS['dbi']->fieldFlags($handle, $i);
2072 $meta = $fields_meta[$i];
2074 // do not use a column alias in a condition
2075 if (! isset($meta->orgname
) ||
strlen($meta->orgname
) === 0) {
2076 $meta->orgname
= $meta->name
;
2078 if (!empty($analyzed_sql_results['statement']->expr
)) {
2079 foreach ($analyzed_sql_results['statement']->expr
as $expr) {
2080 if ((empty($expr->alias
)) ||
(empty($expr->column
))) {
2083 if (strcasecmp($meta->name
, $expr->alias
) == 0) {
2084 $meta->orgname
= $expr->column
;
2091 // Do not use a table alias in a condition.
2093 // select * from galerie x WHERE
2094 //(select count(*) from galerie y where y.datum=x.datum)>1
2096 // But orgtable is present only with mysqli extension so the
2097 // fix is only for mysqli.
2098 // Also, do not use the original table name if we are dealing with
2099 // a view because this view might be updatable.
2100 // (The isView() verification should not be costly in most cases
2101 // because there is some caching in the function).
2102 if (isset($meta->orgtable
)
2103 && ($meta->table
!= $meta->orgtable
)
2104 && ! $GLOBALS['dbi']->getTable($GLOBALS['db'], $meta->table
)->isView()
2106 $meta->table
= $meta->orgtable
;
2109 // If this field is not from the table which the unique clause needs
2110 // to be restricted to.
2111 if ($restrict_to_table && $restrict_to_table != $meta->table
) {
2115 // to fix the bug where float fields (primary or not)
2116 // can't be matched because of the imprecision of
2117 // floating comparison, use CONCAT
2118 // (also, the syntax "CONCAT(field) IS NULL"
2119 // that we need on the next "if" will work)
2120 if ($meta->type
== 'real') {
2121 $con_key = 'CONCAT(' . self
::backquote($meta->table
) . '.'
2122 . self
::backquote($meta->orgname
) . ')';
2124 $con_key = self
::backquote($meta->table
) . '.'
2125 . self
::backquote($meta->orgname
);
2126 } // end if... else...
2127 $condition = ' ' . $con_key . ' ';
2129 if (! isset($row[$i]) ||
is_null($row[$i])) {
2130 $con_val = 'IS NULL';
2132 // timestamp is numeric on some MySQL 4.1
2133 // for real we use CONCAT above and it should compare to string
2135 && ($meta->type
!= 'timestamp')
2136 && ($meta->type
!= 'real')
2138 $con_val = '= ' . $row[$i];
2139 } elseif ((($meta->type
== 'blob') ||
($meta->type
== 'string'))
2140 && stristr($field_flags, 'BINARY')
2141 && ! empty($row[$i])
2143 // hexify only if this is a true not empty BLOB or a BINARY
2145 // do not waste memory building a too big condition
2146 if (mb_strlen($row[$i]) < 1000) {
2147 // use a CAST if possible, to avoid problems
2148 // if the field contains wildcard characters % or _
2149 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2150 } elseif ($fields_cnt == 1) {
2151 // when this blob is the only field present
2152 // try settling with length comparison
2153 $condition = ' CHAR_LENGTH(' . $con_key . ') ';
2154 $con_val = ' = ' . mb_strlen($row[$i]);
2156 // this blob won't be part of the final condition
2159 } elseif (in_array($meta->type
, self
::getGISDatatypes())
2160 && ! empty($row[$i])
2162 // do not build a too big condition
2163 if (mb_strlen($row[$i]) < 5000) {
2164 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2168 } elseif ($meta->type
== 'bit') {
2170 . self
::printableBitValue($row[$i], $meta->length
) . "'";
2173 . $GLOBALS['dbi']->escapeString($row[$i]) . '\'';
2177 if ($con_val != null) {
2179 $condition .= $con_val . ' AND';
2181 if ($meta->primary_key
> 0) {
2182 $primary_key .= $condition;
2183 $primary_key_array[$con_key] = $con_val;
2184 } elseif ($meta->unique_key
> 0) {
2185 $unique_key .= $condition;
2186 $unique_key_array[$con_key] = $con_val;
2189 $nonprimary_condition .= $condition;
2190 $nonprimary_condition_array[$con_key] = $con_val;
2194 // Correction University of Virginia 19991216:
2195 // prefer primary or unique keys for condition,
2196 // but use conjunction of all values if no primary key
2197 $clause_is_unique = true;
2200 $preferred_condition = $primary_key;
2201 $condition_array = $primary_key_array;
2203 } elseif ($unique_key) {
2204 $preferred_condition = $unique_key;
2205 $condition_array = $unique_key_array;
2207 } elseif (! $force_unique) {
2208 $preferred_condition = $nonprimary_condition;
2209 $condition_array = $nonprimary_condition_array;
2210 $clause_is_unique = false;
2213 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2214 return(array($where_clause, $clause_is_unique, $condition_array));
2218 * Generate the charset query part
2220 * @param string $collation Collation
2221 * @param boolean optional $override force 'CHARACTER SET' keyword
2225 static function getCharsetQueryPart($collation, $override = false)
2227 list($charset) = explode('_', $collation);
2228 $keyword = ' CHARSET=';
2231 $keyword = ' CHARACTER SET ';
2233 return $keyword . $charset
2234 . ($charset == $collation ?
'' : ' COLLATE ' . $collation);
2238 * Generate a button or image tag
2240 * @param string $button_name name of button element
2241 * @param string $button_class class of button or image element
2242 * @param string $text text to display
2243 * @param string $image image to display
2244 * @param string $value value
2246 * @return string html content
2250 public static function getButtonOrImage(
2251 $button_name, $button_class, $text, $image, $value = ''
2256 if ($GLOBALS['cfg']['ActionLinksMode'] == 'text') {
2257 return ' <input type="submit" name="' . $button_name . '"'
2258 . ' value="' . htmlspecialchars($value) . '"'
2259 . ' title="' . htmlspecialchars($text) . '" />' . "\n";
2261 return '<button class="' . $button_class . '" type="submit"'
2262 . ' name="' . $button_name . '" value="' . htmlspecialchars($value)
2263 . '" title="' . htmlspecialchars($text) . '">' . "\n"
2264 . self
::getIcon($image, $text)
2265 . '</button>' . "\n";
2269 * Generate a pagination selector for browsing resultsets
2271 * @param string $name The name for the request parameter
2272 * @param int $rows Number of rows in the pagination set
2273 * @param int $pageNow current page number
2274 * @param int $nbTotalPage number of total pages
2275 * @param int $showAll If the number of pages is lower than this
2276 * variable, no pages will be omitted in pagination
2277 * @param int $sliceStart How many rows at the beginning should always
2279 * @param int $sliceEnd How many rows at the end should always be shown?
2280 * @param int $percent Percentage of calculation page offsets to hop to a
2282 * @param int $range Near the current page, how many pages should
2283 * be considered "nearby" and displayed as well?
2284 * @param string $prompt The prompt to display (sometimes empty)
2290 public static function pageselector(
2291 $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
2293 $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
2295 $increment = floor($nbTotalPage / $percent);
2296 $pageNowMinusRange = ($pageNow - $range);
2297 $pageNowPlusRange = ($pageNow +
$range);
2299 $gotopage = $prompt . ' <select class="pageselector ajax"';
2301 $gotopage .= ' name="' . $name . '" >';
2302 if ($nbTotalPage < $showAll) {
2303 $pages = range(1, $nbTotalPage);
2307 // Always show first X pages
2308 for ($i = 1; $i <= $sliceStart; $i++
) {
2312 // Always show last X pages
2313 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2317 // Based on the number of results we add the specified
2318 // $percent percentage to each page number,
2319 // so that we have a representing page number every now and then to
2320 // immediately jump to specific pages.
2321 // As soon as we get near our currently chosen page ($pageNow -
2322 // $range), every page number will be shown.
2324 $x = $nbTotalPage - $sliceEnd;
2325 $met_boundary = false;
2328 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2329 // If our pageselector comes near the current page, we use 1
2330 // counter increments
2332 $met_boundary = true;
2334 // We add the percentage increment to our current page to
2335 // hop to the next one in range
2338 // Make sure that we do not cross our boundaries.
2339 if ($i > $pageNowMinusRange && ! $met_boundary) {
2340 $i = $pageNowMinusRange;
2344 if ($i > 0 && $i <= $x) {
2350 Add page numbers with "geometrically increasing" distances.
2352 This helps me a lot when navigating through giant tables.
2354 Test case: table with 2.28 million sets, 76190 pages. Page of interest
2355 is between 72376 and 76190.
2356 Selecting page 72376.
2357 Now, old version enumerated only +/- 10 pages around 72376 and the
2358 percentage increment produced steps of about 3000.
2360 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2361 around the current page.
2367 $i = $pageNow +
$dist;
2368 if ($i > 0 && $i <= $x) {
2377 $i = $pageNow - $dist;
2378 if ($i > 0 && $i <= $x) {
2383 // Since because of ellipsing of the current page some numbers may be
2384 // double, we unify our array:
2386 $pages = array_unique($pages);
2389 foreach ($pages as $i) {
2390 if ($i == $pageNow) {
2391 $selected = 'selected="selected" style="font-weight: bold"';
2395 $gotopage .= ' <option ' . $selected
2396 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2399 $gotopage .= ' </select>';
2405 * Prepare navigation for a list
2407 * @param int $count number of elements in the list
2408 * @param int $pos current position in the list
2409 * @param array $_url_params url parameters
2410 * @param string $script script name for form target
2411 * @param string $frame target frame
2412 * @param int $max_count maximum number of elements to display from
2414 * @param string $name the name for the request parameter
2415 * @param string[] $classes additional classes for the container
2417 * @return string $list_navigator_html the html content
2421 * @todo use $pos from $_url_params
2423 public static function getListNavigator(
2424 $count, $pos, $_url_params, $script, $frame, $max_count, $name = 'pos',
2428 $class = $frame == 'frame_navigation' ?
' class="ajax"' : '';
2430 $list_navigator_html = '';
2432 if ($max_count < $count) {
2434 $classes[] = 'pageselector';
2435 $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
2437 if ($frame != 'frame_navigation') {
2438 $list_navigator_html .= __('Page number:');
2441 // Move to the beginning or to the previous page
2443 $caption1 = ''; $caption2 = '';
2444 if (self
::showIcons('TableNavigationLinksMode')) {
2445 $caption1 .= '<< ';
2446 $caption2 .= '< ';
2448 if (self
::showText('TableNavigationLinksMode')) {
2449 $caption1 .= _pgettext('First page', 'Begin');
2450 $caption2 .= _pgettext('Previous page', 'Previous');
2452 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2453 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2455 $_url_params[$name] = 0;
2456 $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
2457 . URL
::getCommon($_url_params) . '">' . $caption1
2460 $_url_params[$name] = $pos - $max_count;
2461 $list_navigator_html .= ' <a' . $class . $title2
2462 . ' href="' . $script . URL
::getCommon($_url_params) . '">'
2463 . $caption2 . '</a>';
2466 $list_navigator_html .= '<form action="' . basename($script)
2467 . '" method="post">';
2469 $list_navigator_html .= URL
::getHiddenInputs($_url_params);
2470 $list_navigator_html .= self
::pageselector(
2473 floor(($pos +
1) / $max_count) +
1,
2474 ceil($count / $max_count)
2476 $list_navigator_html .= '</form>';
2478 if ($pos +
$max_count < $count) {
2479 $caption3 = ''; $caption4 = '';
2480 if (self
::showText('TableNavigationLinksMode')) {
2481 $caption3 .= _pgettext('Next page', 'Next');
2482 $caption4 .= _pgettext('Last page', 'End');
2484 if (self
::showIcons('TableNavigationLinksMode')) {
2485 $caption3 .= ' >';
2486 $caption4 .= ' >>';
2487 if (! self
::showText('TableNavigationLinksMode')) {
2491 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2492 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2494 $_url_params[$name] = $pos +
$max_count;
2495 $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
2496 . URL
::getCommon($_url_params) . '" >' . $caption3
2499 $_url_params[$name] = floor($count / $max_count) * $max_count;
2500 if ($_url_params[$name] == $count) {
2501 $_url_params[$name] = $count - $max_count;
2504 $list_navigator_html .= ' <a' . $class . $title4
2505 . ' href="' . $script . URL
::getCommon($_url_params) . '" >'
2506 . $caption4 . '</a>';
2508 $list_navigator_html .= '</div>' . "\n";
2511 return $list_navigator_html;
2515 * replaces %u in given path with current user name
2519 * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2523 * @param string $dir with wildcard for user
2525 * @return string per user directory
2527 public static function userDir($dir)
2529 // add trailing slash
2530 if (mb_substr($dir, -1) != '/') {
2534 return str_replace('%u', PMA_securePath($GLOBALS['cfg']['Server']['user']), $dir);
2538 * returns html code for db link to default db page
2540 * @param string $database database
2542 * @return string html link to default db page
2544 public static function getDbLink($database = null)
2546 if (strlen($database) === 0) {
2547 if (strlen($GLOBALS['db']) === 0) {
2550 $database = $GLOBALS['db'];
2552 $database = self
::unescapeMysqlWildcards($database);
2556 . Util
::getScriptNameForOption(
2557 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2559 . URL
::getCommon(array('db' => $database)) . '" title="'
2562 __('Jump to database "%s".'),
2566 . '">' . htmlspecialchars($database) . '</a>';
2570 * Prepare a lightbulb hint explaining a known external bug
2571 * that affects a functionality
2573 * @param string $functionality localized message explaining the func.
2574 * @param string $component 'mysql' (eventually, 'php')
2575 * @param string $minimum_version of this component
2576 * @param string $bugref bug reference for this component
2580 public static function getExternalBug(
2581 $functionality, $component, $minimum_version, $bugref
2584 if (($component == 'mysql') && (PMA_MYSQL_INT_VERSION
< $minimum_version)) {
2585 $ext_but_html .= self
::showHint(
2587 __('The %s functionality is affected by a known bug, see %s'),
2589 PMA_linkURL('https://bugs.mysql.com/') . $bugref
2593 return $ext_but_html;
2597 * Generates a set of radio HTML fields
2599 * @param string $html_field_name the radio HTML field
2600 * @param array $choices the choices values and labels
2601 * @param string $checked_choice the choice to check by default
2602 * @param boolean $line_break whether to add HTML line break after a choice
2603 * @param boolean $escape_label whether to use htmlspecialchars() on label
2604 * @param string $class enclose each choice with a div of this class
2605 * @param string $id_prefix prefix for the id attribute, name will be
2606 * used if this is not supplied
2608 * @return string set of html radio fiels
2610 public static function getRadioFields(
2611 $html_field_name, $choices, $checked_choice = '',
2612 $line_break = true, $escape_label = true, $class = '',
2617 foreach ($choices as $choice_value => $choice_label) {
2619 if (! empty($class)) {
2620 $radio_html .= '<div class="' . $class . '">';
2624 $id_prefix = $html_field_name;
2626 $html_field_id = $id_prefix . '_' . $choice_value;
2627 $radio_html .= '<input type="radio" name="' . $html_field_name . '" id="'
2628 . $html_field_id . '" value="'
2629 . htmlspecialchars($choice_value) . '"';
2631 if ($choice_value == $checked_choice) {
2632 $radio_html .= ' checked="checked"';
2635 $radio_html .= ' />' . "\n"
2636 . '<label for="' . $html_field_id . '">'
2638 ?
htmlspecialchars($choice_label)
2643 $radio_html .= '<br />';
2646 if (! empty($class)) {
2647 $radio_html .= '</div>';
2649 $radio_html .= "\n";
2656 * Generates and returns an HTML dropdown
2658 * @param string $select_name name for the select element
2659 * @param array $choices choices values
2660 * @param string $active_choice the choice to select by default
2661 * @param string $id id of the select element; can be different in
2662 * case the dropdown is present more than once
2664 * @param string $class class for the select element
2665 * @param string $placeholder Placeholder for dropdown if nothing else
2668 * @return string html content
2670 * @todo support titles
2672 public static function getDropdown(
2673 $select_name, $choices, $active_choice, $id, $class = '', $placeholder = null
2676 . ' name="' . htmlspecialchars($select_name) . '"'
2677 . ' id="' . htmlspecialchars($id) . '"'
2678 . (! empty($class) ?
' class="' . htmlspecialchars($class) . '"' : '')
2681 $resultOptions = '';
2684 foreach ($choices as $one_choice_value => $one_choice_label) {
2685 $resultOptions .= '<option value="'
2686 . htmlspecialchars($one_choice_value) . '"';
2688 if ($one_choice_value == $active_choice) {
2689 $resultOptions .= ' selected="selected"';
2692 $resultOptions .= '>' . htmlspecialchars($one_choice_label)
2696 if (!empty($placeholder)) {
2697 $resultOptions = '<option value="" disabled="disabled"'
2698 . ( !$selected ?
' selected="selected"' : '' )
2699 . '>' . $placeholder . '</option>'
2703 $result .= $resultOptions
2710 * Generates a slider effect (jQjuery)
2711 * Takes care of generating the initial <div> and the link
2712 * controlling the slider; you have to generate the </div> yourself
2713 * after the sliding section.
2715 * @param string $id the id of the <div> on which to apply the effect
2716 * @param string $message the message to show as a link
2718 * @return string html div element
2721 public static function getDivForSliderEffect($id = '', $message = '')
2723 return Template
::get('div_for_slider_effect')->render([
2725 'InitialSlidersState' => $GLOBALS['cfg']['InitialSlidersState'],
2726 'message' => $message,
2731 * Creates an AJAX sliding toggle button
2732 * (or and equivalent form when AJAX is disabled)
2734 * @param string $action The URL for the request to be executed
2735 * @param string $select_name The name for the dropdown box
2736 * @param array $options An array of options (see rte_footer.lib.php)
2737 * @param string $callback A JS snippet to execute when the request is
2738 * successfully processed
2740 * @return string HTML code for the toggle button
2742 public static function toggleButton($action, $select_name, $options, $callback)
2744 // Do the logic first
2745 $link = "$action&" . urlencode($select_name) . "=";
2746 $link_on = $link . urlencode($options[1]['value']);
2747 $link_off = $link . urlencode($options[0]['value']);
2749 if ($options[1]['selected'] == true) {
2751 } else if ($options[0]['selected'] == true) {
2757 return Template
::get('toggle_button')->render(
2759 'pmaThemeImage' => $GLOBALS['pmaThemeImage'],
2760 'text_dir' => $GLOBALS['text_dir'],
2761 'link_on' => $link_on,
2762 'toggleOn' => str_replace(' ', ' ', htmlspecialchars(
2763 $options[1]['label'])),
2764 'toggleOff' => str_replace(' ', ' ', htmlspecialchars(
2765 $options[0]['label'])),
2766 'link_off' => $link_off,
2767 'callback' => $callback,
2770 } // end toggleButton()
2773 * Clears cache content which needs to be refreshed on user change.
2777 public static function clearUserCache()
2779 self
::cacheUnset('is_superuser');
2780 self
::cacheUnset('is_createuser');
2781 self
::cacheUnset('is_grantuser');
2785 * Calculates session cache key
2789 public static function cacheKey()
2791 if (isset($GLOBALS['cfg']['Server']['user'])) {
2792 return 'server_' . $GLOBALS['server'] . '_' . $GLOBALS['cfg']['Server']['user'];
2794 return 'server_' . $GLOBALS['server'];
2799 * Verifies if something is cached in the session
2801 * @param string $var variable name
2805 public static function cacheExists($var)
2807 return isset($_SESSION['cache'][self
::cacheKey()][$var]);
2811 * Gets cached information from the session
2813 * @param string $var variable name
2814 * @param \Closure $callback callback to fetch the value
2818 public static function cacheGet($var, $callback = null)
2820 if (self
::cacheExists($var)) {
2821 return $_SESSION['cache'][self
::cacheKey()][$var];
2825 self
::cacheSet($var, $val);
2833 * Caches information in the session
2835 * @param string $var variable name
2836 * @param mixed $val value
2840 public static function cacheSet($var, $val = null)
2842 $_SESSION['cache'][self
::cacheKey()][$var] = $val;
2846 * Removes cached information from the session
2848 * @param string $var variable name
2852 public static function cacheUnset($var)
2854 unset($_SESSION['cache'][self
::cacheKey()][$var]);
2858 * Converts a bit value to printable format;
2859 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2860 * function because in PHP, decbin() supports only 32 bits
2863 * @param integer $value coming from a BIT field
2864 * @param integer $length length
2866 * @return string the printable value
2868 public static function printableBitValue($value, $length)
2870 // if running on a 64-bit server or the length is safe for decbin()
2871 if (PHP_INT_SIZE
== 8 ||
$length < 33) {
2872 $printable = decbin($value);
2874 // FIXME: does not work for the leftmost bit of a 64-bit value
2877 while ($value >= pow(2, $i)) {
2885 if ($value - pow(2, $i) < 0) {
2886 $printable = '0' . $printable;
2888 $printable = '1' . $printable;
2889 $value = $value - pow(2, $i);
2893 $printable = strrev($printable);
2895 $printable = str_pad($printable, $length, '0', STR_PAD_LEFT
);
2900 * Verifies whether the value contains a non-printable character
2902 * @param string $value value
2906 public static function containsNonPrintableAscii($value)
2908 return preg_match('@[^[:print:]]@', $value);
2912 * Converts a BIT type default value
2913 * for example, b'010' becomes 010
2915 * @param string $bit_default_value value
2917 * @return string the converted value
2919 public static function convertBitDefaultValue($bit_default_value)
2921 return rtrim(ltrim($bit_default_value, "b'"), "'");
2925 * Extracts the various parts from a column spec
2927 * @param string $columnspec Column specification
2929 * @return array associative array containing type, spec_in_brackets
2930 * and possibly enum_set_values (another array)
2932 public static function extractColumnSpec($columnspec)
2934 $first_bracket_pos = mb_strpos($columnspec, '(');
2935 if ($first_bracket_pos) {
2936 $spec_in_brackets = chop(
2939 $first_bracket_pos +
1,
2940 mb_strrpos($columnspec, ')') - $first_bracket_pos - 1
2943 // convert to lowercase just to be sure
2944 $type = mb_strtolower(
2945 chop(mb_substr($columnspec, 0, $first_bracket_pos))
2948 // Split trailing attributes such as unsigned,
2949 // binary, zerofill and get data type name
2950 $type_parts = explode(' ', $columnspec);
2951 $type = mb_strtolower($type_parts[0]);
2952 $spec_in_brackets = '';
2955 if ('enum' == $type ||
'set' == $type) {
2956 // Define our working vars
2957 $enum_set_values = self
::parseEnumSetValues($columnspec, false);
2959 . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2964 $enum_set_values = array();
2966 /* Create printable type name */
2967 $printtype = mb_strtolower($columnspec);
2969 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2970 // this would be a BINARY or VARBINARY column type;
2971 // by the way, a BLOB should not show the BINARY attribute
2972 // because this is not accepted in MySQL syntax.
2973 if (preg_match('@binary@', $printtype)
2974 && ! preg_match('@binary[\(]@', $printtype)
2976 $printtype = preg_replace('@binary@', '', $printtype);
2982 $printtype = preg_replace(
2983 '@zerofill@', '', $printtype, -1, $zerofill_cnt
2985 $zerofill = ($zerofill_cnt > 0);
2986 $printtype = preg_replace(
2987 '@unsigned@', '', $printtype, -1, $unsigned_cnt
2989 $unsigned = ($unsigned_cnt > 0);
2990 $printtype = trim($printtype);
2995 $attribute = 'BINARY';
2998 $attribute = 'UNSIGNED';
3001 $attribute = 'UNSIGNED ZEROFILL';
3004 $can_contain_collation = false;
3007 "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
3010 $can_contain_collation = true;
3013 // for the case ENUM('–','“')
3014 $displayed_type = htmlspecialchars($printtype);
3015 if (mb_strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
3016 $displayed_type = '<abbr title="' . htmlspecialchars($printtype) . '">';
3017 $displayed_type .= htmlspecialchars(
3019 $printtype, 0, $GLOBALS['cfg']['LimitChars']
3022 $displayed_type .= '</abbr>';
3027 'spec_in_brackets' => $spec_in_brackets,
3028 'enum_set_values' => $enum_set_values,
3029 'print_type' => $printtype,
3030 'binary' => $binary,
3031 'unsigned' => $unsigned,
3032 'zerofill' => $zerofill,
3033 'attribute' => $attribute,
3034 'can_contain_collation' => $can_contain_collation,
3035 'displayed_type' => $displayed_type
3040 * Verifies if this table's engine supports foreign keys
3042 * @param string $engine engine
3046 public static function isForeignKeySupported($engine)
3048 $engine = strtoupper($engine);
3049 if (($engine == 'INNODB') ||
($engine == 'PBXT')) {
3051 } elseif ($engine == 'NDBCLUSTER' ||
$engine == 'NDB') {
3052 $ndbver = strtolower(
3053 $GLOBALS['dbi']->fetchValue("SELECT @@ndb_version_string")
3055 if (substr($ndbver, 0, 4) == 'ndb-') {
3056 $ndbver = substr($ndbver, 4);
3058 return version_compare($ndbver, 7.3, '>=');
3065 * Is Foreign key check enabled?
3069 public static function isForeignKeyCheck()
3071 if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'enable') {
3073 } else if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'disable') {
3076 return ($GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON');
3080 * Get HTML for Foreign key check checkbox
3082 * @return string HTML for checkbox
3084 public static function getFKCheckbox()
3086 $checked = self
::isForeignKeyCheck();
3087 $html = '<input type="hidden" name="fk_checks" value="0" />';
3088 $html .= '<input type="checkbox" name="fk_checks"'
3089 . ' id="fk_checks" value="1"'
3090 . ($checked ?
' checked="checked"' : '') . '/>';
3091 $html .= '<label for="fk_checks">' . __('Enable foreign key checks')
3097 * Handle foreign key check request
3099 * @return bool Default foreign key checks value
3101 public static function handleDisableFKCheckInit()
3103 $default_fk_check_value
3104 = $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON';
3105 if (isset($_REQUEST['fk_checks'])) {
3106 if (empty($_REQUEST['fk_checks'])) {
3107 // Disable foreign key checks
3108 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'OFF');
3110 // Enable foreign key checks
3111 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'ON');
3113 } // else do nothing, go with default
3114 return $default_fk_check_value;
3118 * Cleanup changes done for foreign key check
3120 * @param bool $default_fk_check_value original value for 'FOREIGN_KEY_CHECKS'
3124 public static function handleDisableFKCheckCleanup($default_fk_check_value)
3126 $GLOBALS['dbi']->setVariable(
3127 'FOREIGN_KEY_CHECKS', $default_fk_check_value ?
'ON' : 'OFF'
3132 * Converts GIS data to Well Known Text format
3134 * @param string $data GIS data
3135 * @param bool $includeSRID Add SRID to the WKT
3137 * @return string GIS data in Well Know Text format
3139 public static function asWKT($data, $includeSRID = false)
3141 // Convert to WKT format
3142 $hex = bin2hex($data);
3143 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3145 $wktsql .= ", SRID(x'" . $hex . "')";
3148 $wktresult = $GLOBALS['dbi']->tryQuery(
3149 $wktsql, null, DatabaseInterface
::QUERY_STORE
3151 $wktarr = $GLOBALS['dbi']->fetchRow($wktresult, 0);
3152 $wktval = $wktarr[0];
3156 $wktval = "'" . $wktval . "'," . $srid;
3158 @$GLOBALS['dbi']->freeResult($wktresult);
3164 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3166 * @param string $string string
3168 * @return string with the chars replaced
3170 public static function duplicateFirstNewline($string)
3172 $first_occurence = mb_strpos($string, "\r\n");
3173 if ($first_occurence === 0) {
3174 $string = "\n" . $string;
3180 * Get the action word corresponding to a script name
3181 * in order to display it as a title in navigation panel
3183 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3184 * $cfg['NavigationTreeDefaultTabTable2'],
3185 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3187 * @return string Title for the $cfg value
3189 public static function getTitleForTarget($target)
3192 'structure' => __('Structure'),
3194 'search' =>__('Search'),
3195 'insert' =>__('Insert'),
3196 'browse' => __('Browse'),
3197 'operations' => __('Operations'),
3199 // For backward compatiblity
3201 // Values for $cfg['DefaultTabTable']
3202 'tbl_structure.php' => __('Structure'),
3203 'tbl_sql.php' => __('SQL'),
3204 'tbl_select.php' =>__('Search'),
3205 'tbl_change.php' =>__('Insert'),
3206 'sql.php' => __('Browse'),
3207 // Values for $cfg['DefaultTabDatabase']
3208 'db_structure.php' => __('Structure'),
3209 'db_sql.php' => __('SQL'),
3210 'db_search.php' => __('Search'),
3211 'db_operations.php' => __('Operations'),
3213 return isset($mapping[$target]) ?
$mapping[$target] : false;
3217 * Get the script name corresponding to a plain English config word
3218 * in order to append in links on navigation and main panel
3220 * @param string $target a valid value for
3221 * $cfg['NavigationTreeDefaultTabTable'],
3222 * $cfg['NavigationTreeDefaultTabTable2'],
3223 * $cfg['DefaultTabTable'], $cfg['DefaultTabDatabase'] or
3224 * $cfg['DefaultTabServer']
3225 * @param string $location one out of 'server', 'table', 'database'
3227 * @return string script name corresponding to the config word
3229 public static function getScriptNameForOption($target, $location)
3231 if ($location == 'server') {
3232 // Values for $cfg['DefaultTabServer']
3237 return 'server_databases.php';
3239 return 'server_status.php';
3241 return 'server_variables.php';
3243 return 'server_privileges.php';
3245 } elseif ($location == 'database') {
3246 // Values for $cfg['DefaultTabDatabase']
3249 return 'db_structure.php';
3251 return 'db_sql.php';
3253 return 'db_search.php';
3255 return 'db_operations.php';
3257 } elseif ($location == 'table') {
3258 // Values for $cfg['DefaultTabTable'],
3259 // $cfg['NavigationTreeDefaultTabTable'] and
3260 // $cfg['NavigationTreeDefaultTabTable2']
3263 return 'tbl_structure.php';
3265 return 'tbl_sql.php';
3267 return 'tbl_select.php';
3269 return 'tbl_change.php';
3279 * Formats user string, expanding @VARIABLES@, accepting strftime format
3282 * @param string $string Text where to do expansion.
3283 * @param array|string $escape Function to call for escaping variable values.
3284 * Can also be an array of:
3285 * - the escape method name
3286 * - the class that contains the method
3287 * - location of the class (for inclusion)
3288 * @param array $updates Array with overrides for default parameters
3289 * (obtained from GLOBALS).
3293 public static function expandUserString(
3294 $string, $escape = null, $updates = array()
3298 $vars['http_host'] = PMA_getenv('HTTP_HOST');
3299 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3300 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3302 if (empty($GLOBALS['cfg']['Server']['verbose'])) {
3303 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
3305 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
3308 $vars['database'] = $GLOBALS['db'];
3309 $vars['table'] = $GLOBALS['table'];
3310 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION
;
3312 /* Update forced variables */
3313 foreach ($updates as $key => $val) {
3317 /* Replacement mapping */
3319 * The __VAR__ ones are for backward compatibility, because user
3320 * might still have it in cookies.
3323 '@HTTP_HOST@' => $vars['http_host'],
3324 '@SERVER@' => $vars['server_name'],
3325 '__SERVER__' => $vars['server_name'],
3326 '@VERBOSE@' => $vars['server_verbose'],
3327 '@VSERVER@' => $vars['server_verbose_or_name'],
3328 '@DATABASE@' => $vars['database'],
3329 '__DB__' => $vars['database'],
3330 '@TABLE@' => $vars['table'],
3331 '__TABLE__' => $vars['table'],
3332 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3335 /* Optional escaping */
3336 if (! is_null($escape)) {
3337 if (is_array($escape)) {
3338 $escape_class = new $escape[1];
3339 $escape_method = $escape[0];
3341 foreach ($replace as $key => $val) {
3342 if (is_array($escape)) {
3343 $replace[$key] = $escape_class->$escape_method($val);
3345 $replace[$key] = ($escape == 'backquote')
3346 ? self
::$escape($val)
3352 /* Backward compatibility in 3.5.x */
3353 if (mb_strpos($string, '@FIELDS@') !== false) {
3354 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3357 /* Fetch columns list if required */
3358 if (mb_strpos($string, '@COLUMNS@') !== false) {
3359 $columns_list = $GLOBALS['dbi']->getColumns(
3360 $GLOBALS['db'], $GLOBALS['table']
3363 // sometimes the table no longer exists at this point
3364 if (! is_null($columns_list)) {
3365 $column_names = array();
3366 foreach ($columns_list as $column) {
3367 if (! is_null($escape)) {
3368 $column_names[] = self
::$escape($column['Field']);
3370 $column_names[] = $column['Field'];
3373 $replace['@COLUMNS@'] = implode(',', $column_names);
3375 $replace['@COLUMNS@'] = '*';
3379 /* Do the replacement */
3380 return strtr(strftime($string), $replace);
3384 * Prepare the form used to browse anywhere on the local server for a file to
3387 * @param string $max_upload_size maximum upload size
3391 public static function getBrowseUploadFileBlock($max_upload_size)
3395 if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
3396 $block_html .= '<label for="radio_import_file">';
3398 $block_html .= '<label for="input_import_file">';
3401 $block_html .= __("Browse your computer:") . '</label>'
3402 . '<div id="upload_form_status" style="display: none;"></div>'
3403 . '<div id="upload_form_status_info" style="display: none;"></div>'
3404 . '<input type="file" name="import_file" id="input_import_file" />'
3405 . self
::getFormattedMaximumUploadSize($max_upload_size) . "\n"
3406 // some browsers should respect this :)
3407 . self
::generateHiddenMaxFileSize($max_upload_size) . "\n";
3413 * Prepare the form used to select a file to import from the server upload
3416 * @param ImportPlugin[] $import_list array of import plugins
3417 * @param string $uploaddir upload directory
3421 public static function getSelectUploadFileBlock($import_list, $uploaddir)
3424 $block_html .= '<label for="radio_local_import_file">'
3426 __("Select from the web server upload directory <b>%s</b>:"),
3427 htmlspecialchars(self
::userDir($uploaddir))
3432 foreach ($import_list as $import_plugin) {
3433 if (! empty($extensions)) {
3436 $extensions .= $import_plugin->getProperties()->getExtension();
3439 $matcher = '@\.(' . $extensions . ')(\.('
3440 . PMA_supportedDecompressions() . '))?$@';
3442 $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
3443 && isset($GLOBALS['local_import_file']))
3444 ?
$GLOBALS['local_import_file']
3447 $files = PMA_getFileSelectOptions(
3448 self
::userDir($uploaddir),
3453 if ($files === false) {
3455 __('The directory you set for upload work cannot be reached.')
3457 } elseif (! empty($files)) {
3459 . ' <select style="margin: 5px" size="1" '
3460 . 'name="local_import_file" '
3461 . 'id="select_local_import_file">' . "\n"
3462 . ' <option value=""> </option>' . "\n"
3464 . ' </select>' . "\n";
3465 } elseif (empty($files)) {
3466 $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
3474 * Build titles and icons for action links
3476 * @return array the action titles
3478 public static function buildActionTitles()
3482 $titles['Browse'] = self
::getIcon('b_browse.png', __('Browse'));
3483 $titles['NoBrowse'] = self
::getIcon('bd_browse.png', __('Browse'));
3484 $titles['Search'] = self
::getIcon('b_select.png', __('Search'));
3485 $titles['NoSearch'] = self
::getIcon('bd_select.png', __('Search'));
3486 $titles['Insert'] = self
::getIcon('b_insrow.png', __('Insert'));
3487 $titles['NoInsert'] = self
::getIcon('bd_insrow.png', __('Insert'));
3488 $titles['Structure'] = self
::getIcon('b_props.png', __('Structure'));
3489 $titles['Drop'] = self
::getIcon('b_drop.png', __('Drop'));
3490 $titles['NoDrop'] = self
::getIcon('bd_drop.png', __('Drop'));
3491 $titles['Empty'] = self
::getIcon('b_empty.png', __('Empty'));
3492 $titles['NoEmpty'] = self
::getIcon('bd_empty.png', __('Empty'));
3493 $titles['Edit'] = self
::getIcon('b_edit.png', __('Edit'));
3494 $titles['NoEdit'] = self
::getIcon('bd_edit.png', __('Edit'));
3495 $titles['Export'] = self
::getIcon('b_export.png', __('Export'));
3496 $titles['NoExport'] = self
::getIcon('bd_export.png', __('Export'));
3497 $titles['Execute'] = self
::getIcon('b_nextpage.png', __('Execute'));
3498 $titles['NoExecute'] = self
::getIcon('bd_nextpage.png', __('Execute'));
3499 // For Favorite/NoFavorite, we need icon only.
3500 $titles['Favorite'] = self
::getIcon('b_favorite.png', '');
3501 $titles['NoFavorite']= self
::getIcon('b_no_favorite.png', '');
3507 * This function processes the datatypes supported by the DB,
3508 * as specified in Types->getColumns() and either returns an array
3509 * (useful for quickly checking if a datatype is supported)
3510 * or an HTML snippet that creates a drop-down list.
3512 * @param bool $html Whether to generate an html snippet or an array
3513 * @param string $selected The value to mark as selected in HTML mode
3515 * @return mixed An HTML snippet or an array of datatypes.
3518 public static function getSupportedDatatypes($html = false, $selected = '')
3522 // NOTE: the SELECT tag in not included in this snippet.
3525 foreach ($GLOBALS['PMA_Types']->getColumns() as $key => $value) {
3526 if (is_array($value)) {
3527 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3528 foreach ($value as $subvalue) {
3529 if ($subvalue == $selected) {
3531 '<option selected="selected" title="%s">%s</option>',
3532 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3535 } else if ($subvalue === '-') {
3536 $retval .= '<option disabled="disabled">';
3537 $retval .= $subvalue;
3538 $retval .= '</option>';
3541 '<option title="%s">%s</option>',
3542 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3547 $retval .= '</optgroup>';
3549 if ($selected == $value) {
3551 '<option selected="selected" title="%s">%s</option>',
3552 $GLOBALS['PMA_Types']->getTypeDescription($value),
3557 '<option title="%s">%s</option>',
3558 $GLOBALS['PMA_Types']->getTypeDescription($value),
3566 foreach ($GLOBALS['PMA_Types']->getColumns() as $value) {
3567 if (is_array($value)) {
3568 foreach ($value as $subvalue) {
3569 if ($subvalue !== '-') {
3570 $retval[] = $subvalue;
3574 if ($value !== '-') {
3582 } // end getSupportedDatatypes()
3585 * Returns a list of datatypes that are not (yet) handled by PMA.
3586 * Used by: tbl_change.php and libraries/db_routines.inc.php
3588 * @return array list of datatypes
3590 public static function unsupportedDatatypes()
3592 $no_support_types = array();
3593 return $no_support_types;
3597 * Return GIS data types
3599 * @param bool $upper_case whether to return values in upper case
3601 * @return string[] GIS data types
3603 public static function getGISDatatypes($upper_case = false)
3605 $gis_data_types = array(
3613 'geometrycollection'
3616 for ($i = 0, $nb = count($gis_data_types); $i < $nb; $i++
) {
3618 = mb_strtoupper($gis_data_types[$i]);
3621 return $gis_data_types;
3625 * Generates GIS data based on the string passed.
3627 * @param string $gis_string GIS string
3629 * @return string GIS data enclosed in 'GeomFromText' function
3631 public static function createGISData($gis_string)
3633 $gis_string = trim($gis_string);
3634 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3635 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3636 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3637 return 'GeomFromText(' . $gis_string . ')';
3638 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3639 return "GeomFromText('" . $gis_string . "')";
3646 * Returns the names and details of the functions
3647 * that can be applied on geometry data types.
3649 * @param string $geom_type if provided the output is limited to the functions
3650 * that are applicable to the provided geometry type.
3651 * @param bool $binary if set to false functions that take two geometries
3652 * as arguments will not be included.
3653 * @param bool $display if set to true separators will be added to the
3656 * @return array names and details of the functions that can be applied on
3657 * geometry data types.
3659 public static function getGISFunctions(
3660 $geom_type = null, $binary = true, $display = false
3664 $funcs[] = array('display' => ' ');
3667 // Unary functions common to all geometry types
3668 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3669 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3670 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3671 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3672 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3673 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3675 $geom_type = trim(mb_strtolower($geom_type));
3676 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3677 $funcs[] = array('display' => '--------');
3680 // Unary functions that are specific to each geometry type
3681 if ($geom_type == 'point') {
3682 $funcs['X'] = array('params' => 1, 'type' => 'float');
3683 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3685 } elseif ($geom_type == 'multipoint') {
3686 // no functions here
3687 } elseif ($geom_type == 'linestring') {
3688 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3689 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3690 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3691 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3692 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3694 } elseif ($geom_type == 'multilinestring') {
3695 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3696 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3698 } elseif ($geom_type == 'polygon') {
3699 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3700 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3701 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3703 } elseif ($geom_type == 'multipolygon') {
3704 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3705 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3706 // Not yet implemented in MySQL
3707 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3709 } elseif ($geom_type == 'geometrycollection') {
3710 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3713 // If we are asked for binary functions as well
3715 // section separator
3717 $funcs[] = array('display' => '--------');
3720 if (PMA_MYSQL_INT_VERSION
< 50601) {
3721 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3722 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3723 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3724 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3725 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3726 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3727 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3728 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3730 // If MySQl version is greater than or equal 5.6.1,
3731 // use the ST_ prefix.
3732 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3733 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3734 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3735 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3736 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3737 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3738 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3739 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3743 $funcs[] = array('display' => '--------');
3745 // Minimum bounding rectangle functions
3746 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3747 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3748 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3749 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3750 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3751 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3752 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3758 * Returns default function for a particular column.
3760 * @param array $field Data about the column for which
3761 * to generate the dropdown
3762 * @param bool $insert_mode Whether the operation is 'insert'
3764 * @global array $cfg PMA configuration
3765 * @global mixed $data data of currently edited row
3766 * (used to detect whether to choose defaults)
3768 * @return string An HTML snippet of a dropdown list with function
3769 * names appropriate for the requested column.
3771 public static function getDefaultFunctionForField($field, $insert_mode)
3774 * @todo Except for $cfg, no longer use globals but pass as parameters
3775 * from higher levels
3779 $default_function = '';
3781 // Can we get field class based values?
3782 $current_class = $GLOBALS['PMA_Types']->getTypeClass($field['True_Type']);
3783 if (! empty($current_class)) {
3784 if (isset($cfg['DefaultFunctions']['FUNC_' . $current_class])) {
3786 = $cfg['DefaultFunctions']['FUNC_' . $current_class];
3790 // what function defined as default?
3791 // for the first timestamp we don't set the default function
3792 // if there is a default value for the timestamp
3793 // (not including CURRENT_TIMESTAMP)
3794 // and the column does not have the
3795 // ON UPDATE DEFAULT TIMESTAMP attribute.
3796 if (($field['True_Type'] == 'timestamp')
3797 && $field['first_timestamp']
3798 && empty($field['Default'])
3800 && $field['Extra'] != 'on update CURRENT_TIMESTAMP'
3801 && $field['Null'] == 'NO'
3803 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3806 // For primary keys of type char(36) or varchar(36) UUID if the default
3808 // Only applies to insert mode, as it would silently trash data on updates.
3810 && $field['Key'] == 'PRI'
3811 && ($field['Type'] == 'char(36)' ||
$field['Type'] == 'varchar(36)')
3813 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3816 return $default_function;
3820 * Creates a dropdown box with MySQL functions for a particular column.
3822 * @param array $field Data about the column for which
3823 * to generate the dropdown
3824 * @param bool $insert_mode Whether the operation is 'insert'
3826 * @return string An HTML snippet of a dropdown list with function
3827 * names appropriate for the requested column.
3829 public static function getFunctionsForField($field, $insert_mode, $foreignData)
3831 $default_function = self
::getDefaultFunctionForField($field, $insert_mode);
3832 $dropdown_built = array();
3834 // Create the output
3835 $retval = '<option></option>' . "\n";
3836 // loop on the dropdown array and print all available options for that
3838 $functions = $GLOBALS['PMA_Types']->getFunctions($field['True_Type']);
3839 foreach ($functions as $function) {
3840 $retval .= '<option';
3841 if (isset($foreignData['foreign_link']) && $foreignData['foreign_link'] !== false && $default_function === $function) {
3842 $retval .= ' selected="selected"';
3844 $retval .= '>' . $function . '</option>' . "\n";
3845 $dropdown_built[$function] = true;
3848 // Create separator before all functions list
3849 if (count($functions) > 0) {
3850 $retval .= '<option value="" disabled="disabled">--------</option>'
3854 // For compatibility's sake, do not let out all other functions. Instead
3855 // print a separator (blank) and then show ALL functions which weren't
3857 $functions = $GLOBALS['PMA_Types']->getAllFunctions();
3858 foreach ($functions as $function) {
3859 // Skip already included functions
3860 if (isset($dropdown_built[$function])) {
3863 $retval .= '<option';
3864 if ($default_function === $function) {
3865 $retval .= ' selected="selected"';
3867 $retval .= '>' . $function . '</option>' . "\n";
3871 } // end getFunctionsForField()
3874 * Checks if the current user has a specific privilege and returns true if the
3875 * user indeed has that privilege or false if (s)he doesn't. This function must
3876 * only be used for features that are available since MySQL 5, because it
3877 * relies on the INFORMATION_SCHEMA database to be present.
3879 * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3880 * // Checks if the currently logged in user has the global
3881 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3882 * // user has this privilege on database 'mydb'.
3884 * @param string $priv The privilege to check
3885 * @param mixed $db null, to only check global privileges
3886 * string, db name where to also check for privileges
3887 * @param mixed $tbl null, to only check global/db privileges
3888 * string, table name where to also check for privileges
3892 public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
3894 // Get the username for the current user in the format
3895 // required to use in the information schema database.
3896 list($user, $host) = $GLOBALS['dbi']->getCurrentUserAndHost();
3898 if ($user === '') { // MySQL is started with --skip-grant-tables
3903 $username .= str_replace("'", "''", $user);
3904 $username .= "''@''";
3905 $username .= str_replace("'", "''", $host);
3908 // Prepare the query
3909 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3910 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3912 // Check global privileges first.
3913 $user_privileges = $GLOBALS['dbi']->fetchValue(
3921 if ($user_privileges) {
3924 // If a database name was provided and user does not have the
3925 // required global privilege, try database-wise permissions.
3927 $query .= " AND '%s' LIKE `TABLE_SCHEMA`";
3928 $schema_privileges = $GLOBALS['dbi']->fetchValue(
3931 'SCHEMA_PRIVILEGES',
3934 $GLOBALS['dbi']->escapeString($db)
3937 if ($schema_privileges) {
3941 // There was no database name provided and the user
3942 // does not have the correct global privilege.
3945 // If a table name was also provided and we still didn't
3946 // find any valid privileges, try table-wise privileges.
3947 if ($tbl !== null) {
3948 // need to escape wildcards in db and table names, see bug #3518484
3949 $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
3950 $query .= " AND TABLE_NAME='%s'";
3951 $table_privileges = $GLOBALS['dbi']->fetchValue(
3957 $GLOBALS['dbi']->escapeString($db),
3958 $GLOBALS['dbi']->escapeString($tbl)
3961 if ($table_privileges) {
3965 // If we reached this point, the user does not
3966 // have even valid table-wise privileges.
3971 * Returns server type for current connection
3973 * Known types are: MariaDB and MySQL (default)
3977 public static function getServerType()
3979 $server_type = 'MySQL';
3981 if (mb_stripos(PMA_MYSQL_STR_VERSION
, 'mariadb') !== false) {
3982 $server_type = 'MariaDB';
3983 return $server_type;
3986 if (mb_stripos(PMA_MYSQL_VERSION_COMMENT
, 'percona') !== false) {
3987 $server_type = 'Percona Server';
3988 return $server_type;
3991 return $server_type;
3995 * Prepare HTML code for display button.
3999 public static function getButton()
4001 return '<p class="print_ignore">'
4002 . '<input type="button" class="button" id="print" value="'
4003 . __('Print') . '" />'
4008 * Parses ENUM/SET values
4010 * @param string $definition The definition of the column
4011 * for which to parse the values
4012 * @param bool $escapeHtml Whether to escape html entities
4016 public static function parseEnumSetValues($definition, $escapeHtml = true)
4018 $values_string = htmlentities($definition, ENT_COMPAT
, "UTF-8");
4019 // There is a JS port of the below parser in functions.js
4020 // If you are fixing something here,
4021 // you need to also update the JS port.
4026 for ($i = 0, $length = mb_strlen($values_string);
4030 $curr = mb_substr($values_string, $i, 1);
4031 $next = ($i == mb_strlen($values_string) - 1)
4033 : mb_substr($values_string, $i +
1, 1);
4035 if (! $in_string && $curr == "'") {
4037 } else if (($in_string && $curr == "\\") && $next == "\\") {
4040 } else if (($in_string && $next == "'")
4041 && ($curr == "'" ||
$curr == "\\")
4045 } else if ($in_string && $curr == "'") {
4047 $values[] = $buffer;
4049 } else if ($in_string) {
4055 if (strlen($buffer) > 0) {
4056 // The leftovers in the buffer are the last value (if any)
4057 $values[] = $buffer;
4060 if (! $escapeHtml) {
4061 foreach ($values as $key => $value) {
4062 $values[$key] = html_entity_decode($value, ENT_QUOTES
, 'UTF-8');
4070 * Get regular expression which occur first inside the given sql query.
4072 * @param array $regex_array Comparing regular expressions.
4073 * @param String $query SQL query to be checked.
4075 * @return String Matching regular expression.
4077 public static function getFirstOccurringRegularExpression($regex_array, $query)
4079 $minimum_first_occurence_index = null;
4082 foreach ($regex_array as $test_regex) {
4083 if (preg_match($test_regex, $query, $matches, PREG_OFFSET_CAPTURE
)) {
4084 if (is_null($minimum_first_occurence_index)
4085 ||
($matches[0][1] < $minimum_first_occurence_index)
4087 $regex = $test_regex;
4088 $minimum_first_occurence_index = $matches[0][1];
4096 * Return the list of tabs for the menu with corresponding names
4098 * @param string $level 'server', 'db' or 'table' level
4100 * @return array list of tabs for the menu
4102 public static function getMenuTabList($level = null)
4106 'databases' => __('Databases'),
4108 'status' => __('Status'),
4109 'rights' => __('Users'),
4110 'export' => __('Export'),
4111 'import' => __('Import'),
4112 'settings' => __('Settings'),
4113 'binlog' => __('Binary log'),
4114 'replication' => __('Replication'),
4115 'vars' => __('Variables'),
4116 'charset' => __('Charsets'),
4117 'plugins' => __('Plugins'),
4118 'engine' => __('Engines')
4121 'structure' => __('Structure'),
4123 'search' => __('Search'),
4124 'qbe' => __('Query'),
4125 'export' => __('Export'),
4126 'import' => __('Import'),
4127 'operation' => __('Operations'),
4128 'privileges' => __('Privileges'),
4129 'routines' => __('Routines'),
4130 'events' => __('Events'),
4131 'triggers' => __('Triggers'),
4132 'tracking' => __('Tracking'),
4133 'designer' => __('Designer'),
4134 'central_columns' => __('Central columns')
4137 'browse' => __('Browse'),
4138 'structure' => __('Structure'),
4140 'search' => __('Search'),
4141 'insert' => __('Insert'),
4142 'export' => __('Export'),
4143 'import' => __('Import'),
4144 'privileges' => __('Privileges'),
4145 'operation' => __('Operations'),
4146 'tracking' => __('Tracking'),
4147 'triggers' => __('Triggers'),
4151 if ($level == null) {
4153 } else if (array_key_exists($level, $tabList)) {
4154 return $tabList[$level];
4161 * Returns information with regards to handling the http request
4163 * @param array $context Data about the context for which
4164 * to http request is sent
4166 * @return array of updated context information
4168 public static function handleContext(array $context)
4170 if (strlen($GLOBALS['cfg']['ProxyUrl']) > 0) {
4171 $context['http'] = array(
4172 'proxy' => $GLOBALS['cfg']['ProxyUrl'],
4173 'request_fulluri' => true
4175 if (strlen($GLOBALS['cfg']['ProxyUser']) > 0) {
4176 $auth = base64_encode(
4177 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4179 $context['http']['header'] .= 'Proxy-Authorization: Basic '
4186 * Updates an existing curl as necessary
4188 * @param resource $curl_handle A curl_handle resource
4189 * created by curl_init which should
4190 * have several options set
4192 * @return resource curl_handle with updated options
4194 public static function configureCurl($curl_handle)
4196 if (strlen($GLOBALS['cfg']['ProxyUrl']) > 0) {
4197 curl_setopt($curl_handle, CURLOPT_PROXY
, $GLOBALS['cfg']['ProxyUrl']);
4198 if (strlen($GLOBALS['cfg']['ProxyUser']) > 0) {
4201 CURLOPT_PROXYUSERPWD
,
4202 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4206 curl_setopt($curl_handle, CURLOPT_USERAGENT
, 'phpMyAdmin/' . PMA_VERSION
);
4207 return $curl_handle;
4211 * Add fractional seconds to time, datetime and timestamp strings.
4212 * If the string contains fractional seconds,
4213 * pads it with 0s up to 6 decimal places.
4215 * @param string $value time, datetime or timestamp strings
4217 * @return string time, datetime or timestamp strings with fractional seconds
4219 public static function addMicroseconds($value)
4221 if (empty($value) ||
$value == 'CURRENT_TIMESTAMP') {
4225 if (mb_strpos($value, '.') === false) {
4226 return $value . '.000000';
4233 mb_strpos($value, '.') +
7
4238 * Reads the file, detects the compression MIME type, closes the file
4239 * and returns the MIME type
4241 * @param resource $file the file handle
4243 * @return string the MIME type for compression, or 'none'
4245 public static function getCompressionMimeType($file)
4247 $test = fread($file, 4);
4248 $len = strlen($test);
4250 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
4251 return 'application/gzip';
4253 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
4254 return 'application/bzip2';
4256 if ($len >= 4 && $test == "PK\003\004") {
4257 return 'application/zip';
4263 * Renders a single link for the top of the navigation panel
4265 * @param string $link The url for the link
4266 * @param bool $showText Whether to show the text or to
4267 * only use it for title attributes
4268 * @param string $text The text to display and use for title attributes
4269 * @param bool $showIcon Whether to show the icon
4270 * @param string $icon The filename of the icon to show
4271 * @param string $linkId Value to use for the ID attribute
4272 * @param boolean $disableAjax Whether to disable ajax page loading for this link
4273 * @param string $linkTarget The name of the target frame for the link
4274 * @param array $classes HTML classes to apply
4276 * @return string HTML code for one link
4278 public static function getNavigationLink(
4285 $disableAjax = false,
4289 $retval = '<a href="' . $link . '"';
4290 if (! empty($linkId)) {
4291 $retval .= ' id="' . $linkId . '"';
4293 if (! empty($linkTarget)) {
4294 $retval .= ' target="' . $linkTarget . '"';
4297 $classes[] = 'disableAjax';
4299 if (!empty($classes)) {
4300 $retval .= ' class="' . join(" ", $classes) . '"';
4302 $retval .= ' title="' . $text . '">';
4304 $retval .= Util
::getImage(
4314 $retval .= '<br />';
4320 * Provide COLLATE clause, if required, to perform case sensitive comparisons
4321 * for queries on information_schema.
4323 * @return string COLLATE clause if needed or empty string.
4325 public static function getCollateForIS()
4327 $names = $GLOBALS['dbi']->getLowerCaseNames();
4328 if ($names === '0') {
4329 return "COLLATE utf8_bin";
4330 } elseif ($names === '2') {
4331 return "COLLATE utf8_general_ci";
4337 * Process the index data.
4339 * @param array $indexes index data
4341 * @return array processes index data
4343 public static function processIndexData($indexes)
4348 $pk_array = array(); // will be use to emphasis prim. keys in the table
4349 $indexes_info = array();
4350 $indexes_data = array();
4353 foreach ($indexes as $row) {
4354 // Backups the list of primary keys
4355 if ($row['Key_name'] == 'PRIMARY') {
4356 $primary .= $row['Column_name'] . ', ';
4357 $pk_array[$row['Column_name']] = 1;
4359 // Retains keys informations
4360 if ($row['Key_name'] != $lastIndex) {
4361 $indexes[] = $row['Key_name'];
4362 $lastIndex = $row['Key_name'];
4364 $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
4365 $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
4366 if (isset($row['Cardinality'])) {
4367 $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
4369 // I don't know what does following column mean....
4370 // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed'];
4372 $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
4374 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name']
4375 = $row['Column_name'];
4376 if (isset($row['Sub_part'])) {
4377 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part']
4383 return array($primary, $pk_array, $indexes_info, $indexes_data);
4387 * Function to get html for the start row and number of rows panel
4389 * @param string $sql_query sql query
4391 * @return string html
4393 public static function getStartAndNumberOfRowsPanel($sql_query)
4395 $pos = isset($_REQUEST['pos'])
4397 : $_SESSION['tmpval']['pos'];
4398 if (isset($_REQUEST['session_max_rows'])) {
4399 $rows = $_REQUEST['session_max_rows'];
4401 if ($_SESSION['tmpval']['max_rows'] != 'all') {
4402 $rows = $_SESSION['tmpval']['max_rows'];
4404 $rows = $GLOBALS['cfg']['MaxRows'];
4408 return Template
::get('startAndNumberOfRowsPanel')
4412 'unlim_num_rows' => intval($_REQUEST['unlim_num_rows']),
4414 'sql_query' => $sql_query,
4420 * Returns whether the database server supports virtual columns
4424 public static function isVirtualColumnsSupported()
4426 $serverType = self
::getServerType();
4427 return $serverType == 'MySQL' && PMA_MYSQL_INT_VERSION
>= 50705
4428 ||
($serverType == 'MariaDB' && PMA_MYSQL_INT_VERSION
>= 50200);
4432 * Returns the proper class clause according to the column type
4434 * @param string $type the column type
4436 * @return string $class_clause the HTML class clause
4438 public static function getClassForType($type)
4445 $class_clause = ' class="nowrap"';
4447 return $class_clause;
4451 * Gets the list of tables in the current db and information about these
4452 * tables if possible
4454 * @param string $db database name
4455 * @param string $sub_part part of script name
4460 public static function getDbInfo($db, $sub_part)
4465 * limits for table list
4467 if (! isset($_SESSION['tmpval']['table_limit_offset'])
4468 ||
$_SESSION['tmpval']['table_limit_offset_db'] != $db
4470 $_SESSION['tmpval']['table_limit_offset'] = 0;
4471 $_SESSION['tmpval']['table_limit_offset_db'] = $db;
4473 if (isset($_REQUEST['pos'])) {
4474 $_SESSION['tmpval']['table_limit_offset'] = (int) $_REQUEST['pos'];
4476 $pos = $_SESSION['tmpval']['table_limit_offset'];
4479 * whether to display extended stats
4481 $is_show_stats = $cfg['ShowStats'];
4484 * whether selected db is information_schema
4486 $db_is_system_schema = false;
4488 if ($GLOBALS['dbi']->isSystemSchema($db)) {
4489 $is_show_stats = false;
4490 $db_is_system_schema = true;
4494 * information about tables in db
4498 $tooltip_truename = array();
4499 $tooltip_aliasname = array();
4501 // Special speedup for newer MySQL Versions (in 4.0 format changed)
4502 if (true === $cfg['SkipLockedTables']) {
4503 $db_info_result = $GLOBALS['dbi']->query(
4504 'SHOW OPEN TABLES FROM ' . Util
::backquote($db) . ' WHERE In_use > 0;'
4507 // Blending out tables in use
4508 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4509 $tables = self
::getTablesWhenOpen($db, $db_info_result);
4511 } elseif ($db_info_result) {
4512 $GLOBALS['dbi']->freeResult($db_info_result);
4516 if (empty($tables)) {
4517 // Set some sorting defaults
4519 $sort_order = 'ASC';
4521 if (isset($_REQUEST['sort'])) {
4522 $sortable_name_mappings = array(
4524 'records' => 'Rows',
4526 'collation' => 'Collation',
4527 'size' => 'Data_length',
4528 'overhead' => 'Data_free',
4529 'creation' => 'Create_time',
4530 'last_update' => 'Update_time',
4531 'last_check' => 'Check_time',
4532 'comment' => 'Comment',
4535 // Make sure the sort type is implemented
4536 if (isset($sortable_name_mappings[$_REQUEST['sort']])) {
4537 $sort = $sortable_name_mappings[$_REQUEST['sort']];
4538 if ($_REQUEST['sort_order'] == 'DESC') {
4539 $sort_order = 'DESC';
4544 $groupWithSeparator = false;
4547 $limit_count = false;
4548 $groupTable = array();
4550 if (! empty($_REQUEST['tbl_group']) ||
! empty($_REQUEST['tbl_type'])) {
4551 if (! empty($_REQUEST['tbl_type'])) {
4552 // only tables for selected type
4553 $tbl_type = $_REQUEST['tbl_type'];
4555 if (! empty($_REQUEST['tbl_group'])) {
4556 // only tables for selected group
4557 $tbl_group = $_REQUEST['tbl_group'];
4558 // include the table with the exact name of the group if such
4560 $groupTable = $GLOBALS['dbi']->getTablesFull(
4561 $db, $tbl_group, false, null, $limit_offset,
4562 $limit_count, $sort, $sort_order, $tbl_type
4564 $groupWithSeparator = $tbl_group
4565 . $GLOBALS['cfg']['NavigationTreeTableSeparator'];
4569 // - get the total number of tables
4570 // (needed for proper working of the MaxTableList feature)
4571 $tables = $GLOBALS['dbi']->getTables($db);
4572 $total_num_tables = count($tables);
4573 if (isset($sub_part) && $sub_part == '_export') {
4574 // (don't fetch only a subset if we are coming from
4575 // db_export.php, because I think it's too risky to display only
4576 // a subset of the table names when exporting a db)
4579 * @todo Page selector for table names?
4582 // fetch the details for a possible limited subset
4583 $limit_offset = $pos;
4584 $limit_count = true;
4587 $tables = array_merge(
4589 $GLOBALS['dbi']->getTablesFull(
4590 $db, $groupWithSeparator, ($groupWithSeparator !== false), null,
4591 $limit_offset, $limit_count, $sort, $sort_order, $tbl_type
4596 $num_tables = count($tables);
4597 // (needed for proper working of the MaxTableList feature)
4598 if (! isset($total_num_tables)) {
4599 $total_num_tables = $num_tables;
4603 * If coming from a Show MySQL link on the home page,
4604 * put something in $sub_part
4606 if (empty($sub_part)) {
4607 $sub_part = '_structure';
4616 $db_is_system_schema,
4624 * Gets the list of tables in the current db, taking into account
4625 * that they might be "in use"
4627 * @param string $db database name
4628 * @param object $db_info_result result set
4630 * @return array $tables list of tables
4633 public static function getTablesWhenOpen($db, $db_info_result)
4635 $sot_cache = $tables = array();
4637 while ($tmp = $GLOBALS['dbi']->fetchAssoc($db_info_result)) {
4638 $sot_cache[$tmp['Table']] = true;
4640 $GLOBALS['dbi']->freeResult($db_info_result);
4642 // is there at least one "in use" table?
4643 if (isset($sot_cache)) {
4645 $whereAdded = false;
4646 if (PMA_isValid($_REQUEST['tbl_group'])) {
4647 $group = Util
::escapeMysqlWildcards($_REQUEST['tbl_group']);
4648 $groupWithSeparator = Util
::escapeMysqlWildcards(
4649 $_REQUEST['tbl_group']
4650 . $GLOBALS['cfg']['NavigationTreeTableSeparator']
4652 $tblGroupSql .= " WHERE ("
4653 . Util
::backquote('Tables_in_' . $db)
4654 . " LIKE '" . $groupWithSeparator . "%'"
4656 . Util
::backquote('Tables_in_' . $db)
4657 . " LIKE '" . $group . "')";
4660 if (PMA_isValid($_REQUEST['tbl_type'], array('table', 'view'))) {
4661 $tblGroupSql .= $whereAdded ?
" AND" : " WHERE";
4662 if ($_REQUEST['tbl_type'] == 'view') {
4663 $tblGroupSql .= " `Table_type` != 'BASE TABLE'";
4665 $tblGroupSql .= " `Table_type` = 'BASE TABLE'";
4668 $db_info_result = $GLOBALS['dbi']->query(
4669 'SHOW FULL TABLES FROM ' . Util
::backquote($db) . $tblGroupSql,
4670 null, DatabaseInterface
::QUERY_STORE
4672 unset($tblGroupSql, $whereAdded);
4674 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4676 while ($tmp = $GLOBALS['dbi']->fetchRow($db_info_result)) {
4677 if (! isset($sot_cache[$tmp[0]])) {
4679 } else { // table in use
4680 $tables[$tmp[0]] = array(
4681 'TABLE_NAME' => $tmp[0],
4685 'TABLE_COMMENT' => '',
4689 if (count($names) > 0) {
4690 $tables = array_merge(
4692 $GLOBALS['dbi']->getTablesFull($db, $names)
4695 if ($GLOBALS['cfg']['NaturalOrder']) {
4696 uksort($tables, 'strnatcasecmp');
4699 } elseif ($db_info_result) {
4700 $GLOBALS['dbi']->freeResult($db_info_result);
4708 * Returs list of used PHP extensions.
4710 * @return array of strings
4712 public static function listPHPExtensions()
4715 if (DatabaseInterface
::checkDbExtension('mysqli')) {
4716 $result[] = 'mysqli';
4718 $result[] = 'mysql';
4721 if (extension_loaded('curl')) {
4725 if (extension_loaded('mbstring')) {
4726 $result[] = 'mbstring';
4733 * Converts given (request) paramter to string
4735 * @param mixed $value Value to convert
4739 public static function requestString($value)
4741 while (is_array($value) ||
is_object($value)) {
4742 $value = reset($value);
4744 return trim((string)$value);
4748 * Creates HTTP request using curl
4750 * @param mixed $response HTTP response
4751 * @param interger $http_status HTTP response status code
4752 * @param bool $return_only_status If set to true, the method would only return response status
4756 public static function httpRequestReturn($response, $http_status, $return_only_status)
4758 if ($http_status == 404) {
4761 if ($http_status != 200) {
4764 if ($return_only_status) {
4771 * Creates HTTP request using curl
4773 * @param string $url Url to send the request
4774 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4775 * @param bool $return_only_status If set to true, the method would only return response status
4776 * @param mixed $content Content to be sent with HTTP request
4777 * @param string $header Header to be set for the HTTP request
4781 public static function httpRequestCurl($url, $method, $return_only_status = false, $content = null, $header = "")
4783 $curl_handle = curl_init($url);
4784 if ($curl_handle === false) {
4787 $curl_handle = Util
::configureCurl($curl_handle);
4789 if ($method != "GET") {
4790 curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST
, $method);
4793 curl_setopt($curl_handle, CURLOPT_HTTPHEADER
, array($header));
4794 curl_setopt($curl_handle, CURLOPT_HEADER
, true);
4797 if ($method == "POST") {
4798 curl_setopt($curl_handle, CURLOPT_POSTFIELDS
, $content);
4801 curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST
, '2');
4802 curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER
, '1');
4804 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER
,true);
4805 curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION
, 0);
4806 curl_setopt($curl_handle, CURLOPT_IPRESOLVE
, CURL_IPRESOLVE_V4
);
4807 curl_setopt($curl_handle, CURLOPT_TIMEOUT
, 10);
4808 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT
, 10);
4809 $response = @curl_exec
($curl_handle);
4810 if ($response === false) {
4813 $http_status = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE
);
4814 return Util
::httpRequestReturn($response, $http_status, $return_only_status);
4818 * Creates HTTP request using file_get_contents
4820 * @param string $url Url to send the request
4821 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4822 * @param bool $return_only_status If set to true, the method would only return response status
4823 * @param mixed $content Content to be sent with HTTP request
4824 * @param string $header Header to be set for the HTTP request
4828 public static function httpRequestFopen($url, $method, $return_only_status = false, $content = null, $header = "")
4832 'method' => $method,
4833 'request_fulluri' => true,
4835 'user_agent' => 'phpMyAdmin',
4836 'header' => "Accept: */*",
4840 $context['http']['header'] .= "\n" . $header;
4842 if ($method == "POST") {
4843 $context['http']['content'] = $content;
4846 $context = Util
::handleContext($context);
4847 $response = @file_get_contents
(
4850 stream_context_create($context)
4852 if (! isset($http_response_header)) {
4855 preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $out );
4856 $http_status = intval($out[1]);
4857 return Util
::httpRequestReturn($response, $http_status, $return_only_status);
4861 * Creates HTTP request
4863 * @param string $url Url to send the request
4864 * @param string $method HTTP request method (GET, POST, PUT, DELETE, etc)
4865 * @param bool $return_only_status If set to true, the method would only return response status
4866 * @param mixed $content Content to be sent with HTTP request
4867 * @param string $header Header to be set for the HTTP request
4871 public static function httpRequest($url, $method, $return_only_status = false, $content = null, $header = "")
4873 if (function_exists('curl_init')) {
4874 return Util
::httpRequestCurl($url, $method, $return_only_status, $content, $header);
4875 } else if (ini_get('allow_url_fopen')) {
4876 return Util
::httpRequestFopen($url, $method, $return_only_status, $content, $header);